Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it reasonable to have a fair amount of public properties in a class?

Or in more specific words, is it "ok" to not be relying on setters and getters?

I'm dealing with a class that checks the availability of rooms and sets public properties of which there are more than a dozen. Things such as:

  • unitNumber
  • roomTypes ( array )
  • codeCorporate
  • codeGroup
  • numberKids
  • numberAdults
  • numberRooms
  • currency
  • minRate
  • maxRate
  • soapServer
  • units ( array )
  • hotelId

And after an object is instantiated those properties are set with $this-> inside various methods. However the code that deals with the object often sets public properties directly instead of using getter/setter methods:

$object->something = 3;

foreach ($object->things as $thing ) { }

If I have the time to refactor this class..

  • Should I stick all of these properties in a data array that's a private property, and define __set and __get methods?
  • Should I make a single getter method for each of the properties?
like image 751
meder omuraliev Avatar asked Feb 08 '10 21:02

meder omuraliev


1 Answers

In my opinion, it is rarely a good idea to have any public members. It increases coupling between classes, and makes refactoring very complicated (should you need it.)

Setters/Getters are the way to go, and the very small performance penalty that you pay for it is usually either optimized away, or trumped by elegance.

To answer your question about array vs. single-getter-per-var, it's a matter of taste. I tend to only keep variables of a similar type within an array, and separate the rest.

like image 90
An Onion That is Red Avatar answered Oct 30 '22 21:10

An Onion That is Red