dimanche 13 septembre 2020

Canonical Golang: use or not use else clause after then clause which returns

Is Golang opinionated about whether or not to use an else clause if the then clause returns?

In other words, is one or the other of the following two options considered canonical Golang?

Use else:

func IsLeapYear(year int) bool {
  if year%400 == 0 {
    return true
  } else if year%100 == 0 {
    return false
  } else if year%4 == 0 {
    return true
  } else {
    return false
  }
}

Don't use else:

func IsLeapYear(year int) bool {
  if year%400 == 0 {
    return true
  }
  if year%100 == 0 {
    return false
  }
  if year%4 == 0 {
    return true
  }
  return false
}

Apparently opinions about this can be strong: https://blog.mozilla.org/nnethercote/2009/08/31/no-else-after-return-considered-harmful/

Aucun commentaire:

Enregistrer un commentaire