I'm writing some code and the handy tool from CodeClimate, let me know that I have too many return values.
I intentionally did the multiple return values to make the code easier to read but I agree, too many return values.
A clean and simple way to fix that is to change it over to an "every" method.
I put my conditions in to an array and with the assumption that all should return true.
const shouldInitialize = (moreForPromotionService) => {
const urlSearchParams = new URLSearchParams(window.location.search);
const params = Object.fromEntries(urlSearchParams.entries());
if (params.triggerMoreForPromotionsService) {
return true;
}
if (window?.isChina) {
return false;
}
if (window?.isEurope) {
return false;
}
return !!document.querySelector(moreForPromotionService.mountingPoint));
Here it is after my refactor.
const shouldInitialize = () => {
const urlSearchParams = new URLSearchParams(window.location.search);
const params = Object.fromEntries(urlSearchParams.entries());
const conditions = [
(
!!params.triggerMoreForPromotionsService
|| !!document.querySelector(MoreForPromotionsService.mountingPointInit)
),
!window?.isChina,
!window?.isEurope,
];
return conditions.every((condition) => condition);
};
What are you thoughts? Better solution, please let’s see it!
Top comments (2)
The functionality between the original code and the refactored one differs. The refactored version is needlessly complex and less performant.
The original code had the following decision tree:
Return
true
iftrue
andOtherwise return
false
.The decision tree for the refactored version looks like this:
Return
true
iffalse
.Otherwise return
false
.Either way, this allows us to restructure the original conditions into a single return statement
And the refactored decision tree:
How do you like it?
If you want my advice:
Well you’re right! I was caught in a rush and it shows. I appreciate an in depth walk through.