ModeShape

An open-source, federated content repository

To check or not to check (parameters)?

Some topics in software development are all about preferences and personal choices, and so it is with checking method parameters. When is it worth the extra developer time and execution time to check that the parameters of a method adhere to the expectations of the implementation?

What would you want to happen if you passed in a bad value to a method in some library? Would you want some cryptic exception thrown from the bowels of the library? No, chances are you’d rather get an immediate IllegalArgumentException telling you why your value is bad. Plus, you’d like to read in the JavaDocs what is considered a good (or bad) value for each parameter, and what happens when bad values are used.

Not all code has the luxury of a well-defined public API, where developers can focus on providing meaningful messages and documentation for a limited set of “public” methods. Open source libraries rarely have much control over what classes can be used. And maybe we don’t have to document much at all – can’t the developer using the library just look at the source?

My view is that developers should spend a little extra time to make life easier for their customers. This means good documentation and meaningful parameter checks for (most) methods that will or are likely to be used by clients. If you don’t make your source available to your customers, then your documentation probably needs to be “great”, not just “good”.

So what do we do on JBoss DNA? Well, we don’t really have a well-defined “public API” – we want our customers and users to be able to use JBoss DNA in ways that make sense for them, and that may include extending the behavior by writing a new implementation of an interface, using a small component by itself. In short, they’ll probably use our software in ways we don’t anticipate. Our philosophy is to try to be as helpful as possible, because a little bit of work on our part can make it a lot easier for our customers. So most of the time we’ll check the parameters, but in times where we don’t (because of performance, because a method is protected or private, or because there’s a good reason not to) we’ll still document what the method expects.

To make our lives easier, we’ve created a utility to help us to write simple and readable code that checks parameter values and throws meaningful exceptions when a value isn’t valid. Since JBoss DNA is internationalized, all exception messages should be internationalized, and this utility does this, too. So, we can write code like this:

    /**
     * Set the configuration for this component.
     * @param config the new configuration
     * @throws IllegalArgumentException if <code>config</code> is null
     */
    public void setConfiguration( Configuration config ) {
        ArgCheck.isNotNull(config, "config");
        ...
    }

This trivial example shows a couple of things. First, the call to ArgCheck.isNotNull is pretty readable. (In hindsight, CheckArg.isNotNull(config,"config") may have been a better choice. There are other patterns that are even more readable, but then you start trading off performance for readability.) Other examples of ArgCheck methods include isPositive, isNotEmpty, hasSizeOfAtLeast, isGreaterThan, and containsNoNulls. Of course, there are many more.

Second, the ArgCheck methods will internationalize the exception message, so we pass the variable name (which should match the JavaDoc) as the second parameter to isNotNull(...) so that the exception message is meaningful. In this case, the English localization for the message would be “The config parameter may not be null”.

Third, the JavaDoc uses @throws to document the condition when an IllegalArgumentException will be thrown, and we chosen to not duplicate that in the corresponding @param. (Then, in cases where we don’t check the parameter, we don’t put a @throws and we do put the assumption in the @param. For example, “@param config the new configuration; may not be null.“)

When do we not use ArgCheck? We don’t often check parameters in protected methods, since we often have much more control over how the methods are called. And we never need to check parameters of private methods. And some public methods are called so frequently that even the overhead of checking the arguments is not worth it, but in these cases we also try to explicitly say this in the methods’ JavaDoc.

So, in general, we check a lot of our method parameters. What do you do?

Advertisements

Filed under: techniques

6 Responses

  1. Shams says:

    Well I do the same thing for my public methods, only that I don’t bother with i18n, my methods take var args Objects to concatenate Strings to form messages, and my class is named Validator 🙂

  2. Randall says:

    Hiding the construction of the message (and whether or not you i18n the message) is one of the benefits of having a utility like “ArgCheck” (or “Validator”). And, I definitely concede that that IllegalArgumentExceptions may not really <>need<> to be internationalized, since they <>should<> be thrown only during development. I prefer the consistency (and safety, in case an exceptions do happen outside of development).

  3. Wanderlei says:

    why not commons validator? http://commons.apache.org/validator/ I use Commons Validator for public methods and assertions for low visibility methods (private, default and protected).

  4. Randall says:

    We looked at Commons Validator, but there were a couple of reasons why we didn’t use it for checking parameters.The first was that it seemed to solve a different problem. Maybe I’m wrong, but I understood the primary purpose of Commons Validator to be validating JavaBeans and other object instances, not for checking parameters of methods. Commons Validator seems to do object validation pretty well. So even if you did use it for parameter validation, it seems to us to be too heavyweight. You have to create an instance in each method. And since it’s not thread safe, you can’t share a static instance. Our utility is all static, and designed to not do anything complicated (like create the error message) until we know we need it. The thought being that we can use it more often than not, and not pay as little as possible in terms of performance. Again, maybe I’m missing something.Third, it seems overly complex (for parameter checking) to need an XML configuration file. Commons Validator is flexible, but more than we need.Finally, we internationalize our exception messages. For more, see < HREF="http://jbossdna.blogspot.com/2008/08/internationalization-in-jboss-dna.html" REL="nofollow">a later post<>.

  5. Martin J says:

    I’ve gotten used to meticiously check the arguments to public methods throughout my code base if applicable. I’d like my methods to fail-fast if there’s no way that the method can possibly succeed without valid arguments. I usually use Spring’s Assert class or Google Collection’s Objects and Preconditions utility classes (or even those of Commons Lang) because I don’t need to bother with internationalization in most cases. I usually wrap them in classes of my own though to reduce dependencies on third party libraries.@randall: What do you mean by “since they should be thrown only during deveopment”? I think throwing IllegalArgumentException is not strictly reserved for use during development. If you want to check the validity of you method arguments I think it’s the perfect exception type. Some people may throw NullPointerException. I find myself doing this more and more …Martin

  6. Randall says:

    @martin_j – What I meant is that I’d rather find out I’m using a method badly <>during testing and development<> as opposed to production. Doesn’t mean it never happens in production, just that I’d rather it happen in my testing.Again, validating method parameters is just throwing a meaningful exception in place of the certain runtime exception that would occur later on. Validating (user or input) data, such as with Commons Validator, is different and has to happen in production.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

ModeShape is

a lightweight, fast, pluggable, open-source JCR repository that federates and unifies content from multiple systems, including files systems, databases, data grids, other repositories, etc.

Use the JCR API to access the information you already have, or use it like a conventional JCR system (just with more ways to persist your content).

ModeShape used to be 'JBoss DNA'. It's the same project, same community, same license, and same software.

ModeShape

Topics

%d bloggers like this: