will824
will824

Reputation: 2244

How to replace Legacy Flag & Constants bitwise operations with Enums in Java?

Greetings,

I came to a legacy code in C++ that is using a Flag and later updating the status of the flag based on the reads done:

Main file:

#define VINCULACION                 0x00000004L
#define DET_VINCULACION             0x00000008L

long unsigned FlagRead ;

int formerMethod(){
if ((FlagRead & VINCULACION)==0) ReadVinculacion();
//... DO MORE
}

int ReadVinculacion(){
//.. Do DB operations to read Vinculacion variables.
FlagRead|=VINCULACION;
  return 1;
}

//.. Same similar methods to ensure reading DET_VINCULACION but not doing it twice.

Now developing in Java I am not using Constants with Integers or Longs as its good practice to use enums.

Is it there a performance wise and reliable way to do the same task using enums under java?.

Thanks!

Upvotes: 1

Views: 641

Answers (2)

will824
will824

Reputation: 2244

Greetings,

I created per suggestion, one Enum file: Constants.java

public enum Constantes {

  VINCULACION,

  DET_VINCULACION;
}

Then on the Main.java:

private final EnumSet<Constantes> flagRead;

public boolean needsToRead(Constantes constantParameter) {
    return (flagRead.contains(constantParameter)  == false);
  }

public void markAsRead(Constantes constantParameter){
    flagRead.add(constantParameter);
  }

While then needing to check if the set of information regarding the variable has been read or not, then I do the next checks in the file Process.java:

private Main m = new Main();

public int newMethod(){
if (m.needsToRead(Constantes.VINCULACION)){
 ReadVinculacion();
}
//... DO MORE
}

public void readVinculacion(){
//.. Do DB operations to read Vinculacion variables.
m.markAsRead(VINCULACION);
}

I did basic unit and run tests and it worked to simulate the needed Process.

Thanks!

Upvotes: -1

matt b
matt b

Reputation: 139921

Take a look at using an EnumSet to take the place of the FlagRead variable in the C++ code:

Enum sets are represented internally as bit vectors. This representation is extremely compact and efficient. The space and time performance of this class should be good enough to allow its use as a high-quality, typesafe alternative to traditional int-based "bit flags."

You can then test if you should perform certain operations by using set.contains(YourEnum.SOME_VALUE)

Upvotes: 6

Related Questions