Dependent Boolean Properties

Suppose I have an object with two logical properties:

public bool AdvancedMode{ get; set; }
public bool DumpDiagnostics{ get; set; }

Domain rules state that DumpDiagnostics is not allowed unless the AdvancedMode parameter is specified. Therefore, in the whole code you can see the following statements:

if( options.AdvancedMode && options.DumpDiagnostics ){ ... }

The problem is that it's easy to forget to add validation for AdvancedMode and accidentally validate only for DumpDiagnostics.

if( options.DumpDiagnostics ) // Oh no!

So there are two solutions that I can think of:

Option 1: DumpDiagnostics returns true only when AdvancedMode is set.

public bool DumpDiagnostics
{ 
    get{ return AdvancedMode && _dumpDiagnostics; }
    set{ _dumpDiagnostics = value; }
}

Option 2: a new property that reflects the state I'm looking for

public bool CanDumpDiagnostics{ get{ return AdvancedMode && DumpDiagnostics; } }

Question: which is better?

№1 . , . set → get, DumpDiagnostics = true, if (DumpDiagnostics), false.

№ 2 , , . , , , DumpDiagnostics CanDumpDiagnostics.

p.s. , - , .

+3
4

2 . , , "". , , AdvancedMode , reset - false.

DumpDiagnostics DiagnosticDumpRequested, , , .

+3

3... :

public enum Mode
{
    Normal,
    Advanced,
    AdvancedWithDiagnostics
}

( , , )

:
"", :

public enum Mode
{
    Normal = 0,
    Advanced = 1,
    AdvancedWithDiagnostics = 3
}

( , , !):

public Mode SelectedMode { get; set; }
public bool AdvancedMode { get { return (SelectedMode & 1) != 0; } }
public bool DumpDiagnostics { get { return (SelectedMode & 2) != 0; } }
+4

What are the domain rules for getting and setting states? In other words, it seems to me that the set function for DumpDiagnostics should also install AdvancedMode. If so, then just go to option 1, and you only need to verify that DumpDiagnostics is installed in the rest of your code.

0
source

Option 1 is misleading. DumpDiagnostics must not be equal to AdvancedMode && & DumpDiagnostics. I would go with option 2

0
source

Source: https://habr.com/ru/post/1711717/


All Articles