Should I create an object outside of a hierarchy, or pass arguments to create it inside?

StackOverflow https://stackoverflow.com/questions/22274505

  •  11-06-2023
  •  | 
  •  

Question

I couldn't find a similar question so I'm asking my own. I'm sorry if this is actually a duplicate question. (Also, although I tagged this question with Java, it is more of a general OOP question)

Say I have a class hierarchy like this: a manager class called "RestaurantManager" which has "Restaurants" which have "Dishes".

When creating a Restaurant or a Dish, should I create them outside of the RestaurantManager or pass the arguments to the Manager so it can instantiate the objects inside?

In other words, should I do this:

RestaurantManager manager;
manager.addRestaurant(new Restaurant(name));

Or this:

RestaurantManager manager;
manager.addRestaurant(name);

And what if the RestaurantManager has an internal identifier for the Restaurant, or the Dishes?

This is more of a good practice kind of question, but what is the best option?

Was it helpful?

Solution

There is no universal "best" options - both approaches have their pluses and minuses.

The first approach lets you extend hierarchy by additional subclassing (e.g. you can define class Diner extends Restaurant and class FastFoodPlace extends Restaurant, and pass them to your RestaurantManager. You can also change the signature of the constructors of your Restaurant without consequences in the RestaurantManager's methods.

The second approach lets RestaurantManager "own" the implementation of Restaurant from the caller, hiding it from outside view behind some interfaces. Among other things, it lets RestaurantManager decide if a Restaurant is to have a key or not, when and how that key is set, and so on.

You pick one or the other approach based on your needs. The first approach offers more flexibility outside the RestaurantManager, while the second approach offers better encapsulation inside RestaurantManager. The coupling between the manager and the hierarchy becomes tighter, which makes extending the hierarchy harder.

OTHER TIPS

I think your first example makes more sense for OOP, as it actually passes a Restaurant to addRestaurant. And moreover, lets users of the class more control of the objects in your class hierarchy. It can also allow users to pass any subclasses of Restaurant to the constructor.

For the second only usable scenario that occurs to me is that you, for some reason, want to hide the classes your manager uses.

I cannot say any of those two are better than the another, but I think first one is more common.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top