7

In DOM, why is childNodes defined in the Node interface if only some node types such as Element, Document and DocumentFragement, can have childNodes?

Is this considered a good design? In what cases this is admissible? I mean, isn't this like defining a radius on an interface Shape even though we know that not every Shape has a radius?

Alfredo Osorio
  • 904
  • 1
  • 11
  • 18

3 Answers3

7

The simple reason why this is part of the spec is that it makes it much easier to traverse a DOM tree. You can always iterate over a Node's childNodes, even if there aren't any. Otherwise, you'd need to determine the Node's type at each point in the traversal.

The reason why this is okay is that childNodes has a logical and meaningful value for non-Elements: an empty collection. On the other hand, in your radius example, whatever value it might have for non-ellipses is completely meaningless.

Cyanfish
  • 816
  • 6
  • 9
3

Who says only Elements can have child nodes? There are a bunch of node types, and several of them can have children. Obvious examples include Document and DocumentFragment, neither of which are Elements, but both of which have child nodes.

Ross Patterson
  • 10,277
  • 34
  • 43
0

The Composite Pattern has two variations:

  • The abstract Component (parent class of leafs and composites) only includes methods that make sense on a single item.
  • The abstract Component also includes the methods of the Composite, i.e. of a collection of items.

Remember that the purpose of the composite pattern is to treat single items and collections of such items in an uniform way. Given an appropriate structure, the composite methods can be implemented in a way that have some meaning even on leafs. E.g. in the context of the DOM, a text node has no childs, and can return an empty NodeList.

This 2nd variation of the Composite pattern isn't always applicable, but it can increase the elegance of the design in some cases (I would still have designed the DOM without this quirk).

amon
  • 132,749
  • 27
  • 279
  • 375