Standardizing Accessors and Mutators in JavaScript

Implement consistent patterns for getters and setters to ensure reliable and understandable data manipulation in your code.

0 likes
46 views

Rule Content

# Standardizing Accessors and Mutators in JavaScript

## Description

Implement consistent patterns for getters and setters to ensure reliable and understandable data manipulation in your code.

## Category

JavaScript Cursor Rules

## Rules

- **Use Consistent Naming Conventions**
  - Prefix getter methods with `get` and setter methods with `set`.
    - Example: `getUserName()`, `setUserName(value)`.

- **Implement Getters and Setters for Encapsulation**
  - Use getters and setters to access and modify private properties, ensuring encapsulation and control over property access.
    - Example:
      ```javascript
      class User {
        #name;
        get name() {
          return this.#name;
        }
        set name(value) {
          this.#name = value;
        }
      }
      ```

- **Avoid Direct Property Access**
  - Do not access or modify object properties directly; always use the defined getters and setters.

- **Ensure Getters and Setters Are Pure Functions**
  - Getters should not have side effects; they should only return the value of the property.
  - Setters should only modify the property and not perform other operations.

- **Document Getters and Setters Thoroughly**
  - Provide clear documentation for each getter and setter, explaining their purpose and usage.

- **Use Type Annotations Where Applicable**
  - In TypeScript, specify the return type for getters and the parameter type for setters to enhance code clarity and maintainability.

- **Follow Consistent Error Handling in Setters**
  - Implement error handling within setters to manage invalid inputs gracefully.
    - Example:
      ```javascript
      set age(value) {
        if (value < 0) {
          throw new Error('Age cannot be negative');
        }
        this.#age = value;
      }
      ```

- **Adhere to the Principle of Least Privilege**
  - Expose only necessary getters and setters to limit access to internal object properties.

- **Ensure Consistency Across the Codebase**
  - Apply these conventions uniformly to maintain code readability and consistency.

## Rationale

Standardizing the use of getters and setters in JavaScript promotes encapsulation, enhances code readability, and ensures consistent data manipulation practices across the codebase.