This doesn't cover a few downfalls to the approach.
It requires the users of the client know about where to get the singleton and it forces them to access it for every creation of the client class.
Another problem is that the singleton that this ignores the difference in when the singleton is acquired, which could have important implications that need to be addressed.
It should be included in such a suggestion that the client class take the singleton injection as an optional parameter, and access the singleton by default, possibly and specifically on each use of the singleton.
After several failures, we (I and my team in the undisclosed company I work for) got to couple of conclusions: 1. DI frameworks (e.g. Spring) are extremely friendly for testing. 2. If you can't use a DI framework, create (a simple) one. Now (2) requires some explanation – what we do is have one real singleton – The singleton (application context, container, god – take your pick) which acts as a very restricted access map to several contexts "hubs". Each hubs converse directly with the map, first loading it with the required objects, then extracting and typecasting as needed. Context objects have a very small footprint on construction and are only initialized on event (application init) / request (same as real singletons) Testing is facilitated in either of two ways: 1. If you only need a small number of mock contexts, you create them and load them manually into the singleton map. Future requests will retrieve them. On tests teardown, you empty the entire map. 2. If you need a large number of mock contexts (big unit tests / integration tests), you just fire one (or more) of the real hubs and overwrite only what's needed in the map (if anything is) with mock implementations.
This approach has the merit of being very easy on production code and yet (almost) as testable as real DI.
Hmmm, the advantage is that with the second approach, we have extracted the Server creation which will allow us to mock it. That wasn't possible with the first approach.
It's hard to test code that uses singletons. << understatement of the year :P We have had alot of luck using DI for testing, and when singletons are necessary provide an alternative getInstance method which takes in the parameters to construct the object with for testing.
years after... :) well, but PHPUnit official documentation is still linking to this blog post so...
This post is a great and clear explanation of DI benefit at time of unit testing code, but in any case does it demonstrate what problems singletons are causing when unit testing code.
As said haemi, the first Client.process() method implementation could (not should :)) have been done like this:
public int process(Params params) { Server server = new Server(); Data data = server.retrieveData(params); ... }
In this case, we don't have any singleton involved, but we still cannot unit test this method because of a hard dependency on Server class.
Indeed, the biggest issue with singleton is to unit test it's different methods independently, since you're not supposed to be able to reset the instance between method calls.
Using introspection (or, but it's kind of ugly, implementing a resetInstance() public method to delete the current instance and allow instantiating a new one), you can manage to unit test a singleton's methods.
Tu sum up, dependency injection and singletons are not related in any way!
It's NOT hard to test code that uses singletons It's easy.
This is how I test a client that uses a Singleton: First, I refactor the code that obtains the Singleton instance into a new protected method, as follows:
public class Client { public int process(Params params) { Server server = obtainServer(); Data data = server.retrieveData(params); ... } //new method protected Server obtainServer() { return Server.getInstance(); }
}
Then I test it using a mock Server as follows:
public class ClientTest extends Client { public void testProcess() { Client c = new Client() { @Override protected Server obtainServer() { return new MyMockServer(); }
We used this sort of idea extensively on the Iridium Satellite payload project in the late 1990's. Every single interface had an include file with dependency inline functions, that so by swapping the includes you could mock *everything*. As a result, nobody could read anybody else's code because the language of each service was entirely different, and more or less, random.
Sure, but still ur API kind of s*cks. It is not clear hat Client has a strong dependency on Server - whether it is inside the public process() or protected obtainServer() method - unless it is properly documented. Dependency Injection shows off these dependencies right in the API. And you would have to create another subclass on every reuse of Client that needs a different logic to obtainServer(). Not to mention that - at least for me - it seems way out of scope for a client to obtain the server. Just my 2 cents.
This doesn't cover a few downfalls to the approach.
ReplyDeleteIt requires the users of the client know about where to get the singleton and it forces them to access it for every creation of the client class.
Another problem is that the singleton that this ignores the difference in when the singleton is acquired, which could have important implications that need to be addressed.
It should be included in such a suggestion that the client class take the singleton injection as an optional parameter, and access the singleton by default, possibly and specifically on each use of the singleton.
After several failures, we (I and my team in the undisclosed company I work for) got to couple of conclusions:
ReplyDelete1. DI frameworks (e.g. Spring) are extremely friendly for testing.
2. If you can't use a DI framework, create (a simple) one.
Now (2) requires some explanation – what we do is have one real singleton – The singleton (application context, container, god – take your pick) which acts as a very restricted access map to several contexts "hubs". Each hubs converse directly with the map, first loading it with the required objects, then extracting and typecasting as needed. Context objects have a very small footprint on construction and are only initialized on event (application init) / request (same as real singletons)
Testing is facilitated in either of two ways:
1. If you only need a small number of mock contexts, you create them and load them manually into the singleton map. Future requests will retrieve them. On tests teardown, you empty the entire map.
2. If you need a large number of mock contexts (big unit tests / integration tests), you just fire one (or more) of the real hubs and overwrite only what's needed in the map (if anything is) with mock implementations.
This approach has the merit of being very easy on production code and yet (almost) as testable as real DI.
To be honest, I do not see the advantage...
ReplyDeleteWith the first implementation of the Client-Class, it would have been possible to do:
Client c = new Client();
client.process();
That's all... what's the drawback here?
Hmmm, the advantage is that with the second approach, we have extracted the Server creation which will allow us to mock it. That wasn't possible with the first approach.
DeleteIt's hard to test code that uses singletons. << understatement of the year :P
ReplyDeleteWe have had alot of luck using DI for testing, and when singletons are necessary provide an alternative getInstance method which takes in the parameters to construct the object with for testing.
For this thing I use Guice.
ReplyDeleteyears after... :) well, but PHPUnit official documentation is still linking to this blog post so...
ReplyDeleteThis post is a great and clear explanation of DI benefit at time of unit testing code, but in any case does it demonstrate what problems singletons are causing when unit testing code.
As said haemi, the first Client.process() method implementation could (not should :)) have been done like this:
public int process(Params params) {
Server server = new Server();
Data data = server.retrieveData(params);
...
}
In this case, we don't have any singleton involved, but we still cannot unit test this method because of a hard dependency on Server class.
Indeed, the biggest issue with singleton is to unit test it's different methods independently, since you're not supposed to be able to reset the instance between method calls.
Using introspection (or, but it's kind of ugly, implementing a resetInstance() public method to delete the current instance and allow instantiating a new one), you can manage to unit test a singleton's methods.
Tu sum up, dependency injection and singletons are not related in any way!
It's NOT hard to test code that uses singletons
ReplyDeleteIt's easy.
This is how I test a client that uses a Singleton:
First, I refactor the code that obtains the Singleton instance into a new protected method, as follows:
public class Client {
public int process(Params params) {
Server server = obtainServer();
Data data = server.retrieveData(params);
...
}
//new method
protected Server obtainServer() {
return Server.getInstance();
}
}
Then I test it using a mock Server as follows:
public class ClientTest extends Client {
public void testProcess() {
Client c = new Client() {
@Override protected Server obtainServer() {
return new MyMockServer();
}
};
assertEquals(5, c.process(params));
}
Sorry to ask this after so long, but can you explain/point a source about how to create your own mock client?
DeleteThanks!
We used this sort of idea extensively on the Iridium Satellite payload project in the late 1990's. Every single interface had an include file with dependency inline functions, that so by swapping the includes you could mock *everything*. As a result, nobody could read anybody else's code because the language of each service was entirely different, and more or less, random.
DeleteSure, but still ur API kind of s*cks. It is not clear hat Client has a strong dependency on Server - whether it is inside the public process() or protected obtainServer() method - unless it is properly documented. Dependency Injection shows off these dependencies right in the API. And you would have to create another subclass on every reuse of Client that needs a different logic to obtainServer(). Not to mention that - at least for me - it seems way out of scope for a client to obtain the server. Just my 2 cents.
ReplyDeleteBtw guys, you have a typo in the title of this page. See Dependancy vs Dependency.
ReplyDeleteI was spell checking an article which includes a link to this page and this showed up.