Scalable Applications vs. Singletons in the Domain Model/Business Logic

I was giving some thought to whether or not a singleton belongs in a domain model.
 
Adding a singleton to a domain model makes it increasingly difficult (impossible?) to make the component or assembly that houses the logic (dll, ejb, whatever) scalable as there is now state introduced into the model. If you are to add servers to the application to scale it out, the singleton can only reside in one location as they are the key to ensuring that the system maintains a unique instance of that object. It is not recommended that you use stateful objects in a distributed application domain because it creates a huge burdon of maintaining state and places it squarely on the shoulders of your application; you’ve now programmed yourself into a corner you definitely don’t want to go down.
 
The question then becomes, "I know this object is supposed to be a singleton in my domain, but how do I make it stateless, thus allowing my application to maintain scalability?"
 
I suggest that if you define the context of the singleton, you will be able to then better model that object and represent it in a stateless fashion.
 
Example (from Accounting):
Only one General Ledger can exist, leading you to want to implement it as a singleton. It seems like a good candidate, because the statement is true, only one General Ledger can exist. But, this leads you down the path of not being able to scale-out your application.
 
If you add an object that encapsulates the singleton and represents its context, you can then get rid of its reliance on being a singleton and rid yourself of that issue.
 
This leads us to:
Only one General Ledger can exist per company.
 
If I now create a Company object, I no longer have to have the General Ledger be a singleton as the Company object encapsulates only one instance of the General Ledger object. This then solves the problem of having a stateful object within my domain and allows my application to be scalable.
 
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s