- Feature Articles
- CodeSOD
- Error'd
- Forums
-
Other Articles
- Random Article
- Other Series
- Alex's Soapbox
- Announcements
- Best of…
- Best of Email
- Best of the Sidebar
- Bring Your Own Code
- Coded Smorgasbord
- Mandatory Fun Day
- Off Topic
- Representative Line
- News Roundup
- Editor's Soapbox
- Software on the Rocks
- Souvenir Potpourri
- Sponsor Post
- Tales from the Interview
- The Daily WTF: Live
- Virtudyne
Admin
Grin @ the cruel semi-colon-directly-after-the-for-statement-newbie-trap.
Drak
Admin
The coding conventions for Java suggest same-line braces, those for c# suggest new-line braces. It's just a different philosophy, not a question of the century.
Admin
if (typeof(e) == typeof(DataNotFoundException)){...}
Maybe you can't do this because typeof returns a string? You'd be comparing the memory addresses of the two strings, which are different, even when they contain the same information ("DateNotFoundException"). That's why you have the .equals() method.
Disclaimer: I don't even know C#, I could easily be wrong. [:$] In Java the above is true tho.
Admin
I've seen people do something like this anyways:
int i;
for(i=0; i<10; i++); {
blah();
}
So I don't think that saves anything. Also, I think in the following situations same line curly braces give me a headache:
if (someLongBooleanConditionHere
&& someOtherLongBooleanCondition
&& somethingElse
//...
&& lastPossibleLongBooleanCondition) {
something();
}
I also thing with a bunch of nested blocks its much easier to match opening and closing braces:
if (something)
{
if (somethingElse)
{
if(somethingElse2)
{
if(somethingElse3)
{
//...
}
}
}
}
Admin
the only thing more annoying that reading code with the brace-style you hate is reading arguments about brace-styles
Admin
~*honk*
Admin
Hm. I occasionally wonder if the use of this particular forum software is Alex's way of being ironic. [:^)]
About the WTF: (to keep this post on topic)
It kind of reminds me of the fire brigade line.. You know, a bunch of guys line up, handing a pail of water to the next guy and so on...
There is no defense to this code... It's just.. bad. Sure, it works, but then again, so does obfuscated C and bubble sorting. That doesn't necessarily mean it was the best way to handle the task.
Admin
On style:
I don't know why, but the style
[code language="C#"]
if(foo < bar) {
baz(foo,bar);
}
[/code]
Annoys me. To me, it is much more readable to do it as follows:
[code language="C#"]
if(foo < bar)
{
baz(foo,bar);
}
[/code]
It just seems cleaner to me...
Admin
Hnmm, You bring up a good point. I can't even begin to count how many times I have been cought by that :) Only to slap my forehead hours later and exclaim "D'oh!"
Admin
Admin
Get over it and use a code formatter if it really bothers you, it's standard practice among Java developers, and we (the royal we) don't like wrapped braces.
Who defined it? no one, it grew into the standard by excommunicated consensus among the vast majority of experience java developers "out there". In fact, almost all java code formatters you’ll find, do it by default.
Admin
WTF!
The forum software sucks, it just wiped out what I wrote when I submitted it so all I got was the quote! [^o)]
Maybe someone should go through the forum software for new WTFs.
Admin
You're kidding, right? I've done that twice, maybe three times, in 18 years of C/C++/C# programming -- and caught the error the first time I looked at the code for an error. Basically, it just seems wrong when you look at it.
I imagine it's the different between just coding in a language and actually thinking i in it. An example in a natural language would be:
1. "If I was President..."
vs.
2. "If I were President..."
A native speaker of proper English would know the #2 is correct, even if they didn't know why. Someone thinking in a different language and translating into English would often pick #1 as acceptable.
Admin
Nonsense. Like everything else about Java, it was defined by dictum by Sun (who do you think wrote those original code formatters?) Sun, of course, is made up of hard-code UNIX people, so what coding style would you think they would go for?
Admin
That is amusing. You must be an offspring of Juval Lowry.
Admin
This only applies to Java, where Exception is the base class for both checked and unchecked exceptions (i.e. RuntimeException)-- catching Exception in Java will give you problems when a runtime exception such as OutOfMemoryError (i.e. unchecked exception) is thrown.
As far as I can tell, this is C#/.NET, which doesn't have the concept of checked/unchecked exceptions.
Admin
[li]
[Z]
Ahhhhhhh!!!
Admin
There's no typeof operator in Java. But there's one in JavaScript, which really returns a string. But in JS, you can use == to compare strings, so no trouble.
Also, Java has 2 types of unchecked exceptions. The exception hierarchy has
Throwable (checked) -> Exception (checked) -> RuntimeException (unchecked)
|-> Error (unchecked)
Really serious problems, such as stack overflow or out of memory, are Errors and thus aren't caught by a generic catch(Exception). RuntimeExceptions are stuff like division-by-zero, cast type mismatches or index out of bounds.
Admin
i guess you guys simply write up your programs and never read them again.
<FONT style="BACKGROUND-COLOR: #efefef">in the process of code review, source code that has less lines are definitely easier to read. (i can forsee someone put up a one-liner here. what i really mean is, turn the 'word wrap' option on if you use notepad). for this very reason, we at work use LPS (line per screen) to measure code readibility.</FONT>
for (int i=0;i<size;i++) doStuff();
is certainly easier to read than
for (int i=0;i<size;i++)
{
doStuff();
}
also try reading the above code double spaced!
interestingly, sameline-brace-haters tend to screw up the one liner :)
for (int i=0;i<size;i++) doStuff();
{
doMoreStuff();
}
you may be lucky if "size" happens to be 1. now for us sameline-bracers,
for (int i=0;i<size;i++) doStuff(); { //<-- uggh, doesn't seem right
or, if your for statement is too long, use an indented linebreak:
for (................)
doStuff();
also notice the closing brace aligns with the block identifier, which is more meaningful than meeting the open brace.
if ()
{
}
else
{
if
{
if
{
//...
}
}
}
now try to match up the braces. for oneline bracers, we read one less line per block to determine the identifier. on one screen, we see more meaningful code as opposed to space wasting braces.
Admin
fyi world, the only proper way to punctuate C/C++ is like so:
if (something)
{
do some stuff;
do some more stuff;
}
else
{
do some other stuff;
do some more other stuff;
}
// Generalize for loops, switches, etc.
This is based on "proper" PL/I and Pascal style. Even though it's the best way, I may be the only one in the world who uses it. [:(]
Whitespace is not actually infinite, but there's plenty to go around. I started programming on punched cards [:$] but I didn't worry about the "wasted" space then, either.
Admin
The rule of thumb is that you should only catch the exceptions you know how to handle. Otherwise send them along to whoever called you. By catching Exception you are stating that you know how to handle any error. This is really dicey with .NET since it doesn't have checked vs. uncheck (runtime) exceptions, so by catching Exception you are catching everything including when you run out of memory for example. This could cause some very mysterious behavior.
It's probably best to look at the documentation for what you are calling to see what specific exceptions could be thrown and code for that.
Admin
Wrong moosebreath! At least in the manly language of C++ you do this:
Admin
Well, to be honest, It hasn't cought me in the last several years. I generally see it before I save and compile. I had actually learned C while working for a hellhole game company (which, for obvious reasons will remain nameless, but it should be mentioned that any of the titles they created you wouldn't recognise if they slapped you in the face .. and aside from that I'm embarrassed to have my name associated with them, hence, none of the titles have credits), when I encountered the error. I was in a situation where any debugger was impossible (fullscreen w/o a windowed option... I didn't write the graphics engine ...) All I could do to debug the code was watch the behavior and adjust accordingly. I finally found the bug after many hours, and couldn't believe something so simple caused it.
Come to think of it... That was the only encounter. It is easy to miss, though.
Admin
<FONT style="BACKGROUND-COLOR: #efefef">That code has the distict smell of "On ERROR Resume Next"[:D]</FONT>
Admin
Heh. And then watch your program act very strangely if you get an IPF somewhere...
>P@@F<
Admin
The only correct way to use braces is as follows:
public void doSomething(int aValue) {
if (evaluate() > aValue) {
...
} else if (evaluate() < aValue) {
...
} else {
for (int i = 0; i < 10000; i++) {
System.out.println("Newline braces are STUPID");
}
}
}
So that settles it.
Admin
Who actually still codes in an 80x25 line window??? Whether I'm in windows or unix environments, my development environment / terminal emulator can easily support much larger sizes. If no part of the function will conceivably be used anywhere else, why split it out into another function?! Then I have several places to go look instead of simply following the code from top to bottom, have to pass a bunch of parameters and / or state information between them, etc.
Admin
This reply is from the perspective of my current work environment:
Regarding catching Exception in C#, there isn't a single instance in any of the production code here that actually DOES anything about the exception other than present the error info in a nicer way than .NET does when unhandled (or email it to someone). Yes, there may be some cleanup code in the Finally, but nothing in the Catch block ever does anything meaningful to attempt correcting the situation.
In the case of a class library, we mainly use functions that return a boolean value indicating success. If I have a function that attempts to do x, y, and z, and one of those things fail, I don't want to write try/catch blocks around every call to the method for each possible failure type; it's nice to be able to simply use them in conditional statements. I usually only care if it worked or not. In cases where I want more detail, a by-reference string or enum parameter can be stuffed with whatever else I need to know. I know that isn't 100% "proper usage" , but it is the philosphy here and I'm pretty used to it.
If it's an out-of-memory or other truly "unhandleable" exception, who cares if I catch it or let it propagate? The pooch is already screwed... so if I want to attempt to log the exception, no matter what it is, this approach seems to work best.
Admin
Admin
2) Catching Exception in Java:
Yes, you can do this, and in some cases, you even require it. The hardcore exceptions that you should never catch are not Exceptions, but Errors, so you should never catch Throwable nor Error. However, it is "reasonably safe" to catch an Exception.
When writing code that invokes external random code, you'll definetely will want to catch Exception. Say you write an app-server. Do you want exceptions generated by the user's application go to the top of your code? No, you normally want to catch Exception, log it and handle the error (i.e. writing servlet invoking code, writing out an HTTP error response).
Admin
and, finally, to sum up the coding style thread, here's my favourite quote (from gaim's HACKING file):
"Coding styles are like assholes, everyone has one and no one likes anyone elses. This is mine and if you want me to accept a patch from you without getting annoyed you'll follow this coding style. :)"
Admin
<font face="Georgia">IDEs and environments don't enter into it. It doesn't matter if you code in 80x25 or not. You still have to hold the function in your head, and it just seems from my experience that 80x25 is a much better size to hold than what you can fit in an IDE at eyestrain font sizes.
It's a rule of thumb, but it's a good one. If your function is complex enough to require more than this handful of lines, then it's very likely to be too complex. Either you're using a low-level language like C or C++, where every damn wheel has to be reinvented every damn time, or else you're fitting too many concepts into what should be a single function. If you're not deliberately contrary, the discipline of forcing yourself to code short, simple functions pays back a thousand times. Remember: every character in your code will be touched eight times: once when you write it, the rest when you're debugging it. It's better, therefore, to put the work in early to tidy it up and Keep It Simple, Superuser.
Having said this, I accept everyone's right to disagree. In general, the older and wiser you get, the more you tend to agree with this sort of rule of thumb, but there's no rule that says everyone has to be old and wise.
</font>
Admin
leaving aside the coding style, which is a matter of personal/comany preference and a flame starter, there is no other problem than some useless code (well, if one's using a sane programming language, not some weird stupid copy of the latter, anyway); that is, the inner try-catch block is useless (the exception has already been thrown once if it's been caught, hence it's useless to "try" throwing it again). No humor here, just a newbie which is over-cautious; the code fragmens shouldn't create any bug in Java, but when M$ is involved, one can expect anything....
Admin
FWIW, I just worked on some non-company code for the first time in the VS.NET 2003 IDE, which used same-line braces and it auto-formats braces on their own line as you add new braces to the code... There is probably a preference in the options dialog to change that, but I've never looked, and just stick with it.
Agreed about opinions, brace styles, and a-holes... Everyone has one.
Regarding function line density, I do see your point, I just haven't had problems dealing with large functions in my experience.... Perhaps some day I will be old and wise too. :)
Admin
First, you make a class for exceptions that you don't otherwise handle:
You use it like this
Admin
It amuses me that so many programmers fight over something so trivial. We all code for our environment. Fighting over whitespace styles is like fighting over programming languages; many old-school purists (fogeys) would say "C or nothing, 80x25 terminals and same-line braces", while many people shudder at the thought and feel constricted by it. I laugh at that, who cares what style someone else uses? Get a code formatter, and stop bickering - you won't get everyone to listen to you anyway.. it's unproductive to fight over it.
As for the actual WTF, it smacks of typical java hack-work; no idea what someone else's exception does? No time to check the references? Just catch it all and pray you aren't breaking something. That is why I feel that the exception model is not mature enough for production coding, we still don't have an easy way to know what ought to be caught by what, when and why. Still, it's a damn sight better than returning an integer error-code <shudder>
PS: It also amuses me that I read through all the comments and found enough ranting there to add my own $0.02, even though with inflation it's probably worthless. Just goes to show that even though I don't care what your coding style may be, I still hate to hear people whine about it.
Admin
I said easier to read, not identical. I imagine that the loose matching wouldve been the authors intent had he been competant ;)
Generally catch(HorribleException) should be interpreted as "if something horrible goes wrong then do this". DataTooHorribleException and PhotoTooHorribleException generally would be treated similarily.
Admin
Admin
Precisely. Clean easy to read, as opposed to those tree-hugging hippies who goes like "oh, why not waste a whole line on a single character. It'll make it look more confusing and waste space on our screen, so that must be the sensible thing to do. Hell, it even makes it harder to see what expression the '}'-char belongs to, so let's do it! Let's make 10000 allmost empty lines of '{' just to confuse the enemy!! YAY!". You lame no-good hippies can go back and live in your caves, and leave us real people alone!!!! Damn newbies with uneducated crap ways of writing code!!
(actually i wanted to say it was just a matter of personal style, but i got kind a' caught in the moment.)
Admin
The "only correct" way of handling braces is the original method in the file. If you make the file, then you put down the rules.
Admin
Yes, please, no more on the braces. Seriously. It's gotta stop.
If you have time to worry/debate about that stuff, then you really just don't get it.
Let's see if we can all pretend that we really know how to program and focus on the actual CODE itself .... i know that sounds crazy, but give it a shot! You might find out that you become more productive!
Admin
I'll bet Python programmers do argue about how many spaces to use for indentation. :-))
Felix
P.S. Flamewars may be pointless, but they're soo much fun...
Admin
Jeff S wrote: "Yes, please, no more on the braces. Seriously. It's gotta stop.
If you have time to worry/debate about that stuff, then you really just don't get it.
Let's see if we can all pretend that we really know how to program and focus on the actual CODE itself .... i know that sounds crazy, but give it a shot! You might find out that you become more productive!"
Yes - Please! Alex, I think you need to move the messages about same-line braces to a separate side-bar WTF thread... [:@]
Admin
Screen estate isn't.
Admin
If you dont code on a portrait monitor (I am fortunate that works provided me with two nice hp ones which rotate to portrait) then you are a noob ;)
The code still never goes off the side of the screen, and thats with 120dpi fonts too :P
Admin
catch this at http://www.imagetherapists.com
Admin
As a matter form, I always uses braces even for one line for an IF or an ELSE or whatever. <font face="Arial">I've seen too many cases where I've changed this:</font>
<font face="Courier New">if (something==true)
doSomething();
else
doSomethingElse();
</font><font face="Arial">and decided to write to a log as a part of the else:</font>
<font face="Courier New">if (something==true)
doSomething();
else
doSomethingElse();
LogThis(this);
</font>
<font face="Arial">oops. LogThis will always get performed.
Even if it takes up space, for readability and for comfort sake, I always will write:</font>
<font face="Arial">if (something == true)
{
doSomething();
}
else
{
doSomethingElse();
}
I actually wish there were EndIf Nothing like a large method and having
to close your last Else, three if statements and you end up with something like</font>
}
}
}
}
}