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?