Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid write code like "XXX!=null" or "XXX!=null || XXX.isEmpty" [duplicate]

I am writing codes that query the database to get the data. There are some classes that consist of Lists, but sometime the list or other attribute can not be initiated and their value is null, so I need to write list!=null || list.isEmpty or attribute != null, before I can use the attribute.

Unfortunately, it easy to forget it, and I really think it is ugly to do it every time when I operate an attribute. I am going to write some code to explain it.

public class SpotVo {
    private Double avg;

    private String brief;

    private ArrayList<HotelVo> hotels;

    private int id;

    private ArrayList<byte[]> images;

    private AddressVo location;

    private String name;

    private ArrayList<RestaurantVo> restaurants;
}

As you can see, there are some lists and other attributes in this class, there can all be null or empty, can I do something to avoid it?

like image 367
ssj Avatar asked May 25 '13 02:05

ssj


1 Answers

The answer depends on whether null has a special meaning. For example for a String field does your application need to distinguish between null and ""? For a Collection-valued field does it need to distinguish between null and an empty collection object?

If the answer is "no", then you could write your "data object" classes to normalize the nulls to the respective "in band" values. You could do this in the getters or the setters or the constructors, depending on exactly how the objects are materialized from the database.

A couple of other things you could do are:

  • Change the database schema to make the respective columns "not null".

  • If you are using an ORM or a data binding mechanism, try to configure that (via annotations or whatever) to use the "in band" values instead of null.

The point of turning null into "" or an empty array or collection is that you don't need to treat the "in band" value as a special case ... unless the business logic of your application specifically requires this.

In short, if you stamp out the null values systematically, you don't need to test for them in the business logic.


Note that this approach doesn't always work. The case that annoys me is fetching parameters from an HTTPRequest object in a servlet:

  • The application potentially has to deal with 4 distinct cases:

    • parameter not present

    • parameter present with no value / an empty value

    • parameter present with a non-empty value

    • parameter present multiple times.

  • The parameters are being fetched from a standard API rather than a custom class that could be made to normalize the values according to the webapp's requirements.

like image 106
Stephen C Avatar answered Oct 03 '22 23:10

Stephen C