Search code examples
javascriptimmutabilitynaming

Naming convention for a method that create a new object from the current instance but modifies some properties


I was wondering if there are any common conventions for a method that:

  1. returns a new instance of the same type of object;
  2. using the current instance's property values as the defaults;
  3. while changing at least one of the property values.

Example

E.g. If this method were called foo on a class Node, then:

class MyNode {

  constructor({aKey, bKey}) {
    this.aKey = aKey ?? 0
    this.bKey = bKey ?? 0
  }

  /* The method I'm not sure how to name: */
  foo({aKey, bKey}) {
    return new MyNode({
      aKey: aKey ?? this.aKey, // use this instance's value as a fallback.
      bKey: bKey ?? this.bKey
    })
  }

}

const nodeA = new Node({aKey: 1}); 
console.log(nodeA) 
// {aKey: 1, bKey: 0}

const nodeB = nodeA.foo({bKey: 1});
console.log(nodeB);
// {aKey: 1, bKey: 1}

Alternatively, if anyone has a suggestion for a better way to avoid mutating the objects while using existing instances to create new instances, I'd be equally interested in alternative approaches.


Solution

  • Such fluent interfaces often use with as a method name prefix. This convention is explicitly documented for the Java Date-Time API, but can be found in many APIs. It might be related to languages that use with as a keyword in their syntax for record updates (e.g. C#, OCaml), though there's also many languages with immutable record types that don't use a keyword in their syntax (e.g. Haskell, Elm, Rust).

    The convention is also used in JavaScript, see e.g. the native Array.prototype.with method or the with and with… methods in classes of the upcoming Temporal proposal. For your case, it would typically be Node().withAkey(1).withBkey(1) or Node().with({aKey: 1, bKey: 1}).