Created
June 29, 2018 20:38
-
-
Save HaloFour/3a661fda9a9b1b131c1f65c25652a333 to your computer and use it in GitHub Desktop.
Data Classes, Builder with Assignment Validation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class LoginResource { | |
public struct Builder { | |
private byte _assigned; | |
private string _username; | |
private string _password; | |
public string Username { | |
get => _username; | |
set { | |
_assigned = (byte)(_assigned | 1); | |
_username = value; | |
} | |
} | |
public string Password { | |
get => _password; | |
set { | |
_assigned = (byte)(_assigned | 2); | |
_password = value; | |
} | |
} | |
public bool RememberMe { get; set; } | |
internal byte Assigned => _assigned; | |
} | |
public static Builder Init() { | |
var builder = new Builder(); | |
builder.RememberMe = true; | |
return builder; | |
} | |
private readonly Builder _builder; | |
public LoginResource(Builder builder) { | |
byte assigned = builder.Assigned; | |
if ((assigned & 1) == 0) { | |
throw new InvalidOperationException($"{nameof(Username)} was not assigned."); | |
} | |
if ((assigned & 2) == 0) { | |
throw new InvalidOperationException($"{nameof(Password)} was not assigned."); | |
} | |
_builder = builder; | |
} | |
public string Username => _builder.Username; | |
public string Password => _builder.Password; | |
public bool RememberMe => _builder.RememberMe; | |
// other members elided for brevity | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Pretty, pretty, pretty! me like.