I have a quick question on best practice and if getters and setters are the best option in a specific case. The case is when I have class ‘A’ instantiating classes ‘B’ and ‘C’. Class A contains public getters and setters for classes B and C to access so data is centralised.
Is this best practice or would it be best to pass the data to classes B and C through parameters?
Thanks
Chris
The short answer: it depends
The long one: if you B and C classes encapsulate data and/or functionality that might be useful outside of the class A and A is “only” client of B and C, let them be instantiable independent of A and set into A with setters like
setA/setB. This way other classes can possible use B and C for whatever reason. You could also take advantage of inheritance where instances with enhanced functionality get induced into class A during runtime (for example through Inversion of Control frameworks like JohnReeeves stated).If they only make sense in the context of class A, encapsulate functionality that only A directly uses, hide them from the outside world and parametrize by means of class A methods/properties. This gives you the freedom to change implementation of B and C so that no code outside get upset. A is a public interface so to say, B and C are internal implementation.
And generally the more you can hide from your implementation the better, let the outside world know only as little as it neccessarily needs to know to function properly.
So think about the extact goal of A, B and C, their relationship to each other and to the outside world and make you decision.