-1

There's an interesting category of objects I've seen in jQuery and some other DOM tree traversal libraries.

A traditional way of mutating nodes in a tree would work in some way like this:

Elements matches = tree.findAll(condition);
for(Element e in matches) {
    if (condition2(e)) {
        e.setText("Hello");
    }
}

...or by using second-order functions:

tree.findAll(condition)
    .filter(condition2)
    .forEach(e -> e.setText("Hello"));

In those examples, there's an explicit distinction between the collection and the element. However, the type of object I'm talking about instead blurs the line by behaving both as if they're a collection and individal, mutatable elements.

tree.findAll(condition)
    .filter(condition2)
    .setText("Hello"); // Affects all matched nodes, if any

These objects essentially abstract away the concept of plurality. If the object is empty, all mutations are no-ops. If there are multiple elements, it automatically iterates through them and performs the appropriate operation on all of them. Operations that only make sense for individual elements, like String s = matches.getText() tend to, in some well-defined way, choose a specific element (such as the first one) to call.

My question is if there's some proper terminology to refer to these types of, for lack of a better term, "plurality-agnostic" objects.

3

These are simply instances of the Composite design pattern, which makes collections or structures of similar things behave as if they were a single thing.

  • This does indeed appear to the generalized form of what I'm talking about. Thank you. – Smallhacker May 11 '18 at 13:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.