There are lots of books and websites about software design. But often, the devil is in the details. Look after the pennies and the pounds look after themselves. There are a whole lot of little thing that if you pay attention to them, it just makes life a little easier. This is about the little things.
Tuesday, September 6, 2011
Singletons
Singletons are useful, but cause all sorts of problems, the are basically Globals with better PR.
We can however change Singletons a little to make them more testable and more maintainable.
Forget the MyDatabaseSingleTon.GetInstance() Function. Instead, use a Factory, IMyDatabaseFactory, which can return a database instance.
If you want to unit test some code, and pass in a Mock Database Instance Factory, which returns a Mock Database Instance to the client, happy days. Now your unit test does not need a real database.
If you want to later on update the code to use multiple database instances, you have the beginnings of the factory, and all your code knows about it. It becomes a smaller re factoring job.
It's the same old trade off, you introduce indirection == complexity and you get flexibility == maintainability.
Too much of that indirection can however introduce confusion != flexibility or maintainability.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment