<p>I am in the middle of reading the excellent <a href="https://rads.stackoverflow.com/amzn/click/com/0132350882" rel="noreferrer" rel="nofollow noreferrer">Clean Code</a></p>

<p>One discussion is regarding passing nulls into a method.</p>

<pre><code>public class MetricsCalculator {
    public double xProjection(Point p1, Point p2) {
        return (p2.x - p1.x) * 1.5;
    }
}
...
calculator.xProjection(null, new Point(12,13));
</code></pre>

<p>It represents different ways of handling this:</p>

<pre><code>public double xProjection(Point p1, Point p2) {
    if (p1 == null || p2 == null) {
        throw new IllegalArgumentException("Invalid argument for xProjection");
    }
    return (p2.x - p1.x) * 1.5;
}

public double xProjection(Point p1, Point p2) {
    assert p1 != null : "p1 should not be null";
    assert p2 != null : "p2 should not be null";
    return (p2.x - p1.x) * 1.5;
}
</code></pre>

<p>I prefer the <a href="http://java.sun.com/j2se/1.4.2/docs/guide/lang/assert.html" rel="noreferrer">assertions</a> approach, but I don't like the fact that assertions are turned off by default.</p>

<p>The book finally states:</p>

<blockquote>
  <p>In most programming languages there is no good way to deal with a null that is passed by a caller accidentally. Because this is the case, the rational approach is to forbid passing null by default.</p>
</blockquote>

<p>It doesn't really go into how you would enforce this restriction?</p>

<p>Do any of you have strong opinions either way.</p>

[{'answer_id': 32295, 'author': 'wvdschel', 'author_id': 2018, 'author_profile': 'https://Stackoverflow.com/users/2018', 'pm_score': 1, 'selected': False, 'text': "<p>I generally prefer not doing either, since it's just slowing things down. NullPointerExceptions are thrown later on anyway, which will quickly lead the user to discovering they're passing null to the method. I used to check, but 40% of my code ended up being checking code, at which point I decided it was just not worth the nice assertion messages.</p>\n"}, {'answer_id': 32304, 'author': 'Chris Karcher', 'author_id': 2773, 'author_profile': 'https://Stackoverflow.com/users/2773', 'pm_score': 2, 'selected': False, 'text': '<blockquote>\n  <p>It doesn\'t really go into how you would enforce this restriction?</p>\n</blockquote>\n\n<p>You enforce it by throwing an <a href="http://msdn.microsoft.com/en-us/library/system.argumentexception.aspx" rel="nofollow noreferrer">ArgumentExcexception</a> if they pass in null.</p>\n\n<pre><code>if (p1 == null || p2 == null) {\n    throw new IllegalArgumentException("Invalid argument for xProjection");\n}\n</code></pre>\n'}, {'answer_id': 32305, 'author': 'Lasse V. Karlsen', 'author_id': 267, 'author_profile': 'https://Stackoverflow.com/users/267', 'pm_score': 1, 'selected': False, 'text': '<p>I agree or disagree with <a href="https://stackoverflow.com/a/32295/3798217">wvdschel\'s post</a>, it depends on what he\'s specifically saying.</p>\n\n<p>In this case, sure, this method will crash on <code>null</code> so the explicit check here is probably not needed.</p>\n\n<p>However, if the method simply stores the passed data, and there is some other method that you call later that will deal with it, <strong>discovering bad input as early as possible is the key to fixing bugs faster</strong>. At that later point, there could be a myriad of ways that bad data happened to be given to your class. It\'s sort of trying to figure out how the rats came into your house after the fact, trying to find the hole somewhere.</p>\n'}, {'answer_id': 32310, 'author': 'Brian Matthews', 'author_id': 1969, 'author_profile': 'https://Stackoverflow.com/users/1969', 'pm_score': 2, 'selected': False, 'text': '<p>I prefer the use of assertions. </p>\n\n<p>I have a rule that I only use assertions in public and protected methods. This is because I believe the calling method should ensure that it is passing valid arguments to private methods.</p>\n'}, {'answer_id': 32313, 'author': 'aku', 'author_id': 1196, 'author_profile': 'https://Stackoverflow.com/users/1196', 'pm_score': 3, 'selected': False, 'text': '<p>General rule is if your method doesn\'t expect <code>null</code> arguments then you should throw <a href="http://msdn.microsoft.com/en-us/library/system.argumentnullexception.aspx" rel="nofollow noreferrer">System.ArgumentNullException</a>. Throwing proper <code>Exception</code> not only protects you from resource corruption and other bad things but serves as a guide for users of your code saving time spent debugging your code.</p>\n\n<p>Also read an article on <a href="http://en.wikipedia.org/wiki/Defensive_programming" rel="nofollow noreferrer">Defensive programming</a></p>\n'}, {'answer_id': 32314, 'author': 'Shaun Austin', 'author_id': 1120, 'author_profile': 'https://Stackoverflow.com/users/1120', 'pm_score': 1, 'selected': False, 'text': '<p>@Chris Karcher I would say absolutely correct. The only thing I would say is check the params separately and have the exeption report the param that was null also as it makes tracking where the null is coming from much easier.</p>\n\n<p>@wvdschel wow! If writing the code is too much effort for you, you should look into something like <a href="http://www.postsharp.org/" rel="nofollow noreferrer">PostSharp</a> (or a Java equivalent if one is available) which can post-process your assemblies and insert param checks for you. </p>\n'}, {'answer_id': 32384, 'author': 'Jorge Córdoba', 'author_id': 2695, 'author_profile': 'https://Stackoverflow.com/users/2695', 'pm_score': 1, 'selected': False, 'text': '<p>Although it is not strictly related you might want to take a look to <a href="http://research.microsoft.com/SpecSharp/" rel="nofollow noreferrer">Spec#</a>.</p>\n\n<p>I think it is still in development (by Microsoft) but some CTP are available and it looks promising. Basically it allows you to do this:</p>\n\n<pre><code>  public static int Divide(int x, int y)\n    requires y != 0 otherwise ArgumentException; \n  {\n  }\n</code></pre>\n\n<p>or</p>\n\n<pre><code>  public static int Subtract(int x, int y)\n    requires x &gt; y;\n    ensures result &gt; y;\n  {\n    return x - y;\n  } \n</code></pre>\n\n<p>It also provides another features like Notnull types. It\'s build on top of the .NET Framework 2.0 and it\'s fully compatible. The syntaxt, as you may see, is C#.</p>\n'}, {'answer_id': 32666, 'author': 'rcreswick', 'author_id': 3446, 'author_profile': 'https://Stackoverflow.com/users/3446', 'pm_score': 2, 'selected': False, 'text': '<p>Spec# looks very interesting!</p>\n\n<p>When something like that isn\'t available, I generally test non-private methods with a run-time null-check, and assertions for internal methods.  Rather than code the null check explicitly in each method, I delegate that to a utilities class with a check null method:</p>\n\n<pre><code>/**\n * Checks to see if an object is null, and if so \n * generates an IllegalArgumentException with a fitting message.\n * \n * @param o The object to check against null.\n * @param name The name of the object, used to format the exception message\n *\n * @throws IllegalArgumentException if o is null.\n */\npublic static void checkNull(Object o, String name) \n    throws IllegalArgumentException {\n   if (null == o)\n      throw new IllegalArgumentException(name + " must not be null");\n}\n\npublic static void checkNull(Object o) throws IllegalArgumentException {\n   checkNull(o, "object");\n} \n\n// untested:\npublic static void checkNull(Object... os) throws IllegalArgumentException {\n   for(Object o in os) checkNull(o);  \n}\n</code></pre>\n\n<p>Then checking turns into:</p>\n\n<pre><code>public void someFun(String val1, String val2) throws IllegalArgumentException {\n   ExceptionUtilities.checkNull(val1, "val1");\n   ExceptionUtilities.checkNull(val2, "val2");\n\n   /** alternatively:\n   ExceptionUtilities.checkNull(val1, val2);\n   **/\n\n   /** ... **/\n} \n</code></pre>\n\n<p><em>That</em> can be added with editor macros, or a code-processing script.\n<strong>Edit:</strong> The verbose check could be added this way as well, but I think it\'s significantly easier to automate the addition of a single line.</p>\n'}, {'answer_id': 32716, 'author': 'Chris Conway', 'author_id': 1412, 'author_profile': 'https://Stackoverflow.com/users/1412', 'pm_score': 2, 'selected': False, 'text': '<p>Also not of immediate use, but related to the mention of Spec#... There\'s a proposal to add "null-safe types" to a future version of Java: <a href="http://docs.google.com/View?docid=dfn5297z_2kjj2fk" rel="nofollow noreferrer">"Enhanced null handling - Null-safe types"</a>.</p>\n\n<p>Under the proposal, your method would become</p>\n\n<pre><code>public class MetricsCalculator {\n    public double xProjection(#Point p1, #Point p2) {\n        return (p2.x - p1.x) * 1.5;\n    }\n}\n</code></pre>\n\n<p>where <code>#Point</code> is the type of non-<code>null</code> references to objects of type <code>Point</code>.</p>\n'}, {'answer_id': 32791, 'author': 'Cem Catikkas', 'author_id': 3087, 'author_profile': 'https://Stackoverflow.com/users/3087', 'pm_score': 0, 'selected': False, 'text': '<p>Thwrowing C# <code>ArgumentException</code>, or Java <code>IllegalArgumentException</code> right at the beginning of the method looks to me as the clearest of solutions. </p>\n\n<p>One should always be careful with Runtime Exceptions - exceptions that are not declared on the method signature. Since the compiler doesn\'t enforce you to catch these it\'s really easy to forget about them. Make sure you have some kind of a "catch all" exception handling to prevent the software to halt abruptly. That\'s the most important part of your user experience.</p>\n'}, {'answer_id': 32808, 'author': 'Scott Dorman', 'author_id': 1559, 'author_profile': 'https://Stackoverflow.com/users/1559', 'pm_score': 0, 'selected': False, 'text': '<p>The best way to handle this really would be the use of exceptions. Ultimately, the asserts are going to end up giving a <em>similar</em> experience to the end user but provide no way for the developer calling your code to handle the situation before showing an exception to the end user. Ultimatley, you want to ensure that you test for invalid inputs as early as possible (especially in public facing code) and provide the appropriate exceptions that the calling code can catch.</p>\n'}, {'answer_id': 32907, 'author': 'Andrei', 'author_id': 2718, 'author_profile': 'https://Stackoverflow.com/users/2718', 'pm_score': 2, 'selected': False, 'text': '<blockquote>\n  <p>In most programming languages there is no good way to deal with a null that is passed by a caller accidentally. Because this is the case, the rational approach is to forbid passing null by default.</p>\n</blockquote>\n\n<p>I found <strong>JetBrains</strong>\' <code>@Nullable</code> and <code>@NotNull</code> annotations approach for dealing with this the most ingenious, so far. It\'s IDE specific, unfortunately, but really clean and powerful, IMO.</p>\n\n<p><a href="http://www.jetbrains.com/idea/documentation/howto.html" rel="nofollow noreferrer">http://www.jetbrains.com/idea/documentation/howto.html</a> </p>\n\n<p>Having this (or something similar) as a java standard would be really nice.</p>\n'}, {'answer_id': 33552, 'author': 'Russell Mayor', 'author_id': 2649, 'author_profile': 'https://Stackoverflow.com/users/2649', 'pm_score': 3, 'selected': True, 'text': "<p>Both the use of assertions and the throwing of exceptions are valid approaches here.  Either mechanism can be used to indicate a programming error, not a runtime error, as is the case here.</p>\n\n<ul>\n<li>Assertions have the advantage of performance as they are typically disabled on production systems.  </li>\n<li>Exceptions have the advantage of safety, as the check is always performed.  </li>\n</ul>\n\n<p>The choice really depends on the development practices of the project.  The project as a whole needs to decide on an assertion policy: if the choice is to enable assertions during all development, then I'd say to use assertions to check this kind of invalid parameter - in a production system, a NullPointerException thrown due to a programming error is unlikely to be able to be caught and handled in a meaningful way anyway and so will act just like an assertion.</p>\n\n<p>Practically though, I know a lot of developers that don't trust that assertions will be enabled when appropriate and so opt for the safety of throwing a NullPointerException.</p>\n\n<p>Of course if you can't enforce a policy for your code (if you're creating a library, for example, and so are dependent on how other developers run your code), you should opt for the safe approach of throwing NullPointerException for those methods that are part of the library's API.</p>\n"}, {'answer_id': 33566, 'author': 'Russell Mayor', 'author_id': 2649, 'author_profile': 'https://Stackoverflow.com/users/2649', 'pm_score': 1, 'selected': False, 'text': '<p>Slightly off-topic, but one feature of <a href="http://findbugs.sourceforge.net/" rel="nofollow noreferrer">findbugs</a> that I think is very useful is to be able to annotate the parameters of methods to describe which parameters should not be passed a null value.  </p>\n\n<p>Using static analysis of your code, <em>findbugs</em> can then point out locations where the method is called with a potentially null value.  </p>\n\n<p>This has two advantages:</p>\n\n<ol>\n<li>The annotation describes your intention for how the method should be called, aiding documentation</li>\n<li>FindBugs can point to potential problem callers of the method, allowing you to track down potential bugs.</li>\n</ol>\n\n<p>Only useful when you have access to the code that calls your methods, but that is usually the case.</p>\n'}, {'answer_id': 33679, 'author': 'Damien B', 'author_id': 3069, 'author_profile': 'https://Stackoverflow.com/users/3069', 'pm_score': 0, 'selected': False, 'text': "<p>In a Java way, assuming the null comes from a programming error (ie. should never go outside the testing phase), then leave the system throw it, or if there are side-effects reaching that point, check for null at the beginning and throw either IllegalArgumentException or NullPointerException.</p>\n\n<p>If the null could come from an actual <em>exception</em>al case but you don't want to use a checked exception for that, then you definitely want to go the IllegalArgumentException route at the beginning of the method.</p>\n"}, {'answer_id': 248687, 'author': 'Marcus Downing', 'author_id': 1000, 'author_profile': 'https://Stackoverflow.com/users/1000', 'pm_score': 1, 'selected': False, 'text': '<p>Since off-topic seems to have become the topic, Scala takes an interesting approach to this. All types are assumed to be not null, unless you explicity wrap it in an <code>Option</code> to indicate that it might be null. So:</p>\n\n<pre><code>//  allocate null\nvar name : Option[String]\nname = None\n\n//  allocate a value\nname = Any["Hello"]\n\n//  print the value if we can\nname match {\n  Any[x] =&gt; print x\n  _ =&gt; print "Nothing at all"\n}\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/32280', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3295/']