TAG | clean-code

Recently I was watching a video from Uncle Bob (aka Robert Martin) about craftsmanship and ethics in which he was saying the following:

Do not pass boolean parameters to a method or I’ll find you!

Why? Cos you probably won’t understand following lines of code:

this.DeleteCustomer(true); //what does it mean "true"?
//or even more triky
this.HiglightText(true, false, false);

So while looking on above method calls you will need to hover your mouse or press some hotkeys to get information about signature and actual meaning of parameters. And it works only if you are watching you code through IDE. Boring isn’t it?

Lets assume that first method has the following signature:

public void DeleteCustomer(bool onlyMarkAsDeleted);

Instead of doing this I prefer split this method on two, where each one is more explicit:


This is possible only if you own the code, so you are able to perform such refactoring. In other case I prefer to go with one of the following ways:

Define a local variable with a meaningful name and make value assignment right in method call:

bool onlyMarkAsDeleted;
this.DeleteCustomer(onlyMarkAsDeleted = true);
//for the "false" case
this.DeleteCustomer(onlyMarkAsDeleted = false);

Disadvantage: It can be not obvious how it works if you see this for the first time. You just can forget that a result of Boolean value assignment is also a Boolean equal to value assigned.

Define a local variable with a meaningful name and make value assignment before method call:

bool andMarkAsDeleted = true;
//for the "false" case
bool doNotMarkAsDeleted = false;

Disadvantage: This approach requires more care in choosing variable names, this can go tricky sometime.

I think both are a lot more readable and will save a lot of time in future. Surely .NET 4 Rocks with named arguments:

this.DeleteCustomer(onlyMarkAsDeleted: true)

Please, follow these rules or I’ll send your home address to Uncle Bob =)

, , , ,

Find it!

Theme Design by devolux.org