Monday, January 4, 2010

Love Hate

Is there a language feature you absolutely adore? For me it's closures. Blocks in Ruby make me warm and fuzzy, and anonymous functions in JavaScript make me giddy. Anonymous classes in Java make me... puke. Sorry, Java just doesn't have good closure support.

If you have a language feature you adore, chances are good that there is a language feature you loath. For me, it is the ternary operator. I don't care which language you are talking about, ternary operators cause me to run in the corner and hide, cowering, and waiting till they go away, on their merry business.

Perhaps it is a bit of an irrational loathing. I like dense code, but I want my dense code to be readable. I find nothing wrong with something like:


str = list.map { |x|
x * x if x
}.compact.uniq.sort.join ","


But write something like:


str = value.nil? ? "null" : "'#{value}'"


And I will refactor your code. Whatever the case, a ternary operator makes me stop and think more carefully about what is going on whenever I see it. Code nirvana, to me, means code that is intuitive and self documenting. Method names like compact, uniq and sort all lend themselves to self documentation. The ternary operator, on the other hand, feels cluttered and doesn't lend itself to immediately understanding what the purpose of the code is.

I will go to great lengths to avoid a ternary operator. I prefer the more verbose if control structure. Ruby makes the deal even sweeter since an if is an expression (like everything else in the language). I will happily pay the cost of the added lines of code, though, if it means I can stay clear of any ternary code.

If you feel you must use a ternary, do me a favor and use just one per expression. Not just use one, do nothing else on that line of code, so the ternary avoids external clutter to make it even more non-obvious what is going on in the code.

Are there language features that make you cringe every time a fellow developer uses it, regardless of context?

No comments: