-3

How to avoid multiple null checks, if need do something after the each check or how best to handle these checks? java 8+

public void method(Object obj){
    if (Objects.nonNull(obj.getA())) {
        do something;
    }
    if (Objects.nonNull(obj.getB())) {
        do something;       
    }
    if (Objects.nonNull(obj.getC())) {
        do something;
    }
    do something;
}
  • 6
    There's no alternative to null checks in Java8. You have to do it explicitly. Anyway `obj.getA() != null` seems much simpler and succinct than what you have used above. – Ravindra Ranwala Dec 08 '20 at 11:53
  • I can't see anything wrong with it idiomatically, except it does not compile. – terrorrussia-keeps-killing Dec 08 '20 at 11:57
  • Well, you could use some form of loop to check the elements and a lambda to handle those that are null. Whether that makes sense depends on your requirements. One thing you could try (without a custom method) is something like this (conceptually): `Arrays.asList(obj.getA(), obj.getB(), ...).stream().filter(e -> e == null).foreach(e -> /*do something*/)`. – Thomas Dec 08 '20 at 12:00
  • 1
    @Thomas Please, no... :) Streams are not the answer. There are so many useless objects created there for no functional reason. And if they were, you should use Objects::nonNull as the predicate instead of creating a new lambda. – Torben Dec 08 '20 at 12:06
  • So you want to avoid something that is inherently part of your program logic? You mean you are searching for a different syntax for the same thing. If you want to know if the code itself can be optimized, in a sense that a check can truly be avoided, then you need to provide more context: What is the code doing? What is `obj`? What is each branch doing? And so on. – akuzminykh Dec 08 '20 at 12:21
  • @Torben yes I agree :) - that's why I added that "conceptually". The better way would be to use a plain old foreach with varargs and a single lambda. Btw, `Objects::nunNull` would be the wrong one in that case since I wanted to get only those that are null. :D – Thomas Dec 08 '20 at 12:30
  • 1
    @Thomas instead of `Arrays.asList(obj.getA(), obj.getB(), ...).stream()` you can write `Stream.of(obj.getA(), obj.getB(), ...)` – Holger Dec 09 '20 at 13:05
  • @Holger yes that's what I thought but at a quick glance at the API I didn't spot the varargs version of that method so I settled for the more complex one - still it was just to convey an idea and not meant to be used as is. :) – Thomas Dec 09 '20 at 13:39

1 Answers1

0

I am not very clear on your query but you can use the Optional class from Java8 for the null check.

    dataType value=(dataType) Optional.of(obj).orElse(put some value);
garima garg
  • 308
  • 1
  • 8