VOOZH about

URL: https://www.javacodegeeks.com/2014/10/factory-without-if-else.html

⇱ Factory Without IF-ELSE


Object Oriented Language has very powerful feature of Polymorphism, it is used to remove if/else or switch case in code.

Code without condition is easy to read. There are some places where you have to put them and one of such example is Factory/ServiceProvider class.

I am sure you have seen factory class with IF-ELSEIF which keeps on getting big.

In this blog i will share some techniques that you can be used to remove condition in factory class.

 
I will use below code snippet as example:

public static Validator newInstance(String validatorType) {
		if ("INT".equals(validatorType))
			return new IntValidator();
		else if ("DATE".equals(validatorType))
			return new DateValidator();
		else if ("LOOKUPVALUE".equals(validatorType))
			return new LookupValueValidator();
		else if ("STRINGPATTERN".equals(validatorType))
			return new StringPatternValidator();
		return null;
	}

Reflection

This is first thing that comes to mind when you want to remove conditions. You get the feeling of framework developer!

public static Validator newInstance(String validatorClass) {
		return Class.forName(validatorClass).newInstance();		
	}

This looks very simple but only problem is caller has to remember fully qualified class name and some time it could be issue.

Map

Map can be used to to map actual class instance to some user friendly name:

Map<String, Validator> validators = new HashMap<String,Validator>(){
		{
			put("INT",new IntValidator());
			put("LOOKUPVALUE",new LookupValueValidator());
			put("DATE",new DateValidator());
			put("STRINGPATTERN",new StringPatternValidator());
		}
	};
	public Validator newInstance(String validatorType) {
		return validators.get(validatorType);
	}

This also looks neat without overhead of reflection.

Enum

This is interesting one:

	enum ValidatorType {
		INT {
			public Validator create() {
				return new IntValidator();
			}
		},
		LOOKUPVALUE {
			public Validator create() {
				return new LookupValueValidator();
			}
		},
		DATE {
			public Validator create() {
				return new DateValidator();
			}
		};
		public Validator create() {
			return null;
		}
	}

	public Validator newInstance(ValidatorType validatorType) {
		return validatorType.create();
	}

This method is using enum method to remove condition, one of the issue is that you need Enum for each type. You don’t want to create tons of them!

I personally like this method.

Conclusion

If-else or switch case makes code difficult to understand, we should try to avoid them as much as possible. Language construct should be used to avoid some of switch case.

We should try to code without IF-ELSE and that will force us to come up with better solution.

Reference: Factory Without IF-ELSE from our JCG partner Ashkrit Sharma at the Are you ready blog.
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy

Thank you!

We will contact you soon.

πŸ‘ Photo of Ashkrit Sharma
Ashkrit Sharma
October 13th, 2014Last Updated: October 13th, 2014
14 1,856 2 minutes read

Ashkrit Sharma

Pragmatic software developer who loves practice that makes software development fun and likes to develop high performance & low latency system.
Subscribe

This site uses Akismet to reduce spam. Learn how your comment data is processed.

14 Comments
Oldest
Newest Most Voted
Riaz Uddin
11 years ago

Thanks for sharing, I like this.

0
Reply
Quaiks
11 years ago

The map example is not totally equivalent because you can only serve singletons or you are going to create objects that you don’t really need. Isn’t it?

0
Reply
11 years ago
Reply to  Quaiks

You are right it is creating singleton, but idea was to demonstrate mapping names to factory class.
It is easy to store reference of factory class as map value and delegate instance creation to it.

Global state like Singleton are curse and makes testing very difficult, so i try to avoid it.

0
Reply
Quaiks
11 years ago
Reply to  Ashkrit Sharma

Yes, just testing my. Nice article btw.

0
Reply
Quaiks
11 years ago
Reply to  Quaiks

Yes, just testing *myself. Nice article btw.

0
Reply
Rajesh
10 years ago
Reply to  Quaiks

Good catch Quaiks.

0
Reply
mjafari
11 years ago

All implementation above are not exactly same.
In if-then and reflection ways factory each time produce a new instance but in 2 other ways newInstance method always return same object.

0
Reply
Quaiks
11 years ago

The enum example creates new instances every time the create() method is called.

0
Reply
Raveesh
11 years ago

V. Nice article . But I think recently there is a shift from using Factory pattern to DI . Perhaps a better approach would be using @Inject . That seems to be a good way to avoid IF ELSE. Perhaps for the sake of completion of the article, you can add that mechanism as well .

0
Reply
RyanLi
11 years ago

thank you for share.

0
Reply
Dat Huynh
11 years ago

Thank you for your great example, it helped me a lot.

0
Reply
michael
11 years ago

None of these methods work well. You can just put a Case Staement in your factory based swiching on enumeration type. Putting it in the ENUM is just like using a case statement except putting the code in a place where no one would expect to look. Just change your original if staement to a case based on an enumeration type.

0
Reply
Rajesh
10 years ago
Reply to  michael

True Michael. But @Ashkrit intention is to remove conditional things in factory pattern to support more readability

0
Reply
Rajesh
10 years ago

Thumbs up Ashkrit..!!!

0
Reply
Back to top button
Close
wpDiscuz