Who should know about something else?

I always run into confusion with someone who needs to know about something else.

eg:

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

or Draw(&canvas, &circle)

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

or even

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

I think that in the end I am "abstracting" too much where I have all kinds of adapters, so no one knows about anyone.

+6
source share
3 answers

Depending on who has experience.

If you can only draw circles, then of course you can just put this in a Canvas and be on your way. If Canvas has a method for drawing general Shape s, then it falls into various subclasses of Shape for drawing. For example, a circle probably knows how to draw itself on a canvas. I doubt that the canvas initially knows how to draw a circle, unless you code a feature that kills the whole idea of ​​polymorphism.

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

+8
source

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

Does it make sense for someone who knows how to draw themselves? perhaps. It is also possible that something else knows how to draw it. If the object is a graphic object, it probably should know how to draw itself.

As for things like preservation, again, it depends ... it may be useful for things to know how to serialize themselves to an abstraction, like a stream, but it’s also sometimes better not to associate entities with trivial issues like serialization ....

+2
source

For classes that you create, you usually get them to do their job. A Circle will be drawn on a Canvas , so a Rectangle . Thus, if they are all subclasses of Shape , they can draw themselves through the Shape interface. This is the same for saving. It is extensible - you do not need to guess all possible forms when developing the Canvas class.

For the “it depends” cases, for me, utility methods are usually used for classes already defined by some library. For example, save / load commonly used STL data structures, such as map, set, vector, etc .; through the File utility class with static methods.

0
source

Source: https://habr.com/ru/post/902171/


All Articles