Why use flags+bitmasks rather than a series of booleans?

后端 未结 10 2085
猫巷女王i
猫巷女王i 2021-02-05 03:29

Given a case where I have an object that may be in one or more true/false states, I\'ve always been a little fuzzy on why programmers frequently use flags+bitmasks instead of ju

相关标签:
10条回答
  • 2021-02-05 04:16

    From a domain Model perspective, it just models reality better in some situations. If you have three booleans like AccountIsInDefault and IsPreferredCustomer and RequiresSalesTaxState, then it doesnn't make sense to add them to a single Flags decorated enumeration, cause they are not three distinct values for the same domain model element.

    But if you have a set of booleans like:

     [Flags] enum AccountStatus {AccountIsInDefault=1, 
             AccountOverdue=2 and AccountFrozen=4}
    

    or

      [Flags] enum CargoState {ExceedsWeightLimit=1,  
             ContainsDangerousCargo=2, IsFlammableCargo=4, 
             ContainsRadioactive=8}
    

    Then it is useful to be able to store the total state of the Account, (or the cargo) in ONE variable... that represents ONE Domain Element whose value can represent any possible combination of states.

    0 讨论(0)
  • 2021-02-05 04:16

    I would suggest never using enum flags unless you are dealing with some pretty serious memory limitations (not likely). You should always write code optimized for maintenance.

    Having several boolean properties makes it easier to read and understand the code, change the values, and provide Intellisense comments not to mention reduce the likelihood of bugs. If necessary, you can always use an enum flag field internally, just make sure you expose the setting/getting of the values with boolean properties.

    0 讨论(0)
  • 2021-02-05 04:18

    Raymond Chen has a blog post on this subject.

    Sure, bitfields save data memory, but you have to balance it against the cost in code size, debuggability, and reduced multithreading.

    As others have said, its time is largely past. It's tempting to still do it, cause bit fiddling is fun and cool-looking, but it's no longer more efficient, it has serious drawbacks in terms of maintenance, it doesn't play nicely with databases, and unless you're working in an embedded world, you have enough memory.

    0 讨论(0)
  • 2021-02-05 04:18

    It is for speed and efficiency. Essentially all you are working with is a single int.

    if ((flags & AnchorStyles.Top) == AnchorStyles.Top)
    {
        //Do stuff
    } 
    
    0 讨论(0)
提交回复
热议问题