Multiple return paths

Some argue that you shouldn’t have multiple return paths within our code. What are the benefits of having just one entry and one exit point?

Readability

You will keep the flow simple by having just one entry point and one exit point where the result is returned. In this case the code will be easy to read: you can simply read where the value is changed and where the end result is expected.

Controlling your object lifetime cycle

The main origin of the argue having only one return path, has its origin at languages like C or C++. In these languages you actually have to allocate memory when you want to use an instance of an object and deallocate it when you don’t need it anymore. If you forget the last one, you end up with memory leaks. Let’s say you create the instance and after that you return a value when some condition isn’t met. In this case, the line where your object is deallocated will not be called anymore.

A valid use: checking preconditions

A valid point where you could enter multiple return paths is at the beginning of a method, where you check the preconditions of your method. If a user of your method passes invalid arguments, you can quickly return a default value then have additional checks in your code.

 

Posted in Best practices, C#, C++ at June 12th, 2018. No Comments.