Java – Sharing constants in multiple classes (android minesweeper)

Sharing constants in multiple classes (android minesweeper)… here is a solution to the problem.

Sharing constants in multiple classes (android minesweeper)

I’m using extends Button to create an instance of a class and access an integer variable directly for better performance. I use constants to easily identify the current setting of a variable.

I declare constants in both the Button class and the Activity class that instantiates them. I found a similar issue and read that creating a class to hold constants is not good practice.

What is the best way to use the same constant declaration in both classes?

I’m a junior programmer, so I’m likely overlooked a simple solution.

Button class:

public class GridButton extends Button {
  public int displayStatus;

 constants for mine display status
  private static final int UNTOUCHED = 1;
  private static final int UNCOVERED = 2;
  private static final int FLAGGED = 3;
  private static final int HIT = 4;
  ...
}

Activity class:

public class PlayGameActivity extends Activity {      
  private GridButton[][] gridButtons;      

 constants for mine display status
  private static final int UNTOUCHED = 1;
  private static final int UNCOVERED = 2;
  private static final int FLAGGED = 3;
  private static final int HIT = 4;
  ...

 e.g. accessing displayStatus value
  if (gridButtons[currentRow][currentColumn].displayStatus == FLAGGED)
  {
  }
}

Solution

To share something, you can create a constant in a separate class and access it statically

class Constants {
  public static final int UNTOUCHED = 1;
}

THEN IN BOTH CLASSES, YOU CAN USE CONSTANTS.UNTOUCHED.

In this case, I would avoid using Magic Number and replace it with an enumeration.

enum DisplayStatus {
  Untouched, Uncovered, Flagged, Hit
}

and replace all int displayStatus with DisplayStatus displayStatus. Now it’s clear to you and other readers of your code what int stands for.

Ideally, you always want to use a specific type to limit the range of possible values. In your example, only the numbers 1-4 are valid, but your type is as wide as int, so it can be any value (for example, -1 or 23543).

Good luck!

Related Problems and Solutions