Avoiding semantic coupling with Java Collection interfaces

These days I am reading the Code Complete book and I’ve passed the part about coupling-levels (simple-data-parameter, simple-object, object-parameter and semantic coupling). Semantic being the “worst” kind:

The most insidious kind of coupling occurs when one module
makes use not of some syntactic element ofanother module but of some semantic
knowledge of another module’s inner workings.

The examples in the book usually lead to run-time failures, and are typical bad code, but today I had a situation that I’m really not sure how to treat.

First I had a class, let’s call it Provider fetching some data and returning a List of Foo‘s.

class Provider
   public List<Foo> getFoos()
      ArrayList<Foo> foos = createFoos();//some processing here where I create the objects
      return foos;

A consuming class executes an algorithm, processing the Foo‘s, merging or removing from the List based on some attributes, not really important. The algorithm does all of it’s processing with the head of the list. So there is a lot of operations reading/removing/adding to the head.

(I just realized I could have made the algorithm looking like merge sort, recursively calling it on halves of an array, but that doesn’t answer my question 🙂 )

I noticed I’m returning an ArrayList so I changed the providing class’ getFoos method to return an LinkedList. The ArrayList has O(n) complexity with head removals, while LinkedList has constant complexity. But it then struck me that I am possibly making a semantic dependency. The code will certainly work with both implementations of List, there are no side-effects, but the performance will also be degraded. And I wrote both classes so I can easily understand, but what if a colleague had to do implement the algorithm, or if he uses the Provider as a source for another algorithm which favors random access. If he doesn’t bother with the internals, like he should not, I would mess up his algorithm performance.

Declaring the method to return LinkedList is also possible, but what about the “program to interface” principle?

Is there any way to handle this situation, or my design has flaws in the roots?

Source: oop

Leave a Reply