Page 1 of 2

How Many Static Methods is Too Many For One Class?

Posted: Wed Jan 14, 2009 3:45 pm
by gabriel1836
I have the following abstract class:

Code: Select all

abstract class LP_Model_Abstract
{
    protected static $_collectionClass = 'LP_Model_Collection';
    
    protected $_row = null;
 
    protected $_data = array();
    
    public function __construct($row = null)
    {
        $this->_row = $row;
    }
    
    public function __get($key)
    {
        if(method_exists($this, '_get' . ucfirst($key)))
        {
            $method = '_get' . ucfirst($key);
            return $this->$method();            
        }
        elseif(isset($this->_row->$key))
        {
            return $this->_row->$key;
        }
        else
        {
            foreach($this->_data as $gateway)
            {
                if(isset($gateway->$key))
                {
                    return $gateway->$key;
                }
            }
        }   
    }
    
    public function __set($key, $val)
    {
        if(method_exists($this, '_set' . ucfirst($key)))
        {
            $method = '_set' . ucfirst($key);
            return $this->$method($val);            
        }
        elseif(isset($this->_row->$key))
        {
            $this->_row->$key = $val;
            return $this->_row->$key;
        }
        else
        {
            foreach($this->_data as $gateway)
            {
                if(isset($this->_data[$gateway]->$key))
                {
                    $this->_data[$gateway]->$key = $val;
                    return $this->_data[$gateway]->$key;
                }
            }
        }
    }
    
    public function __isset($key)
    {
        return isset($this->_row->$key);
    }
 
    public function save()
    {
        $this->_row->save();
    }
    
    abstract public static function get($params);
    abstract public static function getCollection($params = null);
    abstract public static function create($params);
}
And then this class which provides additional functionality for class table inheritance schemes (where type is important in determining additional functionality in a factory fashion):

Code: Select all

 
abstract class LP_Model_Factory_Abstract extends LP_Model_Abstract
{
    protected static $_collectionClass = 'LP_Model_Collection_Factory';
    
    abstract public static function factory($row);
}
These ultimately result in the following type of class declaration:

Code: Select all

class Model_Artifact extends LP_Model_Factory_Abstract
{
    protected static $_artifactGateway = 'Model_Table_Artifact';
    
    public static function create($params)
    {
        
    }
    
    public static function get($params) 
    {
        $gateway = new self::$_artifactGateway();
        
        $row = $gateway->fetchArtifact($params);
        
        return self::factory($row);        
    }
 
    public static function getCollection($params = null) 
    {
        $gateway = new self::$_artifactGateway();
        
        $rowset = $gateway->fetchArtifacts($params);
        
        $data = array(
            'data' => $rowset,
            'modelClass' => __CLASS__
        );
        
        return new self::$_collectionClass($data);
    }
    
    public static function factory($row)
    {
        $class = 'Model_Artifact_' . $row->fileType;
    }
}
When do you know that you have too many static methods in a class? And how would you refactor the existing design so that the static methods are perhaps encapsulated in some sort of Finder class?

Re: How Many Static Methods is Too Many For One Class?

Posted: Wed Jan 14, 2009 9:47 pm
by Chris Corbyn
:arrow: Move to Theory and Design... you'll get more discussion here ;)

Re: How Many Static Methods is Too Many For One Class?

Posted: Wed Jan 14, 2009 10:01 pm
by Christopher
This is an interesting just because of the discussion of Model and Collection classes (Cory ;)) I am not sure you need statics at all...

Re: How Many Static Methods is Too Many For One Class?

Posted: Thu Jan 15, 2009 6:53 am
by allspiritseve
How Many Static Methods is Too Many For One Class?
1

Re: How Many Static Methods is Too Many For One Class?

Posted: Thu Jan 15, 2009 9:37 am
by gabriel1836
@ arborint: What about the models and collections are so interesting?

And in regard to the number of static methods in the class:
  • 1) From what I understand it becomes really, really difficult to use Unit Testing when code is littered with statics
    2) I keep finding situations where I need to do this thing or that thing which seems to belong to the Model class but it doesn't belong to an instance to the class which is why I'm finding that I keep adding these crappy static methods.
So of course part of this question (which is why I originally posted under Coding Critique) is how could I restructure the code to appropriately remove the static methods into another class?

One suggestion that I received elsewhere was to use the gateway object directly but this seems rather awkward considering the gateway's are supposed to provide the data access layer for the models. So I'm thinking that there's some other class / pattern that I could implement to refactor these static methods?

Re: How Many Static Methods is Too Many For One Class?

