Zirak
Zirak

Reputation: 39808

When is the right time to subclass?

Working on a database class that got quite big, and is likely to get much bigger, I started writing a lot of attributes and methods related to one specific aspect of the database (users, comments, pages etc.) So it feels like it's about time to subclass the database class to several classes, each dealing with their own aspect, and only have the database class contain the absolute core functionality.

However, doing that feels like making extra classes and dealing with includes and the likes for nothing. The code is pretty maintainable as-is and "divided" (via comments) into the correct sections, and it's not like a "big" class is gonna damage performance noticeable.

So, I come to you: When is the right time, in your opinion and experience, to subclass? Not just in this specific case, but in general terms.

Upvotes: 4

Views: 183

Answers (2)

Mārtiņš Briedis
Mārtiņš Briedis

Reputation: 17762

Thats normal. I have like 50 models which deal with all kind of data (a lot of tables).

Problem with includes can be easily solved by following a naming convention and using autoloaders.

For example, I call all my classes like this - ClassNameModel.php and put them in a specific directory.

The autoloader would look like this:

function customAutoloader($class_name){
    $file_name = $class_name . ".php";

    //Modelis
    if(substr($class_name, -5) === "Model"){
        if(is_readable("/models/" . $file_name)){
            require_once("/models/" . $file_name);
        }
        return;
    }
}

and in the main index or config or whatever:

spl_autoload_register('customAutoloader');

and no more includes...

Upvotes: 0

cmutt78
cmutt78

Reputation: 859

I go by logical grouping of methods and functionality.

Upvotes: 2

Related Questions