SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6 - OCEJPAD 6
How To Ask Questions How To Answer Questions
Dave Alvarado wrote:
Currently, in my singleton, I have this ...
Dave Alvarado wrote:Thanks for any clarification
Dave Alvarado wrote:Embia, Could you provide a little more explanation? Is "INSTANCE" a coderanch, non-static member variable? If so, you also define the method "doSomething" as non-static so I'm missing the singletonness of this class.
Brian Cole wrote:If you find the Enumeration semantics confusing, you could do something like this instead.
Pat Farrell wrote:Seriously, Singletons considered evil. Don't use one. They seem to work, and then will break in weird ways.
Seriously, Singletons considered evil. Don't use one. They seem to work, and then will break in weird ways.
John de Michele wrote:Just like most hard-and-fast rules, this is probably overblown. Singletons are like cars: when used properly, they work just fine. When used poorly, you get Toonces the Cat.
Pat Farrell wrote:
I used to think that, and used a lot of them with the IBM article's fix for double-check bug.
But a recent Google java technology talk on testing convinced me that its really stronger. They are just global data stores, often with state. They make your code nearly impossible to properly unit test. And I believe, as do many others, that proper unit testing is critical to large scale systems that are reliable and maintainable. With a Singleton, you can't isolate classes that use it. Building mock objects is a critical part of modern testing.
As important, to me, is that it is fairly easy and painless to just write your code to not use them. And once you do, your testing is tons easier. With easier tests, you can write more tests, that explore more edge and fencepost cases.
Singletons often have state, which means your code is relying upon that state. And Singletons make your API and javadocs lie, as they don't mention the perhaps hundreds of state objects that are controlled by the singleton.
This is one more case where the Gang of Four patterns are really harmful.
John de Michele wrote: Your statements just illustrate the need to properly construct singletons, rather than throwing the baby out with the bath water.
John de Michele wrote:Why use a getInstance() at all? Use an enumeration, as was mentioned above.
John de Michele wrote: Since you brought up factories, I would use a singleton for a factory. Why would you ever need more than one object for that, especially if it is something heavyweight? As a real-world example, I've used a singleton in a model-based testing framework that I created, to generate node objects.
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime. |