Wednesday 7 November 2012

Git Stash

Sometimes you want to just mess around with some code, maybe write some data buffers to a file to examine or whatever else. This leaves the code in a messy state and whenever you want to switch to a different branch you don't want to commit this code but you also don't want to leave your working directory dirty. For this I am loving Git Stash: Just go to a bash prompt (This is very nice and easy from Git Extensions):

The code must be tracked, if not already then simply:

git add .
Save:
git stash save "MyStash"
Coming back to it later:
git stash list
git stash apply stash@{0}
Find your stash with the list command, that will give you the stash number. Then apply Undoing the stash:
git stash show -p | git apply --reverse

Tuesday 6 November 2012

Singleton and Dependency Injection

Ayende wrote this great blog post on the Singleton pattern, I always enjoy these kinds of posts from him because he looks at them from a real world perspective. It reminded me to make a specific subtle point on Singleton and that is:
Most of the issues that people have with the Singleton aren’t with the notion of the single instance, but with the notion of a global static gateway, which means that it becomes very hard to modify for things like tests, and it is easy to create code that is very brittle in its dependencies on its environment.
This has often lead to statements about statics/singletons are evil. But they don't have to be. You should continue to create objects that utilize dependency injection and abstractions and make sure they are decoupled from such statics or instances. The way you do this is very simple: Here is some typical Singleton (Implementations may vary): So when using this you have a choice, you can either use it this way: The above usage is very hard to test and doesn't allow me to change the implementation of the GetRaise method. Another big problem is the Dishonest API, there is no indication when I create the object or call the method that there is a hidden dependency to Manager which is a typical problem with using Singletons and statics like this. The solution is to rather ask for the instance and not let your class know about the singleton at all: Now I can test and change the implementation as I like, for example create a new derivative: If you don't like the manual approach, these days IoC containers are everywhere and the setup for example StructureMap is this easy: The above will just use the default Singleton instance to resolve. But you can also override it as follows: These techniques are indeed very basic but so often overlooked. The singletons are not evil when used correctly but must remain living in the root layer of your application where all the calls are made initially.