C
C#3mo ago
SpReeD

The best-practice way to use a plausibility check

So, I have the following class
namespace CleanLib.Lego.Parts;

public class Color : Entity {
private string? _Name;
public string Name {
get => this._Name!;
set {
value.ThrowIfNullOrWhiteSpace();

this._Name = value;
}
}

private string? _Code;
public string Code {
get => this._Code!;
set {
value.ThrowIfNullOrWhiteSpace();

this._Code = value;
}
}

public Color(string name, string code) {
this.Name = name;
this.Code = code;
}
}
namespace CleanLib.Lego.Parts;

public class Color : Entity {
private string? _Name;
public string Name {
get => this._Name!;
set {
value.ThrowIfNullOrWhiteSpace();

this._Name = value;
}
}

private string? _Code;
public string Code {
get => this._Code!;
set {
value.ThrowIfNullOrWhiteSpace();

this._Code = value;
}
}

public Color(string name, string code) {
this.Name = name;
this.Code = code;
}
}
Is it okay to throw in the setter of the properties or is it somehow "better" to check this in the constructor? Logically spoken, both values won't ever change, but may be "corrected" if inserted wrongly in the database.
1 Reply
Joschi
Joschi3mo ago
No a setter or getter should not throw exceptions! It probably shouldn't even do validation. If you want to insure that your entity is always in a valid state don't expose the setter. Expose a method to change the value instead and that method also performs the validation. Also why do you have nullable backing fields for non nullable properties and then assume they are not null in the Getter? Just use an auto property unless you need a backing field for some specific reason.