Avoid "else" as much as possible, use "?:" instead

To have a 10 week old baby Chihuahua takes a lot of time… the housekeeping is not so easy. I need to go up twice at night to let the little baby boy do his stuff. But it’s really wonderful to have such a small dog in my home, I bought a lot of books about how to be a pack leader.. I love reading books about leadership etc so it should be interesting to read those books about packs. Here is a video on YouTube where I play with him, if anyone is interested to see a dog that has the same size as a cat puppy. http://www.youtube.com/watch?v=KOWZjHTBiKo

Well enough about dog talk. I read a book for some days ago about avoiding using “else” to use OOP. Well I try to avoid switch case and if statements as much as possible, thanks to OO it can be easy to handle that. But the interesting part in the book was just about avoiding the use of else even for a simple check.

The example in the book was like this:

if (experssion)
    return something;
else
    return somethingelse;

 

Instead of using “else” the author wanted us to write the following code instead:


return (expression) ? something : sometingelse;


Now we get rid of the “else”, isn’t that cool? But is it really worth it, I mean what is most readable? I think the if else in the first example is easier for people to read and understand, and also for developers that haven’t seen ?: before.

When it comes to returning true and false we could use the following code:

return (expression);

 

“The beauty is in the eye of the beholder” or?
What do you think, is the ?: more beauty full than if else, and is there a reason I should always use ?: instead of if else (Well it will reduce the line of code, but is that so important in this case)? What do you use and can I still use if else instead of ?: and fell like I’m writing beautiful and good code?

Published Friday, May 16, 2008 8:19 AM by Fredrik N

Comments

# re: Avoid "else" as much as possible, use "?:" instead

Friday, May 16, 2008 2:41 AM by Andreas

I use the ?: syntax quite often although the readability decrease with complexity..

One example where I use this is:

string res = obj.IsNull ? "" : obj.SomeProperty;

I think that the ?: syntax is really neat, but I don't think it is more readable when the true/false result parts gets a little bit more heavy..

# re: Avoid "else" as much as possible, use "?:" instead

Friday, May 16, 2008 2:43 AM by Mikael Söderström

Well, in that case I guess I would write "return expression;". ;-)

If there is a simple if statement with two different outputs like in your example, I use "?:", but if there is a more "advanced" if statement, I use if and else.

But what about the coalesce operator?

string firstname = null;

string lastname = "Söderström";

string name = firstname ?? lastname; // Returns lastname since firstname is null

/Mikael Söderström

# re: Avoid "else" as much as possible, use "?:" instead

Friday, May 16, 2008 2:55 AM by Klas Burén

When I studied at the university, my C++ teacher called the ?-operator "hacker if" so I've been brought up not to use it. In certain situations I suppose it's convenient though.

I haven't tested this or anything, but surely the use of if-else or ?: must result in the same IL?

# re: Avoid "else" as much as possible, use "?:" instead

Friday, May 16, 2008 3:02 AM by Erik

I agree as well, if it gets to complex you should avoid the ? : construction and use if else for readabillity.

For a simple test it's nicer to use the ? : construction.

# re: Avoid "else" as much as possible, use "?:" instead

Friday, May 16, 2008 3:10 AM by Johan Normén

I like the ? too... And i guess it's very usefull when not having to advance operations.

Like Söderström says:

"If there is a simple if statement with two different outputs like in your example, I use "?:", but if there is a more "advanced" if statement, I use if and else."

What do you think about?

if(foo == null)

  return (new Foo());

and

return (foo ?? new Foo());

# re: Avoid "else" as much as possible, use "?:" instead

Friday, May 16, 2008 4:16 AM by Dave Sussman

It depends upon complexity. For very simple things I'll use the short form, but for anything more complex I'll use the full form. And by "simple things" I also mean line length; it's all about readability to me and considering who might read my code later on.

# re: Avoid "else" as much as possible, use "?:" instead

Friday, May 16, 2008 9:05 AM by Mike

I simply use ?: when there is a choice to make (returns and assignments, sometimes nested). If actions need to be performed based on a condition, the if-else construct makes more sense. As for readibility, after using both constructs for many years, I find them both equal. I hate verbosity.

