Java 8 avoids a large number of if / else statements

I have something that looks like this:

public boolean isValidObject(SomeObject obj){
    if(obj.getField() == null){
      LOG.error("error code 1");
      return false;
    }
    if(obj.getField().getSize() > 500){
      LOG.error("error code 2");
      return false;
    }
    ......
    if(someCondition()){
     log something
     return false;
    }

    return true;
}

What is the cleanest way to write this in Java 8 with Lambdas?

Solution

Use polymorphism for this purpose Create a class for each logical validator and link them to the list Here are the good answers you need:

public interface Validator<SomeObject>{
    public Result validate(SomeObject object);
}

Execution:

public class SomeFieldSizeValidator implements Validator<SomeObject> {

@Override
public Result validate(SomeObject obj) {
    // or you can return boolean true/false here if it's enough
    return obj.getField().getSize() > 500 ? Result.OK : Result.Failed;
    }
}

Call validation chain:

List<Validator> validators = ... create ArrayList of needed Validators
for (Validator v : validators) {
if (!v.validate(object)) { 
  ... throw exception,you kNow validator and object here
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>