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;
    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?


  • 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..

  • 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?

  • 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.

  • 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.

  • 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.

  • 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.

  • 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.

  • 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.

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

    something2 == null ? 7: 14,
    something3 == 3 ? 21: 28);

  • 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.

  • 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.

  • 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 =)

  • 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.

  • 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...

  • 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.

  • What code block do you like more?
    IDictionary oCultureCache = s_oResourceCache[p_sCulture] as IDictionary;
    if (oCultureCache == null)
    oCultureCache = new Dictionary<string, Dictionary>();
    s_oResourceCache.Add(p_sCulture, oCultureCache);
    IDictionary oClassCache = oCultureCache[p_sClassName] as IDictionary;
    if (oClassCache == null)
    oClassCache = new Dictionary();
    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>());
    IDictionary oClassCache = (oCultureCache[p_sClassName] as IDictionary) ??
    (oCultureCache[p_sClassName] = new Dictionary());
    oClassCache[p_sKey] = p_sValue;

  • @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))
    &nbsp; &nbsp;_resourceCache[culture] = new Dictionary&lt;string, Dictionary&lt;string, string&gt;&gt;();
    Dictionary&lt;string, Dictionary&lt;string, string&gt;&gt; cultureCache = _resourceCache[culture];
    if (!cultureCache.ContainsKey(className))
    &nbsp; &nbsp;cultureCache[className] = new Dictionary&lt;string, string&gt;();
    Dictionary&lt;string, string&gt; 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.

  • I dissagre.
    Use of ?: is for smal things like converting bool to on / off string and similar
    else is for logic , and is by fare more readable ,

  • 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> ?
    And what are advantages of ContainsKey?

  • 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 statement, I think you're bound to the ?: (or of cource moving logic to codebehind where it belongs)

Comments have been disabled for this content.