loading...

re: Clean Code Applied to JavaScript — Part VI. Avoid Conditional Complexity VIEW POST

FULL DISCUSSION
 

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))
}

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?.()
}

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!

code of conduct - report abuse