Sharing constants in multiple classes (android minesweeper)
android, constants, java
Solution
To share things, you could make the constants in a separate class and access it statically
class Constants {
public static final int UNTOUCHED = 1;
}
And then in both classes you could go `Constants.UNTOUCHED`.
In this case, I'd avoid using magic numbers and replace them with an Enum.
enum DisplayStatus {
Untouched, Uncovered, Flagged, Hit
}
And replace all of your `int displayStatus` with `DisplayStatus displayStatus`. Now it's clearly to you and other readers of the code what that `int` represents.
Ideally you always want to use a specific type to restrict the range of possible values. In your example, only the numbers 1-4 are valid, but your type is as wide as an `int` so could be any value (e.g. `-1` or `23543`).
Good luck!
Problem
I am creating instances of a class with extends Button and accessing an integer variable directly for better performance. I'm using constants to easily identify the variable's current setting. I have the constants declared both the Button class and in the Activity class which is instantiating them. I have found similar questions and read it's not good practice to create a class just to hold constants. What is the best way to use the same constant declaration in both classes? I am a beginner programmer so it's quite possible I am overlooking 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) { } } ```