Suggest proper Design for Java integer constants extension - java

I am sorry if this question was asked before, but I need a good suggestion to solve next design problem:
Task: given that we have a base service that operates with data of given set of types, we need to design support of extensions for that service that has extended type set.
Bad Solution:
class BaseServiceType {
public static final int TYPE_A = 0;
public static final int TYPE_B = 1;
public static final int LAST_USED_BASE_TYPE_INDEX = TYPE_B;
}
And its extension
class ExtendedServiceType extends BaseServiceType {
public static final int TYPE_E = LAST_USED_BASE_TYPE_INDEX + 1;
public static final int TYPE_F = LAST_USED_BASE_TYPE_INDEX + 2;
}
My task is fairly simple that has only one extension. I am not trying to solve more general problem with multiple independent extensions.
I have a feeling that enum would work here, but no idea if it feasible.

One solution is to build the ids dynamically. Class initilization is thread safe so you can do this.
class BaseServiceType {
protected static int id = 0;
public static final int TYPE_A = id++;
public static final int TYPE_B = id++;
}
And its extension
class ExtendedServiceType extends BaseServiceType {
public static final int TYPE_E = id++;
public static final int TYPE_F = id++;
}
class AlsoExtendedServiceType extends BaseServiceType {
public static final int TYPE_X = id++;
public static final int TYPE_Y = id++;
}
The only problem is the order classes are initialized change the ids. If this matters, you need to access the classes in the order you need.

Related

How to construct several objects in one class, then read in another class

I apologize if this is a basic question.
I am attempting to create several unique objects in one class, then get the values of one of the objects in another class.
I have created two classes and followed some examples to end with this
public class Type {
public String name;
public int healthmod;
public int strmod;
public int accmod;
public int armmod;
public int refmod;
public int intmod;
public String advantages;
public String disadvantages;
public Type() {
Type fire = new Type();
fire.name = "Fire";
fire.healthmod = 0;
fire.strmod = 1;
fire.accmod = 0;
fire.armmod = 0;
fire.refmod = 0;
fire.intmod = 1;
}
}
and then in the main class:
Player.typename = Type.fire.name;
Edit
public class Player {
public static String name, classname, racename, elementname;
public static int maxhealth, healthpts, healthptscost, healthupgnum, healthmod, currenthealth, basehealth;
public static int str, strpts, strptscost, strupgnum, strmod;
public static int acc, accpts, accptscost, accupgnum, accmod;
public static int arm, armpts, armptscost, armupgnum, armmod;
public static int ref, refpts, refptscost, refupgnum, refmod;
public static int intelligence, intpts, intptscost, intupgnum, intmod;
public static int mana, maxmana, managain, managainak;
public static int hitChance, critChance, Level, statPts, statTotal, damage, damageDealt, goldmult, itemmod, itemdefboost, itemdamboost, itemmodboost;
public static String[] focusStats;
}
What I am trying to do is create a few objects in the Type class and access them in the Main class in order to store the values in the Player class, but in the Main class, fire "cannot be resolved or is not a field"
Edited to provide more clarity on the purpose.
You are completely mixing things here.
In the concstructor of Type you are creating a new local Object named fire. This object is only available in this constructor and not outside of it, e.g. in the main class.
A valid solution can only be found if you give more information about what you try to accomplish.
I could write like that your Type construct:
public Type() {
this.name = "Fire";
this.healthmod = 0;
this.strmod = 1;
this.accmod = 0;
this.armmod = 0;
this.refmod = 0;
this.intmod = 1;
}
So when using the Player class in your Main method, like that:
public static void main(String args[]) {
Type type = new Type();
Player.typename = type.name;
}
You can also put a reference of type inside Player class like that:
public class Player {
public static Type fire;
}
So in your main method like that:
public static void main(String args[]) {
Player.fire = new Type();
System.out.println(Player.fire.name);
}

Design Pattern: Extending a List of Constants

I know the title isn't very descriptive but hopefully I can clarify some things with code. I have a class that looks like this:
public abstract class Entity {
protected final static int BASE_STATE_SIZE = 3;
protected final static int AGE = 0;
protected final static int X = 1;
protected final static int Y = 2;
protected double[] state;
public Entity () {
state = new double[getStateSize ()];
...
}
protected void initDefaultState () {
state[AGE] = 0;
state[X] = Math.random () * Renderer.size.width;
state[Y] = Math.random () * Renderer.size.height;
}
protected abstract int getStateSize ();
}
public class Critter extends Entity {
protected final static int STATE_SIZE = Entity.BASE_STATE_SIZE + 1;
protected final static int HUNGER = Entity.BASE_STATE_SIZE + 0;
public Critter () {
...
}
protected void initDefaultState () {
super.initDefaultState ();
state[HUNGER] = 0;
}
protected int getStateSize () {
return STATE_SIZE;
}
}
To give a bit more context: entities are just generic objects. Critter is one example of a more specific object. The state of an entity changes frequently throughout its lifetime. In this case, a critter's position, x, y, and hunger change multiple times per second. State values are assigned in the subclass (and occasionally in the main Entity class like age which is updated uniformly for all subclasses). No other outside object should be able to change the state of an entity, only the entity object itself.
This whole design seems a bit fishy to me but I'm not sure how to change it. One alternative would be to make the "state" its own class that is extended by those classes that extend entity. However, with this method each state parameter would require its own function and the parameters could not be iterated through like they can be now. I was wondering if there was a defined design pattern for what I'm doing or if I should just stick with what I have. Thanks!

Using constants across the application

