Skip to content
Advertisement

Refactoring code that contains multiple if conditions

Here is some code I’ve written to save a UrlEntity :

JavaScript

The above code exists in a service class and looks unnecessarily complex. I’m attempting to refactor so that the intent is clear. This is a basic refactoring I’ve written:

JavaScript

This refactoring does not improve the code substantially. Is there a code pattern or idiomatic way to refactor the method saveUrlEntity? I’m using Java11

Advertisement

Answer

This is very subjective, but… Since most of your if statements are guard/short-circuit clauses, which throw or return, there is no need to use else. I think this simple change makes the code much more readable.

JavaScript

I’d also recommend replacing urlEntity.size() > 0 with !urlEntity.isEmpty().

The method does seem to be doing several things, which violates the Single Responsibility Principle; you might want to think about breaking that out better.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement