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?
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)).
I find the answer to this question to be fairly obvious - unless I'm missing something. Adapt to each situation.
The called function should do what it's intended to do. If its intention is to work on some set of arguments, by all means do the checking inside the function.
If you plan to call the function conditionally, do the checking outside.
Moving the check inside just so you can save some extra verification is not a good idea I think, since others might want to call your function and not know whether it actually works given their parameters. I say, unless checking inside is imperative, leave the checking outside.
EDIT:
I just re-read your question...
You basically have:
void foo(bool actuallyExecuteFoo)
{
////
}
Really? REALLY?
But if you have many conditions the validation can get complicated and the code gets longer and longer.
If the validation is complicated, it means that the logic underneath is complicated. Expect your code to be as complicated as your logic - it has to be somewhere out there, right? Just think how to write it in a clean way. And the clean way is not always the shortest way.
I recommend this variant:
if (value == true)
{
DoSomething();
}
Why? Because:
the code calling DoSomething is then more clear (*), as it explicitly shows when the logic of DoSomething should be executed and when not,
DoSomething itself depends on less parameters (which makes it more generic and reusable).
*) Yes, "more clear" actually means "longer" here, but it also means "explicit" and "self-documenting". The shorter variant actually tries to hide some logic, which makes the code less clear.
Check out this for C# not sure why you need C++ :)
If the method can throw a Argument/ArgumentNull Exception, then you should validate it before calling the method. Also, Microsofts Code Contracts, will tell you if you need to validate the input before calling the method, for any code using contracts (basically assertions for static analysis).
The general rule is not to validate the input more than necessary. If something isn't valid, you should throw a exception (C#), or return a error (C++). Not executing the code due to a invalid input, without telling why, makes it near-impossible for the next-developer to figure out what the problem is.
I would recommend the second way, but I have some remarks:
You do not need to check if (value == true), just check if (value) instead.
Return earlier, what I mean if (!value) { return; }
Second way will take more execution time, though code will look better. Why don't you use macro?
#define DOSOMETHING(value) if (value) {DoSomething();}
Replace all
if (value == true) {DoSomething(); }
with macro DOSOMETHING(value)
Your purpose will be solved and code will look better
Related
I am a student and I am currently preparing for my OOP Basics Exam.
When in the controller you have methods which return a value and such that are void - how do you invoke them without using a if-else statement?
In my code "status" is the only one which should return a string to be printed on the Console - the others are void. So I put a if-esle and 2 methods in the CommandHandler.
Since I know "if-else" is a code smell, is there a more High Quality approach to deal with the situation?
if (commandName == "status")
{
this.Writer.WriteLine(this.CommandHandler.ExecuteStatusCommand(commandName));
}
else
{
this.CommandHandler.ExecuteCommand(commandName, commandParameters);
}
This is the project.
Thank you very much.
First, don't worry about if/else. If anybody tells you if/else is a code smell, put it through the Translator: What comes out is he's telling you he's too crazy, clueless, and/or fanatical to be taken seriously.
If by ill chance you get an instructor who requires you to say the Earth is flat to get an A, sure, tell him the Earth is flat. But if you're planning on a career or even a hobby as a navigator, don't ever forget that it's actually round.
So. It sounds to me like CommandHandler.ExecuteStatusCommand() executes the named command, which is implemented as a method somewhere. If the command method is void, ExecuteStatusCommand() returns null. Otherwise, the command method may return a string, in which case you want to write it to what looks like a stream.
OK, so one approach here is to say "A command is implemented via a method that takes a parameter and returns either null or a string representing a status. If it returns anything but null, write that to the stream".
This is standard stuff: You're defining a "contract". It's not at all inappropriate for command methods which actually return nothing to have a String return type, because they're fulfilling the terms of contract. "Return a string" is an option that's open to all commands; some take advantage, some don't.
This allows knowledge of the command's internals to be limited to the command method itself, which is a huge advantage. You don't need to worry about special cases at the point where you call the methods. The code below doesn't need to know which commands return a status and which don't. The commands themselves are given a means to communicate that information back to the caller, so only they need to know. It's incredibly beneficial to have a design which allows different parts of your code not to care about the details of other parts. Clean "interfaces" like this make that possible. The calling code gets simpler and stays simpler. Less code, with less need to change it over time, means less effort and fewer bugs.
As you noted, if you've got a "status" command that prints a result, and then later on you add a "print" command that also prints a result, you've got to not only implement the print command itself, but you've also got to remember to return to this part of your code and add a special case branch to the if/else.
That kind of tedious error-prone PITA is exactly the kind of nonsense OOP is meant to eliminate. If a new feature can be added without making a single edit to existing code, that's a sort of Platonic ideal of OOP.
So if ExecuteCommand() returns void, we'll want to be calling ExecuteStatusCommand() instead. I'm guessing at some things here. It would have been helpful if you had sketched out the semantics of those two methods.
var result = this.CommandHandler.ExecuteCommand(commandName, commandParameters);
if (result != null)
{
this.Writer.WriteLine(result);
}
If my assumptions about your design are accurate, that's the whole deal. commandParameters, like the status result, are an optional part of the contract. There's nothing inherently wrong with if/else, but sometimes you don't need one.
I have this method (modified code) :
public static void PublishXmlForCustomTypes(MyOwnClass DefaultOutputInformation)
{
if (DefaultOutputInformation != null)
{
///lot of code
}
}
and my whole code was inside the if statement and after thinking about it, I changed to this :
public static void PublishXmlForCustomTypes(MyOwnClass DefaultOutputInformation)
{
if (DefaultOutputInformation == null)
{
return;
}
///lot of code
}
As far as I tested it, it seems to be strictly equivalent but is that really the case ?
I mean, the "return" statement get us out of the method right ?
This is strictly equivalent and the second version is the way to go :)
Yes, that's absolutely fine.
Some people dogmatically stick to "one exit point per method" - which was appropriate when it was relatively tricky to make sure you always did the right amount of clean-up at the end of a function in C, for example... but it's not really necessary in C#.
Personally I think it's appropriate to return as soon as you know that you've done all the work you really want to in a method. Use try/finally or using statements to perform any extra "clean up however I exit" work.
yes return gets you out of the method; if you have a finally block and you call return from the try block, the finally block is executed anyway.
Yes, the return statement ends the method.
Yes, the return will exit you out of the code. It's generally good practice as the very first step in a function to verify that the parameters that were passed in are what you think they are and exit (via the return or throwing an exception) so that you don't do any unnecessary processing only to have to abort later in the function.
Yes, your assumptions is correct.
For some background, learn about duality.
Yes, it is exactly the same, you can read the MSDN documentation about the keyword return to fully understand how it works : http://msdn.microsoft.com/en-us/library/1h3swy84.aspx
As to decide which way is better : both are good, but the second version makes it more readable because then your whole code isn't inside an if block. This way, you can see what the condition does really easily instead of reading the whole code of the method.
Indeed the return gets you out of the method, so it is equivalent to the first way you used. Which way is better depends on your code, although generally I would prefer the second version.
Looking at the revised code, the second one is the way to go. While being functionally equivalent, think about the case where you passed in 4 different variables to a function that you want to check. Instead of having a do a nasty 4 level if statement with {'s everywhere, the second method allows you to clean up the appearance of the code and not add unnecessary levels of brackets. If you're writing in C/C++, you can even make this a macro such as VERYIFY_NOT_NULL(x) and make the code nice and neat.
Readable/maintainable code trumps nano-seconds of performance 99% of the time.
I have a similar question to the one posted here:
I have an if statement in an mvc controller that looks like this:
if (submitButton != "Search")
{
ModelState.Clear();
}
TempData["searchParameter"] = searchParameter;
however if the condition is false, TempData["searchParameter"] is never used. Is it a better practice to leave the code as above or put the TempData["searchParameter"] assignment in an else statement?
Put it in an else statement.
It makes the logic flow more explicit and an unnecessary operation is omitted, which affects the performance positively.
Id use the else statement. Makes it clearer and securer if any changes are made in the future.
I guess its also good practice.
In your example, TempData["searchParameter"] is assigned to regardless of of whether submitButton != "Search". Is this the behaviour you are expecting?
If not, an else statement will resolve this for you.
In your specific case, running unnecessary code is never a good idea when it can be easily avoided. It may not seem like a big deal in this case, but it is not a good habit to get into.
More generally, I always use an else statement even when the code flow would be identical without it. For example:
if(null == foo) {
return false;
} else {
foo.Bar();
return true;
}
The else is not strictly necessary, and some code analysis tools will recommend removing it. But I prefer the explicitness of being able to tell just by glancing at the structure of the code that only one of those blocks is actually going to be executed. Without the else, you have to analyze the first block to determine that it is exclusive of the second block.
I understand this is a subjective question, so I apologize if it needs to be closed, but I feel like it comes up often enough for me to wonder if there is a general preference for one form over the other.
Obviously, the best answer is "refactor the code so you don't need to test for falsehood" but sometimes there's no easy way to do so and the "else" branch is simply to continue processing. So when you must have an "if not false" construct, which is the preferred standard:
The not operator
if (!value)
Or the test for false
if (value == false)
if (!value) is easier/faster to follow. Subjective as you said. As long as you are consistent, this is the main thing.
EDIT
One other point to add - omitting the true/false keywords should also (hopefully) force the coder to use better named variables. Bool variables should always indicate meaning or state purpose, such as:
if (MyWallet.IsEmpty)
There is no reason with the above to use == false or == true as it's redundant. The above is human readable immediately.
Far better than having to decipher:
if (MyWallet.EmptyStatus == true) or something ridiculous like this.
I personally like
if ((value == false) == true) ...
cause this is verifying that the statement value is false is actually evaluating to a boolean true...
and, then, obviously, covering both posssibilites adds even more clarity,
if ((value == false) == true && (value == false) != false)
<grin/>
and for those of you who are real gluttons for clarity, and demand incontrovertible readability, I'd suggest
if (((value == false) == true && (value == false) != false) == true)
But seriously, and I just thought of adding this, creating appropriate and meaningful variable Names is the key to this issue. You can easily, in the class where value is declared, add a computed variable as in (say "value "is actually "LaunchMissile"),
public bool AbortLaunch => !LaunchMissile,
then all you need is
if (AbortLaunch) ...,
and then it is terse, eminently readable, and avoids the negation operator.
if (!value)
This is always clearer in my opinion.
if (value == false)
I hate to say this, because it sounds kind of mean, but this normally shows that the person writing the code doesn't really understand the use of boolean values. You don't need to re-validate what a boolean is in an if statement. It's redundant.
(Personally, I would be annoyed at the person too if they named the variable value instead of something more meaningful. I have a feeling what you posted is just psuedo code, I would definitely ding that on a review.)
Edit (in response to a comment below):
It may look trivial, but often it is a sign of much bigger things. Truthfully, most people who do use var == true etc. don't understand. It's just a fact. I'm not saying their stupid or they shouldn't be programmers just that there is probably something that they need to review and learn. The problem is that when logic gets much more complex, not understanding concepts like this can lead to much much bigger problems down the road. Some people say "it's a style." That's fine. The real question in this case is, "How is it beneficial for me to do it this way? What do I or other people get from it?" If you can't solidly answer that question, then you need to ask yourself "Why is this a good idea?"
I would never use if(value == true), so just for consistency I would also not use if(value != false).
if(!value) is clearer and more "elegant", specially if you name boolean variables correctly
isWhatever
hasWhatever
etc
Something like
if (Page.IsPostback == true)
seems redundant to me
Dissenting opinion (kind of)
From a compilation standpoint, you're going to get the same IL, so it really only matters from a readability standpoint.
From that standpoint, the if(value == false) is more obvious to a casual reader, and there is less chance of missing the ! before the bool.
Honestly, I use both approaches, and most times, I make it depend on my variable name. If it still sounds ok to say "not" in place of the "bang", I'm likely to use the bang notation
e.g.
if(!gotValue) {}
//if (I've) not gotValue
//but
if(checkValue == false){}
//If (I've) not checkValue doesn't quite work here grammatically.
I use Not value when coding in VB but tend to use value == false when coding in C#. I find that the exclamation point can sometimes be lost in the name of the variable (e.g. !legal). Maybe it's because I'm, uh, a seasoned veteran.
I would favor using if(!value) because, depending on the names of the variables involved, the "true" case makes much more sense according to English semantics.
Consider one of the examples in this MSDN article:
if(pane.IsChecked)
reads in English as, "If the pane is checked".
However, if(pane.IsChecked == true) reads in English as "If whether the pane is checked is true". That statement that is far less clear in English than it should be.
One of the reasons why we don't write C# code in binary is human readability. If you're given the choice between code that flows well when you read it and code that doesn't, side with the one that is more readable. I don't think adding the "== true" makes this example more readable, and MSDN doesn't think so either.
Granted, this is a rather small example to worry about. But as some of the other answers have indicated, not applying this way of thinking to larger-scale cases can hurt readability.
I would normally prefer if (!value) too, when I know for sure that value is a boolean. But many times it can be a string, or a number.
The number zero would evaluate to false in conditionals in a lot of languages (not all, though); however, the string "0" would evaluate to true. This is a problem particularly in JavaScript, particularly if you receive JSON strings from the server, particularly if the server is written in PHP (because most PHP developers are careless enough to just take values from the DB and call json_encode on them, not knowing that the DB yields strings and not having a clue that all those zeros and ones that they use as boolean fields will be encoded as strings on the other end, thus all treated as true in conditionals).
Rant over. My suggestion: be explicit, especially if your language is the “very dynamic” type (i.e. JavaScript, PHP, Perl).
Whatever one you prefer. Pick one and stick to it.
I am sorry to say, the second just looks stupid to me.
I'd add an extra level, if someone prefers it:
if( (value==false) == true )
:)
I don't think it's all that subjective. I have never seen it recommended in the longer form. Actually all the books and coding guides and "How to be a good programmer" HowTos I've read discourage it.
It falls in the same category as
if (value) {
return true;
} else {
return false;
}
OTOH, all the answers given here make my first statement kinda equal not true.
I favour the if (!value) style at least for evaluating variables or common properties like Page.IsPostback and the like. For anything more complex I tend to parenthesise the expression like thus:
if (!(SomeType.SomeProperty.CallingAMethod(input).GetSomething.BooleanProperty))
Just to draw a little more attention to it.
All in all, it's an argument for Perl-style unless and until keywords.
If the condition is just a check of a single value, then !value is quicker.
However, when the condition contains multiple value checks, I find it much easier to read value == false. Somehow it is easier to parse multiple checks for equality than multiple negations of values.
I actually many of forms possible.
This is not actually how it is written to standards, but this is how I see it:
//if foo is(or exists)
if(foo)
//if foo is true
if(foo == true)
//if foo doesn’t exist
if(!foo)
if foo is false
if(foo == false)
Hence I don’t see == false is redundant.
I prefer the second option, the if (value == false) one.
I gladly use if (~value) or if (not value) in languages that support it, but that ! just merges waaaaay too easily either with the variable name or opening braces or | or || operators... at least in my opinion.
Also, two things:
I never do if (value == true), and I'm aware I'm inconsistent. And although consistency is very important in my opinion, that pesky ! is simply worse.
I think it's really a matter of personal taste, just like the brace-on-a-newline debate. I would never criticize a teammate for silly little things like that, and I have a hard time understanding the people who will.
I use if (value == false)
The ! in if (!value) is so small I sometimes miss it.
Whatever condition an if block should evaluate in order to execute must evaluate to true.
Hence, when value is false, the reason why if (!value) allows an if block to execute is because the ! operator essentially flips the false value of value to true, thus making the resultant condition within the parentheses evaluate into a true one that an if block needs in order to execute.
if (value), if (!value), if (flag == value), if (value == true), if (value == false), depending on what's to be achieved, are valid code. E.g. if (value == true) is very useful when value is a nullable boolean, because if (value) will give a syntax error, and if (value.Value == true) will throw exception if you didn't ensure that value is not null before the if block is executed.
I am also of the opinion that using == inside an if is redundant and I have another suggestion, at least visually, by introducing spaces:
if ( ! created)
Even using OpenDyslexic as font, the not sign ! next to the opening bracket ( can be too close to distinguish it at a glance if(!created).
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
Which one is better (implicit control flow via return or control flow via if) -- see below. Please explain what you see as advantage/disadvantage to either one. I like option A because it's less code.
Flow via Return:
public ActionResult Edit(MyClass class)
{
if (!class.Editable)
return null;
class.Update();
return View();
}
Flow via If/Else:
public ActionResult Edit(MyClass class)
{
if (class.Editable)
{
class.Update();
return View();
}
else
{
return null;
}
}
There's not much difference in this specific example, but in general I like the first approach because it uses a guard clause to return early. If you start adding nested conditions to the second approach you'll see that your code readability will suffer. Guard clauses can go a long way toward reducing the nesting depth, and really enhance the readability of your code.
I personally like the if/else approach. For one, your if statement is a positive, not a negative, making it easier to read. For two, you've encapsulated the conditions in curly brackets, and I'm a fan of that style.
Anyway, it's much easier to follow what's going on in the second than in the first. And that always wins in my book.
I prefer the second approach for the sake of readability and maintainability. Readability because it just reads 'cleaner' to me than the first approach, and maintainability because I don't have to worry about adding curly braces if I need to modify the if or else clauses. Further, the first approach is only 7 characters less than the second approach if you don't include new lines, which hardly seems a justification for choosing the first over the second.
That said, I actually prefer this:
public ActionResult Edit(MyClass class)
{
ActionResult rv = null;
if (class.Editable)
{
class.Update();
rv = View();
}
return rv;
}
It's more code, but I can now set a single breakpoint on the return statement to inspect the value being returned instead of having to set two breakpoints to do the same in the two choices you offered.
Both of those statements are controlling flow via an if statement. It's just a matter of how you handle the condition.
I'm always on the fence when it comes to writing logic statements like this. Part of me likes the first option because it's a little less code. The other part of me likes the second option because it's much easier to follow the flow of logic. With the first option, it's easy to miss the return statement which can lead to manageability issues in the future.
...and for that reason, the second option always wins in my book. It's better to write code that is easier to read and maintain than try to take shortcuts.
I would prefer the one I identify as being the one which EXECUTES less code.
If it is more common to class.Editable being false then I'd go for A.
But this example does not give much of an advantage in either case.
In any given situation a developer should analyze the input and adjust the code to be optimized on the most common input data.
EDIT:
To clarify:
By executes less code I in reality mean is most efficient...
Exit early - I prefer to see all the conditions that will cause the method to exit without doing much up front. I avoid else statements if I can at all avoid it.
This is actually a fairly prominent school of thought among the Code Contracts crowd.
under these circumstances, I would go with option A. In this case you are doing your input validation and then preventing execution of the rest of the code if the input is not valid (not editable). This keeps the entire body of the function out of a big if/else statement and makes it more readable.
However, I would also consider raising an exception rather than retuning a null - that is assuming that passing in a non-editable object into an "edit" function isn't a normal occurrence.
They are both valid options, and one isn't necessarily any better than the other. Which one you choose is, ultimately, personal preference. Yes, Option A results in slightly less code, but overall they are pretty much equal.
In both cases you are controlling flow via an if and a return. It's really a question of how you prefer to see your boolean logic - negative or positive?
Is ActionResult an enum or a base class? If it's an enum, why are you returning null when Edit returns what appears to be an enum? Wouldn't it be cleaner simply to return an ActionResult value that indicates no action was taken because the object wasn't in an editable state?
I prefer if/else, too. Legibility, readability and maintainability stands above anything else, for me.
First option, using return, is better, because:
you have a place to put all guards and preconditions, near your asserts and all that stuff.
for me, it's easier to think "let's see all that can be wrong, and return. From this point, I have everything I need and I am on the Happy Path
if you do use the if / else approach, you have all code in that method / function indented. Add other if, or for, and things start to get funny
One proponent of this method (return) is Marcus Zarra, in the Cocoa is my Girlfriend coding style
I prefer the first option, provided the case you check is a guard/precondition that needs to be met for the method call to be valid. Although you could argue if you should return null, or throw an (Argument)Exception. When a class isn't editable, should it really be a parameter for this method?
Maybe a better option would be to create an IEditable interface and implementing this on the class you're passing an instance of right now.
I also prefer option 1. For me, it reads better like a book. Also I'm always pained by there not being a return at the end of option 2.