How to return flag plus optional message in Java?

I want to write a method in Java that checks that some conditions are stored on some data, and confirms that the data is valid or generates the corresponding error message otherwise.

The problem is that we cannot return more than one method from the method, so I wonder what is the best solution (in terms of readability and maintainability).

First decision. Easy, but we can’t know what exactly made us check:

boolean verifyLimits1(Set<Integer> values, int maxValue) {
    for (Integer value : values) {
        if (value > maxValue) {
            return false; // Out of limits
        }
    }
    return true; // All values are OK
}

The second solution. We have a message, but we use exceptions in such a way that we should not (besides, probably, this should be a domain dependent exception, too many service IMOs):

void verifyLimits2(Set<Integer> values, int maxValue) {
    for (Integer value : values) {
        if (value > maxValue) {
            throw new IllegalArgumentException("The value " + value + " exceeds the maximum value");
        }
    }
}

. , : , ( javadoc).

String verifyLimits3(Set<Integer> values, int maxValue) {
    StringBuilder builder = new StringBuilder();
    for (Integer value : values) {
        if (value > maxValue) {
            builder.append("The value " + value + " exceeds the maximum value/n");
        }
    }
    return builder.toString();
}

? (?)?

(: , , Collections.max(values) > maxValue ? "Out of range." : "All fine.": -).)

+3
11

, . , :

public class Validation {
    private String          text    = null;
    private ValidationType  type    = ValidationType.OK;

    public Validation(String text, ValidationType type) {
        super();
        this.text = text;
        this.type = type;
    }
    public String getText() {
        return text;
    }
    public ValidationType getType() {
        return type;
    }
}

:

public enum ValidationType {
    OK, HINT, ERROR;
}

:

public Validation validateSomething() {
    if (condition) {
        return new Validation("msg.key", ValidationType.ERROR);
    }
    return new Validation(null, ValidationType.OK);
}

.

+7

: VerificationResult . boolean status String message, , . , String, boolean, a VerificationResult.

, , . .


:

, , , a boolean , . String whatWentWrongLastTime(), false. concurrency .., "" .

, , , java.util.Scanner, IOException ( ). , - " ", ioException(), IOException null .

+5

IllegalArgumentException - , : (), . IAE .

, .

+4

- Status:

 public class Status {
   public final static Status OK = new Status("OK");
   private String message;
   public Status(String message) { this.message = message; }
   public String getMessage() { return message; }
 }

, Status.OK, .

 public Status validate(Integer input, int maxValue){
   if (input > maxValue) {
     return new Status(
         String.format("%s value out of limits (maxValue=%s)", input, maxValue);
   }

   return Status.OK;
 }

:

 Status status = validate(i, 512);
 if (status != Status.OK) {
   // handle the error
 }
+3

, "false", -, . verifyLimits , , "false".

 class VerifyLimitsResult{
       //Ignore get, set methods
        Integer maxValue;
        Integer value;

        public VerifyLimitsResult(Integer maxValue, Integer value) {
           this.maxValue = maxValue;
           this.value = value;
        }

        public boolean isOK(){
           return value==null;
        }

        public String getValidationInfo(){
           if(isOK()){
              return "Fine";
           }else{
              return "The value " + value + " exceeds the maximum value/n"
           }
        }
 }
....
VerifyLimitsResult verifyLimits4(Set<Integer> values, int maxValue) {

         for (Integer value : values) {
             if (value > maxValue) {
                   return new VerifyLimitsResult(maxValue, value);  
            }
        }
         return new VerifyLimitsResult(maxValue, null);  
}
+1

, , . RuntimeException; , , . , (?) -, , . , .

, , . , , ", " ( ). , , ! , , .

+1

, , < interface.

interface , :

// A simple listener to be implemented by the calling method.
public interface OutOfLimitListener {
    // Called whenever a limit is violated.
    public void outOfLimit(int value, int maxValue);

    // ... Add additional results as parameters
    // ... Add additional states as methods
}

/ . , . antother , .

. , :

private boolean verifyLimits(Set<Integer> values, int maxValue, OutOfLimitListener listener) {
    boolean result = true; // Assume all values are OK
    for (Integer value : values) {
        if (value > maxValue) {
            listener.outOfLimit(value, maxValue);
            result = false; // At least one was out of limits
        }
    }
    return result;
}

, , , :

@Test
public final void test() throws IOException, InterruptedException {
    // Make up a test set of random numbers
    Set<Integer> testSet = new HashSet<Integer>();
    for(int i=0; i<10; i++) testSet.add((int) (Math.random() * 100));

    // Implement the interface once with appropriate reaction to an out-of-limit condition      
    OutOfLimitListener listener = new OutOfLimitListener() {
        @Override
        public void outOfLimit(int value, int maxValue) {
            System.out.printf("The value %d exceeds the maximum value %d\n", value, maxValue);
        }
    };

    // Call verification
    verifyLimits(testSet, 50, listener);
}

Android . , .

+1

, RuntimeException.

0

, HashMap, . HashMap .

0

( IllegalArgumentException, ).

, ( - - ), , , / .

0

, , ...

, .

0
source

Source: https://habr.com/ru/post/1761071/


All Articles