Violation of the principle of uniform responsibility in Iterator from the Java kernel

Why does java.util.Iterator interface have remove() method?

Of course, sometimes this method is necessary, and they are all used to its presence. But in fact, the main and only goal of the iterator is simply to provide access container elements. And when someone wants to create their own implementation for this interface, and is unable or unwilling for some reason to provide the ability to delete an element, then he is forced to throw an UnsupportedOperationException . And throwing this exception usually indicates not too thought out architecture or some design flaws.

In fact, I do not understand the reasons for this decision. And I think it would be more appropriate to split a specific helper interface to support an optional method:

diagram

Any reasoned version, why remove() is part of Iterator ? Is this an example of a direct violation of SOLID sole responsibility SOLID ?

+7
java iterator oop design-patterns solid-principles
source share
3 answers

In addition to the fantastic technical answers ... please see also the schedule. The “principle of shared responsibility” was coined by Robert Martin at some point in the mid / late 90s.

The Java iterator interface came with Java 1.2; therefore, around 1998.

It is very possible that people at Sun never heard of this concept while working on early Java releases.

Of course, many smart people have the same ideas without reading a book about it ... therefore a good designer could implement "SRP" without knowing about "SRP", but it also requires a high degree of awareness to reveal all the big and small violations of this rule ...

+6
source share

This design decision is explained in the Java Collections API APIs . In particular, see the first question about why collections do not support immutability and require additional operations instead. The short answer is that they did not want an “explosion” in the number of interfaces.

+3
source share

There seems to be a confusion of semantics. Robert C. Martin defines shared responsibility as "the only reason for change" ( SRP.pdf ), and not as "doing only one thing." SRP is very strongly associated with cohesion: a software module should contain only those functions that are functionally related to each other.

Given these things, I don’t think that using the remove method included in Iterator violates SRP. Removing an element is often something you might want to do, iterating over the elements; operations are essentially integer. In addition, the ability to delete items through Iterator makes the Iterable interface (which was added in Java 5) much more powerful. This feature is used, for example, by many of the methods in the Guava Iterables utility class .

Read more about the history of this term in this excellent article by Uncle Bob himself.

+2
source share

All Articles