How to elegantly check null check for java method parameter?

854 Views Asked by At

How to elegantly check null check for java method parameter?

I have code like this:

    public void updateAccount(String a, int b, double c, float d, List e, Set f, Map g, Collection h, Enum i ...String) {
        if(a != null && !a.isBlank()) {
            this.a = a;
        }
        if(b != null && !b.isBlank()) {
            this.b = b;
        }
        if(c != null && !c.isBlank()) {
            this.c = c;
        }
        if(d != null && !d.isBlank()) {
            this.d = d;
        }
        if(e != null && !e.isBlank()) {
            this.e = e;
        }
        if(f != null && !f.isBlank()) {
            this.f = f;
        }
        if(g != null && !g.isBlank()) {
            this.g = g;
        }
        if(h != null && !h.isBlank()) {
            this.h = h;
        }if(i != null && !i.isBlank()) {
            this.i = i;
        }
        ....
    }

All parameters are checked for null, and if not null, the value of the corresponding field is changed.

I feel that the above method is too hard-coded.

I'm wondering how I can turn this into more efficient code.

Best Regards!

1

There are 1 best solutions below

0
On

You can do null checks for the parameters using the following ways:

use @NonNull annotation from project lombok. For more information please refer to lombok documentation.

If you are using frameworks like Spring framework then Spring has an @NotNull annotation that leverages JSR-305 standard.

If you don't want to use any of the above solutions then you can as well using Optional.ofNullable() starting from java 8. You can check more about Optional class at: https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html