- 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
This is Java, Not C#. In Java, Throwable is top of the exception hierarchy, Exception is not a super class of Error, which is thrown when OutOfMemoryError occurs, and most other spontaneous exceptions.
With that being said, in Java Integer is the c# equivalent of nullable int (int?), this method will incorrectly catch NullPointerException as log it as NumberFormatException.
In reality, there are ways to do insert this code post compilation, or adjust runtime to do this.
Admin
Let us remember: outsourcing is never about quality of code; it's about money. Rookies (the people doing outsourcing coding) work cheap; experienced, competent coders cost real money, because they know what they are doing.
One's IT infrastructure is too precious to outsource. But what do I know: I'm only a 30+ year IT veteran.
MK
Admin
Presumably is is changed for each method, otherwise the isValidString method is being logged as isValidInteger.
Admin
You're going to want to call this about 100 times a second, because if the Universe ever stops being deterministic you'll want to know right away that your calculations and logic are no longer reliable.
Where it really gets interesting, then, is the code that calls isUniverseStillDeterministic. What are you going to do when you get a false? Better yet, how do you test that branch in your code? And if it does happen, you better log as much detail as possible to help unravel some of the fundamental problems of quantum mechanics.
Admin
Admin
Admin
This would have been a valuable function if those Java jerks hadn't made the Integer class final. If you wrote a class like this:
... this method would catch it. And log the details effectively except for eating the stack trace and not letting you know where or why it failed. Awesome.
Admin
People who are new to programming often don't entirely grok the concept of using a literal value directly in an expression of some kind; you'll see them constantly creating useless variables because they don't understand that literal values can be used outside of assignment operations. Such people also have trouble with using the return value of an expression or method call directly in an expression, without assigning it to a variable first.
This is particularly common with students learning Java with no prior programming experience, which is not a slight against the language itself, but more against the way it is taught in American universities.
Admin
The default config of some IDE (maybe Visual Studio) gives you warnings for the second code-block because it thinks you don't have a guaranteed return condition.
Admin
Logging every function call is not enterprisey enough. They should have converted the integer to XML and back to as a validation test.
Admin
OK, my guess is that whatever IDE they were using was generating method templates for them that included all of the logging, methodName, and other general crap.
Is anyone familiar enough with CMMI to know whether all of this logging is "mandatory"? I worked for an organization that was working towards their certification, but that was 10+ years ago and I purged all that from my brain.
Admin
I read recently that Korean Air Lines found that they had a safety problem stemming from cockpit communications between co-pilot and pilot. Apparently the polite words in Korean slowed down certain kinds of problem reports, which can be catastrophic in airlines. Switching to English, with its lack of inherent power considerations, brought their safety record into line with international standards.
I suspect that the offshore development enterprises have a similar issue: being cheap, they hire lots of moderate talent. Having large teams, they hire lots of management. Having lots of managers, they implement CMMI-style processes. Given a soulless process, pointless bureaucracy, arcane specs, and a huge team of co-workers, I suspect that the individuals fail to take pride of ownership. It's the only explanation I have for the amazingly bad code quality.
Admin
They should have used
to catch the null as an NFE...
Admin
I like the fact that this can return false:
Admin
hehehe, I would not be too surprised if the management at the outsourcing company had something in place where developers were rewarded on defects per KLOC (kilo-lines of code). Solution, write your code unnecessarily long and add redundant methods.
Admin
Hmm, I think I have an improvement to the code:
public static boolean isValidNumber(Integer number) { methodName = "isValidNumber"; Logger logger = LoggingHelper.getLogger(LOGGER); logger.entering (CLASS, methodName);
:)
Admin
This totally made my day. I'm just glad I wasn't drinking anything when I read your post. Thanks.
Admin
Admin
You often see this pattern in embedded systems....
Admin
ioccc,
You might have done that as a joke, but to actually improve it a lot (from the error handling point of view, of course), change Exception ex to RuntimeException ex, and rethrow that after logging, instead of returning false. Or just get rid of the generic catch all together, and let unexpected exceptions go up to a level that can handle them right. (and decide if you should warn the user and/or close with a fatal message, or whatever).
Of course, the method would still be useless, would have ridiculous logging and all... But at least it would be handling its exceptions right.
Admin
Of course, you should always avoid nullpointers instead of catching them. Java compilers even have warnings for unchecked potencial null references. But anyway, catching it would be better than the original.
Admin
You guys are missing TRWTF. The CTO said the people responsible for this abomination will make his team look bad. Imagine what quality of WTFs we'll get from their team.
Admin
Sounds similar to ISO 9000 and all of its spawn. It's easy to standardize measurements, documentation, etc. Unfortunately, it's not easy to standardize design, innovation, or creativity.
Admin
Not Visual Studio. At least not any version of it I've ever used.
Admin
I'm pretty sure it cannot... floats don't "miraculously" change value, the bits are still the same. What happens to floats are that sometimes the arithmetic is "fuzzy" and the result of a function may not be exactly what you would expect. The value of a float in memory will always be the same (unless the memory is faulty).
Admin
It wouldn't even compile pre Java 5, but from 5 forwards, we get auto-boxing of primitive types (similar, but not quite like, auto-boxing in C#).
So if you were to pass an int variable, say x, as an argument to a function taking an Integer, the compiler would create an Integer object initialized with x. Same when assigning an Integer to a int (or any standard primitive wrapper to/from an actual primitive type.)
It's sort of a helpful feature, but it can cause a NPE (and many programmers are awfully unaware of that.) I don't quite like auto-boxing as in Java because, quite frankly, there is a lot of pre-5 code out there, and most Java programmers are "stream-of-consciousness" programmers. That is, they just spit code without considering things like this:
int i = integerObjectComingFromSomewhere; // NPE waiting to happen when careless.
Autoboxing would work wonderfully if java had some sort of "elvis" operator, but it doesn't so.... one has to be conscious about the possibility of nulls when relying on autoboxing.
Other than having an Integer argument (which is not necessarily a bad thing), the method is a wtf simply because of its excessive usage of logging statements. Worse still, the log statements are of the "Captain Obvious" type, completely useless.
When you see code like that, it is usually a sign of lack of experience programming and/or using a debugger.
Another thing, kinda debatable, is the reliance of an exception for determining if a string is numeric or not. Exceptions are expensive.
But there aren't any clean alternatives in Java. We could use scanners, parsers or Character.isDigit in a loop, but these are awfully clunky and easy to get wrong. Having an optimized, built-in "isNumeric" method somewhere (anywhere) in Java that does not rely on exceptions, that is something I just don't know why it doesn't exist in Java. Oh well.
Admin
Thank you, Ath! I've decided that this will be my next opensource project.
I'll try to use as much of the content I find here, and I'll keep Alex and the gang updated whenever they require it.
Please disregard my nickname this time.
Admin
That depends on context. If some situations, you do want to throw an exception (and let/pray an upper-level exception handler catch it).
In other cases, what is required is to return a boolean value instead.
Again, it's all dependent on the context, on what the code is supposed to do.
Admin
Famous last words ;-)
And then there are values that are by definition equal to nothing, even to themselves:
outputs false.
Admin
You know, some other WTF programmer is going to see this method and try to use it as it might have originally been intended - to check the validity of the value entered into a text box. But since the method only takes an Integer parameter, he/she is going to parse the text into an Integer to get around the compiler error.
Hmm...
Admin
Hum, no, sorry.
For an unexpected error, you should't return false. It's a very bad pattern. Common, but very bad nevertheless.
Returning false, null, -1 or any other stupid values when unexpected errors happen, removes from the caller the opportunity to properly handle the error.
Let's think of the indexOf function in specific collection, for example. When it can't find a value (an expected and banal error), it returns -1. If anything else happens, it should throw an exception. That's the correct behavior. I can check for -1, and I'll know that it doesn't have what I'm looking for.
If it just decides to return -1 on weird errors, when it returns -1, all I know is that it couldn't find it, but can't be sure about the reason. Most of the time it doesn't have the item we're searching, but maybe the collection detected some internal inconsistence, had a nullpointer, or whatever. That's a programming mistake, and as such, has to go up as a runtime exception.
Admin
when the parameter is null.
Admin
Excellent
Admin
Admin
If it were just wanting to assign something to a variable before use, it'd be relatively harmless (actually, I find that practice to be useful sometimes as a sanity check). The problem is, it's being assigned to a global, and, because it's a static method, that's got to be a static global.
Now, let's assume this method is in a class called TestMethods. Since you can't have a static class (annoying), you can create instances of TestMethods, even in different threads. Now, let's assume that there's another function that takes a while. Say,
public static void TakeALongTimeAndLog(){ methodname = "TakeALongTimeAndLog"; Thread.sleep(3600); logger.fine(methodName + " slept 3600 seconds"); }
Say you invoke TakeALongTimeAndLog in one string, and then isValidNumber in another. Guess what TakeALongTimeAndLog thinks the method name is?
Admin
Admin
Having been through a CMMI evaluation in a Level-4 rated origanization, I have to say: CMM(I) is not about the code, it's about the process. Level 5 organisations are not necessarily good at coding, they're good & theoretically self-improving process junkies.
Admin
But, in this case, the (very bad) programmer thinks that his exception-handler will only catch (expected) number-format exceptions, and thus returning false when the provided Integer isn't an integer. The problem is that if you can cram the data in question into an Integer, you've already tested every case except '== null'. There shouldn't be an exception rethrown, because this isn't a case of a valid exception being handled, it's an attempt to exploit exceptions to test an expected condition.
Admin
This code is incorrect. It can return true - a result with which any person knowing quantum mechanics (or QED) would disagree.
Admin
Couldn't you just use regex matching to match a string to "\d+.?\d*" or similar? Or, for integers only (as here), just "\d+"?
Admin
Adding the catch for the format exception and returning false is abusing exceptions, but isn't a error handling mistake.
That would be right, if he added the correct catch case. Since he didn't, it can catch anything. Even a bug on Integer class or something. Thus, runtime exceptions should ever be rethrown, even if they are very unlikely to happen. It's not any difficult, just catch only what you need, and let the rest go up. If you want to, catch it, log it, and let it go.
Don't ever assume "no other exceptions can happen". Even when true, it's a horrible pattern, and will lead to future very hard to detect problems once the code is changed.
Admin
Admin
What am I missing here? What's wrong with that approach? Or is it just that their procedures forced that style over the equivalent if/else?
Captcha: No-one gives a crap what your captcha was.
Admin
As a previous poster said, CMMI does not say a word about coding or logging practices. It's all about the process followed to create software.
This process will be documented and measurable and thus will be manageable and repeatable (I stil have issues with the fixation on having to measure something to be able to manage it, but...) So yes, a CMMI level 5 organization can assure you that they have the right processes in place to always deliver the same level of quality. Even if it is absolutely awful.
Admin
Admin
hmm. lets use this code in a server app or something? with a lot of request per second :) and see what happens? :D
Admin
touche
although, I'd use this as an example instead:
As that's how I verified it, more closely resembles the actual test (comparing the same variables).
"Miraculously" this does work:
(and yes, I use c# not java, but the results should be the same.)
Admin
I kept thinking 'I've seen worse' as I was reading, thinking thats ok, it'll catch strings and things, till I saw (Integer number). haha
Admin
Nope. See e.g. http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Float.html#equals(java.lang.Object):
Admin
No, but you can always deduce that it did from the logs on the ground.