Skip to content

Instantly share code, notes, and snippets.

@NMillard
Last active February 17, 2021 16:21
Show Gist options
  • Save NMillard/90787582d132eed762f0c28d7d3aa8f1 to your computer and use it in GitHub Desktop.
Save NMillard/90787582d132eed762f0c28d7d3aa8f1 to your computer and use it in GitHub Desktop.
Medium 2
public class User {
// Terrible property - this can be set to anything without reason
public string Username { get; set; }
// slightly better, but requires additional field
// and we still wouldn't know why "username2" changed
private string username2;
public string Username2 {
get => username2;
set {
if (string.IsNullOrEmpty(value)) throw new ArgumentException("Must have a value");
if (value.Length > 50) throw new ArgumentException("Too long");
username2 = value;
}
}
public string Username3 { get; private set; }
public void ChangeUsername(string newUsername) {
ValidateUsername(newUsername);
// (maybe) add some additional logic
Username3 = newUsername;
}
private void ValidateUsername(string username) {
if (string.IsNullOrEmpty(username)) throw new ArgumentException("Must have a value");
if (username.Length > 50) throw new ArgumentException("Too long");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment