Reputation: 463
I want to get my head around the idea of using setters and getters in superclass and subclass in terms of software good practices. From your experience, which method of the below are appropriate and also promote good software re-usability:
Upvotes: 0
Views: 253
Reputation: 3164
I pick 1 mostly when I am going to create an abstract class.
Otherwise, I always pick 2 (creating getter/setter). Because:
Not only that avoid any accidental/unintended modification to class's member variable, it also help when you will go about creating jUnit test-cases for your classes.
Decouple the classes.
Any good book on Object Oriented Programming will list other benefits of using getter and setter.
Upvotes: 1
Reputation: 14299
Depends on your style of coding. Some prefer concise code over more verbose structured code. If your ultimate goal is interoperability and scalability, you're 'safer' using getters/setters. Another advantage is with the getters/setters you can perform multiple operations instead of only a single operation, for instance getUsers() may actually tabulate multiple data rows. This way you can consolidate that operation instead having to repeat it in subclasses.
Use your best judgement. If the values are simple booleans or strings, probably don't need a g/s. If they're query related or make specific, repeated modifications to state or data, use a g/s approach.
Upvotes: 3
Reputation: 29739
I pick number 1. That's exactly the situation where the existence of protected
is justified. Getters and setters are for classes using another non-related class.
Upvotes: 1
Reputation: 7961
Both methods are acceptable. Normally, I would have public getter/setter methods since anyone can use them, not just subclasses.
Upvotes: 1