Sinan
Sinan

Reputation: 463

Software good practices - set and get methods

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:

  1. declaring a protected instance variables in the superclass and let the subclass uses them.
  2. declaring a private instance variables in the superclass with public getter methods to let the subclass inherits the getter methods from the superclass.

Upvotes: 0

Views: 253

Answers (4)

Watt
Watt

Reputation: 3164

I pick 1 mostly when I am going to create an abstract class.

Otherwise, I always pick 2 (creating getter/setter). Because:

  1. 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.

  2. Decouple the classes.

Any good book on Object Oriented Programming will list other benefits of using getter and setter.

Upvotes: 1

FlavorScape
FlavorScape

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

Alp
Alp

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

Bernard
Bernard

Reputation: 7961

Both methods are acceptable. Normally, I would have public getter/setter methods since anyone can use them, not just subclasses.

Upvotes: 1

Related Questions