Either Design Pattern

Reading time:

2–3 minutes

Dear community, raising and handling class-based exceptions can quickly add complexity to source code. However, recognizing error situations and dealing with them appropriately is absolutely necessary to develop robust source code. The Either design pattern could be helpful in this context to reduce complexity.

The problem

Error handling based on TRY/CATCH/ENDTRY can quickly make a source code confusing. As a reader of a source code full of exceptions that are raised and handled, it is difficult to follow the happy path.

It can be hard to find the handling of an exception in a high-level module when exception is raised 3 levels deeper in another module. You can pass exceptions far up. A local context quickly becomes a global context, just because of error handling.

Either Design Pattern as a solution

One way to avoid the problem described above is to use the Either design pattern. It refers to the return of a method.

Either the method returns an object of the “Left” class (error) or an object of the “Right” class (expected return value). The method then no longer needs exceptions. The terms Left/Right are just a convention. They could also be called something else.

The caller of the respective method must check the return object after calling it. Either it is a Left object or a Right object. Left object means there was an error. Right object means everything went as expected and you are following the happy path.

Importance

This design is interesting because it forces the caller of a method to take a closer look at the result of the method call. Error handling therefore becomes local again and not a global matter as with passing on exceptions.

On the other hand, this comes at the cost of a more complex design that must be known to all developers in the team. Otherwise, exciting speculations quickly arise as to why the program was designed this way. This can be entertaining, but it costs time.

Example implementation

Furkan COSGUN has published an ABAP implementation for Either on GitHub.

I would like to take this opportunity to thank him for the time and effort he has invested. Without his implementation, which I happened to see on GitHub, I would probably never have noticed this interesting design. After a bit of research, Either seems to be more well-known in other programming languages ​​such as Java.

This also shows the value of GitHub. You always see interesting projects from other developers and learn something from them. That’s exactly why, dear readers: network.

Have fun coding

Michael