gregoryyoung is the Page Editor for the C# and DotNET topic areas. This article continues his series on design patterns. To read more, see his blog.
Nearly every programmer learns the singleton as their very first design pattern partially due its simplicity and partially to it being the first one listed in nearly every basic pattern book. It is a good introduction to the concept of design patterns and immediately people will have places within their own code to experiment with their new knowledge.
//Singleton implementation in C#
//Singleton implementation in VB.NET
Looking at the singleton from a life cycle perspective, the first method to be called is guarenteed by the CLR to be the static constructor for the type which sets the internal instance to be an instance of the singleton class. It is important to note that the constructor for the object is marked private; this ensures that the object cannot be created externally to the singleton itself. A client seeking to access the object is forced to use the static Instance property which will always return the same instance to the caller. Thus the singleton has insured that only a single instance of the object can exist. There are two major design flaws that come up with the singleton and if not carefully implemented they can become a nightmare of a change.
1) The item which was deemed to have a maximum count of 1 and now it has a maximum count of N. Imagine a simple application that talks to a 68040 embedded system. At the time of production there is only a need for a single serial port interface so it is implemented as a singleton, but later the requirements change and multiple serial ports are needed. This problem is further made worse by the fact that when we change to having multiple objects we will likely also want to change to having multiple CONCRETE objects -- in other words we would no longer want to deal with our singleton as a concrete type but as an abstract type. An example would be if we wanted to support serial communications and IR communications with similar but functionally different protocols. Since the singleton is bound to the concrete type the move to an abstract type will cause futher issues.
2) The application changes to require multiple application domains. I see this one on a regular basis with people using the singleton pattern in ASP.NET. They develop their application in a single ASP.NET instance and then run into problems with their singleton when they move to production. The way IIS works with ASP.NET is that it starts 1..N processes running your application, and the more processes you have, the more concurrent requests you can handle. If you remember the singleton is scoped to the application domain so it is not shared between these processes. In order to share the singleton you must use a singleton that is housed in another process that the processes share -- for instance using a networked singleton through remoting.
The major problem with both of these problems is that depending on how your singleton is being used you may have MANY places that will require a change to simply make it support either multiple objects in the first case or a networked object in the second case. The reason for this is the fact that the singleton's instance method is bound to the type ex: Singleton.Instance. This will force us to change any code that is directly accessing the instance in such a manner. This is extremely important when dealing with libraries, since a simple change such as making a singleton a networked object could feasibly bubble out to every application using the library as well as the library itself.
One can help alleviate the number of places that need to be changed by passing the singleton into methods as opposed to having the methods call the singleton directly.
vs.
But alas, this causes many problems as well. For example you are nine levels deep into method calls when you realize that you need an instance of the singleton to perform a task. At this point you are left with two choices: you can either pass the singleton through those nine levels of methods (changing their method signatures and breaking countless other areas of code) or you can call the instance property on the singleton type directly which will lead to future problems as discussed above.
For a reasonable answer as to how to avoid these design nightmares in our future we need to analyze exactly what a singleton does for us and how it does it.
1) The singleton guarentees that only a single instance of an object will be created by encapsulating the creation of the object in a private scope.
2) The singleton pattern includes a static factory method which allows us access to the internal instance.
Given that the singleton is actually a specialized factory method, what would happen to our system if we were to add a level of indirection by putting a factory method in front of our class?
It is important to note that another method of obtaining a similar result is to make the singleton a normal object with an internal constructor and make the factory method actually construct it and maintain the instance. The only difference in functionality between having a true singleton and a factory which acts as a singleton is the private constructor on the object, which completely prevents any other instances from being created. If the class is internal to a library and a level of discipline can be maintained by the development team, this is often a much better approach. Also, the contextual variable is not always necesary or available but if required and identifiable should be created at the time the factory is created.
This will give us substantially more flexibility and isolate us from sweeping changes in our code base. The best part is that there is no functional difference between this and the singleton implementation we looked at earlier, yet we have removed the coupling between the singleton and the singleton type. We can now call the singleton factory wherever we want and not have to worry about passing the singleton through large amounts of code in order to use it (although in many cases it is a good practice to do so if contextual boundaries are not being crossed, as the future factory method has an unknown overhead associated with it).
This is a common case where thought ahead of time can help reduce the impact of change later. As we all know change is often times a project (or even a department) killer, the best way to keep it from killing you is to plan ahead for possible changes and isolate the scope of their effect.
Greg Young
The Moderators have asked us to pass along a "festive message about 'Tis the session to patch your bleedin' PC. Stop spam and worms in one simple step..."
Which is pretty good advice for any season, but the current variants of the Sober worm have turned a lot of members' machines into zombies that are sending out the same message over and over. Since the Mods are pretty well-versed on keeping their computers protected, it wouldn't bother them if some of you would do a little checking up.
We've also seen a number of questions recently that are requesting changes of usernames. This screenshot shows what EE says when you signed up; this tells you the problems you'll face if you really want to change it.
Finally, we're seeing a lot of reports of people asking the same question in several TAs for 500 points each time. This exceeds the 500 point maximum for any question; the Moderators will either reduce the points in each, or they'll turn all but one of the questions into pointer questions. Please save them some work by reading this section of the Help page.
A recent study by Booz Allen Hamilton says that most organizations are unhealthy with respect to how they adapt to a changing environment. The study is based on responses from about 50,000 people, most of them respondents to a brief online survey.
A while back, gregoryyoung wrote a column for this newsletter that talked about what he called "anti-patterns" -- "...well-documented and commonly-made mistake[s] for which there are known solutions." Greg's article dealt primarily with larger organizations, but what is apparently the case is that the same issues that afflict larger organizations also show up in smaller ones.
The hypothesis behind the study is old news; Max Weber, the German sociologist, wrote in the 1920s that organizations become both oligarchical and conservative, both of which are impediments to fundamental (or even incidental) change. What makes the Booz Allen Hamilton study interesting is that first, it statistically demonstrates its thesis (as opposed to using anecdotal data), and second, it suggests that the anti-change behavior of organizations is detrimental to their self-interest.
But what makes one really sit up and take notice is this: "The ability to execute, like health, is not something you can hire or mandate. It is inherent, embedded in the organization's "genes," and expressed in the thousands of individual decisions and actions that collectively constitute and define firm performance. The first step in resolving execution breakdowns is to understand how these inherent traits of an organization influence and, in some ways, even determine how each individual thinks and acts on the job. That behavior is what drives results."
In other words, it's not enough to simply prepare a mission statement, or require adherence to a set of processes or standards; from top to bottom, the relationship of the individual to others in the organization and to the whole of the organization matters. More to the point, the perception of how the individual views his relationship with others and the organization can determine not only how well the individual will function within the organization, but indeed, whether the organization will become, to use Booz Allen Hamilton's term, "marginalized."
Some of the points made along the way are priceless; for example, "...our most salient finding is a very simple and sobering one: Most organizations, by their own employees' admission, are sick." It's hardly surprising to find that a good percentage of the sample universe would think that there are things that need fixing; what's remarkable is that half of the people who took the survey feel that way. More remarkable is the implied opinion that they're powerless (or think they're powerless) to do anything about it.
So what makes an organization unhealthy?
First, individuals aren't clear on what their decision rights are. In other words, they don't know if something is their responsibility or not, and rather than take the chance that they're wrong by making a decision, they'll leave it for someone whose responsibility they're certain it is. Organizations without clear decision rights are also characterized by a lot of second-guessing.
Second, unhealthy organizations are characterized by a lack of free-flowing information required for making good decisions. In other words, "I'm scared to death that I'm making a decision without knowing all of the relevent information." Just as importantly, individuals don't understand the context of their decisions; the reason behind telling a customer that he can't have his sausage with breakfast could be that the sausage didn't get ordered (which means the bacon is fine) or that the walk-in refrigerator broke down (which means one should consider eating toast). It might not be the server's job to tell the customer the details, but it certainly should be someone's job to tell the server.
Third, the bigger an organization is, the more likely it is to be unhealthy. This one is almost self-evident; there's a good reason that Windows Vista has taken so long to develop, and will take another year before it actually gets sold to anyone. It's also the same reason that a good number of people don't see any compelling reason to purchase Microsoft's new operating systems -- which just marginalizes Microsoft even more than its slow decision-making processes with respect to the development of a new operating system. It's a lot easier to turn a canoe than it is to turn a yacht, but compare either to a battleship.
Finally, upper management is clueless as to an organization's health. Okay, that's a bit of an exaggeration, but what is true is that upper managers generally seem to think their organziations are more healthy than they really are. "... it becomes clear," the study says, "that not only is senior management out of touch with the rest of the organization, but they don't know what they don't know." Part of that, one suspects, is that upper managers are frequently insulated from the rank and file; but another part is that upper managers only pay lip service to the first two issues raised.
Take the survey and let us know if you think it's actually accurate.
<Off topic>: Peter Drucker, whose writings on the management -- and mismanagement -- of companies around the world are one of the standards by which such work is measured, died November 11. He will be missed.
AnnieMod is the Moderator responsible for managing the process of cleaning up abandoned questions at Experts Exchange.
I've been thinking about writing this for a few months, and I always decide that it is not needed. But it is.
Very often I see askers and experts mad at the Cleanup Volunteers. That is why I'm writing this -- they deserve "thanks" and not yelling and insults.
A few years ago no one was taking care of the questions which were left unclosed by the Askers. The Moderators decided to start closing these and now, a few years later we have a process. Cleanup has its good and bad moments but it works; Experts get the points they've earned.
The process:
Every Cleanup Volunteer receives a range of questions in a given area. Their responsibility is to:The problems:
When we begin the process, there is a common range of problems:How can you help?
If you are an Asker, please make sure you close your questions in a timely manner:If you are an expert, make sure you pay attention to the pings and recommendations. And we will be very thankful if you educate the users when you see that they want to close the questions but have no idea how.
If you want to help as a CV, mail me at annieMod@experts-exchange.com and give me a few days to answer. (If I don't respond in a day or so, mail me again -- sometimes some mails go in the Trash and I just miss them although I check it regularly).
Thanks to all the Askers who close their questions promptly, thanks to all the Experts who help the users, and thanks to the unsung heroes of EE -- the CVs. You make this great site better.
AnnieMod
Cleanup Admin
I have a dream... in which the guys who write
viruses that cause my inbox to get filled up with garbage are ... never
mind. I really do try to be a lady most of the time.
But this latest strain of the Sober worm has done pretty much what it was expected to do -- make me dread clicking on the icon that opens my email. It's not that I'm really THAT worried, because most of my email goes through at least three levels of protection (one at EE, one at my ISP, and one at my computer). But the problem is just the sheer volume of it all.
The Moderators have it much worse, from what I gather. Someone out there has the Mods' group address at EE in their address book, and they're getting hundreds of spam emails every day. Maybe it will finally get bad enough that someone will invent a program that automatically floods an IP address with email if the person behinds it sends out spam; it would certainly make me sit up and take notice if I got a million emails saying "Clean the virus off your computer, you idiot!!"
Oh, and lest you think this latest strain of Sober is just another passing fancy, Symantec says that the worm will try to download a file on January 5, 2006, if you computer isn't protected. I used to have a hard time believing anyone would surf the Internet or get email without being protected, but the last couple of weeks have shattered that illusion.
C'mon, people.
Expert | Certified | in Topic Area |
---|---|---|
dmitryz6 Painfree888 adwiseman Racimo nmcdermaid DonKronos flavo dtodd SquareHead WMIF Proactivation naveenkohli Maher-Jendasi ibost kalliopi Ahmad1012 martie_11 amit_g dbritt TimYates -sg- simpswr tim_qui JoeZ430 MrAruba McKnife RobWill 0xSaPx0 r_naren22atyahoo | Guru Master Wizard Guru Guru Master Master Master Wizard Guru Master Guru Master Master Master Master Master Sage Wizard Master Master Guru Master Master Master Master Guru Master Master | MS Access MS Access Microsoft SQL Microsoft SQL Microsoft SQL Microsoft SQL Microsoft SQL Microsoft SQL ASP ASP ASP ASP.NET ASP.NET ASP.NET ASP.NET ASP.NET ASP.NET JavaScript JavaScript JavaScript JavaScript Windows XP Windows XP Windows XP Windows XP Windows XP Networking Networking Networking |
Expert | Certified | in Topic Area |
---|---|---|
herbus Gnart dbkruger mikelittlewood ciuly AmirAzhdari ziolko sas13 Amado_Urtis garycase tmj883 TheLearnedOne davidrichardson Netman66 Chris-Dent joedoe58 ram_0218 sujit_kumar InteractiveMind CSecurity rkannan2000 Kelvin81 war1 nytekgirl JBlond mmc98dl1 trigger-happy carl_legere ptjcb | Master Master Master Guru Master Master Master Master Master Wizard Wizard Genius Master Genius Guru Guru Guru Guru Wizard Master Master Master Sage Master Master Guru Master Master Master | Networking Networking Java Delphi Delphi Delphi Delphi Delphi Exchange_Server Hardware Hardware VB.NET VB.NET Win Server 2003 Win Server 2003 Win Server 2003 Oracle Oracle Programming Programming Web Development Excel Outlook Outlook Outlook ColdFusion Flash Microsoft Network Databases |
Expert | Certified | in Topic Area |
---|---|---|
PsiCop r-k craylord bruintje JammyPak leew angelIII rugdog dakyd oBdA CodedK SysExpert meverest harbor235 dopyiii bruintje sramesh2k srikrishnak ramrom amit_g rindi nprignano brettmjohnson RobWill nobus gecko_au2003 JFrederick29 ahoffmann | Master Master Master Genius Master Master Master Master Master Guru Master Master Master Guru Master Master Master Guru Master Master Master Master Guru Master Master Master Master Master | Operating Systems Operating Systems Operating Systems MS Office Linux Applications PHP and Databases Perl CSS Windows Security Miscellaneous Lotus Notes/Domino WinNT Net. Routers Word Word Browser Issues Firewalls FoxPro Unix Prog. Linux Setup FrontPage Macintosh VPN Printers MultiMedia Apps DSL/Cable Web Servers |