Easy way to Increment private variables? - java

I was wondering if there was an easier way to increment another class's private variables. Here is how I generally would go about it:
If I only need to do this rarely in my code:
pc.setActionsCurrent(pc.getActionsCurrent()-1);
If I need to do lots of incrementing, I would just make a special setter:
//In the PC class
public void spendAction(){
this.actionsCurrent--;
}
//In the incrementing Class
pc.spendAction();
Is there a better way to go about this? If the variable were public
pc.actionsCurrent--;
would be enough, and I can't help but feel I'm over-complicating things.

No. The method abstraction is generally the way to go about it, you might also pass in the increment value (and you can leverage that in your implementation). Consider something like
private long increment = 1;
private long myVariable = 0;
public void setMyVariable(long myVariable) {
this.myVariable = myVariable;
}
public void setIncrement(long increment) {
this.increment = increment;
}
public long getMyVariable() {
return this.myVariable;
}
public void addToMyVariable(long val) {
this.myVariable += val;
}
public void incrementMyVariable() {
addToMyVariable(increment);
}
The above would allow the increment value to vary (and this is generally called encapsulation).

Just define an increment method. For generality you could supply the increment as a parameter, and it could be negative:
public void increment(int augend)
{
this.actionsCurrent += augend;
}

Related

Can adding conditional diagnostics in Java be zero cost when they are off?

