I was wondering if there are any common conventions for a method that:
- returns a new instance of the same type of object;
- using the current instance's property values as the defaults;
- 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.
Such fluent interfaces often use
withas 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 usewithas 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.withmethod or thewithandwith…methods in classes of the upcoming Temporal proposal. For your case, it would typically beNode().withAkey(1).withBkey(1)orNode().with({aKey: 1, bKey: 1}).