Lets say I have an object with two boolean properties:
public bool AdvancedMode{ get; set; }
public bool DumpDiagnostics{ get; set; }
The domain rules state that DumpDiagnostics is not allowed unless AdvancedMode is also true. So throughout the code you might see statements like this:
if( options.AdvancedMode && options.DumpDiagnostics ){ ... }
The problem with this is that it’s easy to forget to add the check forAdvancedMode and accidentally check only for DumpDiagnostics.
if( options.DumpDiagnostics ) // Oh no!
So there are two solutions that I can think of:
Option 1: DumpDiagnostics only returns true when AdvancedMode is true.
public bool DumpDiagnostics
{
get{ return AdvancedMode && _dumpDiagnostics; }
set{ _dumpDiagnostics = value; }
}
Option 2: New property that reflects the condition I’m looking for
public bool CanDumpDiagnostics{ get{ return AdvancedMode && DumpDiagnostics; } }
Question: Which is better?
Option #1 seems pretty easy and less prone to error. There’s always one authority on whether diagnostics can be dumped. But, it does change the set -> get semantics where you can assign DumpDiagnostics = true, followed by if( DumpDiagnostics ) where it returns false.
Option #2 is good because it isolates the logic and makes it clear what the purpose is. The biggest drawback I see with it is that it’s still easy to just check for DumpDiagnostics instead of using the new CanDumpDiagnostics property.
p.s. I know it’s an awkward title but couldn’t come up with something more precise, feel free to modify.
Option 2 makes more sense to me. I don’t like properties which can be set but don’t “take hold”. I was going to suggest throwing an exception in the setter, but then remembered that you’d also have to throw an exception in the setter for
AdvancedModein case that was reset to false.I’d rename
DumpDiagnosticsto something likeDiagnosticDumpRequestedto make it clearer that it doesn’t guarantee it’ll be honoured.