1

I have a class like this..

Class A {

    public void someNullCheckingMethod(Student stu) {

        if (stu.getName() != null) {
            String name = stu.getName();
        } else {
                // get name from other source(its something like 
                // fallback)
               }

        if (stu.getId() != null) {
            String id = stu.getId();
        } else {
                // get id from other source(its something like 
                // fallback)
               }

        if (stu.getAddress() != null) {
            String address = stu.getAddress();
        } else {
                // get address from other source(its something like 
                // fallback)
               }

        if (stu.getCity() != null) {
            String city = stu.getCity();
        } else {
                // get city from other source(its something like 
                // fallback)
               }

        if (stu.getGender() != null) {
            String gender = stu.getGender();
        } else {
                // get gender from other source(its something like 
                // fallback))
               }
    }
}

is there a way to avoid too many if statements? As you can see here I am checking null condition for each property but i don't want many checks to get desired result just want to reduce if conditions as well as want to get same desired result whatever I will get by putting all these if conditions.

  • 2
    Possible duplicate of [Avoiding != null statements](https://stackoverflow.com/questions/271526/avoiding-null-statements) – Ivar Aug 23 '18 at 10:15
  • 2
    Where have you put those `if` statements? The given example will not work since they are in the class, but not in a method or a constructor. – deHaar Aug 23 '18 at 10:15
  • 2
    Explaining the goal of your class, and maybe providing a bit more of context would help to come with a solution. – Benoit Aug 23 '18 at 10:18
  • 1
    Hello. Welcome to SO. As it is, your question is unclear. You should consider providing a more detailed example. To do so, I suggest you to take a look to the following documentation : [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) – Mickael Aug 23 '18 at 10:22
  • 1
    And why would you like to avoid the `if` statements? Does that have any thing to do with a coding rule violation? Or is it a simple matter of taste? In case it is, you can move on to another language such as *Kotlin* since *Java* is meant to be so ;) – tmarwen Aug 23 '18 at 10:50
  • Use annotations like `@NotNull` and try to avoid code duplication. Project Lombok can also help. – Guillaume F. Aug 23 '18 at 10:52
  • Your code does not compile - instances of type Object do not have method getName() etc. – tbsalling Aug 23 '18 at 10:54
  • Fighting all urges to say _use Kotlin_, lol. _If only the real world let you just switch languages whenever something gets nasty_. – Bassinator Aug 23 '18 at 12:35
  • Please give the complete context of the question. Based on your current code you even not require a null check – DEVAS Aug 23 '18 at 14:11

3 Answers3

2

Since you don't provide any context there's a few things you can do based on some assumptions.

Assumption one:
if the values are initialized as null

String name;
// or
String name = null;

Then you can just assign the values and ignore if the fields are null or not since the class members are null already.

String name = stu.getName(); // String name = "Some Name" OR null, depending on return value of method

Assumption two:
If you just want to avoid the if statements you can go with ternary operators

String name = stu.getName() != null ? stu.getName() : null; // Or some other default value

There are a few other methods that pops into my mind as well but without more context they are a bit useless at this point.

Brenin
  • 195
  • 1
  • 2
  • 16
0

If using an external library is an option, then you should take a look at Dozer or MapStruct.

tbsalling
  • 4,477
  • 4
  • 30
  • 51
0

You could at least reduce the "verbosity" with Optional.

String name;
if (stu.getName() != null) {
    name = stu.getName();
} else {
    name = "default"
}

Would become

String name = Optional.ofNullable(stu.getName()).orElse("default");

Th choice is yours to return an Optional directly from the POJO Student for any value that could be null.

This would give a cleaner solution :

String name = stu.getName().orElse("default");

If getName looks like :

public Optional<String> getName(){
    return Optional.ofNullable(name);
}
AxelH
  • 14,325
  • 2
  • 25
  • 55