Alexis Pister
Alexis Pister

Reputation: 499

What behaviors should be in and out of the class

Let's say I have a class modeling some kind of object, for example a graph (in the graph theory sense).

I will have the graph structure and data inside the class, but what about other more complex behaviors? For example, I want to create a function that transforms the graph in a specific way, or that dumps the graph in JSON format. Should these functions be inside or outside the class?

My first thought is to put these kinds of functions inside the class, but if I put a lot of functions, each graph object will take way more memory right?

Are there clear guidelines for this question ? Also, is it language dependant?

Upvotes: 0

Views: 28

Answers (1)

Cosmin Ioniță
Cosmin Ioniță

Reputation: 4055

There are not strong guidelines around this AFAIK, apart from OOP principles.

The function that dumps the graph in JSON format should be part of the class, because it directly uses the graph data-structure (which should be private), so instead of exposing that externally and using a different class to convert the graph to JSON, it's more convenient to have a method like graph.toJson() and get JSON string.

On the same idea, if you want to transform a graph into a tree, or to balance a tree, it's more convenient to call graph.toTree() or tree.balance(), so methods should be part of the class.

Generically, I would add the functionality outside of the class, only when it can be re-used and it doesn't depend on the internal state of the class.

When you add multiple methods on a class, this doesn't mean the object consumes more memory. Memory gets allocated when the method is called. When you just pass around graph objects, the main memory will be allocated by the graph data-structure.

Upvotes: 1

Related Questions