# re: Avoid "else" as much as possible, use "?:" instead

Friday, May 16, 2008 9:45 AM by Ryan Lanciaux

I agree with Dave and Mike... it really depends on the project and context. In places where the ternary may be overlooked, I use else. Otherwise I prefer ternary.

# re: Avoid "else" as much as possible, use "?:" instead

Friday, May 16, 2008 10:06 AM by Fredrik N

Thanks for all the comments!

I think it’s too much symbols, but can be useful, at least to reduce the number of lines of code. But I don’t think it’s wrong to still keep the “else” in this simple scenario if people like it more.

# re: Avoid "else" as much as possible, use "?:" instead

Friday, May 16, 2008 10:38 AM by David Fauber

I like it, but its definitely stigmatized.  Kind of feel like I'm smoking in a public restaurant whenever I drop it into some production code.

# re: Avoid "else" as much as possible, use "?:" instead

Friday, May 16, 2008 1:12 PM by Dave

Please. Its the best way to handle sending items into methods.

dosomething(

something1

something2 == null ? 7: 14,

something3 == 3 ? 21: 28);

# re: Avoid "else" as much as possible, use "?:" instead

Friday, May 16, 2008 3:52 PM by Chad Myers

Perhaps I can refine your point a little more, Fredrik: Try to avoid having a situation where you need an else. Sometimes, for simple logic, you need an else condition and it should be very simple such that an ?: operator makes sense.

If you (anyone, all of us) have a big if() and then a big else condition, your design may smell a little and you should reconsider some of your design choices such that you minimize the number of conditional branches. This increases cyclomatic complexity and decreases your ability to test this functionality effectively.

# re: Avoid "else" as much as possible, use "?:" instead

Saturday, May 17, 2008 2:01 AM by Fredrik

I think that multiple return statements is generally BAD and the use of ? is therefore a better alternative in that specific case. When multiple if/else statements is needed the ? operator can actually improve readabillity in the code by reducing the number of sourcelines.

# re: Avoid "else" as much as possible, use "?:" instead

Saturday, May 17, 2008 5:11 AM by Travis

If you're doing returns, I prefer the following:

if (expression)

 return val1;

return val2;

And, if the expression is a simple validation, I'll put the return on the same line:

public string WrappedToUpper(string s) {

 if (string.IsNullOrEmpty(s)) return string.empty;

 return s.ToUppper();

}

Horses for courses =)

# re: Avoid "else" as much as possible, use "?:" instead

Saturday, May 17, 2008 1:07 PM by Rick Strahl

Personally I think we should use ? : only when required, which is when you need a simple expression in place, for things like parameters into other methods etc. But even then I suppose it could be argued it's better to go into an intermediary value.

To me the ? : gets unwieldy very quickly so I rarely use it. In most situations it's just cleaner to have the written out syntax which is easier on the (my) mind to parse.

# re: Avoid "else" as much as possible, use "?:" instead

Saturday, May 17, 2008 1:54 PM by Luis Abreu

well, i do use ?: a lot in my code...but i do also lots of lambda expressions. why? simply because I enjoy compact code. Most of the time, I think it does not decrease readibility, but when I show the code to newcomers, I've noticed that some do have a  hard time reading it...

# re: Avoid "else" as much as possible, use "?:" instead

Wednesday, May 21, 2008 6:19 AM by Joakim Sundén

It is hard to tell, since you omitted the title of the book, what the author intended with her advice, but since you mention that it is about OOP I guess that it isn’t about brevity. If you use “else” chances are you, or your fellow developers, will be more prone to introduce more code in the if-else-statements or even add more conditionals to them when maintaining the code. The use of ?: then serves as a reminder to avoid if-else chaining.

# re: Avoid "else" as much as possible, use "?:" instead

Thursday, May 22, 2008 12:50 AM by Snakeville

What code block do you like more?

