6

Should ActiveRecord-based domain models have visible properties? Why or why not?

My experience and studies have always lead me to believe that object properties should always be protected, and that data should only be manipulated/accessed through methods. This ensures that if the internals of the class need to be refactored, other objects that rely on that object do not then also need to be refactored.

I often see domain models with publicly visible properties however, and the models can be passed to say view objects which directly access those properties while building the view. I have always thought that this is perhaps the one exception to the above mentioned rule, because otherwise you would basically have to create getters and setters for objects like the view to use, or some other equally troubling sounding solution. Perhaps I am wrong on this? I would like to get some feedback on the subject.

yannis
  • 39,547
  • 40
  • 183
  • 216
dqhendricks
  • 626
  • 1
  • 6
  • 12

2 Answers2

1

Public methods are extremely convenient and require less code, as you don't have to write the mutator methods. I'm guessing that reason Active Record models with public properties are common is that they are considered PODs (POJOs, POPOs, POCOS etc), DTOs or Value Objects.

But models typically carry behaviour and there's absolutely no reason, conceptual or otherwise, for any other class that carries behaviour to go against encapsulation. Unless you have very extreme performance considerations and want to keep everything as lightweight as possible I'd advice against exposing your properties.

My experience and studies have always lead me to believe that object properties should always be protected, and that data should only be manipulated/accessed through methods.

No, they should almost always be private, only declare them protected when you absolutely need to access them in a child class. Most of the times you can just use your getters in the child class instead, if in doubt go with private properties and public getters and setters, and if at some point in the future you need protected properties, just update your API.

Related questions:

yannis
  • 39,547
  • 40
  • 183
  • 216
1

I don't think your concern applies to Ruby or other languages that support properties. In Ruby, you can attach any desired behavior to the setting of a property, by defining an accessor. This affords clients a convenient syntax while giving the class designer complete control over the behavior. Set and get methods are unnecessary in Ruby.

kevin cline
  • 33,608
  • 3
  • 71
  • 142