DEV Community

Discussion on: Probably the hottest code refactoring you ever saw πŸ”₯

Collapse
 
bsaad profile image
bsaad •

Great post, I like how you took the time to explain step by step.

I'd suggest also the following change to make the "business rules" clearer by extracting them from the formatting logic:

const formatMap = {
  uk: ["zip", "suburb", "city", "state"],
  us: ["city", "state", "zip"],
  nz: ["zip", "city", "county", "state"],
  default: ["zip", "suburb", "state", "county"],
}

const formatAddress = (address) => { 
  const format = formatMap[address.countryCode] || formatMap.default;
  return format.map(field => address[field]).filter(Boolean).join(', ');
};
Collapse
 
ancientswordrage profile image
AncientSwordRage •

This is the final image in a magneto_perfection.jog meme. I love it.

Collapse
 
kamalhm profile image
Kamal •

this is also what i like to do whenever a switch case appears

Collapse
 
faezshaeran profile image
Faiz Shahiran •

this is nice.. considering formatMap value can be saved in config file or database. Its easier to scale.

Collapse
 
kelerchian profile image
Alan • • Edited

Unless formatMap is something that needs to be dynamic, I suggest not to do this.

This mixes up type and data and also smells like premature abstraction.

Collapse
 
potouridisio profile image
Ioannis Potouridis •

Well one way or another the formatAddress function needs to know the business rules. If I went with your approach I would pass the rules as an argument.

Collapse
 
tomazfernandes profile image
Tomaz Fernandes •

I’d never seen this pattern in JS, looks just as nice as in Java πŸ‘πŸΌπŸ‘πŸΌ

Collapse
 
tomazfernandes profile image
Tomaz Fernandes •

Actually I’ve just written a post about this kind of pattern, if you’d like to take a look:
dev.to/tomazlemos/keeping-your-cod...

Collapse
 
potouridisio profile image
Ioannis Potouridis •

Thanks for sharing this. πŸ™