class A {
    B bObject;

class B {
    private List<SomeType> list;
    public List getList() {return list;}
    public void foo(int i) {
       list.get(i).someTypeMethod(); // 2 dots

class SomeType {
    public void someTypeMethod() {}

Suppose I want to call get on the list from bObject in class A. Should I simply call getList().get(3), or maybe it's better to rewrite a method in the B class that retrieves or adds the element at the specified position from/in the list?

In general, if class B field wasn't a List, but some other class C, should B prevent class A from calling C methods directly?

2 Answers 2


You can follow the Law of Demeter.

You mostly want to avoid having 2 or more '.' in your methods. You try to avoid calls like 'a.b.c.d.e' which are known as train wrecks.

  • 1
    its not a simple as counting '.'s though e.g. fluent interfaces are fine
    – jk.
    Apr 1, 2016 at 9:29
  • @jk. I'd call the multiple '.'s a codesmell, you should think twice about your code if you're using it. For fluent API's it's fine yes.
    – Carra
    Apr 1, 2016 at 9:51
  • What about the case where I have a List holding some objects in my class and have to call a method of one object from the collection? First I need to call get(i) and then the method - I need 2 dots for it. Apr 1, 2016 at 9:56
  • 1
    If for example B has a List<Person> the 'correct way' to do it would be to add a method in B GetPerson(Id x).
    – Carra
    Apr 1, 2016 at 9:58
  • 1
    @user4205580 class B already knows about your SomeType so it's fine for B to access SomeTypeMethod via list.get(i). But If you need to write list.get(i) several times in B, then this potentially violates the DRY principle. It would not be a bad thing to implement SomeType Get(id) method in class B - even if its a private method. Apr 1, 2016 at 19:10

This is perfectly fine if you don't need specific rules to control the content of the list.

if you have some specific logic to implements for adding/removing item, then you shouldn't expose the getter on the list and expose only add/remove/find/iterator methods in order to protect your list.

Another solution could be to extends an existing type of List (who said ArrayList ? :)) And override add/remove/.. method to add your logic here. So in B class you stay with the getList().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.