2
\$\begingroup\$

My code keeps some int value about the date range, and there is a method to check if all of it is zero. Is there a better way to do it than doing this?

public bool IsAllDayZero
{
    get
    {
        return
            Today == 0 &&
            Days1_2 == 0 &&
            Days3_6 == 0 &&
            Days7_10 == 0 &&
            Days11_15 == 0 &&
            Days16_30 == 0 &&
            Days31_45 == 0 &&
            Days46_60 == 0 &&
            Days60Plus == 0
            ;
        }
}
\$\endgroup\$
4
\$\begingroup\$

The question is: Why do you want to change it?

I bet you can get a shorter form with some use of xor, and, or etc. functions but I believe it's not worth it. For example:

public bool IsAllDayZero
{
    get
    {
        return
            (Today | Days1_2 | Days3_6| Days7_10 | Days11_15 |
             Days16_30 |  Days31_45 | Days46_60 | Days60Plus) == 0;                
        }
}

It's indeed shorter but no way that it's more clear for some other person about what this code tries to achieve.

Or you can get a faster version that will revert the conditions and then execute only few conditions without a need to check them all but again I doubt that clarity of the code will worth such a changes.

However your current implementation is clear, complete and does exactly what it has to do without some extra noise and I just recommend not to change it.

\$\endgroup\$
  • 1
    \$\begingroup\$ Maybe having return (Today + Days1_2 + Days3_6 + Days7_10 + Days11_15 + Days16_30 + Days31_45 + Days46_60 + Days60Plus) == 0; would make it a little more clear to other people. \$\endgroup\$ – Piers Myers Sep 9 '11 at 11:11
  • \$\begingroup\$ @Piers. It would be clear but not correct - we need to think about overflow in this case. If I try to write the sum of two bytes (1 and 255) into byte field the result will be 0; \$\endgroup\$ – Andrey Taptunov Sep 9 '11 at 11:26
  • \$\begingroup\$ yeah, you're probably right. As you stated, the current implementation is fine and is probably how I would have done it, plus && is a short-circuit operator in C# and will stop evaluating subsequent conditions as soon as one becomes false. \$\endgroup\$ – Piers Myers Sep 9 '11 at 12:09
2
\$\begingroup\$

I see 3 alternative solutions:

  1. Use array of days, and then: days.All(d => d == 0)
  2. You can define boolean variable areAllDayZero or something else :-) and change it when you set values to properties
  3. Use reflection
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.