Code Design - What would you choose?

Lucian Ghinda - Aug 29 - - Dev Community

Context

Consider a list of predicates for an object and the fact that there is a logical priority of considering them.

This is just an example, so please do not focus on the requirements themselves.

If an account is _archived_ or _closed_ then that is the final status (**Archived** 
or **Closed**) and everything else should be ignored. 
Eg: 
- An account _not verified_ and _closed_ is **Closed**
- An account _not verified_ and _archived_ is **Archived**

If an account is _active_ and _not verified_ the status should be **ActionRequired**.
Else if the account is _active_ and _verified_ the status should be **Completed**.
Enter fullscreen mode Exit fullscreen mode

Case statement vs if/else

Example of case statement and if/else implementation

Left side contains a case statement without a case condition and the right side the same logic implemented with if/else.

Which one do you prefer and why?

Case Statement vs Early Returns/Guard-like clauses

Example of case statement and guard clause implementation

Here is an alternative (right side) using guard clauses instead of if/else.

Which one do you prefer and why?

Multiple statuses

Image with code sample about multiple statuses

What if there are more statuses to take into consideration?

Which one do you prefer and why?

My preference

Somehow, for me, the case statement makes more sense when I take into consideration:

  • the order in how the conditions are assessed
  • it is a bit more open to add more statuses
  • I somehow feel a bit uneasy after using 2 guard clauses (or early returns) in a method
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player