Refactor if…else condition right now — Code reviewer

Kesavan
2 min readApr 20, 2023

--

In one of my existing projects, there was quite a bit of filtering of records. For the Filtering of records, we used multiple if…else conditions. the filter condition got reached the last line of the visual studio code and the code got checked in waiting for code review.

One fine Friday after having heavy lunch got a comment from the code reviewer

Heavy lunch side effect.

Refactor if…else condition right now “ and the filter should be dynamic in nature and add a filter of “=” (equals).

Was a bit confused about how to refactor code without breaking the existing workflow.

yes me too, after reading you will be confused. Please read further

Please find below my sample dirty example:

function getMovies(movieParams){
if(movieParams.type === ‘NewMovies’)
{
NewMovies();
}
else if(movieParams.type === ‘OldMovies’){};
else if(movieParams.type === ‘RetroMovies’){};
// else if never ends
}

The next day a geek present in me came up with a solution of using a factory pattern.

Now, let me explain the below implementation. Instead of using the if…else condition replaced with the object of movie_collection. based on “movieParam.type” respective movies will be retrieved.

If I am going to add a filter of “=” (equals) as it is a comment from my code reviewer we have added it buildNewMovies function. Based on “movieParams.Operation” the required filter will be applied before hitting the service/API call.

function getMovies(movieParams){
var movie_collection = {
‘NewMovies’: buildNewMovies

}

movieParams.map(function(movieParam) {
var movieBuilder = movie_collection[movieParam.type];
return movieBuilder(param);
});
}

function buildNewMovies(movieParams){

var movieOperations = {
“equals”: buildNewMovieWhichMatches
“notequals”: buildNewMovieNotMatches
}

return movieFilterOperation = movieOperations(movieParams.Operation);
}

function buildNewMovieNotMatches(movieParams) { // call service with movie-params query }
function buildNewMovieMatches(movieParams) { // call service with movie-params query }

Thanks for reading till now with patience.

--

--

Kesavan

.NET developer with good experience in JavaScript and trying to convince people javascript as my primary skill