I\'m attempting to write a java program that initializes certain layouts based on what the user selects. What I want to do is try to avoid writing a bunch of if-statements s
I think using if-statements for initialization is fine. You're trying to avoid the repeated use of if-statements to "select" behavior throughout the program. Using if-statements once for initialization is fine.
To be sure, there are certainly ways to avoid even those initializer if-statements, but you have to decide what level of complexity and possible loss of readability is appropriate for your app.
For example, here are some approaches to this problem from simple to more complex:
A good example of the last method (dynamic registration) is to look at how JDBC works. JDBC drivers are registered in the app using Class.forName()
and then a specific JDBC driver is selected using a JDBC URL. Here's a typical workflow:
Potential target JDBC drivers are added classpath.
The app is configured with a list of these drivers, e.g. by listing the JDBC drivers in a property file.
The app initializes by calling Class.forName()
on each driver in the list. Each driver knows to register itself with the DriverManager when it gets loaded by Class.forName()
The app is determines what target database resource to use and resolving that to a JDBC URL, e.g. in a configuration dialog or user prompt.
The app asks the DriverManager for a connection based on the target JDBC URL. The DriverManager polls each registered driver to see if it can handle the target JDBC URL until the DriverManager finds one that works.
This would be the opposite extreme to avoid those if-statements.