Phil CK

Early Return

Last updated on

I find C++ code can be bad for this, but early bailing can lead to cleaner code.

Consider this contrived example.

void
some_func(int a, int b, int c) {
  if(a) {
    if(b > 2) {
      if(c != a) {
        call_func();
      }
    }
  }
}

This maybe personal pref but I find its easier to read when we don’t nest everything. but I’ve seen 2000 line functions that are nested like the previous example and they are not easier to read.

void
some_func(int a, int b, int c) {
  if(!a) { return }
  if(b <=2 ) { return }
  if(c == a) { return }

  call_func();
}