Home > database >  How do I refactor nest if-statements for this block of code?
How do I refactor nest if-statements for this block of code?

Time:11-08

In what way can I refactor nested if statements like this? A condition is met, however there are some exceptions to the condition. I recognize that this starts to approach the Arrow Anti-Pattern.

Specifically, are there any dart language features that can help me refactor or re-write this code to be more clear?

Let's use "leap years" as an example:

// on every year that is evenly divisible by 4
//   except every year that is evenly divisible by 100
//     unless the year is also evenly divisible by 400
bool isLeapYear(int year) {
  assert(!year.isNegative);
  if (year % 4 == 0) {
    if (year % 100 == 0) {
      if (year % 400 == 0) {
        return true;
      }
      return false;
    }
    return true;
  }
  return false;
}

CodePudding user response:

Here is one way you could refactor the code:

bool isLeapYear(int year) {
  assert(!year.isNegative);
  return year % 4 == 0 && year % 100 != 0 ||
      year % 4 == 0 && year % 100 == 0 && year % 400 == 0;
}

CodePudding user response:

You are combining boolean checks with boolean returns. That probably means you can do it all in one expression.

I'd do:

bool isLeapYear(int year) => 
    year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);

(Now, if you want to optimize, then modulo, %, is more expensive than bitwise and, &, so you can also do:

bool isLeapYear(int year) =>
  year & 3 == 0 && (year & 15 == 0 || year % 100 != 0);

which should be slightly more efficient.)

  •  Tags:  
  • dart
  • Related