Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many variables are too much for a class?

I want to see if anyone has a better design for a class (class as in OOP) I am writing. We have a script that puts shared folder stats in a CSV file. I am reading that in and putting it in a Share class.

My boss wants to know information like:

  • Total Number of Files
  • Total Size of Files
  • Number of Office Files
  • Size of Office Files
  • Number of Exe Files
  • Size of Exe Files
  • etc ....

I have a class with variables like $numOfficeFiles, $sizeOfficeFiles, etc. with a ton of get/set methods. Isn't there a better way to do this? What is the general rule if you have a class with a lot of variables/properties?

I think of this as a language agnostic question, but if it matters, I am using PHP.

like image 338
Ben Avatar asked Nov 30 '22 07:11

Ben


1 Answers

Whenever I see more than 5 or 6 non-final variables in a class I get antsy.

Chances are that they should probably be placed in a smaller class as suggested by Outlaw Programmer. There's also a good chance it could just be placed in a hashtable.

Here's a good rule of thumb: If you have a variable that has nothing but a setter and a getter, you have DATA, not code--get it out of your class and place it into a collection or something.

Having a variable with a setter and a getter just means that either you never do anything with it (it's data) or the code that manipulates it is in another class (terrible OO design, move the variable to the other class).

Remember--every piece of data that is a class member is something you will have to write specific code to access; for instance, when you transfer it from your object to a control on a GUI.

I often tag GUI controls with a name so I can iterate over a collection and automatically transfer data from the collection to the screen and back, significantly reducing boilerplate code; storing the data as member variables makes this process much more complicated (requires reflection).

like image 167
Bill K Avatar answered Dec 05 '22 19:12

Bill K