2

In recent reading, I see conflicting recommendations on encapsulation methods and OOP best practices.

I am beginning development of a series of PHP classes that will be used to transport and transform data from multiple source systems to a final destination. Therefore, the properties of the first class are to contain source URL and authentication values.

Which of the following is best for a long-term project with unlimited potential for expansion?

  1. Declare as public properties. Set values externally for each source when constructing class. Pro: simple. Con: No encapsulation advantage

  2. Use __get and __set. Set values externally for each source. Pro: Follows OOP convention. Con: Opens all to external access; again, no encapsulation

  3. Declare properties as protected. For each source system I need to work with, extend the original class and set the properties in the subclass. Pro:OOP with encapsulation. Con: more classes, and potentially files, to manage.

Currently, option 3 seems the best, despite the file overhead. I'm also open to other ideas.

References I have read for this question:

http://typicalprogrammer.com/?p=23

Getter and Setter?

http://www.php.net/manual/en/language.oop5.overloading.php

Independent getter/setter methods, or combined?

http://martinfowler.com/bliki/GetterEradicator.html

Is it worth making get and set methods in OOP?

Community
  • 1
  • 1
Paul S.
  • 307
  • 4
  • 16

2 Answers2

5

There is at least one more option: inject these parameters into the objects on construction and make them read-only "properties" through a getter. Construct objects only through a factory (you can possibly enforce this as well but I 'm not sure if there's any tangible benefit in doing so).

The factory can be configured on startup (which could be a plus), there is only one class of transport, and consumers can only view each transport's state in the manner it chooses to expose it (encapsulation).

Jon
  • 428,835
  • 81
  • 738
  • 806
  • 2
    +1 Good for you for distilling a wealth of OO and testability knowledge into a concise answer that someone with limited exposure will understand ... I'm way too lazy :) –  Aug 30 '12 at 18:56
  • Thank you Jon. I am returning to my studies of design patterns, and have started reading about dependency injection. – Paul S. Sep 04 '12 at 14:59
2

Choice three, but you actually should make them private. (Note that there are more optioins than just the three you listed, and this isn't necessarily optimal but I don't have enough information to decide for you.) Neither of the other two options is particularly useful for developing an extensible OOP application.

Lusitanian
  • 11,012
  • 1
  • 41
  • 38
  • +1 for suggesting `private` to avoid the "protected members break my encapsulation" pitfall. –  Aug 30 '12 at 18:58
  • Thank you for this. I will read more on `private` vs. `protected` in inheritance. – Paul S. Sep 04 '12 at 15:05