Suppose you have a class that is frequently (or even exclusively) used as part of a linked list. Is it an anti-pattern to place the linkage information within the object?
For example:
public class Item
{
private Item prev;
private Item next;
...
}
An often-cited recommendation is to simply use a generic container class (such as java.util.LinkedList in Java), but this creates the overhead of having a separate node object (and the linked object cannot readily refer to its siblings).
Thoughts?
It is not necessarily an anti-pattern. Anti-patterns must have negative side-effects to earn the right to the “anti”.
For example, a
Nodein aTreedata structure would need it’s linkage cached inside of theNode. Anything else would violate the much more important concept of encapsulation and localization of data and code based on responsibility of the object.On the other hand, a
Customerdata structure that embeds its “next” customer would imply that theCustomerdata structure is handling two unrelated responsibilities, that of maintaining theCustomerdata, and that of maintaining theCustomer‘s list data structure. In such a scenario, the two responsibilities could intermingle in ways that impact the ease of maintenance; and hence, would be seen as an anti-pattern.