简体   繁体   English

填充可重用方法 Java 中使用的常量映射的最佳实践

[英]Best practice for populating constant map used in reusable method Java

I am using a reusable method to map two codes, when we receive 'a' we want to use '01' in our code.我正在使用一种可重用的方法来映射两个代码,当我们收到“a”时,我们想在我们的代码中使用“01”。 This is a static method so is it right that it only gets created once and we reuse the method or is this bad practice and it is unnecessarily processing every time we call this method?这是一个静态方法,所以它只创建一次并且我们重用该方法是正确的,还是这种不好的做法并且每次我们调用这个方法时都不必要地进行处理? this good practice or should I be creating this map somewhere else and just using the method for returning the values from it?这是一个很好的做法,还是我应该在其他地方创建这个地图并只使用从它返回值的方法?

    private static String mapStatus(String duckStatus){

       
        Map<String, String> statusMap = new HashMap<String,String>();
        statusMap.put("a","01");
        statusMap.put("b","02");
        statusMap.put("c","03");

        if (!statusMap.containsKey(duckStatus)){
            throw new NullPointerException("Invalid Code does not map to status code");
        }
        return statusMap.get(duckStatus);
    }
    

As per the comments, enum can be a good choice but again as already mentioned by @kendavidson it is debatable.根据评论, enum可能是一个不错的选择,但正如@kendavidson 已经提到的那样,它是有争议的。 From the performance angle I don't see much of a difference between enum and HashMap here but in my opinion HashMap will be more appropriate and will provide better readability.从性能的角度来看,我看不到enumHashMap之间的太大区别,但在我看来HashMap会更合适,并且会提供更好的可读性。 Only difference I suggest in the code you have written is, make the HashMap statically populated so that HashMap build up time is avoided every time you want to lookup the statusMap whenever the call is made to mapStatus method.我在您编写的代码中建议的唯一区别是,使HashMap静态填充,以便在每次调用mapStatus方法时要查找statusMap时避免HashMap建立时间。 The modified code will look like below:修改后的代码如下所示:

public class Test {
    private static final Map<String, String> STATUS_MAP = new HashMap<>();
    static {
        // Mapping the status values in Duck Creek to the Values used here
        STATUS_MAP.put("a", "01");
        STATUS_MAP.put("b", "02");
        STATUS_MAP.put("c", "03");
    }

    private static String mapStatus(String duckStatus) {
        if (!STATUS_MAP.containsKey(duckStatus)) {
            throw new IllegalArgumentException("Invalid code " + duckStatus + " does not map to status code");
        }
        return STATUS_MAP.get(duckStatus);
    }
}

Note:笔记:

  1. Not sure if you wanted to check for duckStatus in duckCreekToEDMStatusMapper or STATUS_MAP , I am using STATUS_MAP不知道,如果你想检查duckStatusduckCreekToEDMStatusMapperSTATUS_MAP ,我使用STATUS_MAP
  2. Instead of NullPointerException better to use IllegalArgumentException as it is appropriate here.使用IllegalArgumentException代替NullPointerException更好,因为它在这里是合适的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM