NYCPHP Meetup

NYPHP.org

[nycphp-talk] Static Methods Usage

Andrew Yochum andrew at plexpod.com
Fri Jan 6 16:15:47 EST 2006


On Fri, Jan 06, 2006 at 03:25:09PM -0500, Daniel Krook wrote:
> Cliff & Andrew,
> 
> > On Fri, Jan 06, 2006 at 02:07:30PM -0500, Cliff Hirsch wrote:
> > > As I refactor my code yet again, I am torn about whether to make
> > > wide-spread use of static methods (in PHP 5) when appropriate.
> ...
> > 
> > If all your methods are static then you're OO code is not too much
> > different than prcocedural code. So, the answer is to use them when
> > appropriate.
> 
> 
> I disagree that extensive use of static methods makes your OOP code 
> equivalent to procedural code (meaning that you'd want to avoid it). While 
> it's true that you can essentially just create function namespaces when 
> you do this, conceptually you're still binding operations under an object 
> with distinct responsibilities.

I agree.  From Cliff's original note I had somehow gotten the impression
that Cliff thought they were speedier therefore should be used
everywhere, though now I realize that is incorrect.  I did not mean to
never use them, just not to make *every* method static because its
slightly faster.  They are extremely useful and valuable in everyday
code.
 
> I tend to use static methods for read only operations on particular other 
> objects.  For example:
> $dogs = DogManager::getLatestAdoptableDogs();
> 
> foreach ($dogs as $dog) {
>         echo $dog->firstName;
> }
> 
> When I need to write to a database I like to use a singleton* instance of 
> that manager to make sure that only one update is happening on a shared 
> connection at any given time.  For example:
> $dog = new Dog($someData);
> 
> $dm = DogManager::getInstance();
> $dogId = $dm->saveDog($dog);
> $dm->createAdoptionRecord($dogId, $humanId);

Great examples.  Singletons and factory methods are great places for
static methods.  Note that such methods won't usually use the $this
variable, thus my guideline.  Though, consider it a guide - not a hard
rule.
 
> In any case, I tend to do much of this without consideration for 
> performance.  Logically organized code with intuitive responsibilities 
> takes higher precedence in my mind, so I would encourage you to use static 
> methods in your new code.

Agreed.  I'd like to add that well-designed OO comes with practice.
You'll refactor code, and make it better, and learn.  Next time you code
something similar, you'll recognize the pattern and do it the better way
first.  Wash, rinse, repeat.

Regards,
Andrew
-- 
Andrew Yochum
Plexpod
andrew at plexpod.com
718-360-0879



More information about the talk mailing list