2 September 2004 - 17:00A Discussion on Java Style Standards
Today I read the Sun Java Coding Standards paper, and I agreed with everything except one point. I’m a big fan of coding standards. Although sometimes I run into small issues with them, I find that they make things easier to read and understand. The biggest issue that I find most people have with coding standards is that it doesn’t match their way of coding. I can understand their complaints to some extent but in general I think it works best if a project is in one format. Usually coding standards are fairly strict and cut down on a lot of the “fun” things that you can do: assignments inside statements, goto’s, multiple statement lines. Now, on to Sun’s surprise.
The only part that I was shocked to see was:
if (condition) {
return x;
}
return y;
should be written as
return (condition ? x : y);
I was stunned. Although the inline if was something that I was familiar with, I had no idea that someone would promote it. I personally like it, but I have been told by many people to avoid it.
Background
For those who don’t know about this ternary expression, it works very similar to an if statement. Something like this:
(condition ? value1 : value2)
The condition is evaluated. If the result is true, value1 is returned. If condition evaluates to false, value2 is returned. There’s only one problem, it’s not an if statement. The following won’t work.
(a == b ? System.out.println("Some problem"), return a);
The inline if must have both results evaluate to the same type. In that case the first is void, and the second doesn’t even evaluate to anything. Both are not good. In this place you need an if/else.
Summary
Anyway, I’m going to use it more. I always hate code that looks like it’s holding you by the hand and trying not to be complicated. Now I can throw a nice curve in while still keeping the code clean.
No Comments | Tags: Programming