简体   繁体   中英

JAVA - Best suitable data structure

Im kind of new to Java but now im facing a dilemma. I have an error list that looks like:

"ERROR CODE" "POSITION" "Error description"
"000" "1" "No error"
"001" "1" "Connection error"
"002" "1" "Error sending reversal or batch capture process"
"003" "1" "Error after authorization – message sent to host and answer received"
"004" "1" "Error sending message for authorization"
"005" "1" "Error receiving message from host"

and a lot more errors.

Now im working on a JAVA Library what i really need to do is to implement this errors (errors never change, they are always the same) somehow so that the developers that use the library can easily identify the error description by the given ERROR_CODE.

eg: String getError(ERROR_CODE); and to return the string of the error description associated to ERROR_CODE.

I thought of declaring ENUM data stucture but i cant seem to make it work properly.

Thank you very much.

You can use an enum like so:

enum Error {

    ERROR_000("000", 1, "No error"),
    ERROR_001("001", 1, "Connection error"),
    ERROR_002("002", 1, "Error sending reversal or batch capture process"),
    ERROR_003("003", 1, "Error after authorization – message sent" +
                        "to host and answer received"),
    ERROR_004("004", 1, "Error sending message for authorization"),
    ERROR_005("005", 1, "Error receiving message from host");

    private final String code;
    private final int position;
    private final String description;
    private static final Map<String, Error> errorMap =
        new HashMap<String, Error>();

    static {
        for (Error error : Error.values()) {
            errorMap.put(error.code, error);
        }
    }

    Error(final String code, final int position, final String description) {
        this.code = code;
        this.position = position;
        this.description = description;
    }

    public static Error getError(String code) {
        return errorMap.get(code);
    }
    // add getters and setters here:
    public String getCode() { return this.code; }
    public int getPosition() { return this.position; }
    public String getDescription() { return this.description; }
}

You can build a structure using enum :

public enum Error {

   public final int code;
   public final String message;

   e0 (000, "No Error"),
   e1 (001, "Connection error");

   public Error(int code, String message) {
      this.code = code;
      this.message = message;
   }

   public static Error byCode(int code) {
        return Error.valueOf("e"+code); // you may add try/catch on IllegalArgumentException, etc.
   }
}

You can add as many accessors (static or not, they could for example use a static HashMap to find by message) as you need.

You can use enum values in switch statements since java 1.5.

use a java.util.Map implementation (HashMap). Use error code as the key and description as the value.

enum ErrorCode{
 001,002
}

and

class ErrorWrapper{
 private ErrorCode errorCode;
 private String description;
 //setters + getters    
}

Have a Map<ErrorCode, List<ErrorWrapper>>

Just use a

HashMap<String, String> 

since you stated your error codes are strings and the description is also a string.

First of all, "errors never change" will be wrong in the near future :)

I would use a properties file to store these error code and descriptions (if necessary "position" data can be parsed)

Properties properties = new Properties();
    try {
        properties.load(new FileInputStream("errors.properties"));
    } catch (IOException e) {}

Then, your getError method would be:

public String getError(String errorCode){
     return properties.getProperty(errorCode);
}

Your errors.properties file would be like:

001=No error
002=Connection error

I think, this will be more dynamic

I wrote something up for you; test code is included. Just make a class Main in the default package, copy paste my code and run it. You can use the method getError(String code) from the class Errors to get the error message by code:

import java.util.*;
public class Main {
    public static void main(String[] args) {
        for(String code : new String[]{"000", "001", "002", "003", "004", "005"}) {
            System.out.println(Errors.getError(code));
        }
    }
}
class Errors {
    static {
        Errors.errors = new HashMap<String, Error>();
        for(String[] error : new String[][]{
                {"000", "1", "No error"},
                {"001", "1", "Connection error"},
                {"002", "1", "Error sending reversal or batch capture process"},
                {"003", "1", "Error after authorization – message sent to host and answer received"},
                {"004", "1", "Error sending message for authorization"},
                {"005", "1", "Error receiving message from host"}
        }) {
            Errors.errors.put(error[0], new Error(error[0], error[1], error[2]));
        }

    }
    private static Map<String, Error> errors;
    public static String getError(String code) {
        return Errors.errors.get(code).message;
    }
    private static class Error {
        private String code;
        private String position;
        private String message;
        public Error(String code, String position, String message) {
            super();
            this.code = code;
            this.position = position;
            this.message = message;
        }
        @Override
        public String toString() {
            return this.getClass().getSimpleName() + " | code: " + this.code + " | position: " + this.position + " | message: " + this.message;
        }
    }
}

Java enum are good fit to your problem. I could think of another approach which is slightly more flexible in terms of adding new error codes or modifying existing code.

  1. Create a property file with the entries like following
    • 000-1=No error
    • 001-1=Connection error
  2. Bundle this file in your jar which will be distributed to developers.
  3. Create a Class and put a code which will read this file from within jar and create a Map (or HashMap)of these name value pair.
  4. Put this code in a static block so that the HashMap is initialized the moment class is loaded.
  5. The getError(ERROR_CODE) method will simply append -1 to the input error code and query this Map and return the appropriate error message.
  6. For adding new message or modifying existing message, just change the content of property file. No code change is needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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