Posted: Thu Jan 15, 2009 9:58 am
by allspiritseve
gabriel1836 wrote:1) From what I understand it becomes really, really difficult to use Unit Testing when code is littered with statics
It does, and thats one reason why I dont use them ;)
gabriel1836 wrote:2) I keep finding situations where I need to do this thing or that thing which seems to belong to the Model class but it doesn't belong to an instance to the class which is why I'm finding that I keep adding these crappy static methods.
Could you give some examples? Im sure we could help find the appropriate place for them.

Re: How Many Static Methods is Too Many For One Class?

Posted: Thu Jan 15, 2009 10:16 am
by gabriel1836
@allspiritsteve:

If you look at the code blocks in the original post, you'll find these four methods:

Code: Select all

 
abstract public static function get($params);
abstract public static function getCollection($params);
abstract public static function create($params);
abstract public static function factory($row);
 
The final block of code shows how each of these functions is implemented. The factory method is used only in situations where I need to implement some form of class table inheritance where I have types of some sort of object with varying properties and behaviors beyond the base set.

Additionally, I thought some more about the create() method and I think that I might just remove it in favor of use the save() instance method to insert to the database if the necessary records don't already exist otherwise save() would just update the database. Does anyone see any issues with that?

Re: How Many Static Methods is Too Many For One Class?

Posted: Thu Jan 15, 2009 2:41 pm
by alex.barylski
Static methods are questionable inside the context of an objet, if you think about it.

Depends I guess what purpose the class or object serves. On one hand, statics in a class that is used as an object seem to break the Single Responsibility Principle (SRP) at least from the class/object perspective, not the typical model perspective.

At least this is what I have always struggled with when I wanted to use a static.

That being said, I do use them but very sparingly. Maybe one method per 20 classes, maybe even 50 classes.

When the functionality clearly belongs to a class and *really* makes sense in that context ONLY I would then maybe make a method static.

I'll give you a bad example.

A while back I developed Accounts model which had several CRUD methods, authenticateMe() logoutMe() type methods (not actual names but for sake of discussion).

This model class allowed me to reset the password of accounts and for that to happen, I needed to generate a random string of characters. I've seen this a billion times before so without thinking I implemented a generateRandomString() inside the context of Account class.

Everything worked like a charm. A few weeks later I needed a random string again, so instead of re-inventing the wheel, I called on the static generateRandomString() inside my notification sub-system and fired off an email.

Now I'm looking to release a open source version of my product, a stripped down version without account management, forcing users to use .htaccess or similar trivial authentication.

So I delete the accounts class and BAM application stops working because of the concrete dependency on Account::generateRandomString().

The moral of the story: Keep dependencies to a minimum. Keep classes SRP and OCP compliant. Try to visualize ever repercussion that might come from having a method being static or being stored in your class at all.

The short of it, IMHO and experience usually static methods are best left as globals as they can usually be reused outside the scope of any given class.

Cheers,
Alex

Re: How Many Static Methods is Too Many For One Class?

Posted: Thu Jan 15, 2009 2:48 pm
by nor0101
allspiritseve wrote:
How Many Static Methods is Too Many For One Class?
1
Unless you count the constructor, which is implicitly static... 8)

Re: How Many Static Methods is Too Many For One Class?

Posted: Thu Jan 15, 2009 3:08 pm
by alex.barylski
Unless you count the constructor, which is implicitly static...
It is? Not from what I understand it isn't...

It's purpose is to initialize the object's state and that implicitly requires access to the objects internals, which explicitly makes it not static. :lol:

Re: How Many Static Methods is Too Many For One Class?

Posted: Thu Jan 15, 2009 3:21 pm
by nor0101
Good point. I suppose it's a special case in that regard but it does behave statically in that it is available before instantiation.

Re: How Many Static Methods is Too Many For One Class?

Posted: Thu Jan 15, 2009 3:44 pm
by alex.barylski
I suppose it's a special case in that regard but it does behave statically in that it is available before instantiation.
Technically, once the object is constructed:

Code: Select all

$obj = new Object();
It is instantiated (instance available) but not initialized.

I'm sorry to disagree but I see no semblance between a static and/or a Ctor() other than they are both functions, the latter beinf of a special type (ie: Has no return value).

Re: How Many Static Methods is Too Many For One Class?

Posted: Thu Jan 15, 2009 4:33 pm
by nor0101
I did some research and I was definitely wrong on this! Not sure what I had in mind when I wrote the original post.

Re: How Many Static Methods is Too Many For One Class?

Posted: Thu Jan 15, 2009 5:09 pm
by alex.barylski
Probably thinking something along the lines of a singleton pattern, where the instance of the object is kept to one or a few and is no longer explicitly controlled by a developer.

Re: How Many Static Methods is Too Many For One Class?

Posted: Fri Jan 16, 2009 7:23 am
by Jenk
It depends entirely on the context, and content, scope and behaviour. Some of my classes only have static methods, and lots of them. Some have a handful, as well as instanced behaviour. It all depends on the scope of the method.