简体   繁体   中英

Functional Programming function cadence

I have a software project where I have a bunch of functions that check one thing. So the code looks like this:

 const isRed = color => color === 'red;; const isBlue = color => color === 'blue'; function whichColour(color){ if(isRed(color){ return 'X' } if(isBlue(color){ return 'Y' } } 

This is just an example and the application has ALOT more of these functions that check one thing. I thought having all of these functions, that do one thing, is in accordance with functional programming paradigms.

However recently I have been thinking it would be better to do this:

 const isColor = (color, targetColor) => color === targetColor; function whichColor(color){ if(isColor(color, 'red'){ return 'X' } if(isColor(color, 'blue')){ return 'Y' } } 

I think they are both just as readable, as you can see the desired value, and it would save a lot of space because I truly do have a lot of these little functions. However, I am not sure which is actually better.

Let me know what you think.

The better approach is the one that reduces the amount of duplicated code in general, since it leaves the code neater and more approachable most of the times. So the second way is the one that I would go with in this case. The only change that I would suggest to do is to name the method sameColor or colorMatch .

const colors = {
    red: 'X',
    blue: 'Y',
    green: 'Z',
    // a lot of other colors
}

function whichColor(color) {
    return colors[color]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM