• B00nbuster (unregistered)

    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.

  • B00nbuster (unregistered)

    @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.

  • BillClintonsThirdTerm (unregistered) in reply to shadowman
    shadowman:
    Sam:
    I'm a java programmer so...

    Checking method parameters for null's and throwing IllegalArgumentException is totally appropriate, and considered more correct than just letting a NullPointerException happen.

    Having a class to assist this doesn't seem like a bad thing to me. Maybe i need to see how Guard (bad name) is used in other classes to understand.

    The real WTF sounds like the reimplemented Collection classes.

    I'm not a Java programmer, so I don't know how it works there. To me it just seems like a slight semantic difference between a nullreferenceexception occuring naturally when the null parameter is used vs checking and preemptively throwing argumentnullexception for the same purpose. In either case, you end up with an exception and both are correct when they occur at the appropriate time.

    Would make more sense to simply handle the nullreferenceexception or do some other checking elsewhere to prevent it from occuring, etc. Not just cut one exception off with another.

    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.

  • (cs) in reply to Severity One
    Severity One:
    midas:
    Appearantly the "policy" for NullReferenceException is different in Java but I must say the Java way here seems kind of retarded.
    That's what I think of C#'s lack of checked exceptions. But that's a different kettle of fish, and a whole other debate.
    I don't see what the benefit of disabling this kind of assertions in runtime would give? I mean, basically, deciding wether to have this test is basically "less code vs easier debugging". Having an assertion and disabling at runtime gives "more code" bot no "easier debugging".
    An assertion throws an error as opposed to an exception, as in 'java.lang.Error'. You don't catch Errors (well, you're not supposed to, let's put it that way) and your program will crash and burn if the assertion fails. So there's some incentive to disable assertions at runtime. Obviously, then you'd get an unchecked exception, which you aren't supposed to catch either, but my personal opinion is that yes, you can catch even unchecked exceptions if it means that the end user doesn't seem some ugly stack trace, or that his programs stops working.

    The problem is, though, that a NulllPointerException indicates a bug. If you're still accessing null objects in production code, you have an issue with your testing. This point has been put several times now, by a variety of posters, but it doesn't appear to hit home.

    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.

  • Spewin Coffee (unregistered)

    The real problem is that there is an ERP system written in C#.

    There is coffee on my monitor.

  • BillClintonsThirdTerm (unregistered) in reply to Severity One
    Severity One:
    Sam:
    I'm a java programmer so...

    Checking method parameters for null's and throwing IllegalArgumentException is totally appropriate, and considered more correct than just letting a NullPointerException happen.

    Having a class to assist this doesn't seem like a bad thing to me. Maybe i need to see how Guard (bad name) is used in other classes to understand.

    I think it's of a higher priority that you start to understand exceptions. What you're doing is catching an unchecked exception (NullPointerException) and in its stead, throw a different unchecked exception (IllegalArgumentException). Not only is that essentially useless, because it doesn't make applications any more stable, but it's also highly confusing because you're replacing a perfectly good NullPointerException (after all, the parameter is null) by an exception that is designed for other purposes. If anything, throw a NullPointerException directly.

    But that is tainted too. An unchecked exception means that you have a bug in your code. Checking each parameter at the beginning of a method means that you trade performance at runtime for a modicum of expedience during development. That sounds plain daft to me.

    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.

  • AP2 (unregistered) in reply to Severity One
    Severity One:
    JolleSax:
    Let me reiterate this. A nullreferenceexception tells you there's something wrong with the code.

    THERE'S SOMETHING WRONG WITH THE CODE.

    Good code doesn't let them occur.

    Exactly. We've reached the point that 'getting a NullPointerException means bad code' morphed into 'having NullPointerExceptions is bad' and finally into 'NullPointerExceptions are bad', so that solutions are sought to get rid of these 'bad' NullPointerExceptions, which are caused by 'bad' null objects.

    Don't get me wrong: there's nothing wrong with having the compiler check certain things. I'm not complaining about getting ArrayIndexOutOfBoundsException either. And having a runtime check for non-null values makes sense, too.

    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.

    (Hmm... the previous paragraph reads rather a lot like the Book of Armaments, chapter 2, verses 9-21.)

    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.

  • (cs) in reply to B00nbuster
    B00nbuster:
    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.

    Wow, such a compelling argument! I mean, other people highlight the advantages or disadvantages of either method in order to support their viewpoints, but you come right out and say "Period". And with such conviction.

    You. I better watch out for you.

  • (cs) in reply to boog
    boog:
    Wow, such a compelling argument! I mean, other people highlight the advantages or disadvantages of either method in order to support their viewpoints, but you come right out and say "Period". And with such conviction.

    You. I better watch out for you.

    Righteous burn bro!

  • (cs) in reply to Spewin Coffee
    Spewin Coffee:
    The real problem is that there is an ERP system written in C#.

    There is coffee on my monitor.

    There are ERP systems written in FOXPRO!

  • (cs) in reply to AerieC
    AerieC:
    hoodaticus:
    Alex:
    No WTF to be found here. NullReferenceExceptions might not be thrown until the middle of a method, or not at all, if for example the value is simply stored somewhere. Calling the static methods of the Guard class at the top of the method for each argument will avoid this scenario.

    If you look at Microsoft's implementation of the .NET Framework, they check the passes arguments all the time, instead of just trying to run the method until a null reference is dereferenced and throws an exception.

    My company doesn't pay me to waste time and performance checking every exception that the framework will be checking anyway.

    That's like giving your car's bumper its own bumper. It's a WTF.

    If it's actually going to cause a problem if you let a null slip through, then of course you check it. But this is almost never the case; 99.0% of the time, you don't need all that redundant bullcrap.

    Yeah. It's like driving; 99.0% of the time you wont get into an accident.

    Who needs seat belts and airbags?

    It's more like a condom. 99% of the time, you aren't having sex, so most people don't wear condoms around all day.

    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.

  • (cs) in reply to pedantic
    pedantic:
    bits:
    I minus well not comment on the grammer - it's a mute point.
    moot

    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.

  • (cs) in reply to Matt Westwood
    Matt Westwood:
    Severity One:
    An assertion throws an error as opposed to an exception, as in 'java.lang.Error'. You don't catch Errors (well, you're not supposed to, let's put it that way) and your program will crash and burn if the assertion fails. So there's some incentive to disable assertions at runtime. Obviously, then you'd get an unchecked exception, which you aren't supposed to catch either, but my personal opinion is that yes, you can catch even unchecked exceptions if it means that the end user doesn't seem some ugly stack trace, or that his programs stops working.

    The problem is, though, that a NulllPointerException indicates a bug. If you're still accessing null objects in production code, you have an issue with your testing. This point has been put several times now, by a variety of posters, but it doesn't appear to hit home.

    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.

    Hey, be more sympathetic Severino. Clearly this guy must have caught some unchecked exception sleeping with his wife or something. How else would you explain the hostility?

    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"

  • midas (unregistered) in reply to Severity One
    Severity One:
    The problem is, though, that a NulllPointerException indicates a bug. If you're still accessing null objects in production code, you have an issue with your testing. This point has been put several times now, by a variety of posters, but it doesn't appear to hit home.

    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.

  • (cs) in reply to Severity One
    Severity One:
    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.

    (Hmm... the previous paragraph reads rather a lot like the Book of Armaments, chapter 2, verses 9-21.)

    NaN is right out.

  • (cs) in reply to midas
    midas:
    Severity One:
    The problem is, though, that a NulllPointerException indicates a bug. If you're still accessing null objects in production code, you have an issue with your testing. This point has been put several times now, by a variety of posters, but it doesn't appear to hit home.
    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.
    Does the former lack a stack trace?
  • (cs) in reply to boog
    boog:
    midas:
    Severity One:
    The problem is, though, that a NulllPointerException indicates a bug. If you're still accessing null objects in production code, you have an issue with your testing. This point has been put several times now, by a variety of posters, but it doesn't appear to hit home.
    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.
    Does the former lack a stack trace?

    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.

  • midas (unregistered) in reply to boog
    boog:
    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"

    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.

  • (cs) in reply to boog
    boog:
    midas:
    Severity One:
    The problem is, though, that a NulllPointerException indicates a bug. If you're still accessing null objects in production code, you have an issue with your testing. This point has been put several times now, by a variety of posters, but it doesn't appear to hit home.
    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.
    Does the former lack a stack trace?
    In one of our production error reporting systems, all of them lack a stack trace. "Paramter x was null" is much more useful than "there's a null somewhere"
    Matt Westwood:
    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.
    This is especially true in my experience.

    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.

  • Brian White (unregistered) in reply to Severity One
    Severity One:
    QJo:
    Severity One:
    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.
    I disagree. It is prudent to guard against the users being silly. It adds value to tell them in what way they are being silly. If nothing else, then it removes the cause of some of the interruptions that go along the lines of: "I called your stupid useless method on your stinking class and it through a damned NullPointerException."
    Trust me: nobody at work talks to me in a such a way.
    Using defensive programming techniques may irritate the purists who claim that they should not need to trap out values which are non-compliant with the terms of the API, but it sure does make your class easier to use.
    It has nothing to do with being purist. It has everything to do with me not being a school teacher. You may call it defensive programming; I call it not trusting other programmers. It's not my fault that he cannot ensure that he isn't passing a null object, so it's not my responsibility either to make sure he doesn't.

    It's like putting ABS on a car. The result is that drivers take more risk, because "the car brakes better". The net result is a far lower decrease in accidents than you might have expected. Defensive driving versus defensive engineering.

    And it's not easier to use. It's perhaps a bit easier to track bugs in your own code, but that's not the task of an API. The task of an API is to do whatever it's been designed for, and I never design APIs to train chimps.

    Which would you rather do - spend some extra time ensuring that the arguments coming in adhere to appropriate values, throwing e.g. an IllegalArgumentException complete with an explanatory error message detailing exactly what the client software has done incorrectly, or spend no little time on the telephone smugly explaining in a superior voice that your program is fine, it's the fault of the stupid user?
    I think you could have done without such adjectives like 'smuggly' (OK, that's an adverb) and 'superior'.

    But you also need to read carefully: I didn't say I never check arguments for validity; I said I don't check arguments for the possibility that the developer using my classes is a trained chimp. If it makes sense to test a parameter, I will. I may even throw an IllegalArgumentException if you need to pass an enum, which is checked inside a switch() block, and it might be null. But that is purely to handle the default case, which one should always do.

    However, I very much prefer the sort of design where mistakes are avoided in the first place, instead of having checks everywhere because somebody else might be a lazy sod, or otherwise unfit to be called a developer.

    Where this is not feasible, though, I'm not going jump through hoops to do somebody else's job.

    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.

  • (cs)

    You guys are arguing about what the hell "null" is and missing the point. Take a simpler example.

    void fooMethod(SomeClass instanceWhichCantBeNull)
    {
        doSomeReallyHardToReverseShit();
        instanceWhichCantBeNull.bar();
    }
    

    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()?

  • (cs) in reply to midas
    midas:
    boog:
    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"

    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).
    I can appreciate the clarity of ArgumentNullException (and any additional information) vs. NullReferenceException, but considering I almost always want my arguments to be defined, I'm not too keen on checking every fucking argument for null in every fucking method in my API. This nuisance would far exceed the time it takes me to track down a bug because I passed a null reference; personally, I usually only get null exceptions within the same scope as where they were supposed-to-be-defined, not because I passed them as an argument.

    midas:
    Second, there are plenty of scenarios where null is a perfectly valid input and make perfect sense.
    I'm not denying this, I have on rare occasion written code that expects a null argument. However, since you cannot invoke methods on a null object, I'm sure you'd agree that having a null object would therefore be a special case (typically accompanied by special code to handle it).
  • (cs) in reply to smxlong
    smxlong:
    You guys are arguing about what the hell "null" is and missing the point. Take a simpler example.
    void fooMethod(SomeClass instanceWhichCantBeNull)
    {
        doSomeReallyHardToReverseShit();
        instanceWhichCantBeNull.bar();
    }
    

    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()?

    Sorry, I'll try to remember to use qualifiers like "usually" and "mostly", though one guy did say "99.0% of the time".

    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.

  • Brendan (unregistered)

    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).

  • (cs) in reply to Brendan
    Brendan:
    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).

    +1 QFT

  • (cs) in reply to Brendan
    Brendan:
    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)?
    You assume that because you know which argument is null (in a given program state), it only takes 10 seconds to determine why it is null and fix it?
    Brendan:
    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 blah blah...

    Those are my only two choices? Damn...

  • (cs) in reply to boog
    boog:
    Brendan:
    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)?
    You assume that because you know which argument is null (in a given program state), it only takes 10 seconds to determine why it is null and fix it?

    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.

  • (cs) in reply to Matt Westwood
    Matt Westwood:
    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.

    Judging from your rudeness, you're probably from North America, am I right?

    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.

    Matt Westwood:
    I can only assume that Severity One only works on noddy-programs.
    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.

  • Burt R (unregistered) in reply to Severity One
    1. Throwing an exception is hardly hiding anything.
    2. Calling Americans rude is hardly basic civility.

    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.

    1. It's hardly up to you to tell people to reply or not.
  • L. (unregistered) in reply to Brendan
    Brendan:
    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).

    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.

  • Burt R (unregistered) in reply to Severity One
    Severity One:
    midas:
    Am I getting this right - checking for null reference and throwing an ArgumentNullException is concidered a WTF, or am I missing something else?
    No, you're not getting it right. Checking for null and throwing an IllegalArgumentException (instead of a NullPointerException) is a WTF, though.
    Like in commons.lang.Validate?
  • Paul (unregistered) in reply to B00nbuster
    B00nbuster:
    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.

    That's exactly what i think. Every class in Microsoft Core Libraries checks for null arguments and eventually throws an ArgumentNullException. What would happen, for example, if I pass a null argument to String.Format? A random unreadable exception. That's the reason why .NET 4.0 has Code Contracts.

  • zAPP (unregistered) in reply to An alternate explanation
    An alternate explanation:
    [The problems with null references].

    The problem with the null references problem is that you can't just remove null references.

    Because how would you for example implement a tree structure if you can't set children to null. (You need to set the children to null at the bottom of the tree).

    I think a good solution would be to have 2 reference types. One which can be null, and one which can't. Then the type of the reference will indicate if it can be null or not. (And this should be verified at compile time).

    You could solve it by requiring a valid null-value for everything. You know, like an integer can actually be 0 and you can check if it is, by comparing it with 0.

    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.

  • QJo (unregistered) in reply to Severity One
    Severity One:
    Matt Westwood:
    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.

    Judging from your rudeness, you're probably from North America, am I right?

    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.

    Matt Westwood:
    I can only assume that Severity One only works on noddy-programs.
    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.

    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.

  • (cs) in reply to Severity One
    Severity One:
    Judging from your rudeness, you're probably from North America, am I right?

    Nah, he's a Brit. They're way ruder than us.

  • (cs) in reply to Burt R
    Burt R:
    1. Throwing an exception is hardly hiding anything.
    The fact remains that it's just moving things about. Suppose that you have a method called parseFile, which takes a File or an InputStream as a parameter, and the first thing the method attempts to do is read from that file. If you pass a null, you'll get a NullPointerException. It's useless to put an extra check there.

    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:

    Do not use assertions for argument checking in public methods.

    Argument checking is typically part of the published specifications (or contract) of a method, and these specifications must be obeyed whether assertions are enabled or disabled. Another problem with using assertions for argument checking is that erroneous arguments should result in an appropriate runtime exception (such as IllegalArgumentException, IndexOutOfBoundsException, or NullPointerException). An assertion failure will not throw an appropriate exception.

    ...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.

    2. Calling Americans rude is hardly basic civility.
    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.
    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.
    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.

    3. It's hardly up to you to tell people to reply or not.
    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.
  • (cs) in reply to method1
    method1:
    pedantic:
    bits:
    I minus well not comment on the grammer - it's a mute point.
    moot

    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.

    It's not even a troll, it's a joke. But yeah, for some people it works that way two.

  • (cs) in reply to zAPP
    zAPP:
    You could solve it by requiring a valid null-value for everything. You know, like an integer can actually be 0 and you can check if it is, by comparing it with 0.
    Sometimes, I use a java.lang.Integer (the nullable object) instead of an int because I need to be able to set it to null, instead of a numeric value (including 0). So whilst your solution would solve one problem, it would create a new one as well.

    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.)

  • Sock Puppet #5 (unregistered) in reply to Zebedee
    Zebedee:
    Dortical:
    Zebedee:
    eVil:
    Sock Puppet #5:
    What happens if you divide a positive number by 0? Any mathematician will tell you that the answer is not determined. However, in Java, the answer will be Number.POSITIVE_INFINITY. Obviously, this is true for limits, but not for an ACTUAL CALCULATION. Any function that accepts a divisor should therefore check it for zero and throw a IllegalArgumentException if it is expected to be non-zero.
    Does it really do that?
    No it doesn't do that, you'll get an ArithmeticException.
    I do deplore these dialogues during which we daftly delude our demented selves of the well-documented demeanor of doubles or groups of digits otherwise. http://www.concentric.net/~ttwang/tech/javafloat.htm

    captcha: delenit

    Oops, I stand corrected!

    Want to prove I'm not trolling. Let me prefix it with this: I have no idea what articles were referenced--author did not take the time to use the link, so I did not take the time to read them. If you divide a primitive by zero, I think you get an error; but I have reached a case where division by zero took place, and it resulted in no exception. I'm not going to go through the effort to reproduce this case, because my original point still stands. The function in question needed to test inputs, and because it did not the WTF error occurred.

    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.

  • midas (unregistered) in reply to Severity One
    Severity One:
    zAPP:
    You could solve it by requiring a valid null-value for everything. You know, like an integer can actually be 0 and you can check if it is, by comparing it with 0.
    Sometimes, I use a java.lang.Integer (the nullable object) instead of an int because I need to be able to set it to null, instead of a numeric value (including 0). So whilst your solution would solve one problem, it would create a new one as well.

    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.)

    C# has "Nullable<DateTime>", which can also be written as "DateTime?". I don't know how that works with SOAP though.

  • (cs) in reply to QJo
    QJo:
    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".
    Fair enough, but unless Mr Westwood is of the simian variety himself, I don't see how he should feel personally insulted on a site intended to laugh at other people's stupidity when it comes to programming. The same cannot be said of his comments.
    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).
    There's no clear answer. It depends on 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.
    But it's not either good or bad in all circumstances, is it? 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".

    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.

  • (cs) in reply to smxlong
    smxlong:
    You guys are arguing about what the hell "null" is and missing the point. Take a simpler example.
    void fooMethod(SomeClass instanceWhichCantBeNull)
    {
        doSomeReallyHardToReverseShit();
        instanceWhichCantBeNull.bar();
    }
    

    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()?

    Everyone on this thread agrees that you need to check for null there. It's all the other cases that are being debated.
  • midas (unregistered) in reply to Severity One
    Severity One:
    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.

    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...

  • (cs) in reply to Burt R
    Burt R:
    1. Throwing an exception is hardly hiding anything. 2. Calling Americans rude is hardly basic civility.

    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.

    1. It's hardly up to you to tell people to reply or not.
    Matt's not an American, though he is usually much more witty.
  • QJo (unregistered) in reply to Severity One
    Severity One:
    QJo:
    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".
    Fair enough, but unless Mr Westwood is of the simian variety himself, I don't see how he should feel personally insulted on a site intended to laugh at other people's stupidity when it comes to programming. The same cannot be said of his comments.
    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).
    There's no clear answer. It depends on 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.
    But it's not either good or bad in all circumstances, is it? 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".

    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.

    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.

  • Grim (unregistered) in reply to Alex
    Alex:
    No WTF to be found here.

    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.

  • (cs)
  • (cs) in reply to Severity One
    Severity One:
    It's the responsibility of the library ... 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. It's enough to ensure that your API performs as documented when used as documented.

    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.

  • (cs) in reply to Grim
    Grim:
    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.
    Or it's a sign that resources are finite. What is the anticipated cost and savings from implementing null checks for every input parameter that requires an instance, in addition to documenting that a null should not be passed? If the profit is positive then you do it.

    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.

  • (cs) in reply to Matt Westwood
    Matt Westwood:
    boog:
    Brendan:
    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)?
    You assume that because you know which argument is null (in a given program state), it only takes 10 seconds to determine why it is null and fix it?
    No but it helps.
    As you may have noticed, I agree that it can help. However, most (probably 98.2%, who can say for sure really?) arguments I expect to be non-null, because as I said before, null objects are rarely useful. This means I'd have to write null checks against 98.2% of my methods' arguments, which is far too much work just to save a small amount of time in the rare situation where I pass a null argument.

Leave a comment on “The Rockstar's Guard”

Log In or post as a guest

Replying to comment #:

« Return to Article