Bill Mol
Bill Mol

Reputation: 31

code readability / habitual practice / design pattern?

I have been analyzing some classes that can be sumarized like this:

public class RulerFather {
    private Girl girl;
    private Pet  pet;

    public  RulerFather()
    {
        girl = new Girl(this);
        pet  = new Pet(this);
    }

    /*
     *  allowed messages between Girl and Pet   
     */
    public feedPet()
    {
        pet.receiveFood();
    }

    public lickGirl()
    {
        girl.beLicked();
    }
}
public class Girl {
    Father father;
    public Girl(Father father)
    {
        this.father = father;
    }
...

Father instantiates girl and pet, and defines allowed messages that can be exchanged. E.g. in the code of Girl, she can feed the pet (send a message to the pet) by doing:

father.feedPet();

I mean, objects created by father can exchange messages but only using the method provided by father, so father is kind of "ruler" defining which methods are allowed to exchange between them (at that level of interaction).

My question is, in the code I analyzed, I saw a mixture between the mentioned above and another way that is just making the references of girl and pet public instead of private (this leads to freedom and some confusion as girl can call any method of pet, in some way RulerFather defines a number of valid interactions between girl and pet during the scope of the objects created by RulerFather).

Is this related to any recommended coding practice ? (or perhaps even a design pattern i do not know?)

Upvotes: 0

Views: 61

Answers (1)

GhostCat
GhostCat

Reputation: 140467

It is an interesting approach, albeit leading to several issues:

  • cyclic dependencies: the father class knows the two subclasses, and vice versa. So the three make up a pretty strange triangle
  • implicit coupling: the girl class understands that there is a father that probably has a pet

Yet, this is one way of reducing interfaces. Sometimes, you end up with legacy classes that can't be changed, but that offer too many methods for a new usage. Then you need a reasonable way to provide a view with reduced "scope". But the approach works by somehow duplicating code: the father class defines its completely own interface!

Beyond that, I don't recognize a specific pattern here.

In order to mitigate the issues I touched on, you would definitely look into using interfaces. So all classes should implement their own interface, and no implementation class knows anything about other implementation classes. Maybe with the sole exception of the code that has to know what impl classes to instantiate for the different interface types.

Upvotes: 1

Related Questions