Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Who should know about the other?

Tags:

c++

oop

I always run into confusion with who should know about the other.

for example:

Circle.Draw(&canvas) or Canvas.Draw(&circle)

or Draw(&canvas, &circle)

EmployeeVector.Save(&file) or File.Save(&employee_vector)

or even still

  void operator() (Employee e) { Save( e.Serialize();}
  for_each(employees.begin(), employees.end(),File)

I think I end up "abstracting" too much where I have all kinds of adapters so nobody knows about anybody.

like image 337
Joe McGrath Avatar asked Nov 23 '11 04:11

Joe McGrath


People also ask

Why is knowing other people important?

The skill of understanding others helps us predict what people might feel in a certain situation, but it also allows us to make sense of how people react.


2 Answers

Depends on who has the expertise.

If the only thing you can draw are circles, then of course you could just put that in Canvas and be on your way. If Canvas has a method to draw generic Shapes, then it falls on the various subclasses of Shape to draw themselves. For instance, a circle surely knows how to draw itself on a canvas. I doubt a canvas knows natively how to draw a circle, unless you hardcode the functionality, which kinda kills the whole idea of polymorphism.

For the same reasons, a vector would probably know how to save itself to a file, but I doubt a file knows what to do with a vector. But a vector can contain a variety of things, so it should delegate most of the work to its actual elements. So the for_each idea is probably the best.

like image 146
Etienne de Martel Avatar answered Sep 21 '22 22:09

Etienne de Martel


Like most design questions, the answer is, it depends. :-)

Is it meaningful for something to know how to draw itself? possibly. It's also equally possibly that something else knows how to draw it. If the object is a graphical entity, it probably should know how to draw itself.

As for things like saving, again, it depends... it can be good for things to know how to serialize themselves to an abstraction like a stream, but also, sometimes, it's better not to couple entities to such trivial matters like serialization....

like image 26
Keith Nicholas Avatar answered Sep 21 '22 22:09

Keith Nicholas