I’m very to Java and I use enum for the first time like this:
public class Web {
public String baseUrl;
public static enum Environment {
DEVELOPMENT("http://development") ,
PRODUCTION("http://production"),
SANDBOX("http://sandbox");
public final String baseUrl;
private Environment(String baseUrl)
{
this.baseUrl = baseUrl;
}
}
}
The enum Environment has the three constants DEVELOPMENT, PRODUCTION,SANDBOX. The Web class also has the baseUrl to which the Environment‘s baseUrl to be set ( not sure this is the good practice to do so ).
For setting up the baseUrl I’m currently doing like this :
new Web().setBaseUrl(Web.Environment.PRODUCTION.baseUrl)
I’m not sure this is the right way to use the enums with the classes. Are there any way to directly set Web baseUrl to enums baseUrl.
Am I missing something here.
Thanks in advance
I think you’re on the right track, but you’re losing some of the strength of Java’s enum by accessing the URL in this manner. Instead, use the type of the enum to help ensure that you pass correct values to your method. That is, pass the enum alone, and let the method extract whatever value from it. For example:
Now you can only pass Environments to your Web class, rather than any ol’ string.
[Edit] Then your Web.setEnvironment method looks like this:
This way, I can’t come along and call
new Web().setEnvironment("marvo")by accident. It enforces a certain level of correctness.And vishal_aim is right. Even with Enums you should practice data hiding and encapsulation, so make the instance variable private, and provide an accessor like getBaseUrl() to retrieve the value.