On Wed, Sep 4, 2013 at 12:25 PM, Micky Hulse <mickyhulse.li...@gmail.com>wrote:

> I want to have a "utility" class that contain utility methods which should
> have the option of being called multiple times on a page.
> ...
> To put it another way, is there any reason why I would not want to use the
> above code?


The main problem caused by static methods is testability. Mocking or
stubbing a static method requires using a PHP extension and ensuring that
the original is reset whether the test passes or fails. As long as your
utility methods don't perform actions you want to avoid during tests, this
is fine.

Good examples for a utility class are string-processing functions such as
parsing and formatting, trimming and/or normalizing empty string to null,
etc. You want tests to work against these methods directly since there's no
need to avoid the work.

You'll want to avoid static methods whenever you want to be able to fix the
behavior (stubbing) to test scenarios in the class under test. An example
is anything hitting a database or external service. In order to test that
your downloader sends the correct warning email to the sysadmin when a REST
call fails, you need to be able to force the REST call to fail. This is
easy to do when you plug in an instance implementing the API because you
can give it an implementation/mock that fails for all calls.

I can't say if what you're thinking of will make a good utility class since
the code you posted is fake. If you post some examples of methods you want
to make static, we can give you pointers on which are good candidates and
which are best left to instance methods.

Peace,
David

Reply via email to