mocking a singleton class - java

I recently read that making a class singleton makes it impossible to mock the objects of the class, which makes it difficult to test its clients. I could not immediately understand the underlying reason. Can someone please explain what makes it impossible to mock a singleton class? Also, are there any more problems associated with making a class singleton?

Of course, I could write something like don't use singleton, they are evil, use Guice/Spring/whatever but first, this wouldn't answer your question and second, you sometimes have to deal with singleton, when using legacy code for example.
So, let's not discuss the good or bad about singleton (there is another question for this) but let's see how to handle them during testing. First, let's look at a common implementation of the singleton:
public class Singleton {
private Singleton() { }
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
public String getFoo() {
return "bar";
}
}
There are two testing problems here:
The constructor is private so we can't extend it (and we can't control the creation of instances in tests but, well, that's the point of singletons).
The getInstance is static so it's hard to inject a fake instead of the singleton object in the code using the singleton.
For mocking frameworks based on inheritance and polymorphism, both points are obviously big issues. If you have the control of the code, one option is to make your singleton "more testable" by adding a setter allowing to tweak the internal field as described in Learn to Stop Worrying and Love the Singleton (you don't even need a mocking framework in that case). If you don't, modern mocking frameworks based on interception and AOP concepts allow to overcome the previously mentioned problems.
For example, Mocking Static Method Calls shows how to mock a Singleton using JMockit Expectations.
Another option would be to use PowerMock, an extension to Mockito or JMock which allows to mock stuff normally not mock-able like static, final, private or constructor methods. Also you can access the internals of a class.

The best way to mock a singleton is not to use them at all, or at least not in the traditional sense. A few practices you might want to look up are:
programming to interfaces
dependency injection
inversion of control
So rather than having a single you access like this:
Singleton.getInstance().doSometing();
... define your "singleton" as an interface and have something else manage it's lifecycle and inject it where you need it, for instance as a private instance variable:
#Inject private Singleton mySingleton;
Then when you are unit testing the class/components/etc which depend on the singleton you can easily inject a mock version of it.
Most dependency injection containers will let you mark up a component as 'singleton', but it's up to the container to manage that.
Using the above practices makes it much easier to unit test your code and lets you focus on your functional logic instead of wiring logic. It also means your code really starts to become truly Object Oriented, as any use of static methods (including constructors) is debatably procedural. Thus your components start to also become truly reusable.
Check out Google Guice as a starter for 10:
http://code.google.com/p/google-guice/
You could also look at Spring and/or OSGi which can do this kind of thing. There's plenty of IOC / DI stuff out there. :)

A Singleton, by definition, has exactly one instance. Hence its creation is strictly controlled by the class itself. Typically it is a concrete class, not an interface, and due to its private constructor it is not subclassable. Moreover, it is found actively by its clients (by calling Singleton.getInstance() or an equivalent), so you can't easily use e.g. Dependency Injection to replace its "real" instance with a mock instance:
class Singleton {
private static final myInstance = new Singleton();
public static Singleton getInstance () { return myInstance; }
private Singleton() { ... }
// public methods
}
class Client {
public doSomething() {
Singleton singleton = Singleton.getInstance();
// use the singleton
}
}
For mocks, you would ideally need an interface which can be freely subclassed, and whose concrete implementation is provided to its client(s) by dependency injection.
You can relax the Singleton implementation to make it testable by
providing an interface which can be implemented by a mock subclass as well as the "real" one
adding a setInstance method to allow replacing the instance in unit tests
Example:
interface Singleton {
private static final myInstance;
public static Singleton getInstance() { return myInstance; }
public static void setInstance(Singleton newInstance) { myInstance = newInstance; }
// public method declarations
}
// Used in production
class RealSingleton implements Singleton {
// public methods
}
// Used in unit tests
class FakeSingleton implements Singleton {
// public methods
}
class ClientTest {
private Singleton testSingleton = new FakeSingleton();
#Test
public void test() {
Singleton.setSingleton(testSingleton);
client.doSomething();
// ...
}
}
As you see, you can only make your Singleton-using code unit testable by compromising the "cleanness" of the Singleton. In the end, it is best not to use it at all if you can avoid it.
Update: And here is the obligatory reference to Working Effectively With Legacy Code by Michael Feathers.

It very much depends on the singleton implementation. But it mostly because it has a private constructor and hence you can't extend it. But you have the following option
make an interface - SingletonInterface
make your singleton class implement that interface
let Singleton.getInstance() return SingletonInterface
provide a mock implementation of SingletonInterface in your tests
set it in the private static field on Singleton using reflection.
But you'd better avoid singletons (which represent a global state). This lecture explains some important design concepts from testability point of view.

It's not that the Singleton pattern is itself pure evil, but that is massively overused even in situations where it is inapproriate. Many developers think "Oh, I'll probably only ever need one of these so let's make it a singleton". In fact you should be thinking "I'll probably only ever need one of these, so let's construct one at the start of my program and pass references where it is needed."
The first problem with singleton and testing is not so much because of the singleton but due to laziness. Because of the convenience of getting a singleton, the dependency on the singleton object is often embedded directly into the methods which makes it very difficult to change the singleton to another object with the same interface but with a different implementation (for example, a mock object).
Instead of:
void foo() {
Bar bar = Bar.getInstance();
// etc...
}
prefer:
void foo(IBar bar) {
// etc...
}
Now you can test function foo with a mocked bar object which you can control. You've removed the dependency so that you can test foo without testing bar.
The other problem with singletons and testing is when testing the singleton itself. A singleton is (by design) very difficult to reconstruct, so for example you can only test the singleton contructor once. It's also possible that the single instance of Bar retains state between tests, causing success or failure depending on the order that the tests are run.

There is a way to mock Singleton. Use powermock to mock static method and use Whitebox to invoke constructor YourClass mockHelper = Whitebox
.invokeConstructor(YourClass.class);
Whitebox.setInternalState(mockHelper, "yourdata",mockedData);
PowerMockito.mockStatic(YourClass.class);
Mockito.when(YourClass.getInstance()).thenReturn(mockHelper);
What is happening is that the Singleton byte code is changing in run-time .
enjoy

Related

In Java unit testing, how to mock the variables that are not injected but created inside the to-be-tested class?

For example, the class to be tested is
public class toBeTested {
private Object variable;
public toBeTested(){
variable = someFactory(); // What if this someFactory() sends internet request?
// Can I mock "variable" without calling
// someFactory() in testing?
}
public void doSomething(){
...
Object returnedValue = variable.someMethod(); // In testing, can I mock the behavior of
// this someMethod() method when
// "variable" is a private instance
// variable that is not injected?
Object localVariable = new SomeClass(); // Can I mock this "localVariable" in
// testing?
...
}
}
My questions are as stated in the comments above.
In short, how to mock the variables that are not injected but created inside the to-be-tested class?
Thanks in advance!
Your question is more about the design, the design of your class is wrong and it is not testable, It is not easy (and sometimes it is not possible at all) to write a unit test for a method and class that have been developed before. Actually one of the great benefit of TDD(Test Driven Development) is that it helps the developer to develop their component in a testable way.
Your class would have not been developed this way if its test had been written first. In fact one of the inevitable thing that you should do when you are writing test for your component is refactoring. So here to refactor your component to a testable component you should pass factory to your class's constructor as a parameter.
And what about localVariable:
It really depends on your situation and what you expect from your unit to do (here your unit is doSomething method). If it is a variable that you expext from your method to create as part of its task and it should be created based on some logic in method in each call, there is no problem let it be there, but if it provides some other logic to your method and can be passed as parameter to your class you can pass it as parameter to your class's cunstructor.
One more thing, be carefull when you are doing refactoring there will be many other components that use your component, you should do your refactoring step by step and you should not change the logic of your method.
To add another perspective: If faced with situations in which you have to test a given class and aren't permitted to change the class you need to test, you have the option to use a framework like PowerMock (https://github.com/powermock/powermock) that offers enhanced mocking capabilities.
But be aware that using PowerMock for the sole purpose of justifying hard to test code is not advisable. Tashkhisi's answer is by far the better general purpose approach.

How do I find where an instance of a Java singleton is created?

In a large, complex program it may not be simple to discover where in the
code a Singleton has been instantiated. What is the best approach to keep track of created singleton instances in order to re-use them?
Regards,
RR
A Singleton usually has a private constructor, thus the Singleton class is the only class which can instantiate the one and only singleton instance.
It's the responsibilty of singleton class developer to make sure that the instance is being reused on multiple calls.
As a user, you shouldn't worry about it.
class Singelton
{
private static Singelton _singelton = null;
private Singelton()
{
}
// NOT usable for Multithreaded program
public static Singelton CreateMe()
{
if(_singelton == null)
_singelton = new Singelton();
return _singelton;
}
}
Now, from anywhere in your code, you can instantiate Singelton, how many times you like and each time assign it to different reference. but c'tor is called ONLY once.
I would use an enum
enum Singleton {
INSTANCE:
}
or something similar which cannot be instantiated more than once and globally accessible.
General practice for naming methods which create/return singletons is getInstance(). I don't understand the situation when you can't find the place in code where singletons created, but you can search for this method name.
If you want to catch the exact moment of singleton creation - you can use AOP. AspectJ is a good example in java. You will be able to execute your code before/after creation of class or calling getInstance() method.
If your question is about reusing of created Singletons, then search this site. For example

Why doesn't Mockito mock static methods?

I read a few threads here about static methods, and I think I understand the problems misuse/excessive use of static methods can cause. But I didn't really get to the bottom of why it is hard to mock static methods.
I know other mocking frameworks, like PowerMock, can do that but why can't Mockito?
I read this article, but the author seems to be religiously against the word static, maybe it's my poor understanding.
An easy explanation/link would be great.
I think the reason may be that mock object libraries typically create mocks by dynamically creating classes at runtime (using cglib). This means they either implement an interface at runtime (that's what EasyMock does if I'm not mistaken), or they inherit from the class to mock (that's what Mockito does if I'm not mistaken). Both approaches do not work for static members, since you can't override them using inheritance.
The only way to mock statics is to modify a class' byte code at runtime, which I suppose is a little more involved than inheritance.
That's my guess at it, for what it's worth...
If you need to mock a static method, it is a strong indicator for a bad design. Usually, you mock the dependency of your class-under-test. If your class-under-test refers to a static method - like java.util.Math#sin for example - it means the class-under-test needs exactly this implementation (of accuracy vs. speed for example). If you want to abstract from a concrete sinus implementation you probably need an Interface (you see where this is going to)?
Mockito [3.4.0] can mock static methods!
Replace mockito-core dependency with mockito-inline:3.4.0.
Class with static method:
class Buddy {
static String name() {
return "John";
}
}
Use new method Mockito.mockStatic():
#Test
void lookMomICanMockStaticMethods() {
assertThat(Buddy.name()).isEqualTo("John");
try (MockedStatic<Buddy> theMock = Mockito.mockStatic(Buddy.class)) {
theMock.when(Buddy::name).thenReturn("Rafael");
assertThat(Buddy.name()).isEqualTo("Rafael");
}
assertThat(Buddy.name()).isEqualTo("John");
}
Mockito replaces the static method within the try block only.
As an addition to the Gerold Broser's answer, here an example of mocking a static method with arguments:
class Buddy {
static String addHello(String name) {
return "Hello " + name;
}
}
...
#Test
void testMockStaticMethods() {
assertThat(Buddy.addHello("John")).isEqualTo("Hello John");
try (MockedStatic<Buddy> theMock = Mockito.mockStatic(Buddy.class)) {
theMock.when(() -> Buddy.addHello("John")).thenReturn("Guten Tag John");
assertThat(Buddy.addHello("John")).isEqualTo("Guten Tag John");
}
assertThat(Buddy.addHello("John")).isEqualTo("Hello John");
}
Mockito returns objects but static means "class level,not object level"So mockito will give null pointer exception for static.
I seriously do think that it is code smell if you need to mock static methods, too.
Static methods to access common functionality? -> Use a singleton instance and inject that
Third party code? -> Wrap it into your own interface/delegate (and if necessary make it a singleton, too)
The only time this seems overkill to me, is libs like Guava, but you shouldn't need to mock this kind anyway cause it's part of the logic... (stuff like Iterables.transform(..))
That way your own code stays clean, you can mock out all your dependencies in a clean way, and you have an anti corruption layer against external dependencies.
I've seen PowerMock in practice and all the classes we needed it for were poorly designed. Also the integration of PowerMock at times caused serious problems(e.g. https://code.google.com/p/powermock/issues/detail?id=355)
PS: Same holds for private methods, too. I don't think tests should know about the details of private methods. If a class is so complex that it tempts to mock out private methods, it's probably a sign to split up that class...
In some cases, static methods can be difficult to test, especially if they need to be mocked, which is why most mocking frameworks don't support them. I found this blog post to be very useful in determining how to mock static methods and classes.

Java Singleton Design Pattern : Questions

I had an interview recently and he asked me about Singleton Design Patterns about how are they implemented and I told him that using static variables and static methods we can implement Singleton Design Patterns.
He seems to be half satisfied with the answer but I want to know
How many different ways we can
implement Singleton Design Pattern
in Java ?
What is the scope of Singleton Object and how does it actually work inside JVM ? I know we would always have one instance of Singleton Object but what is the actual scope of that object, is it in JVM or if there are multiple application running than it's scope is per context basis inside the JVM, I was really stumped at this and was unable to give satisfying explanation ?
Lastly he asked if it is possible to used Singleton Object with Clusters with explanation and is there any way to have Spring not implement Singleton Design Pattern when we make a call to Bean Factory to get the objects ?
Any inputs would be highly appreciated about Singleton and what are the main things to keep in mind while dealing with Singletons ?
Thanks.
There are a few ways to implement a Singleton pattern in Java:
// private constructor, public static instance
// usage: Blah.INSTANCE.someMethod();
public class Blah {
public static final Blah INSTANCE = new Blah();
private Blah() {
}
// public methods
}
// private constructor, public instance method
// usage: Woo.getInstance().someMethod();
public class Woo {
private static final Woo INSTANCE = new Woo();
private Woo() {
}
public static Woo getInstance() {
return INSTANCE;
}
// public methods
}
// Java5+ single element enumeration (preferred approach)
// usage: Zing.INSTANCE.someMethod();
public enum Zing {
INSTANCE;
// public methods
}
Given the examples above, you will have a single instance per classloader.
Regarding using a singleton in a cluster...I'm not sure what the definition of "using" is...is the interviewer implying that a single instance is created across the cluster? I'm not sure if that makes a whole lot of sense...?
Lastly, defining a non-singleton object in spring is done simply via the attribute singleton="false".
I disagree with #irreputable.
The scope of a Singleton is its node in the Classloader tree. Its containing classloader, and any child classloaders can see the Singleton.
It's important to understand this concept of scope, especially in the application servers which have intricate Classloader hierarchies.
For example, if you have a library in a jar file on the system classpath of an app server, and that library uses a Singleton, that Singleton is going to (likely) be the same for every "app" deployed in to the app server. That may or may not be a good thing (depends on the library).
Classloaders are, IMHO, one of the most important concepts in Java and the JVM, and Singletons play right in to that, so I think it is important for a Java programmer to "care".
I find it hard to believe that so many answers missed the best standard practice for singletons - using Enums - this will give you a singleton whose scope is the class loader which is good enough for most purposes.
public enum Singleton { ONE_AND_ONLY_ONE ; ... members and other junk ... }
As for singletons at higher levels - perhaps I am being silly - but my inclination would be to distribute the JVM itself (and restrict the class loaders). Then the enum would be adequate to the job .
Singleton is commonly implemented by having a static instance object (private SingletonType SingletonType.instance) that is lazily instantiated via a static SingletonType SingletonType.getInstance() method. There are many pitfalls to using singletons, so many, in fact, that many consider singleton to be a design anti-pattern. Given the questions about Spring, the interviewer probably was looking for an understanding not only of singletons but also their pitfalls as well as a workaround for these pitfalls known as dependency injection. You may find the video on the Google Guice page particularly helpful in understanding the pitfalls of singletons and how DI addresses this.
3: Lastly he asked if it is possible to used Singleton Object with Clusters with explanation and is there any way to have Spring not implement Singleton Design Pattern when we make a call to Bean Factory to get the objects ?
The first part of this question is hard to answer without a technological context. If the cluster platform includes the ability to make calls on remote objects as if they were local objects (e.g. as is possible with EJBs using RMI or IIOP under the hood) then yes it can be done. For example, the JVM resident singleton objects could be proxies for a cluster-wide singleton object, that was initially located / wired via JNDI or something. But cluster-wide singletons are a potential bottleneck because each call on one of the singleton proxies results in an (expensive) RPC to a single remote object.
The second part of the question is that Spring Bean Factories can be configured with different scopes. The default is for singletons (scoped at the webapp level), but they can also be session or request scoped, or an application can define its own scoping mechanism.
a static field can have multiple occurrences in one JVM - by using difference class loaders, the same class can be loaded and initialized multiple times, but each lives in isolation and JVM treat the result loaded classes as completely different classes.
I don't think a Java programmer should care, unless he's writing some frameworks. "One per VM" is a good enough answer. People often talk that way while strictly speaking they are saying "one per classloader".
Can we have one singleton per cluster? Well that's a game of concepts. I would not appreciate an interviewer word it that way.
There's the standard way, which you already covered. Also, most dependency-injection schemes have some way to mark a class as a singleton; this way, the class looks just like any other, but the framework makes sure that when you inject instances of that class, it's always the same instance.
That's where it gets hairy. For example, if the class is initialized inside a Tomcat application context, then the singleton instance's lifetime is bound to that context. But it can be hard to predict where your classes will be initialized; so it's best not to make any assumptions. If you want to absolutely make sure that there's exactly one instance per context, you should bind it as an attribute of the ServletContext. (Or let a dependency-injection framework take care of it.)
--
Not sure I understand the question - but if you're talking about having a singleton instance that's shared between several cluster nodes, then I think EJB makes this possible (by way of remote beans), though I've never tried it. No idea how Spring does it.
Singleton is a creational pattern and hence governs object instantiation. Creating singletons would mandate that you voluntarily or involuntarily give up control on creating the object and instead rely on some way of obtaining access to it.
This can be achieved using static methods or by dependency injection or using the factory pattern. The means is immaterial. In case of the normal protected constructor() approach, the consumer perforce needs to use the static method for accessing the singleton. In case of DI, the consumer voluntarily gives up control over the instantiation of the class and instead relies on a DI framework to inject the instance into itself.
As pointed out by other posters, the class loader in java would define the scope of the singleton. Singletons in clusters are usually "not single instances" but a collection of instances that exhibit similar behavior. These can be components in SOA.
The Following Code is from here
The Key point is you should Override the clone method...The Wikipedia example also is helpful.
public class SingletonObject
{
private SingletonObject()
{
// no code req'd
}
public static SingletonObject getSingletonObject()
{
if (ref == null)
// it's ok, we can call this constructor
ref = new SingletonObject();
return ref;
}
public Object clone()
throws CloneNotSupportedException
{
throw new CloneNotSupportedException();
// that'll teach 'em
}
private static SingletonObject ref;
}
Query 1:
Different ways of creating Singleton
Normal Singleton : static initialization
ENUM
Lazy Singleton : Double locking Singleton & : Initialization-on-demand_holder_idiom singleton
Have a look at below code:
public final class Singleton{
private static final Singleton instance = new Singleton();
public static Singleton getInstance(){
return instance;
}
public enum EnumSingleton {
INSTANCE;
}
public static void main(String args[]){
System.out.println("Singleton:"+Singleton.getInstance());
System.out.println("Enum.."+EnumSingleton.INSTANCE);
System.out.println("Lazy.."+LazySingleton.getInstance());
}
}
final class LazySingleton {
private LazySingleton() {}
public static LazySingleton getInstance() {
return LazyHolder.INSTANCE;
}
private static class LazyHolder {
private static final LazySingleton INSTANCE = new LazySingleton();
}
}
Related SE questions:
What is an efficient way to implement a singleton pattern in Java?
Query 2:
One Singleton instance is created per ClassLoader. If you want to avoid creation of Singleton object during Serializaiton, override below method and return same instance.
private Object readResolve() {
return instance;
}
Query 3:
To achieve a cluster level Singleton among multiple servers, store this Singleton object in a distributed caches like Terracotta, Coherence etc.
Singleton is a creational design pattern.
Intents of Singleton Design Pattern :
Ensure a class has only one instance, and provide a global point of
access to it.
Encapsulated "just-in-time initialization" or "initialization on
first use".
I'm showing three types of implementation here.
Just in time initialization (Allocates memory during the first run, even if you don't use it)
class Foo{
// Initialized in first run
private static Foo INSTANCE = new Foo();
/**
* Private constructor prevents instantiation from outside
*/
private Foo() {}
public static Foo getInstance(){
return INSTANCE;
}
}
Initialization on first use (or Lazy initialization)
class Bar{
private static Bar instance;
/**
* Private constructor prevents instantiation from outside
*/
private Bar() {}
public static Bar getInstance(){
if (instance == null){
// initialized in first call of getInstance()
instance = new Bar();
}
return instance;
}
}
This is another style of Lazy initialization but the advantage is, this solution is thread-safe without requiring special language constructs (i.e. volatile or synchronized). Read More at SourceMaking.com
class Blaa{
/**
* Private constructor prevents instantiation from outside
*/
private Blaa() {}
/**
* BlaaHolder is loaded on the first execution of Blaa.getInstance()
* or the first access to SingletonHolder.INSTANCE, not before.
*/
private static class BlaaHolder{
public static Blaa INSTANCE = new Blaa();
}
public static Blaa getInstance(){
return BlaaHolder.INSTANCE;
}
}

Is it a good or bad practice to call instance methods from a java constructor?

There are several different ways I can initialize complex objects (with injected dependencies and required set-up of injected members), are all seem reasonable, but have various advantages and disadvantages. I'll give a concrete example:
final class MyClass {
private final Dependency dependency;
#Inject public MyClass(Dependency dependency) {
this.dependency = dependency;
dependency.addHandler(new Handler() {
#Override void handle(int foo) { MyClass.this.doSomething(foo); }
});
doSomething(0);
}
private void doSomething(int foo) { dependency.doSomethingElse(foo+1); }
}
As you can see, the constructor does 3 things, including calling an instance method. I've been told that calling instance methods from a constructor is unsafe because it circumvents the compiler's checks for uninitialized members. I.e. I could have called doSomething(0) before setting this.dependency, which would have compiled but not worked. What is the best way to refactor this?
Make doSomething static and pass in the dependency explicitly? In my actual case I have three instance methods and three member fields that all depend on one another, so this seems like a lot of extra boilerplate to make all three of these static.
Move the addHandler and doSomething into an #Inject public void init() method. While use with Guice will be transparent, it requires any manual construction to be sure to call init() or else the object won't be fully-functional if someone forgets. Also, this exposes more of the API, both of which seem like bad ideas.
Wrap a nested class to keep the dependency to make sure it behaves properly without exposing additional API:class DependencyManager {
private final Dependency dependency;
public DependecyManager(Dependency dependency) { ... }
public doSomething(int foo) { ... }
}
#Inject public MyClass(Dependency dependency) {
DependencyManager manager = new DependencyManager(dependency);
manager.doSomething(0);
}
This pulls instance methods out of all constructors, but generates an extra layer of classes, and when I already had inner and anonymous classes (e.g. that handler) it can become confusing - when I tried this I was told to move the DependencyManager to a separate file, which is also distasteful because it's now multiple files to do a single thing.
So what is the preferred way to deal with this sort of situation?
Josh Bloch in Effective Java recommends using a static factory method, although I can't find any argument for cases like this. There is, however, a similar case in Java Concurrency in Practice, specifically meant to prevent leaking out a reference to this from the constructor. Applied to this case, it would look like:
final class MyClass {
private final Dependency dependency;
private MyClass(Dependency dependency) {
this.dependency = dependency;
}
public static createInstance(Dependency dependency) {
MyClass instance = new MyClass(dependency);
dependency.addHandler(new Handler() {
#Override void handle(int foo) { instance.doSomething(foo); }
});
instance.doSomething(0);
return instance;
}
...
}
However, this may not work well with the DI annotation you use.
It also messes badly with inheritance. If your constructor is being called in the chain to instantiate a subclass of your class, you may call a method which is overridden in the subclass and relies on an invariant that is not established until the subclass constructor has been run.
You'd want to be careful about using instance methods from within the constructor, as the class has not been fully constructed yet. If a called method uses a member that has not yet been initialized, well, bad things will happen.
You could use a static method that takes the dependency and constructs and return a new instance, and mark the constructor Friend. I'm not sure Friend exists in java though (is it package protected.) This might not be the best way though. You could also use another class that is a Factory for creating MyClass.
Edit: Wow another posted just suggested this same exact thing. Looks like you can make constructors private in Java. You can't do that in VB.NET (not sure about C#)... very cool...
Yeah, it's actually illegal, It really shouldn't even compile (but I believe it does)
Consider the builder pattern instead (and lean towards immutable which in builder pattern terms means that you can't call any setter twice and can't call any setter after the object has been "used"--calling a setter at that point should probably throw a runtime exception).
You can find the slides by Joshua Bloch on the (new) Builder pattern in a slide presentation called "Effective Java Reloaded: This Time It's for Real", for example here:
http://docs.huihoo.com/javaone/2007/java-se/

Categories