encapsulation - Should objects know about their users in certain cases? -


i'm laying out foundations potential game, i'm having trouble designing classes encapsulated yet efficient.

generally, people objects should rely little on each other preserve modularity , encapsulation.

however, seems convenient have object know each other.

let's have class called dog.

public class dog {    public void eat() { ... }   public void wagtail() { ... }  } 

dogs have owners, there dog owner class.

public class dogowner {   private dog dog;    public dog getdog() { return dog; }   public void petdog() { ... }   public void takedogforwalk() { ... } } 

now, if have dog, don't have owner? seems make sense make getowner() method dog.

public class dog {   private dogowner owner;    public void eat() { ... }   public void wagtail() { ... }   public dogowner getowner() { return owner; }  } 

however, gives dog information dogowner, seems violate information hiding. seems create redundancy, because dog has dogowner, , dogowner has dog.

another way find owner through owners, , find corresponding dog. though not create dependency of dog , dogowner, seems lot more expensive needs be, because have cycle through owners.

so, alright dog have getowner() method? if not, other alternatives there efficiently access owner if dog known?

"should rely little" - as needed, not more, not less.

of course dog can have link owner. asked alternatives: one, carry dog , owner information together, when lots of code doesn't care owner. two, if have dog , don't know owner, can't ask owner. have hash table mapping dogs owners, might store dog owner. or have database of dog owners , scan owner of dog - not scaleable.


Comments

Popular posts from this blog

OpenCV OpenCL: Convert Mat to Bitmap in JNI Layer for Android -

android - org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope -

python - How to remove the Xframe Options header in django? -