When are classes to modular? How many classes are too many?

Not for 'how-to' coding questions but PHP theory instead, this forum is here for those of us who wish to learn about design aspects of programming with PHP.

Moderator: General Moderators

Post Reply
penguinboy
Forum Contributor
Posts: 171
Joined: Thu Nov 07, 2002 11:25 am

When are classes to modular? How many classes are too many?

Post by penguinboy »

I like small effecient classes that do one specific task;
but I worry that small classes could == too many classes.

Is there a time when a class can be too modular?
penguinboy
Forum Contributor
Posts: 171
Joined: Thu Nov 07, 2002 11:25 am

Post by penguinboy »

Looking at this; I realize I'll problably never have too many clases...
McGruff
DevNet Master
Posts: 2893
Joined: Thu Jan 30, 2003 8:26 pm
Location: Glasgow, Scotland

Post by McGruff »

Really it depends on what the class has to encapsulate.

As a general rule - with plenty of exceptions - 6 or 7 lines is a nice size for functions and six or seven methods is a nice size for classes. I've got plenty that are smaller or larger than that though. Smallest are a bunch of validators with only 5 or so lines of code which actually does anything. I find I've got 30-40 separate classes per script on average (you can find out approximately how many with printR(get_declared_classes()) - this is just what's been declared: could have more than one instance of a class).

It's always good to refactor ruthlessly till you hear 'em start to squeal.

Take a look at Eclipse for a good example of responsibility driven design.
penguinboy
Forum Contributor
Posts: 171
Joined: Thu Nov 07, 2002 11:25 am

Post by penguinboy »

Another question:

classes within classes

will this set up work?
is it 'proper' ?

Code: Select all

<?php
class master
{
  var $debug; // debug class
  var $example; // example class

  function master()
  {
    $this->debug = new debug();
    $this->example = new example();
  }
}

class debug
{
  var $log;  // array of debug messages
  function debug()
  {
     $this->log[] = 'Debug started';
  }

  function append_log($log)
  {
    $this->log[] = $log;
  }
}

class example extends master
{
  var $debug;
  function example()
  {
    $this->debug->append_log('Example Started.');
  }
}
?>
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post by timvw »

I don't think you want another $debug in your example class, as master already has one..
penguinboy
Forum Contributor
Posts: 171
Joined: Thu Nov 07, 2002 11:25 am

Post by penguinboy »

But how would you access it?

This example here.

Looks like you have to 'pass' the extended var.
It is a PHP5 example though, so I couldn't be wrong...
Post Reply