I didn't find a similar question, so I apologize if it already exists.
In my system I want a number of function libraries to ease a number of tasks across the whole system. That could be validating an e-mail. There's no reason to write the full regular expression each time if I can have a function do it, so I only need to change things and fix errors in one place.
Say I write a class called Files_Tools.
I can make it work both by dependency injecting an instance of this class into the objects that needs functions from this class. But I can also write the Files_Tools class with static functions and access them with the scope resolution operator. But as I have come to understand one of the major things about DI (dependency injection) is to avoid this kind of "global use". So my logic tells me to go with the DI approach. Yet, it still doesn't feel "right" that I'm doing it this way.
So my question is - What is regarded as the most correct way to create a toolset for a system? First of all, is it to make it as a class, instead of just plain functions? And then if it really is a class is the way to go, should I aim for the SRO or DI?
I understand there is probably not a definitive answer to this question, but I want to know if I'm completely off track or heading where many other coders would have done too.
Thanks in advance :)
DI makes it easier to unit test your classes and methods without dependency on the injected class... you can mock the injected object and manipulate its returns as appropriate for your tests. Scope resolution leaves you with this dependency so the tests aren't fully isolated.
Many of my earlier projects use static classes for such functionality, and trying to write unit tests for them 6 years on is now a real chore because I didn't use DI.
Related
It's time for some more seemingly simple questions that I just can't seem to find the answer to.
I'm developing a library with TDD (PHP). To my understanding, when using TDD, you should not write any production code without first writing a failing test to warrant it.
I have a mutator method, that appends data to an array with private visibility. How should I test that? Should I just test the various accessor instead? Should the test for the accessor cover the mutator method?
Is it OK for a test to test an accessor and a mutator, or should these be separate tests?
My library requires a dependency, which I will inject through the constructor. What test code might prompt me to write the constructor code?
Sorry for such noobish questions. I've been studying TDD quite a lot, and thought I had it all figured out, but as soon as I try to make use of it, all these little questions come to mind. Obviously I want to make sure that, I implement it effectively and to the best of my knowledge.
Perhaps I'm being too strict? Perhaps the injection is tested implicitly using a mock and checking expectations of a method that makes use of the injected class?
I understand these questions might be subjective, and the answers might be based on people's opinions, but I'm fine with that. I just want to get started in a way that makes sense and works.
Many thanks in advance.
I would test the setter and getter methods together, because that is by far the simplest way to do it without having to change the visibility of your array, which you shouldn't do. Your injected class will be tested implicitly by these tests.
In general try to write your unit tests from the perspective of another user trying to use your class under test. You need to think, what is this class supposed to do or what is its contract (i.e. this class holds an array of objects that users can add and remove from), then write tests to be certain it satisfies that contract. After that, write just enough code to get the test to pass.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Who needs singletons?
I always write with respect to best practice, but I also want to understand why a given thing is a best practice.
I've read on in an article (I unfortunately don't remember) that singleton classes are prefered to be instantiated, rather than being made with static functions and accessed with the scope resolution operator (::). So if I have a class that contains all my tools to validate, in short:
class validate {
private function __construct(){}
public static function email($input){
return true;
}
}
I've been told this is considered bad practice (or at least warned against), because of such things as the garbage collector and maintenance. So what the critiques of the "singleton class as static methods" wants, is that I instantiate a class I'm 100% certain I will only ever instantiate once. To me it seems like doing "double work", because it's all ready there. What am I missing?
What's the view on the matter? Of course it's not a life and death issue, but one might as well do a thing the right way, if the option is there :)
An example singleton classes in php:
Creating the Singleton design pattern in PHP5 : Ans 1 :
Creating the Singleton design pattern in PHP5 : Ans 2 :
Singleton is considered "bad practice".
Mainly because of this: How is testing the registry pattern or singleton hard in PHP?
why are singleton bad?
why singletons are evil?
A good approach: Dependency Injection
Presentation on reusability: Decouple your PHP code for reusability
Do you need a dependency injection container
Static methods vs singletons choose neither
The Clean Code Talks - "Global State and Singletons"
Inversion of Control Containers and the Dependency Injection pattern
Wanna read more? :
What are the disadvantages of using a PHP database class as a singleton?
Database abstraction class design using PHP PDO
Would singleton be a good design pattern for a microblogging site?
Modifying a class to encapsulate instead of inherit
How to access an object from another class?
Testing Code That Uses Singletons
A Singleton decision diagram (source):
A singleton object is an object that is only instantiated once. That is not the same as the Singleton Pattern, which is a (Anti-) Pattern how to write a class that can be only instantiated once, the Singleton (large S at the beginning):
“Ensure a class has only one instance, and provide a global point of access to it.”
As far as PHP is concerned, you normally do not need to implement the Singleton Pattern. In fact you should avoid to do that when you ask for best practice, because it is bad practice.
Additionally most PHP code examples you find are half-ready implementations of the pattern that neglect how PHP works. These bogus implementations do not go conform with the "ensure" in the pattern.
This also tells something: Often that it is not needed. If a sloppy implementation does the work already while not even coming close to what the pattern is for, the wrong pattern has been used for the situation, it's starting to become an Anti-Pattern.
In PHP there normally is no need to ensure at all costs that a class has only one instance, PHP applications are not that complex that you would need that (e.g. there are no multiple threads which might need to refer to an atomic instance).
What is often left is the global access point to the class instance, which is for what most PHP developers (mis-) use the pattern. As it's known as-of today, using such "Singletons" lead to the standard problems of global static state that introduce complexity into your code across multiple levels and decrease re-usability. As a programmer you loose the ability to use your code in a flexible way. But flexbility is a very important technique to solve problems. And programmers are solving problems the whole day long.
So before applying a Design Pattern the pro and cons need to be evaluated. Just using some pattern most often is not helpful.
For starters I would say, just write your classes and take care how and when they are instantiated in some other part of your application logic so things are kept flexible.
Well, this isn't actually a singleton; a singleton ensures that you only have a single instance of a class, and there is no method here that would retrieve a single instance of Validate. Your design here appears to be a static class. This will not cause an issue with the garbage collector (at least the code you've placed here), because this would be loaded into memory no matter what.
I've got this Config-class that I use in my PHP5 application to load & parse my static config. This far I've managed to keep the class from being a singleton/registry and instead passed the instance of the Config class around to wherever it's needed with the help of Dependency injection.
But now as I need to set/make changes in my Config during runtime at one place, my changes aren't reflected globally and being far from a specialist with the use of the static modifier in PHP, I need to ask:
What is the best way to ensure that changes to the properties in my Config-class are reflected throughout my application without making the class into a singleton? Can I just make the variable holding the config data static?
This far I've managed to keep the class from being a singleton/registry and instead passed the instance of the Config class around to wherever it's needed with the help of Dependency injection.
If you pass the same instance of your Config class to every part of your application and you change a setting it should be reflected everywhere else.
In case you are creating multiple objects of the class (and parse that config file every time?!) you might want to stop doing that. It's possibly wasteful and I'd say it is confusing.
So if you create only one and pass that around everything should be fine.
Under the assumption that you create multiple instances of the object that only should exist once:
If you are able to "fix" your architecture to allow you to do that: Do so.
If you can't to that... well.. creating a static property to hold your values in a class that you can have multiple instances off is, at least in my book, a major wtf factor. If you can't fix (meaning it's to much off a hassle to do so) just "break" it in an expected way so other people don't trip over it.
I'd rather have a singleton than something that creates all the issues with singletons and also lies about being a wrapper for a global variable.
Blindly avoiding design patterns because you hear on Internet forums that they're bad is about as much an anti-pattern as singletons are in general. If a tool is right for a job, then it's right.
Look at your question, you're trying to emulate singletons through a complex multi-update system for God's sakes... And just so you know, making a class static is essentially turning it into a singleton, albeit an insecure one that can be overwritten at any time.
TL;DR: Think for yourself and use the right tools; make your config class a singleton.
In a theoretical database access class, I found that there are quite a few helper functions that I use in the class, which have nothing to do the class's instance (and others, that could be manipulated to be unrelated to the class's instance using dependency injection).
For example, I have a function that gets a string between two other strings in a variable. I've been thinking of moving that to a String_Helper class, or something of the sort. This function has already been made static.
Also, I have a function that queries a database, query($sql). The connection details are provided by the instance, but I've been considering making it static, and using query($sql, $connection). Developers would then be able to call it statically and not need to instantiate the database class at all.
For me, the questions are:
Is it worth it to do something like this? Functions like the query function make me wonder if this is not just me trying to make everything as static as possible, without any real need to. Under what circumstances would you consider this useful?
I know static functions are harder to test, but if I make sure that their code is completely dependency free (or uses dependency injection where necessary), then they're just as easy to test as everything else, surely?
It isn't a concern at the moment, but if, in the future, I decided to extend the classes with the static functions, it would be impossible for me to make the current code use my extended functions. I've thought of Singletons, but the same problem arises: the code would be calling Singleton_Class::getInstance(), and not My_Extended_Singleton_Class::getInstance(). Dependency Injection seems to be the only way to solve this issue, but it might lead to a clunkier API, as every dependency has to be given to an object on __construct().
I have a container class, which holds certain pieces of information statically so that they can be accessed anywhere in the script (global scope). If I can't use static functions or singletons, a class that contained instances of different variables would be great. One could use for example Container::$objects['MyClass'] = $MyClass_object;, and then the rest of the code could just access Container::$objects['MyClass']. If I extended the MyClass class, I could use Container::$objects['MyClass'] = $MyExtendedClass_object;, and the code that used Container::$objects['MyClass'] would use MyExtendedClass, rather than MyClass. This is by far the best way to do it, in my opinion, but I'd like to know what you think about it.
Ok, let me answer these one by one...
1. Is it worth doing something like this
Yes and no. Splitting out the helper functions into their own classes is a good idea. It keeps the "scope" of each of the classes rigidly defined, and you don't get creap. However, don't make a method static just because you can. The query method is there to make your life easier by managing the connection, so why would you want to lose that benefit?
2. They are harder to test
They are not harder to test. Static methods that depend on state are harder to test (that access static member variables or global variables). But static methods in general are just as easy to test as instance methods (in fact, they can be easier since you don't need to worry about instantiation).
3. Extending the classes
This is a valid concern. If you put String_Helper::foo() in the class itself, you'll run into issues. But an option would be to set the name of the string helper as a class variable. So you could then do {$this->stringHelper}::foo() (note, PHP 5.3 only). That way to override the class, all you need to do is change the string helper class in that instance. The Lithium framework does this a lot...
4. Global Registry
I would stay away from this. You're basically just making every class a singleton without enforcing it. Testing will be a nightmare since you're now dependent on global scope. Instead, I'd create a registry object and pass it to classes via the constructor (Dependency Injection). You still accomplish the same thing since you have a store for the objects/classes, but you're no longer dependent on a global scope. This makes testing much easier.
In general
When you're looking at doing things like this, I like to stop when I hit questions like this. Stop and sit down and think *What actual problem am I trying to solve?". Enumerate the problem explicitly. Then pull our your supposed solutions and see if they actually solve them. If they do, then think about the future and if those solutions are really maintainable in the long run (Both from a bug fix standpoint, and with respect to feature additions). Only if you're happy with both of those answers should you even consider doing it. Oh, and also remember to keep it simple. Programming is not about making the most complex, most clever or most amazing solution. It's about making the simplest solution that solves the problem...
I hope that helps...
Good Luck!
I have am working on a web application that makes use of helper classes. These classes hold functions to various operation such as form handling.
Sometimes I need these classes at more than one spot in my application, The way I do it now is to make a new Object. I can't pass the variable, this will be too much work.
I was wondering of using singleton classes for this. This way I am sure only one instance is running at a time.
My question however is when I use this pattern, should I make a singleton class for all the objects, this would b a lot of code replication.
Could I instead make a super class of superHelper, which is a singleton class, and then let every helper extend it.
Would this sort of set up work, or is there another alternative?
And if it works, does someone have any suggestions on how to code such a superHelper class.
Thank you guys
I can't pass the variable, this will be too much work.
Are you sure though? People tend to overestimate the effort of passing around dependencies. If you do it in the constructor, it's usually fairly simple to do.
That said, you can put shared functionality in the global scope, in different ways in php. The simplest is to use a global function. Eg. a function that doesn't belong to any class. Another option is to use a static class method. These two a very similar; except for their syntax, they essentially have the same properties. A slightly looser coupled solution is to put the functionality as a method on an (abstract) base class, that your concrete class extends from. This shares the functionality between all child classes.
Common for the above-mentioned solutions is that they have a compile time coupling. You can't change the dependency at run time, which makes your application rather rigid. Their main benefit is the low level of complexity they carry.
If you want a looser coupled application, you can try to replace the hard dependency with a variable, to give a level of indirection. The simples is to create an object and make this shared globally throughout the application. There are a number of ways to do this in PHP, such as a singleton or simply a variable in the global scope (You can access this with the global keyword, or through the $GLOBALS array).
While global variables offer a level of indirection, they also tend to introduce a lot of complexity, since they make it very hard to figure out which parts of the application that depends on each other. For this reason, they are often avoided by experienced programmers. This is especially true if the variable has state; The problem is less prevalent if the shared object is stateless.
The only way to avoid the perils of global variables, is to use local variables instead. Eg. To pass the dependencies around. This can be a bit of a hassle, but in my experience it's often not as big a problem as it's made out to be. At least, the benefits often outweigh the problems. That said, there are techniques to easy the pain; Notably dependency injection containers, which are automatic factories that take care of all the wiring for you. They come with their own level of complexity though, but for larger applications they can certainly be a good solution.
Look into the factory pattern and dependency injection.
http://www.potstuck.com/2009/01/08/php-dependency-injection/
You can't extend a singleton class. Remember in singleton class we make the constructor private so if a constructor is private than how could you extend this class? We all know what we create an object of a class we call its constructor and in child class constructor it implicitly called the parent constructor. So in this scenario a private constructor can't be called in the child class.
While sometimes necessary, singletons are evil (because they're global state). Try to avoid them if you can help it.
EDIT: If you can't avoid singletons, at least parameterise the reference to that state. In other words, in a class, pass in the singleton to its constructor or those methods that use the singleton.
Simply making references all over your codebase to your singleton will compromise your ability to test classes in isolation.
If your singleton's stateful, your tests will suddenly become stateful, and your tests can start "cascade failing" because their preconditions become corrupted by earlier tests failing.