How do I return flags and optional messages in Java?

I want to write a method in Java to verify whether some data exists for some conditions, confirm that the data is valid, or generate an appropriate error message

The problem is that we can't return multiple things from a method, so I want to know what the best solution is (in terms of readability and maintainability)

The first solution is easy, but we don't know what makes the check fail:

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
}

II. Solutions We have messages, but we are using exceptions in a way that we should not use (in addition, it should be domain specific checked exceptions, excessive overhead IMO):

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

The third scheme We have a detailed message, but the contract is not clean: we let the client check whether the string is empty (he needs to read 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();
}

Which solution would you recommend? Or have a better (hope!)?

(Note: I wrote this small example. My actual use case involves complex conditions of heterogeneous data, so don't pay attention to this specific example and put forward collections. Max (values) > maxvalue? "Out of range.": "Everything is fine.": -).)

Solution

If you need multiple values, you should return a simple class instance Here are some examples we use in some cases:

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;
    }
}

This uses a simple enumeration of types:

public enum ValidationType {
    OK,HINT,ERROR;
}

The verifier method may be as follows:

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

nothing more.

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
分享
二维码
< <上一篇
下一篇>>