Tell Don't Ask
Published on

Imperative vs Declarative naming

Authors

Arrange

The most common issue with naming during code reviews, besides awful ones like one letter or using singular for a lists, relates to developers using imperative naming for properties. And that happens while building a modal component.

export default {
  data() {
    return {
      show: false,
    }
  },

  methods: {
    hide() {
      this.show = false
    },
    show() {
      this.show = true
    }
  }
}

First sign of a problem should be that you have a property and method named the same. By naming it the same you increase the chance of typing show when you want to do show() and the other way around. Not to mention the confusion you bring to the code and other developers.

When you say show it sounds like a command, like an action that you can execute to change something inside an object.

What some developers do to fix it is rename show property to shown. While it is correct, someone could still mistype it cause only one letter separates them apart.

export default {
  data() {
    return {
      shown: false,
    }
  },

  methods: {
    hide() {
      this.shown = false
    },
    show() {
      this.shown = true
    }
  }
}

Act

Let's find a declarative alternative.

In those situations best thing to do if you can not come up with a synonym is to go to thesaurus site and type in the shown and check the results. Maybe the best option is not found straight away, so you can click through a few suggestions until you find what is better suited for your scenario. So in this case if you click on displayed it will present you with what is a better option, visible. So let's swap in visible into our code example.

export default {
  data() {
    return {
      visible: false,
    }
  },

  methods: {
    hide() {
      this.visible = false
    },
    show() {
      this.visible = true
    }
  }
}

It is way better. What about the scenarios when you can not find a better option. In those cases it is best to add some prefix to increase the difference between a method and a property. Good option would be to prefix the shown with is so it becomes isShown.

export default {
  data() {
    return {
      isShown: false,
    }
  },

  methods: {
    hide() {
      this.isShown = false
    },
    show() {
      this.isShown = true
    }
  }
}

Good prefixes for boolean properties are is or has.

It can feel a bit repetitive if you have a private property, and you have to expose a method that will be used for decision-making outside that object.

protected bool $isVisible = false;

public function isVisible(): bool
{
  return $this->isVisible;
}

It is still better than using imperative style to name properties.

Assert

Long story short, use imperative to name the methods, and declarative to name the properties that represent the internal state of the object.