javaarraylistrefactoringlaw-of-demeter

Preserving Law of Demeter with ArrayLists


If I have an ArrayList of objects then any time I need to call any method on a member of the ArrayList I need to do it like this:

list.get(i).doSomething();

This looks suspiciously like a Law of Demeter violation. I can not see any way of getting around this. Is this fine or should I rethink how I do things like this. Is the ArrayList an object defined to ignore the Law of Demeter?


Solution

  • It is not a violation.

    If you had a class

    Class A {
        private B b1, b2, b3;
    
        ...
    
       private void method() {
           b1.doSomething();
           b2.doSomething();
           b3.doSomething();
       }
    }
    

    there is no violation. If we collect the instance of B into a List<B> you get

    Class A {
        private List<B> listOfB;
    
        ...
    
       private void method() {
           listOfB.forEach(B::doSomething);
       }
    }
    

    Using an List<B> to hold the instances of B results in no tighter coupling between A and B.