Is NULL arguments a bad practice?

39,941

Solution 1

It's fine, in cases when there are too many overloaded methods. So instead of having all combinations of parameters, you allow some of them to be null. But if you do so, document this explicitly with

@param foo foo description. Can be null

In your case I'd have the two methods, where the first one invokes the second with a null argument. It makes the API more usable.

There is no strict line where to stop overloading and where to start relying on nullable parameters. It's a matter of preference. But note that thus your method with the most params will allow some of them to be nullable, so document this as well.


Also note that a preferred way to cope with multiple constructor parameters is via a Builder. So instead of:

public Foo(String bar, String baz, int fooo, double barr, String asd);

where each of the arguments is optional, you can have:

Foo foo = new FooBuilder().setBar(bar).setFooo(fooo).build();

Solution 2

I use a very simple rule:

Never allow null as an argument or return value on a public method.

I make use of Optional and Preconditions or AOP to enforce that rule. This decision already saved me tons of hours bugfixing after NPE's or strange behaviour.

Solution 3

It's common practice, but there are ways of making your code clearer - avoiding null checks in sometimes, or moving them elsewhere. Look up the null object pattern - it may well be exactly what you need: http://en.m.wikipedia.org/wiki/Null_Object_pattern?wasRedirected=true

Solution 4

The rule is: simple interface, complicated implementation.

Design decisions about your API should be made by considering how the client code is likely to use it. If you expect to see either

getAllCompaniesList(null);

or

if (companyFilter == null) {
    getAllCompaniesList();
} else {
    getAllCompaniesList(companyFilter);
}

then you're doing it wrong. If the likely use-case is that the client code will, at the time it is written, either have or not have a filter, you should supply two entry points; if that decision is likely not made until run-time, allow a null argument.

Solution 5

Another approach that may be workable may be to have a CompanyFilter interface with an companyIsIncluded(Company) method that accepts a Company and returns true or false to say whether any company should be included. Company could implement the interface so that companyIsIncluded method's behavior mirrored equals(), but one could easily have a singleton CompanyFilter.AllCompanies whose companyIsIncluded() method would always return true. Using that approach, there's no need to pass a null value--just pass a reference to the AllComapnies singleton.

Share:
39,941
Maddy.Shik
Author by

Maddy.Shik

Updated on July 09, 2022

Comments

  • Maddy.Shik
    Maddy.Shik almost 2 years

    Is it a bad practice to pass NULL argument to methods or in other words should we have method definitions which allow NULL argument as valid argument.

    Suppose i want two method 1. to retrieve list of all of companies 2. to retrieve list of companies based upon filter.

    We can either have two methods like as below

        List<Company> getAllCompaniesList();
        List<Company> getCompaniesList(Company companyFilter);
    

    or we can have one single method

        List<Company> getCompaniesList(Company companyFilter);
    

    here in second case, if argument is NULL then method return list of all of companies.

    Beside question of good practice practically i see one more issue with later approach which is explained below.

    I am implementing Spring AOP, in which i want to have some checks on arguments like 1. Is argument NULL ? 2. is size of collection 0?

    There are some scenarios where we can not have null argument at all like for method

        void addBranches(int companyId, List<Branch>);
    

    This check can be performed very well by using Spring AOP by defining method like following

    @Before(argNames="args", value="execution(* *)")
    void beforeCall(JoinPoint joinPoint ,Object[] args )
    { 
               foreach(Object obj in args)
               {
                     if(obj == NULL)
                     {
                         throw new Exception("Argument NULL");
                     } 
               }   
    }
    

    But problem i am facing is since i have defined some of methods which should accept NULL argument for multiple functionality of one single method as mentioned above for method List getCompaniesList(Company companyFilter); So i can not apply AOP uniformly for all of methods and neither some expression for methods name match will be useful here.

    Please let me know if more information is required or problem is not descriptive enough.

    Thanks for reading my problem and giving thought upon it.