I usually try to encapsulate my code, meaning each objects works on its data via public methods. The problem is, that a lot of stakeholder/other objects of an object lead to a lot of requirements and thus a lot of methods in this object, which are then only used by one stakeholder. In such a scenario, should I rather pass the raw data to the stakeholder, so that it can process the data itself?
When should an object process its own data for other objects (offering methods) and when should it simply return its data (via getters) to let the caller do the processing itself?

- 484
- 3
- 18
-
If you have a piece of working code and would like feedback on this kind of thing (and/or any other aspect of the code), consider putting it up on [CodeReview.se]. Stack Overflow is usually about much more specific issues. – Mathieu Guindon Jul 09 '22 at 20:46
-
1It's a judgment call. If you feel that a method could have general use, write the method. If the request is oddly specific, your class should already have the getters for the requestor to use. – Gilbert Le Blanc Jul 09 '22 at 21:25
1 Answers
I think it depends on many factors such as:
- purpose of class (some real world object)
- data that object has (description of this object)
- desired behavior (some actions of this behavior)
For example, we have two objects:
- a big bucket with water
- kettle.
Then we can ask myself:
- can big bucket have method
boil()
or should big bucket just have methodgiveWater()
? So it can be concluded that bucket of water should just expose getter for exposing water for other users such as kettle
And by using this technique you can decide whether should an object process its own data for other objects (offering methods) and when should it simply return its data (via getters)
In addition, you should apply Single Responsibility Principle of SOLID in your classes. As Robert C. Martin says:
Martin defines a responsibility as a reason to change, and concludes that a class or module should have one, and only one, reason to be changed (e.g. rewritten).
So SRP defines a responsibility of a class as a reason to change, and states that a class might only have one reason to change.
So if someone edits logging code in class Radio
, then it means that she/he violates SRP principle. She/he should edit logging code in Log
class. These classes can communicate through references or composition.

- 36,391
- 15
- 88
- 148