Re: When to instantiate a new class
| From: | Larry Garfield | Date: | Sun, 28 Jun 2015 16:30:42 +0000 |
| Subject: | Re: When to instantiate a new class | ||
| References: | 1 2 3 4 5 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-324974@lists.php.net to get a copy of this message | ||
On 06/27/2015 03:30 PM, Ashley Sheridan wrote:
On 27 June 2015 19:05:18 BST, Larry Garfield <larry@garfieldtech.com> wrote:That's totally easy to do with caching in the service object itself. Having a "read twice" guard is fine, and often good. But the object should not be its own guard. That makes unit testing it, or using it in cases where you may not want the guard, or using it in pretty much any situation other than the very specific one you coded it for, much harder or impossible. Complecting together multiple different responsibilities (loading file off disk, caching, and a guard) is very very easy to do. It's also a trap. Sustainable code requires active, conscious effort on the part of the developer to avoid inadvertently complecting responsibilities together. --Larry GarfieldOn 06/20/2015 08:00 AM, Jesse Schalken wrote:I do think in some circumstances it's the responsibility of the class itself to ensure only one instance of itself exists. Consider a class that loads in file excerpts on a loop, and stores them in the object structure to avoid repetitive disk reads that aren't necessary. If the class is set up as a Singleton, it can't be misused by other code. Dependency injection won't solve that.Also also, I've never quite figured out why "dependency injection containers" exist. Dependency injection just means you pass throughto aclass/method the things it needs, rather than letting it instantiatethemitself, so the caller can decide how those dependencies areimplemented. Iflots of things need the same set of dependencies, then just wrap themallup in another class that has properties or getters for each. It's nothard. What you describe is a service locator. Which is basically the same thing as a dependency injection container that you pass into the object you're using. Google "service locator bad" for why you shouldn't do that. :-) --Larry Garfield