This is really a question about Java, not c++.
The idea is you'd like to be able to add in-line diagnostics that you could turn on and off by setting a flag. And you'd like the cost to be low and near or at zero when the flag is turned off.
Years ago I implemented a class I called "Debugger" in C++ that did this. The design uses enums for the flag names so you can have code that's readable and efficient and type-safe. The usage looks like this.
enum DebugBits {
testCondition1,
testCondition2,
testCondition3
nTestConditions
}`
Debugger testDebug("testDebug", nTestConditions,
"condition1",
"condition2",
"condition3");
Critical::doStuff()
{
...
if (testDebug.on(testCondition2))
doSomethingSpecial();
...
}
This was easily implemented with bits indexed with the enum values and inline methods. It works well in a large real-time system and has very near zero cost when the debugging is turned off. Its a valuable tool.
Anyway, back to the question. Today I was looking at doing the same thing in Java, for personal reasons, but given that you can't subclass enums, and yet it would be good to use them, its not so easy to keep the declaration clear and the usage in the code brief.
So here's an implementation that works, and is somewhat efficient. The questions are,
Can the implementation be more efficient?
At the same time can the usage in the code be kept clear?
I suspect there are better Java coders out there that may have better ideas about how to do this. Add a package at the top and this should compile and run. There is another class at the bottom to demonstrate the usage. Note that there's lots more that should be in this, but this is the core part the is interesting. Well... to me.
import java.util.BitSet;
import java.util.EnumSet;
import java.util.Vector;
public class Debugger {
private final EnumSet mEnumSet;
private final BitSet mBits;
private final Vector<String> mNames;
public Debugger(EnumSet es) {
mEnumSet = es;
mBits = new BitSet(es.size());
mNames = new Vector<>();
for (Object i : mEnumSet)
mNames.add(i.toString());
}
public void set(int bit) {
mBits.set(bit);
}
public void set(String bitName) {
int bit = mNames.indexOf(bitName);
if (bit >= 0)
mBits.set(bit);
}
public boolean on(int bit) {
return mBits.get(bit);
}
public boolean on(Object arg) {
if (arg.getClass() == Enum.class) {
int bit = ((Enum)arg).ordinal();
return mBits.get(bit);
}
return false;
}
public boolean on(String bitName) {
int bit = mNames.indexOf(bitName);
return bit >= 0 && mBits.get(bit);
}
}
class SampleUsage {
static class Debug extends Debugger {
enum Bits {
zero, one, two, three;
public static final EnumSet<Bits> bits = EnumSet.allOf(Bits.class);
}
public Debug() {
super(Bits.bits);
}
}
public static final Debug debug = new Debug();
public SampleUsage() {}
void doStuff() {
if (debug.on(Debug.Bits.three))
showDebugInfo();
if (debug.on("three"))
showDebugInfo();
}
private void showDebugInfo() {}
}
I think you’ve missed the point of EnumSet<>. The EnumSet<> is your type-safe set of highly efficient debug flags.
enum Debug {
FLAG0, FLAG1, FLAG2;
}
EnumSet<Debug> debug = EnumSet.noneOf(Debug.class);
debug.add(Debug.FLAG0);
if (debug.contains(Debug.FLAG0)) {
showDebugInfo0(); // Will be executed.
}
if (debug.contains(Debug.FLAG1)) {
showDebugInfo1(); // Will not be executed because FLAG1 was not added to the EnumSet.
}
There is no need to translate the enum values into ordinals, and add that ordinal to a BitSet. EnumSet<> is already implemented using something like a BitSet (except the EnumSet<> is of a fixed size, based on the number of identifiers in the Enum, so cannot be extended to an arbitrary length).
If you want to test if a flag is set by name, you can use the Enum.valueOf() to convert the name into the correct Enum, and test if the EnumSet<> contains that.
if (debug.contains(Enum.valueOf(Debug.class, "FLAG2")) {
showDebugInfo2(); // Also not executed, because FLAG2 was not added to the EnumSet.
}
Again, no need for a Vector<String> that contains all of the Enum names, which you must find the .indexOf(). The Enum comes with that method built-in. Vector<> was not an efficient choice to use anyway, since Vector<> operations are automatically synchronized, so are slightly slower than an equivalent ArrayList<>.
Note: Minor difference: .indexOf() returns -1 when not found; Enum.valueOf() will raise an IllegalArgumentException if you give it an unknown identifier name.
Assuming you want .on(), not .contains(), and you want simpler test flag by name usage in your code, we’ll need to wrap the EnumSet<> in another class. This Debug class might look like:
class Debug<T extends Enum<T>> {
private final Class<T> enum_class;
private final EnumSet<T> flags;
public Debug(Class<T> enum_class) {
this.enum_class = enum_class;
flags = EnumSet.noneOf(enum_class);
}
public void set(T flag) {
flags.add(flag);
}
public boolean on(T flag) {
returns flags.contains(flag);
}
public void set(String flag_name) {
flags.add(Enum.valueOf(enum_class, flag_name));
}
public boolean on(String flag_name) {
return flags.contains(Enum.valueOf(enum_class, flag_name));
}
}
So with minor mods to your implementation, it shows brevity and clarity and uses fewer resources. The Enum.valueOf() I missed entirely. The string conversion is a goal I did not describe, but is useful when trying to set bits through a subsystem that is unaware of the class containing the enums, but the user knows the names. I got parts of it right, but you got me out of the weeds. Thanks much.
Oh... and I changed the name.
import java.util.EnumSet;
class Diagnostic<T extends Enum<T>> {
private final Class<T> enum_class;
private final EnumSet<T> flags;
public Diagnostic(Class<T> enum_class) {
this.enum_class = enum_class;
this.flags = EnumSet.noneOf(enum_class);
}
public void set(T flag) {
flags.add(flag);
}
public boolean on(T flag) {
return flags.contains(flag);
}
public void set(String flag_name) {
try {
flags.add(Enum.valueOf(enumClass, flag_name));
}
catch (Exception e) {}
}
public boolean on(String flag_name) {
try {
return flags.contains(Enum.valueOf(enumClass, flag_name));
}
catch (Exception e) {
return false;
}
}
}
class SampleUsage {
enum DiagBits {
zero, one, two, three;
}
public static final Diagnostic<DiagBits> diag = new Diagnostic<>(DiagBits.class);
public SampleUsage() {}
void doStuff() {
if (diag.on(DiagBits.three))
showDebugInfo();
if (diag.on("three"))
showDebugInfo();
}
private void showDebugInfo() {}
}

Setter methods, multiple with no parameters or single with value?

I'm working on a java based game with a friend and I've noticed he's taking an approach that concerns me, in terms of maintainability.
For a class representing a playable Character, instead of just creating 1 method which sets an object's property, he's creating separate methods which set the property to a specific value.
Which of these 2 options would be the best to follow going forward?
Option 1
public void runFast() {
this.character.speed = 5.0f
}
public void walk() {
this.character.speed = 2.0f
}
public void stop() {
this.character.speed = 0.0f;
}
Option 2
public void setSpeed(float speedTemp) {
this.character.speed = speedTemp;
}
Why not use an enum to set the speed - then you can still have
void setSpeed(Speed speed) {
this.character.speed = speed.getAmount();
}
with:
enum Speed {
FAST(5.0f), WALK(2.0f), STOP(0.0f);
private final float amount;
private Speed(flaot a) { this.amount = a; }
public float getAmount() {
return amount;
}
}
That way, you can quickly update the values, but still have a predefined amount. Its flexible and easy to maintain. You might want to save the enum instead of the float.
My Solution would be to use Enums instead,
it is cleaner and has more context and easily extensible if you have more to do with your speed maxHeartRate in the future.
public class Character {
private Speed speed;
public Speed getSpeed() {
return speed;
}
public void setSpeed(Speed speed) {
this.speed = speed;
}
};
public enum Speed {
STOP(0),
RUN(5.5),
WALK(2.5);
double value;
Speed(double value) {
this.value = value;
}
public double getValue() {
return value;
}
};
IMHO the best option would be to declare constants/enums, and use the option 2.
Example (constants) :
public static final float STOP = 0.0f;
public static final float WALK = 2.0f;
public static final float FAST = 5.0f;
setSpeed(STOP|WALK|FAST);
Example (enums) :
public enum Speed
{
FAST(5.5f),
STOP(0),
WALK(2.5f);
float value;
Speed(float pValue)
{
this.value = pValue;
}
public float getValue()
{
return this.value;
}
}
setSpeed(Speed.FAST);
It depends. For example
Are speeds limited to a few predefined values? In that case using an enum would be a good solution.
Is walking / running / stopping going have side effects other than just setting the speed? As a contrived example, starting to run might cause the character to drop an item it's holding, or stopping might cause the character to skid a little. In this case having separate methods might make sense.
Or maybe there are only a few predefined states, but depending on the environment running speed might be different.
What it comes down to is: Which way of conceptually modeling the properties of your character works best for your game logic / physics? Work this out and then base the interface of your classes on that. Don't get too hung up on the exact API early on, this sort of stuff is pretty easy to refactor.
getter and setters are useful when you want that your code is readble and for avoiding that public class fields can be used in the wrong way from another classes.
This example show how is important.
CLASS A:
public class ClassA{
// in the body class
private String fieldClass1;
//classic setter
public void setfieldClass1(String f1)
{
fieldClass1 = f1;
}
}
CLASS B:
public class ClassB{
// in the bodyclass
public String fieldClass2;
//classic setter
public void setfieldClass2(String f2)
{
setfieldClass2 = f2;
}
CLASS C:
public class ClassC{
//in the body of the class this method use class a and class b
public void calc()
{
ClassA aObject = new ClassA();
ClassB bObject = new ClassB();
ClassA.fieldClass1 = 5 + 5; // illegal expression for the compiler and costrain the developer to use setters
ClassB.fieldClass2 = 8 + 8; // legal expression
}
}
This mean that you must define a "modifiers logic" (protected, private, public) before make setters and getters. Define before the modifiers and after define the setters and getters.

Which method should change the field, when calling a hierarcy of private methods?

When a class' public method needs to call a private method that results in a field being changed, which method should change the field? Is there any common convention for this? Is one approach preferable over the other?
Consider these two code snippets:
public class boolHolder {
private boolean theBool = false;
public void doYourThing() {
// Do a lot of other stuff
setBool();
}
private void setBool() {
// Do a lot of other stuff, justifying a private method for this
this.theBool = true;
}
}
VS
public class boolHolder {
private boolean theBool = false;
public void doYourThing() {
// Do a lot of other stuff
theBool = setBool();
}
private boolean setBool() {
// Do a lot of other stuff, justifying a private method for this
return true;
}
}
These two snipped of course being a very simple case, but I'm sure I'm not the only one ending up with public methods calling a huge tree of private methods. Should the field be set at the end of the branch, or should a value be passed back?
I think it makes more sense that only a single place would set the value of the field, and it should be the last method being called. It makes the code easier to understand. Your first snippet looks much more readable to me.
Here's another snippet which, in my opinion, supports this convention :
Lets say we have an int member with two setters - one accepts an int and the other accepts a String representation of that int (which is used, for example, if we de-serialize an instance from an XML String).
int value;
public void setIntField (String value)
throws SomeException
{
if (value == null)
throw new SomeException();
try {
int val = Integer.parseInt (value);
setIntField (val);
}
catch (NumberFormatException ex) {
throw new SomeException();
}
}
public void setIntField (int value)
throws SomeException ()
{
if (value < MIN_ALLOWED || value > MAX_ALLOWED)
throw new SomeException ();
this.value = value;
}
Apart from renaming theBool and setBool to something more understandable (which I'm going to assume you did eitherway in the real application), I'd go with the first one. Methods with the word set are expected to be setters and not many people will expect a return value.
It doesn't change much, but you can try to use a better naming for your methods: i don't like that you name your second method setBool().
If you write "Do a lot of other stuff, justifying a private method for this" you can try to associate a verb to that stuff you do.
Say you update an account status and upon completion want to signal with the boolean the status, well use something like what you did but call it in a meaningful way, e.g. updateAccount() and either return a true if the update went fine or set it inside:
public class boolHolder {
private boolean accountUpdated = false;
public void doYourThing() {
// Do a lot of preliminary stuff
updateAccount();
}
private void updateAccount() {
// try to update account
// if update went fine
this.accountUpdated = true;
}
}
or
public class boolHolder {
private boolean accountUpdated = false;
public void doYourThing() {
// Do a lot of preliminary stuff
this.accountUpdated = updateAccount();
}
private boolean updateAccount() {
// try to update account
// if error happens, rollback change and set
return false;
// else (update went fine)
return true;
}
}
are both perfectly fine, but make your method tell what they do, since updating the bool is not the main action since you "Do a lot of other stuff, justifying a private method for this".
The value setting inside is more compact if you use a default to false as you did, but the other is more explicit in what it does. So I tend to prefer that: returning a result for you operation.

The pattern of final array instead of non-final variable for boolean flag in inner class

I often have a situation in my Java code when I need to set a boolean flag inside an inner class. It is not possible to use primitive boolean type for that, because inner class could only work with final variables from outside, so I use pattern like this:
// class from gnu.trove is not of big importance, just to have an example
private final TIntIntHashMap team = new TIntIntHashMap();
// ....... code ............
final boolean[] flag = new boolean[]{false};
team.forEachValue(new TIntProcedure() {
#Override
public boolean execute(int score) {
if(score >= VICTORY_SCORE) {
flag[0] = true;
}
return true; // to continue iteration over hash map values
}
});
// ....... code ..............
The pattern of final array instead of non-final variable works well, except it is not look beautiful enough to me. Does someone know better pattern in Java ?
Use AtomicBoolean.
Here's a popular StackOverflow question about this issue: Why are only final variables accessible in anonymous class?
How about having a generic holder class which holds object of any type. In your case, it can hold a Boolean type. Something like:
class Holder<T> {
private T genericObj;
public Holder(T genericObj) {
this.genericObj = genericObj;
}
public T getGenericObj() {
return genericObj;
}
public void setGenericObj(T genericObj) {
this.genericObj = genericObj;
}
}
And use it as:
public class Test {
public static void main(String[] args) throws Exception {
final Holder<Boolean> boolHolder = new Holder<Boolean>(Boolean.TRUE);
new Runnable() {
#Override
public void run() {
boolHolder.setGenericObj(Boolean.FALSE);
}
};
}
}
Of course, this has the usual problems that occur with mutable objects that are shared across threads but you get the idea. Plus for applications where memory requirements are tight, this might get crossed off when doing optimizations in case you have a lot of invocations of such methods. Also, using AtomicReference to swap/set references should take care of use from multiple threads though using it across threads would still be a bit questionable.
There are situations where this is the best pattern.
The only improvement I can suggest is return false when you have found a match.
One problem is that the TIntIntHashMap does not have a fold/reduce method so you have to simulate it using foreach. You could try to write your own class extending TIntIntHashMap adding a reduce method.
Other solution is to just extend TIntProcedure to have a value. Something like:
abstract class TIntProcedureWithValue<T> implements TIntProcedure {
private T accumulator;
public T getValue() {return accumulator;}
}
Then you can pass an instance of this class to foreach, set the internal accumulator instead of the external flag array, and get the resulting value afterwards.
I am not familiar with gnu.trove, but generally it's better for the "algortihm" function to be more specific, leaving less code here.
private final IntIntHashMap team = new IntIntHashMap();
boolean found = team.value().containsMatch(new IntPredicate() {
public boolean is(int score) {
return score >= VICTORY_SCORE;
}
});
(More concise syntax should be available in Java SE 8.)
maybe something like that? (implements or extends... I don't know what is TIntProcedure, unfortunately) :
class FlagResult implements TIntProcedure {
boolean flag = false;
#Override
public boolean execute(int score) {
flag = score >= VICTORY_SCORE;
return !flag;
}
};
FlagResult result = new FlagResult();
team.forEachValue(result);
boolean flag = result.flag;

java return from private method to public

I have a public method and a private method. they are both supposed to return int values. The private method is the one that does all the work and the public is the one that is called from the main program. How can I return the results returned from the private method by the public method?
its like this
public int longer()
{
longer(a.length);
}
private int longer(int n)
{
int index
//find largest index recursively
//make recursive call longer(n-1)
return index;
}
I want to pass it up to the public method and then return it from there. Would I just return it from the public method by saying return longer.index; or something along those lines?
i guess i should clarify. n isnt index. idnex is being calculated based on whats being passed into the method. the public and the private is because its going to be a recursive method. i'll edit what i posted above to make itm ore accurate of what im trying to do. passing in an array and recursively working on it.
public int longer()
{
return longerInternal(a.length);
}
private int longerInternal(int n)
{
int index
//find largest index recursively
//make recursive call longer(n-1)
return index;
}
From your public method, you can call down into the private method. I renamed the private method so that there was not a naming collision for your methods. A simple implementation should look something like this:
public class MyClass {
private int[] a;
public MyClass(int[] _a) {
a = _a;
}
public int longer()
{
return longerInternal(a.length);
}
private int longerInternal(int n)
{
int index;
//do recursive call
return index;
}
}
And it can be called like this:
MyClass myClass = new MyClass(new int[]{1,2,3,4,5,10});
int result = myClass.longer();
First, you probably need better function names.
You'd call your public function getLonger(int n) and then pass it to your private longer(int n) function. When this function is done, it will return to getLonger(int n) and then back to the caller.
You mentioned in an answer to a comment that the "caller does not need to have access to all internal workings of a class."
To me that suggests that you want to use an interface.
Create an interface that describes the class that will contain that secret algorithm:
package com.stevej;
public interface Longer {
public int longer();
}
Implement that interface using your secret algorithm:
package com.stevej;
public class LongerImpl implements Longer {
private int longer(int n){
return 0; // whatever
}
#Override
public int longer() {
return longer(5); // whatever
}
}
Now the caller only creates objects using the interface definition, guaranteeing that there are no exposed methods that he can access by accident. That implementation is hooked to that interface-defined object:
package com.stevej;
public class LongerProcessor {
Longer longerImpl = new LongerImpl();
public LongerProcessor() {
super();
}
public int longer() {
return longerImpl.longer();
}
}
Now you can rewrite the implementation of Longer as often as you like. As long as the interface definition never changes, the caller (LongerProcessor) will never have a problem. Heck, you could have two or more different implementations (LongerImplRecursive, LongerImplBruteForce, and so on), each implementing Longer, and all in use in different places in the same program:
package com.stevej;
public class LongerProcessor {
Longer longerImpl;
public LongerProcessor(boolean useRecursive) {
super();
if (useRecursive){
longerImpl = new LongerImplRecursive();
}else{
longerImpl = new LongerImplBruteForce();
}
}
public int longer() {
return longerImpl.longer();
}
}
How cool is that? Since you tagged this question as "homework", I'm wondering if the problem is supposed to engage you to think about separating the contract (interface) from the implementation (implementing class).

Categories

Resources