mercredi 2 octobre 2019

Architecture - Should an object implement its behavior or we (other class) should control the object's behavior?

Dear Development Masters and Software Ninjas!

Recently, I started to feel the insuperable desire to make the architecture of my code better, therefore, I started to read books and articles about it. It turned out that it's an infinitely complex and large topic with an infinite number of approaches and architectural patterns to different types of problems, so I even feel a little lost now. Today I'd like to ask for at least some sharing of your understanding and experience.

The question is should an object implements its own behavior (I mean inside its class) or we should state only the data in the object's class and process the required behavior in a separate class (like in the ECS pattern)?

Let me give an example to avoid misunderstanding. Imagine we have some objects on the screen (no matter which ones — game objects, UI elements, etc). When the mouse cursor is over an object it does some action (a game object can be rendered with the outline, a UI element can be highlighted, etc). The question is should an object itself process the required behavior (a game object adds/removes the outline itself, a UI element adds/removes highlighting itself) or we should have some other class (like System in ECS) which, for example, serves as the event manager which controls the mouse events and processes these events (e.g. mouse cursor entered the area over object 1 -> do something, mouse cursor left the area over object 1 -> do something, etc)

The problem of my understanding is both of these approaches (and an infinite number of others) are applicable and have their own pros and cons. However, how to peak the right choice and what is better — I cannot understand. For example, in the former approach in the example above, everything is in one place and the class itself responsible for its behavior. In the latter example, the object holds only data and doesn't depend on the implementation of particular actions? which means that we can change the processing logic without the need to change the object.

I will be infinitely thankful for any advice. And thank you for your time.

Regards, Ivan.

P.S. ECS pattern here serves only as an example since it demonstrates the differences among approaches quite well.

Aucun commentaire:

Enregistrer un commentaire