- 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 not a WTF. Period.
The real WTF is that some people think it's a WTF. If you think it's a WTF, you're probably a WTF coder without a clue on good style.
Admin
@Greg Mitchel:
Maybe you still can learn a thing or two from your companies rockstar. I am glad he is the rockstar in your company and not you n00b.
Admin
Throwing the ArgNullEx allow for a more meaningful understanding of what actually went wrong in the program, instead of tracing through the method to find potential spots where the NullRefEx could have popped.
TRWTF is the <exception cref>'s. Who ever cares to read that stuff. Its like RTFM.
Admin
Oh right I get it, you're not prepared to put an elementary argument check at the top of your method because somebody else's code (always somebody else's, you're fucking perfect) may pass a null in by accident.
What you seem to be saying is that before a parameter is passed to your method (nice and clean without all that tedious parameter-checking) it is necessary for the calling code to sanitise its own data before passing it in.
So that means that rather than have the null pointer check (or whatever other fucking parameter sanity checking that might or might not be necessary) in the method which does stuff on these parameters, it's better for all the sanity checking to be done in all the client code instead?
So if a method is called a couple of dozen places in the program (or programs, we seem to be talking about an API written for applications written by chimps here), it is better to duplicate that sanity checking in all those dozen places instead of checking it in "your code" (which would offend your selfish sensibilities)?
You're a cunt.
Admin
The real problem is that there is an ERP system written in C#.
There is coffee on my monitor.
Admin
I hope for your own professional sake that you are trolling. If not, I hope I never have to work on your code.
Its not a modicum of expedience during development, its forever after that you gain this additional insight to what is actually happening.
Micro-optimization is largely useless. Knowing specifically why an error occurred, after code has been deployed to production and cannot be debugged, is invaluable.
Stop throwing 50cent words around to make yourself sound correct.
Admin
The checks are a red herring; they're an hack made to solve a problem that should have been solved by the type system, which should ensure that if a variable was passed to the library, its value couldn't possibly be a NULL in any circumstance, or it would fail to compile.
Admin
You. I better watch out for you.
Admin
Admin
Admin
Let's say I have this:
void foo(MyObject a) { a.MyInstanceMethod(); }
There is almost no conceivable reason to test for null there if all you're going to do is throw a NullReferenceException, since the stack trace (possibly stored on the production client) will tell you where it came from. Although at that point, it might be inlined...
My philosophy here is not to check unless you know you're gonna need it.
Admin
I was going to post that, but I thought it must be a troll...surely. It really bugs me when people actually say "It's a mute point" though.
Admin
As for the discussion, I'm going to have to agree with Severity One. Mainly because I don't think null-checking is a form of sanity-checking, since calling a method on a null object is never not insane. That's why Java and C# automatically freak the fuck out* when it happens.
*I admit this is a slight exaggeration for "throw a NullPointerException"
Admin
TRWTF, right here... Of course it's a bug and it's not more or less of a bug regardless if a NullReferenceException or if an ArgumentNullException is thrown. The only difference is that the latter tells more about where and what the problem is than the former.
Admin
NaN is right out.
Admin
Admin
Stack traces only tell you what line of code it failed at. A properly annotated exception specifically crafted to include all the relevant information tells you what the objects were that were null, or out of range, or otherwise breaking the contract between method and client.
Just including in the comment "This method will break if you send it data outside of the following constraints" is IMO not sufficient. It may not be code-chimp's direct fault that under certain circumstances something untoward has caused this contract to break, but software design is not a pissing contest - it's much more convenient that as soon as it has been established that the numbers are out of range, an exception be thrown (be it NullPointerException or what the fuck ever) which the client code would immediately catch.
The nature of the exception itself, and specifically what causes it, would also be documented in the header (Javadocs for javanauts, dunno what shit C-quack programmers use) and the method in question becomes that much easier to validate, and far easier to prove that the problem lies in the client code.
I'm prepared to accept that there are cases where it doesn't make sense to trap exceptions (a private method in a class, for example, you may be able to get away without it) but as a general rule, failure to perform some sort of parameter checking is a point of weakness in the code.
From experience, I've found that the most time-consuming bugs to track down are those caused by insufficient sanity checking of parameters, including omitting to specifically check for nulls.
I can only assume that Severity One only works on noddy-programs.
Admin
First, many Microsoft libraries throws NullReferenceException only if some internal error happens - public methods often throw ArgumentNullException (MSs own style checking utilities encourage the practice that is appearantly concidered a "WTF" today).
Second, there are plenty of scenarios where null is a perfectly valid input and make perfect sense.
I must admit that I rarely implement this checking myself. However, if it's there, that's great - it's better that it's there than that it's not - I just skip it to save time. It's nowhere near being a WTF though.
Admin
Also, everything I write is used internally, but it's still used by developers on other teams. If I report to them "Object was null" I'm going to get a phone call and waste my time. If I report to them "x was invalid"... then I'm still going to get a phone call and waste my time, but I can say "put in a valid x" and go back to my work.
Admin
Car safety features save lives. A quite significant number of them. Including mine, on more than one occasion. I don't mind you driving a Ford Pinto with a still in the back seat, but please don't argue that it is a safer car to use than a car with a 5 star crash safety rating.
Admin
You guys are arguing about what the hell "null" is and missing the point. Take a simpler example.
Suppose some jackass passed null. Is it a bug that some jackass passed null? Maybe, but it might be out of your control. You ARE, however, reponsible for not doingSomeReallyHardToReverseShit() if the call to .Foo() is about to detonate. What's easier for you, checking for null first, or implementing undoSomeReallyHardToReverseShit()?
Admin
Admin
But I appreciate the counterexample. I admit, if my code was designed to doSomeReallyHardToReverseShit() without needing instanceWhichCantBeNull and then do something with instanceWhichCantBeNull, in that case I would write a null check.
But in reality I 1) would try really hard not to design my code that way, and 2) would test my code in a non-production environment to make sure that I'm never passing null for instanceWhichCantBeNull. The jackass should test his code too, and I don't feel sorry for him if he destroys his production environment for a lack of sufficient testing.
Admin
It really comes down to this: Do you want to get an exception thrown on the line where you made a mistake (10 second fix) or the line where that mistake matters (at least several minutes to fix)?
If your answer is "I never make mistakes", then you, sir, are TRWTF.
If you answer is "Screw everyone who uses my class, they're wrong and deserve to pay!", then consider that if you really do know what you're doing, most programmers aren't as good as you, and making things harder for them is just hurting your company (you know, the one that pays you).
Admin
+1 QFT
Admin
Admin
No but it helps.
Look at it like this. Something passes a parameter with a dodgy value to this method which you are (very visibly) responsible for. Stuff goes horribly wrong and it is clear that the problem happened because your method choked on a null variable.
Do you think your boss is going to listen to the "wah wah wah my pussy hurts" nature of your whining that "it would have been all right if the user hadn't entered such a stupid number."?
If it was me writing this code, I'd make pretty damn sure that it didn't get that far by sanitising the inputs before I start.
Admin
But you really don't understand the issue, or don't want to understand, or are just intentionally trolling. Whatever the case, allow me to explain. Again. Because it doesn't seem to register unless repeated often, and slowly.
Also, we're talking Java here, which doesn't have a separate NullReferenceException and ArgumentNullException. It just has a NullPointerException, which typically happens when an attempt is made to access a member of a null object. I'm not qualified to talk about Microsoft's development frameworks, so I won't.
A NullPointerException means that you have a bug in your code. Now, I don't know where you get the crazy idea from that the "client should do sanity checking", because it doesn't make sense to write in-place code to check if you have bugs in your code. It makes perfect sense to write unit tests, or to debug, or run a source code analyser, whatever it takes to remove bugs before code goes into production, but throwing an exception whilst in production?
An exception is meant to handle an exceptional situation, and try and recover from it. How do you recover from a bug? That's why I think that parameter checking and throwing an exception to indicate that there's a bug is merely fooling yourself and hiding the issue.
It's been at least 25 years since I wrote programs in Noddy. You go and figure out the reference.Oh, and please don't bother replying before you learn some basic civility.
Admin
If the Guard class was used in a library or an API, accessed by "chimps", or anyone for that matter, then throwing an exception stating the nature of the problem will save everyone lots of time. The person writing the method call will know he's got a bug, and probably not waste the Rockstar's time by blaming his code.
Now, it could be a WTF, depending on how the Guard class's methods are used, but I doubt they're used in the UI.
Admin
Exactly what I said, except you omitted the important part : THIS IS BAD QUALITY CODING ! (and the business doesn't care) And again, the main reason for this "requirement to make your class noob-friendly" is the way people hire developpers and consider coding projects ("weehaaa let's throw in some manyears, a bit of mayonnaise, a bit of hardware, 1 year in the oven and BOOOM bug-infested software for you") -
In the case (unlikely) that you work for yourself and refuse to work with incompetent coders, you may very well design a much better API that isn't noob friendly, but much faster, cleaner and better.
Again, quit trying to find a consensus between "awesome" code and "good for the business" code, there is no relationship between those in the bigger part of the software industry at the moment. (I'm quite sure they don't let incompetent devs pass null values to a cruise missile's targeting system - at least I hope so)
Last but not least, you may all be convinced that the business way is the right way, but don't forget your 'noob-friendly' code will always be needlessly heavier and slower and in the end doomed to be replaced by better code.
The very notion of defensive programming (and most of Java's forced syntax) exists mostly to enable a ton of bad programmers to deliver 'working' software, it's in no way a guarantee or even a requirement to write great code or deliver 'working' software.
In other words, my internal methods aren't noob-safe, and I don't care because I'm the only one using them and I enforce the conditions within which they cannot fail.
Aaaand... the fact that the current exception fails to be descriptive is obviously a problem for many and (if it's really an issue,) it should be fixed in the language or debug tools, not worked around in the code.
Admin
Admin
Admin
You would have to define a Null-state of each class that will get created with the first object of that class. Pointers at these objects, that are set to NULL, would point to that NULL-object instead. You could then still access it without an exception and have the predefined results.
Admin
While I cannot condone the use of such bad language as has been used against you, I feel it's fair to say that you started it, by referring to those who fail to adhere to the published API on your software as "trained chimps".
The question is of course larger than just checking for an object being a null, and whether such a check is indicated by using an IllegalArgumentException or a NullPointerException, this merely being a detail of implementation in the overall strategy.
The question revolves around: is it good or bad to perform parameter checking (including checking to see whether they are null, and making sure their bounds are within the limits beyond which the method would fail).
On the one hand the opinion is that it is a good idea to include such parameter checking, particularly in an API which is public enough to be used in contexts beyond that envisaged by the original programmer. The main reason for this is that there is an immediate response to the parameters being out of range / invalid whose reason is clear to the programmer. Whether this happens during development, during testing or during production is neither here nor there. I completely concur that simians of all levels of training and evolutionary status ought to ensure that their code is fully functional - but a friendly API can make the development process considerably easier.
On the other hand the suggestion is that all such parameter checking causes unnecessary code bloat and slows it down unacceptably. The argument is that if the client code has been written correctly, then the parameters will all be valid and to check this fact would be redundant and wasteful (and besides, writing such checks is irritating and tedious). In certain types of program, for example, real-time control of rapid-response devices, yadayada, such concerns may be valid. But most of the time, and in the general context of programming that is usually under discussion on this site, there is no such processing bottle-neck, and the code being too bloated and slow is an incorrect assessment of the situation.
In short, I am more likely to believe that the overwhelmingly usual reason for not putting parameter checks in place on public APIs is because of laziness, which is why I initially expressed intolerance when discussing this matter yesterday. I have read nothing since which has convinced me to change my mind.
Admin
Nah, he's a Brit. They're way ruder than us.
Admin
Now, suppose you have a method called performTransaction, which takes a File (or InputStream) as one of its parameters, and does some critical things both before and after reading from or writing to that file. If you leave the method like that and allow a NullPointerException to happen, that is very much a problem in your own code, and not that of the client program.
There are several ways to solve this, one of which is to check parameters, and throw an exception if they are invalid. But you could also write your method in a different way, or change the whole program flow, so that this situation would never arise in the first place. There are more ways that lead to Rome.
It's the responsibility of the library (which is what we're talking about) to not mess up and leave things in an indeterminate state if invalid data is passed. It is not the task of the library to point out bugs in the client program.
This is why I strongly oppose the notion that "you should always check your parameters" without any further qualification. Then it becomes an article of faith, instead of good practice.
This is what Sun/Oracle have to say about the subject, particularly assertions:
...so that settles my argument for using assertions. Oh well.Anyway, the way I'm interpreting the above is not that you should always check parameters, but that the appropriate exception should be thrown if erroneous parameters are passed. And with a null object, you do get the NullPointerException. It's just that it's thrown by the virtual machine, instead of your own code.
I'm not calling Americans rude. The vast majority of Americans is very polite. Such extremely rude on-line behaviour to a person you don't even know is something I see mostly with people from that area, though. Must have something to do with the way that (political) debate is conducted over there. And of course, the time of posting is a hint. But you do get an exception. It just doesn't necessarily happen at the beginning of the method.Again, a NullPointerException indicates a bug. You can blame Java for not having non-nullable objects, but there are many ways to hunt bugs, and loking for them in every API is clearly not the way.
I'm not telling him not to reply. I'm telling him that he shouldn't bother if he's rude again, because I refuse to be insulted just because he takes issue at my opinion. If he starts again with "you are a cunt", and such, he can stick his reply in a certain place.Admin
Admin
TRWTF is Java not having non-nullable object. It's one of the reasons why communicating between Java and C# using SOAP, particularly when a date is involved, is such a hassle.
(Although it ought to be mentioned that SOAP does allow fields to be null, or to be not present, which I don't believe you can easily express in C# dates.)
Admin
This is Java, so let the Java-bashing ensue. Since this article is a day-old, let me assure you that I will never read your responses.
Admin
C# has "Nullable<DateTime>", which can also be written as "DateTime?". I don't know how that works with SOAP though.
Admin
It's not binary. It's not even tertiary. It's a broad spectrum that really depends on the situation. Which is why the mantra "parameters should always be checked" is just as incorrect as "parameters should never be checked".
From developers, I expect them to read what I write, and not trying to infer something that was never written. Nowhere, I write that parameters should never be checked; what I do believe is that checking parameters, because the client program might be written by a typical subject of the stories published on this site, is a waste of my time.
And to be frank, in the last 10 years I've never come across the situation where one of my fellow developers had a problem with one of my many libraries because he or she was passing invalid information to it, and blamed me. But on the other hand, I do demand (and wish I had the time to enforce) strict adherence to coding requirements. No, I'm not a manager, just the guy in charge of this particular niche.
Admin
Admin
However, this WTF was written i C#. C# has ArgumentNullException, which would be even more appropriate than NullReferenceException.
I think we can all agree on that doing a check and throwing an ArgumentNullException is at least NOT A WTF. Right?
Then we can argue forever if these checks are actually worth the effort and extra LOC or not...
Admin
Admin
I see you've changed your position from:
"But I refuse to check parameters passed to my API methods to make sure that the other developer isn't a trained chimp. If I write in the JavaDocs that you must pass a non-null instance of ClassX, you must pass a non-null instance of ClassX. You must not pass an instance of ClassY, except if it's derived from ClassX, and you must most definitely not pass null. If you do pass null, I can guarantee you that you get a NullPointerException at some point in the code. "
to:
"There are clear examples where checking parameters is useless, because you'll get exactly the same exception two lines down anyway. And there are clear examples where not checking parameters is like giving a hand grenade to a baby and saying "remember, don't pull out the pin"."
But oh, how I wish I were a clever person like you so that I can always tell whether what I've programmed is going to be the equivalent of a hand-grenade with a baby clutching it. In point of fact I know that my judgment is imperfect, and understanding this fact (and understanding the fact that others may likewise have a less-than-perfect sense of discrimination) I would prefer that programs with which I am involved should espouse the philosophy of "safety first", and when in doubt put a parameter check in. Not to do so because you think you know better may not be laziness then, but it's pretty close to foolhardiness.
Admin
I concur. The "== false" is a littly iffy (pardon the pun), but argument validation is fundamental.
It's always preferable to validate arguments and throw ArgumentNullException instead of letting the runtime engine throw a NullReferenceException. NullReferenceException is usually a sign that the coder doesn't really understand what's going on in his own code.
Admin
MSDN recommends validating arguments. http://msdn.microsoft.com/en-us/library/ms229025(v=VS.100).aspx
Admin
Non-conforming use of an API can, does, and should result in undefined behavior.
The argument in favor of ALWAYS checking every parameter seems to be supported by the same kinds of people who put "WARNING - DO NOT USE IN BATHTUB" stickers on AC electrical appliances. The time/money I spend on that is NOT being spent adding new features or improving the design, potentially in ways that would make this whole argument moot.
Admin
See what I'm getting at here? This is not an "it's always preferable" situation. I submit that - except for commercial library dev - it is never profitable to "always check every input".
Check the parameters where figuring out what went wrong or reversing the damage will cost more money than implementing the check. It's really that simple.
Most often, it's not worth it. It also uglies up the code and kills performance, because more code means less will fit in the CPU caches, reducing your locality of reference.
If you check as few as 2 or 3 parameters for null, you have just ensured that your method will NEVER be inlined by the JIT. Methods must be at or under 32 bytes of code to be inlined. Congratulations.
Very little in development is black and white, and whether to check arguments or not is a design decision that you need to make.
Admin