是否有可能重构并完全避免使用if else else语句以获得更好的可读性

时间:2016-11-30 20:30:04

标签: javascript

是否有可能重构并完全避免使用if else else语句以获得更好的可读性。例如:

 function canIWatch(age) {
if (age < 6 && age > 0) return "You are not allowed to watch Deadpool after 6:00pm.";
else if (age >=6 && age < 17) return "You must be accompanied by a guardian who is 21 or older.";
else if (age >=17 && age < 25) return "You are allowed to watch Deadpool, right after you show some ID.";
else if (age >= 25 && age < 50 ) return "Yay! You can watch Deadpool with no strings attached!";
else if (age >= 50) return " You are too old to watch deadpool";
else return "Invalid age."
}

如何在没有这么多if else语句的情况下编写更清晰的代码

2 个答案:

答案 0 :(得分:6)

您可以更改检查并以最小值开始并跳过else部分,因为您返回。

function canIWatch(age) {
  if (age < 0) {
      return "Invalid age."
  }
  if (age < 6) {
      return "You are not allowed to watch Deadpool after 6:00pm.";
  }
  if (age < 17) {
      return "You must be accompanied by a guardian who is 21 or older.";
  }
  if (age < 25) {
      return "You are allowed to watch Deadpool, right after you show some ID.";
  }
  if (age < 50) {
      return "Yay! You can watch Deadpool with no strings attached!";
  }
  return "You are too old to watch deadpool";
}

console.log(canIWatch(-1));
console.log(canIWatch(2));
console.log(canIWatch(8));
console.log(canIWatch(20));
console.log(canIWatch(28));
console.log(canIWatch(60));

另一种解决方案是使用带有对象的数组

function canIWatch(age) {
    var terms = [
            { age: 0, text: "Invalid age." },
            { age: 6, text: "You are not allowed to watch Deadpool after 6:00pm." },
            { age: 17, text: "You must be accompanied by a guardian who is 21 or older." },
            { age: 25, text: "You are allowed to watch Deadpool, right after you show some ID." },
            { age: 50, text: "Yay! You can watch Deadpool with no strings attached!" },
            { age: Infinity, text: "You are too old to watch deadpool" },
        ],
        text;

    terms.every(function (a) {
        text = a.text;
        return a.age <= age;
    });
    return text;
}

console.log(canIWatch(-1));
console.log(canIWatch(2));
console.log(canIWatch(8));
console.log(canIWatch(20));
console.log(canIWatch(28));
console.log(canIWatch(60));

答案 1 :(得分:1)

事实上你使用了返回,你应该至少避免使用其他,但仅使用

  function canIWatch(age) {
    if (age < 6 && age > 0) return "You are not allowed to watch Deadpool after 6:00pm.";
    if (age >=6 && age < 17) return "You must be accompanied by a guardian who is 21 or older.";
    if (age >=17 && age < 25) return "You are allowed to watch Deadpool, right after you show some ID.";
    if (age >= 25 && age < 50 ) return "Yay! You can watch Deadpool with no strings attached!";
    if (age >= 50) return " You are too old to watch deadpool"; 
    return "Invalid age."
  }