Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice: Validate conditions for method calls?

Tags:

c++

c#

I guess in almost every programm sometimes methods don't need to be called all the time but under specific conditions only. It it very easy to check if a method must be called. A simple if-statment can do the trick.

if (value == true)
{
    DoSomething();
}

But if you have many conditions the validation can get complicated and the code gets longer and longer. So I wrote code with the method called every time and the method itself will check and validate if her code needs to be executed.

DoSomething(value);

... then ...

public void DoSomething(bool value)
{
    if (value == true)
    {
    // Do Something here ...
    }
}

Now I have two ways of doing things. I am not exactly sure which way is the right way. Or maybe there is even another option?

like image 484
TalkingCode Avatar asked Mar 17 '26 21:03

TalkingCode


1 Answers

Clean Code — A Handbook of Agile Software Craftsmanship promotes not to write methods accepting a single boolean parameter because each method should do one thing and one thing only. If a method takes a boolean parameter to decide what to do, it automatically does two things: deciding what to do and actually doing something. The method should be refactored into two separate methods doing something and a single method deciding which of the two methods to call.

Furthermore, evaluating a boolean value using value == true is redundant and unnecessary. The value itself represents a boolean state (true / false) and does not need to be compared to true again. That said, the best practice is using if (value) instead of if (value == true) (or if ((value == true) == true; this seems idiotic but does not differ much from the approach of if (value == true)).

like image 171
Marius Schulz Avatar answered Mar 20 '26 10:03

Marius Schulz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!