0

I have to return a value that I want to represent as a set of enums in Java that I can OR together where some of the values are "warnings" and should be positive values and half are "errors" and should be negative values so that the recipient can check for < 0 and say an error occurred, but use the individual bits to put out a series of messages indicating the types of problems found (sorted by severity). Something like the following:

public enum ErrorCode {
OK(0),
// Hard errors, (some code not run at all)
PARSE_ERROR(0xC000), // 1100 0000 0000 0000
NOT_IMPLEMENTED(0xB0000), // 1010 0000 0000 0000
// Soft errors, suspicious behavior (action mocked but not performed)
UNINITIALIZED_VARIABLE(0x0001), // 0000 0000 0000 0001
ACCESS_WEB(0x0002), // 0000 0000 0000 0010
START_PROCESS(0x0004), // 0000 0000 0000 0100
WRITE_TO_DISK(0x0008), // 0000 0000 0000 1000
WRITE_TO_REGISTRY(0x0010); // 0000 0000 0001 0000

private Integer exitCode;
public Integer getExitCode() { return exitCode; }
private ExitCode(Integer exitCode) { this.exitCode = exitCode; }
}

However, I'm wondering if there is a better way than explicitly using hex values. Something were I could get the code to "compute" the values. E.g.

PARSE_ERROR(1<<31 | 1<<30),
NOT_IMPLEMENTED(1<<31 | 1<<29),
UNINITIALIZED_VARIABLE(1<<0),
ACCESS_WEB(1<<1),

The advantage being if the recipient decides that some error should be a hard rather than soft error, I just add the 1<<31 | to the value. And a slight advantage that the distinct bits are listed (0..30). But the disadvantage that the results aren't visible.

Or maybe there is a fixed length bitset class in Java with this functionality that I am just not aware of.

I want to use them in code like the following:

public class ExitCode {
  private Integer exitCode = 0;

  public void setExitCode(ErrorCode errorCode) {
    exitCode |= errorCode.getExitCode();
  }

  public exit() { // for end of main()
     System.exit(exitCode);
  }
}

Thus, as my program accumulates status info (the ENUMS), there is a summary value reported to the command line (as well as detailed information in .json files). That's what my client wants. The code is slightly more complicated than this, but this is the section I am focused on making maintainable.

intel_chris
  • 708
  • 1
  • 6
  • 17
  • Does this answer your question? [Can I set enum start value in Java?](https://stackoverflow.com/questions/1067352/can-i-set-enum-start-value-in-java) – Progman Dec 15 '20 at 19:31
  • 2
    Still not sure what you're asking. Neither sample is valid Java code. – xehpuk Dec 15 '20 at 19:38
  • I've seen this done with int values. The java.awt.Font class is but one example. I've not seen enums ORed together. – Gilbert Le Blanc Dec 15 '20 at 21:50

0 Answers0