gtap-dev / javascript

JavaScript Style Guide
MIT License
0 stars 0 forks source link

Remove or relax 3.5? #3

Closed mjomble closed 2 months ago

mjomble commented 3 years ago

Group your shorthand properties at the beginning of your object declaration.

Example code, based on an interface from react-base:

// Matches the "natural" order of the interface

const textField: ITextFieldProps = {
  id: 'aaa',
  label: 'bbb',
  value: fieldValue,
  onChange: handleChange,
  attributes: {
    placeholder: 'ccc',
    autoComplete: 'tel',
  },
  inputClassName: 'ddd',
}

// Extract attributes into variable, need to move it up

const textField: ITextFieldProps = {
  attributes,
  id: 'aaa',
  label: 'bbb',
  value: fieldValue,
  onChange: handleChange,
  inputClassName: 'ddd',
}

// Rename fieldValue and handleChange, need to move them up

const textField: ITextFieldProps = {
  value,
  onChange,
  attributes,
  id: 'aaa',
  label: 'bbb',
  inputClassName: 'ddd',
}

// Change value to an expression, need to move it down again

const textField: ITextFieldProps = {
  onChange,
  attributes,
  value: someCondition ? value : otherValue,
  id: 'aaa',
  label: 'bbb',
  inputClassName: 'ddd',
}

// Alternative: keeping the original field order

const textField: ITextFieldProps = {
  id: 'aaa',
  label: 'bbb',
  value: someCondition ? value : otherValue,
  onChange,
  attributes,
  inputClassName: 'ddd',
}

In my opinion, this rule can actually hurt readability, even though the goal is to improve it. Also, it seems annoying to maintain in code that changes over time.

It would be fine as a recommendation and may work perfectly in some examples, but I'd prefer not to make this a strict rule.

mihkeleidast commented 3 years ago

The changeset aspect of this is a great example - one of our other principles is that the git changesets should be as small and a simple as possible. This rule definitely hurts that aspect.

It would be nice if we could enforce the "natural order" of properties somehow though, as just the "naturality" part is subjective - maybe force them to be in the same order as in the interface definition? Or required (= more important) props first? WDYT?

mjomble commented 3 years ago

My preference would be to prefer interface definition order, but also allow exceptions.

For example, when an interface extends another, the "natural" order can be difficult to determine. The first members of the child interface may be more "important" than the last members of the parent interface, etc.

Any strict / automatically enforcable rules that try to cover all possibilities would probably become too complicated, so I'd leave this as a recommendation.