Skip to content

Latest commit

 

History

History
57 lines (35 loc) · 2.16 KB

no-get-with-default.md

File metadata and controls

57 lines (35 loc) · 2.16 KB

no-get-with-default

✅ The "extends": "plugin:ember/recommended" property in a configuration file enables this rule.

🔧 The --fix option on the command line can automatically fix some of the problems reported by this rule.

This rule attempts to catch and prevent the use of getWithDefault.

Rule Details

Even though the behavior for getWithDefault is more defined such that it only falls back to the default value on undefined, its inconsistency with the native || is confusing to many developers who assume otherwise. Instead, this rule encourages developers to use:

  • || operator
  • ternary operator

In addition, Nullish Coalescing Operator ?? will land in the JavaScript language soon so developers can leverage safe property access with native support instead of using getWithDefault. But note that ?? checks for either undefined or null whereas getWithDefault only checks for undefined.

Examples

Examples of incorrect code for this rule:

const test = this.getWithDefault('key', []);
import { getWithDefault } from '@ember/object';

const test = getWithDefault(this, 'key', []);

Examples of correct code for this rule:

const test = this.key === undefined ? [] : this.key;
// the behavior of this is different because `test` would be assigned `[]` on any falsy value instead of on only `undefined`.
const test = this.key || [];

Configuration

This rule takes an optional object containing:

  • boolean -- catchSafeObjects -- whether the rule should catch non-this imported usages like getWithDefault(person, 'name', '') (default true)
  • boolean -- catchUnsafeObjects -- whether the rule should catch non-this usages like person.getWithDefault('name', '') even though we don't know for sure if person is an Ember object (default true)

References

  • RFC to deprecate getWithDefault
  • spec

Related Rules