DEV Community

Cover image for Clean Code Applied to JavaScript — Part VI. Avoid Conditional Complexity

Clean Code Applied to JavaScript — Part VI. Avoid Conditional Complexity

Carlos Caballero on January 10, 2020

Introduction Conditional complexity causes code to be more complicated to understand and therefore to maintain. In addition, conditional...
Collapse
 
josemunoz profile image
José Muñoz

Very good patterns, the only thing that I would like to add is that the null-object pattern is rendered obsolete with conditional chaining, i.e: animal?.sound() will return null if the object is null or if it doesn't have the property, IMO it keeps things DRY. Polymorphism is a concept from OO, this and the last pattern can be both solved with object literals (which is already a part of the command pattern), consider the following:

function logMessage(message = "CRITICAL::The system ...") {
    const [level, messageLog] = message.split("::");
    const handler = param => {
        NOTICE: `notice: ${param}`
        CRITICAL: `critical: ${param}`
        CATASTROPHE: `catastrophe: ${param}`
    }[level]

    console.log(handler(messageLog))
}
Enter fullscreen mode Exit fullscreen mode

the same could be applied to polymorphism but I don't know where the type value is coming from, maybe if you're already using objects then polymorphism is the right choice, however mostly any switch can be replace with an object literal, in conjunction with optional chaining you could safely have a switch that doesn't break when you pass an invalid type, i.e:

Auto.prototype.getProperty = () => {
  const handler = {
    BIKE: this.getBaseProperty
    CAR: () => this.getBaseProperty() - this.getLoadFactor()
    BUS: () => this.isNailed ? 0 : this.getBaseProperty(this.voltage)
  }[this.type]

  return handler?.()
}
Enter fullscreen mode Exit fullscreen mode

but then again, if you're using classes you might want its own separate entity instead like illustrated in the article, I have found that its not very common in JS since classes tend to be verbose, these are only my opinions based on anecdotal evidence of course, great series!

Collapse
 
swarupkm profile image
Swarup Kumar Mahapatra • Edited

I think the whole intent of this article is "let the client code/ calling code do the if/switch and pass on messages"...
Conditionals can be delegated IMO, but cannot be eliminated.