First:

           IDictionary oCultureCache = s_oResourceCache[p_sCulture] as IDictionary;

           if (oCultureCache == null)

           {

               oCultureCache = new Dictionary<string, Dictionary<string, string>>();

               s_oResourceCache.Add(p_sCulture, oCultureCache);

           }

           IDictionary oClassCache = oCultureCache[p_sClassName] as IDictionary;

           if (oClassCache == null)

           {

               oClassCache = new Dictionary<string, string>();

               oCultureCache.Add(p_sClassName, oClassCache);

           }

           oClassCache[p_sKey] = p_sValue;

Or second:

               IDictionary oCultureCache = (s_oResourceCache[p_sCulture] as IDictionary) ??

                                           (IDictionary)(s_oResourceCache[p_sCulture] =

                                                          new Dictionary<string, Dictionary<string, string>>());

               IDictionary oClassCache = (oCultureCache[p_sClassName] as IDictionary) ??

                                         (IDictionary)

                                         (oCultureCache[p_sClassName] = new Dictionary<string, string>());

               oClassCache[p_sKey] = p_sValue;

# re: Avoid "else" as much as possible, use "?:" instead

Thursday, May 22, 2008 4:25 AM by Fredrik N

@Snakeville:

To be honest, no one ;)

Regarding to the .Net naming Guidelines, no prefix should be used ;)

I should use the ContainsKey instead of using “as” and compare the object with null to see if I succeed to cast or the Cache has the value.

But I prefer your first code because it’s easier to read regarding to me, but still the beauty is in the eye of the beholder.

I should probably do something like this:

if (!_resourceCache.ContainsKey(culture))

   _resourceCache[culture] = new Dictionary<string, Dictionary<string, string>>();

Dictionary<string, Dictionary<string, string>> cultureCache = _resourceCache[culture];

if (!cultureCache.ContainsKey(className))

   cultureCache[className] = new Dictionary<string, string>();

Dictionary<string, string> classCache = cultureCache[className];

classCache[key] = value;

But it depends on the use, maybe I need more members to get resources and also maybe members to get a list of added cultures etc. In that case I should refactoring the code and it will be less code to add a or save a resource.

# re: Avoid "else" as much as possible, use "?:" instead

Thursday, May 22, 2008 6:50 AM by Donald

I dissagre.

Use of ?: is for smal things like converting bool to on / off string and similar

if

{}

else   is for logic , and is by fare more readable ,

# re: Avoid "else" as much as possible, use "?:" instead

Thursday, May 22, 2008 7:27 AM by Snakeville

Thank you, Fredrik.

But I have some additional questions.

>Regarding to the .Net naming Guidelines, no prefix should be used ;)

Unfortunately, the company, for which this code was written, uses other guidelines.

BTW, where can I find .Net naming Guidelines you're talking about?

>I should use the ContainsKey instead of using “as” and compare the object with null to see if I succeed to cast or the Cache has the value.

What if _resourceCache contains a key we are looking for, but a corresponding value is not Dictionary<string, Dictionary<string, string>> ?

And what are advantages of ContainsKey?

# re: Avoid "else" as much as possible, use "?:" instead

Friday, May 23, 2008 12:58 AM by Fredrik N

@Snakeville:

Here is MS internal guidlines: blogs.msdn.com/.../361363.aspx

>>What if _resourceCache contains a key we are looking for, but a corresponding value is not Dictionary<string, Dictionary<string, string>> ?

By using Generics you know that the value is of a specific type.

>>And what are advantages of ContainsKey?

Well, it  will check if a specific key exists in the list, and I prefer to see if the key exists or not when I want to update or add a new key value pair.

# re: Avoid "else" as much as possible, use "?:" instead

Tuesday, November 04, 2008 6:52 AM by Stefan Bergfeldt

The number of lines of code is completly irrelevant in this case, since both examples will be compiled to the same MSIL-code. I prefere the if-way to do it, but there are a few cases when I use the ?: instead. It basically depends on the situation.

When writing ugly-as code with conditions in the presentationlayer (ie in an <%#eval()%> statement, I think you're bound to the ?: (or of cource moving logic to codebehind where it belongs)

Leave a Comment

(required) 
(required) 
(optional)
(required)