Java – how to use enum in the right way?

I like Java very much. I use enumeration for the first time, as shown below:

public class Web {
        public String baseUrl;
        public static enum Environment {

            DEVELOPMENT("http://development"),PRODUCTION("http://production"),SAND@R_503_2419@("http://sand@R_503_2419@");

            public final String baseUrl;

            private Environment(String baseUrl)
            {
                this.baseUrl = baseUrl;
            }
        }
    }

The enumeration environment has three constants: development, production, SAND@R_503_2419 @The. Web class also has a baseurl to set the baseurl of the environment (not sure if this is a good habit)

To set up baseurl, I am now doing this:

new Web().setBaseUrl(Web.Environment.PRODUCTION.baseUrl)

I'm not sure this is the right way to use enumeration in a class Is there any way to directly set Web baseurl to enumeration baseurl

I missed something here

Thank you in advance

Solution

I think you're on the right track, but you lose some of the advantages of Java enumeration by accessing URLs in this way Instead, use the type of enumeration to help ensure that the correct value is passed to the method That is, the enumeration is passed separately, allowing the method to extract any value from it For example:

new Web().setEnvironment(Web.Environment.PRODUCTION);

Now, you can only pass the environment to the web class, not any string

[Edit] then your web The setenvironment method is as follows:

public void setEnvironment(Environment environment) {
    this.baseUrl = environment.getBaseUrl();
}

This way, I can't accidentally call the new web () setEnvironment(“marvo”). It enforces a degree of correctness

vishal_ Aim was right Even with enums, you should practice data hiding and encapsulation, so set the instance variable private and provide accessors such as getbaseurl () to retrieve values

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>