I have few constant values which I refer across my application. I am creating a class something like below snippet.
public class Styles {
public static final String tableStyle = "TableGrid";
public static final String fontFamily = "Calibri";
public static final String headerStyle = "Heading2";
public static final String footerStyle = "Heading3";
public static final String tableHeaderStyle = "Heading1";
public static final String tableDataFontFamily = "Cambria";
public static final int tableHeaderFontSize = 16;
public static final int tableDataFontSize = 12;
}
I am assigning the values in it and I am referring them like Styles.headerStyle . My doubt is, is this the good way or is there any better approach to achieve this? something like Enum ?
Thanks in advance.
It depends on the nature of your application, in most cases it is not a good practice to have a collection of constants in that way, but it is difficult to tell without knowing the context of your application. BTW, are sure that you'll never (or almost never) change things like "fontFamily"?
Of course an enum would be a little less verbose and more functional:
public enum Styles {
TABLE_STYLE("TableGrid"),
FONT_FAMILY("Calibri"),
HEADER_STYLE("Heading2"),
FOOTER_STYLE("Heading3"),
TABLE_HEADER_STYLE("Heading1"),
TABLE_DATA_FONT_FAMILY("Cambria"),
TABLE_HEADER_FONT_SIZE("16"),
TABLE_DATA_FONT_SIZE("12");
private String value;
private Styles(String value) {
this.value = value;
}
public String getStringValue() {
return value;
}
public int getIntValue() {
return Integer.valueOf(value);
}
}
1) You can use an external file as a Property File.
2) You can use an enum as #morgano answer
3) I would change your class declaration to
public final class Styles { // final class can't have childs
private Styles(){} // you cannot instanciate
public static final String tableStyle = "TableGrid";
.
.
.
}

Better way to map from String constants to int constants in Java

I have a load of images of musical symbols which I need to do some processing on and for each one I need to get the integer code corresponding to its file name. There are 23 possible file name strings and 23 integer code and there are many images with the same name under different directories.
The solution I have so far is given (abbreviated) below. I have just defined a load of int and String constants and then written a method which is just a huge chain of if statements to do the translation.
What would be a better way to achieve the same effect? The way I've done it seems really awful! I thought about using some kind of Map, but I wasn't sure of the best way to do so.
public class Symbol {
public static final int TREBLE_CLEF = 0;
public static final int BASS_CLEF = 1;
public static final int SEMIBREVE = 2;
// ...
public static final String S_TREBLE_CLEF = "treble-clef";
public static final String S_BASS_CLEF = "bass-clef";
public static final String S_SEMIBREVE = "semibreve";
// ...
public static int stringCodeToIntCode(String strCode) {
if (strCode == S_TREBLE_CLEF) {
return TREBLE_CLEF;
} else if (strCode == S_BASS_CLEF) {
return BASS_CLEF;
} else if (strCode == S_SEMIBREVE) {
return SEMIBREVE;
} //...
else {
return -1;
}
}
}
I think you are looking for Enum where you can have String constant and its value.
Example:
public enum YourEnumClass{
STRING_CONST (5),
STRING_CONST2 (7),
.....
//constructor
//getValue() method
}
read linked tutorial for more details.
enum StringToInt{
TREBLE_CLEF(0),
......
}
Enum is the way to go.
Another example:
public enum Color {
WHITE(21), BLACK(22), RED(23), YELLOW(24), BLUE(25);
private int code;
private Color(int c) {
code = c;
}
public int getCode() {
return code;
}
how about a hashmap
HashMap<String,Integer> hm=new HashMap<String,Integer();
hm.put("treble-clef",0);
//rest
and get it by using this
int value=hm.get("treble-clef");

Android Getting value from an Integer arraylist becomes a number

I am new to Android and from what I read here most of the question goes to Imageview setting image. Here is my problem same as ImageView errors
Ive created a arraylist of Integer because of some function needed Int List rather than String List. Basically like most of function I created it like this one
private ArrayList<Integer> myArrayList = new ArrayList<Integer>();
public void setPicture(Integer datanumber)
{
if (datanumber>=10)
{
myArrayList.add(R.drawable.picture);
}
else{
myArrayList.add(R.drawable.picture_gray);
}
///and so on
}
Everything works fine until I found out that I cannot get this string ex "R.drawable.picture" using this code
myArrayList.get(0).toString();
Instead it gives me random number that I cannot understand.
My question is how can I return it to default value(or the one that I add on my list)
Thank you for spending time reading my question
Use String.valueOf(myArrayList.get(0));
instead of myArrayList.get(0).toString();
It isn't giving you a Random number. It is giving you the value of R.drawable.picture. All resources in R.*.*are referenced through numbers. This is evident if you take a look inside R.java, which shows something like:
public final class R {
public static final class attr {
}
public static final class drawable {
public static final int help=0x7f020000;
public static final int ic_action_search=0x7f020001;
public static final int ic_launcher=0x7f020002;
public static final int splash1=0x7f020003;
}
public static final class id {
public static final int userName=0x7f070002;
}
public static final class layout {
public static final int splash=0x7f030003;
}
public static final class menu {
public static final int action=0x7f060000;
public static final int menu=0x7f060001;
}
public static final class string {
public static final int app_name=0x7f040000;
public static final int create_user=0x7f040004;
public static final int help=0x7f040001;
public static final int image=0x7f040002;
public static final int primarymodtext=0x7f040003;
}
}
What you are getting is the int value R.drawable.picture. This is because when you're adding a value to the array list, you're passing in the int value stored in R.drawable.picture.
You can still use this integer value you get like you would use R.drawable.picture. Just pass it in normally.

Categories