Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
86 views
in Technique[技术] by (71.8m points)

java - What is a clean way to replace a wall of if-statements that only return false?

I'm writing a simple email verifier. I have a working solution, but it uses a wall of if-statements that all just return false. Is there a cleaner way or a design pattern for this kind of problem? (I only included the code I want to simplify)

if (prefix.length() == 0 || domain.length() == 0 || topLevelDomain.length() < 2) {  // if prefix or domain length == 0, or topLevelDomain < 2
    return false;
} else if (!isBuiltFrom(prefix, alpha + digit + special)) {  // if any char in prefix is not (a-z), (0-9), '_', '.' or '-' return false
    return false;
} else if (!isBuiltFrom(domain, alpha + digit + "-")) {  // if any char in domain is not (a-z), (0-9), or '-' return false
    return false;
} else if (!isBuiltFrom(topLevelDomain, alpha)) {  // if any char in topLevelDomain is not (a-z) return false
    return false;
} else if (special.contains("" + prefix.charAt(0))) {  // if prefix leading special char return false
    return false;
} else if (special.contains("" + email.charAt(prefixIndex - 1))) {  // if prefix trailing special char return false
    return false;
} else if (special.contains("" + domain.charAt(0))) {  // if domain leading special char return false
    return false;
} else if (special.contains("" + email.charAt(domainIndex - 1))) {  // if domain trailing special char return false
    return false;
}

return true;

question from:https://stackoverflow.com/questions/65929001/what-is-a-clean-way-to-replace-a-wall-of-if-statements-that-only-return-false

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
if (A) {
    return false;
} else if (B) {
    return false;
} else if (C) {
    return false;
} else if (D) {
    return false;
} else {
    return true;
}

Convert to:

return !A && !B && !C && !D;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...