Alex Rivera | Logout

Help refactoring this C# function

Asked 2010-08-14T12:50:58.300
23

I have written functions that look like this:

bool IsDry(bool isRaining, bool isWithUmbrella) {
    if (isRaining) {
        if (isWithUmbrella)
            return true;
        else
            return false;
    }
    else
        return true;
}

I need to check, if it's raining, then the person needs to carry an umbrella in order to keep dry (don't laugh, this is just an example, our actual business rules are more serious than this).

How can I refactor this, because right now it looks clumsy.

Thanks for the help, guys! =)

c#
Edit
Report

2 Answers

3

How can I refactor this

With unit tests.

Seriously. There are two Boolean inputs, so you only need four unit tests to fully cover this method.

Then, with full branch coverage already in place, you can just play around with the implementation. Try something that seems right (I find it very helpful to write a truth table in this case), and the tests will tell you if you got a detail wrong.

And as a further benefit, you can keep the tests around forever, as documentation of what the method actually does. This is especially useful if you opt for a clever implementation, like fancy Boolean expressions -- if you're scratching your head trying to follow the flow, you can just look at the tests and see, "Oh, I see -- if I pass this and this, I get this."

answered 2010-08-14T17:24:13.370
1
bool IsDry(bool isRaining, bool isWithUmbrella) {
 return isRaining ? isWithUmbrella : true;
}
answered 2010-08-14T15:21:11.277

Your Answer