So I have a field called optionType and I want it to be able to take on 4 different integer values corresponding to certain options. For example optionType = 0 means the user wants to handle something a certain way, optionType = 1 means another way, etc.
But numbers by themselves are meaningless so I wanted to define constants instead in the class.
public class MyClass {
public static final int OPTION_TYPE_DO_THIS = 0;
public static final int OPTION_TYPE_DO_THAT = 1;
public static final int OPTION_TYPE_DO_SOMETHING_ELSE = 2;
public static final int OPTION_TYPE_DO_COOL_THING = 3;
private int optionType;
....
Is it considered normal to define all the constants out like that or is it better to use an enum like
public enum OPTION_TYPE {DO_THIS, DO_THAT, DO_SOMETHING_ELSE, DO_COOL_THING};
Or am I supposed to be using Enum instead somehow?
The key point is more on "how will that information be used at runtime". You see, if you starting thinking about writing code such as
switch(someEnum) {
case DO_THIS: ...
case DO_THAT:
... then you are already going into the wrong direction!
The point is: very often think that enums (or their even-more-low-level numeric constant cousins) are a good way to express such designs.
But that actually leads to quite some problems. Very often, the better, "more OO" way of thing is to use some abstract base class with specific subclasses; in other words: polymorphism!
Edit: just to make that more clear ... a "single" switch over an enum isn't really a problem. But far too often, people end up with many many places in code where they switch over their enums. And all of those places might need updates when you create additional enum constants. A coworker of mine calls that the "enum trap".
Take a look at this question and answer,
Even though it is written in the C# context, the conclusion states that:
Enums are great for lightweight state information.
Static class members would be able to support this multiple state without any extra functionality.
In java enums are more than just "enumerated names" as they are in other language (e.g. in C/C++).
My preferred use is to provide stateless behavior:
class Calculator {
enum Operation {
ADD{
double calculate(double a, double b){ return a + b;}
}
SUB{
double calculate(double a, double b){ return a - b;}
}
MUL{
double calculate(double a, double b){ return a * b;}
}
DIV{
double calculate(double a, double b){ return a / b;}
}
abstract double calculate(double a, double b);
}
Map<String,Operation> operations = new HashMap<>();
Calculator(){
operations.put("+",ADD);
operations.put("-",SUB);
operations.put("*",MUL);
operations.put("/",DIV);
}
public double calculate(double a, String operation, double b){
return operations.get(operation).calculate(a,b);
}
}
Related
My CustomNumber class extends the Number class (implements all the method, but not listed here). The class has a division method, which should work as the following: I can give to it any type of Number argument, and always get a the calculation without precision loss. That is why I'm thinking about double values. But in this case, I can't call this method with anything else, but Double Objects. How can I make this method, any maybe the whole class 100% generic?
public class CustomNumber<T> extends java.lang.Number {
java.lang.Number value;
public CustomNumber(java.lang.Number value) {
this.value = value;
}
public static CustomNumber<Double> division(Number a, Number b) {
return new CustomNumber<>(a.doubleValue() / b.doubleValue());
}
}
In this respect, Java is extremely annoying.
They dogmatically disallowed operator overloading (although Scala has it), so you are compelled to code / into a method called divide or similar, and so on.
For more specifics see how the arbitrary precision libraries such as BigInteger are implemented, and base your solution from that.
One a plus point in Java, you might get away with using BigDecimal and doing away with your idea entirely. Although the code you end up with when performing complex mathematical operations with it is practically unreadable. (For this reason I resort to using C++ with a JNI).
If this was what you were trying, it doesn’t work:
CustomNumber<Integer> quotient = division(5, 3);
We get “Type mismatch: cannot convert from CustomNumber<Double> to CustomNumber<Integer>”. For an obvious reason. Even though the numbers you tried to divide were autoboxed into Integer.
The straightforward solution is to drop the generics completely:
public class CustomNumber extends java.lang.Number {
// ...
public static CustomNumber division(Number a, Number b) {
return new CustomNumber(a.doubleValue() / b.doubleValue());
}
}
Now we have no problem doing:
CustomNumber quotient = division(5, 3);
System.out.println(quotient);
With an appropriate toString method in your class this should print:
1.6666666666666667
java.lang.Number offers very few methods. Division, for instance, doesn't really do the same thing for each type. 1.0d/2.0d is 0.5d but 1/2 is 0. So you're going have to decide which you're doing. Also note the double does not exactly represent long or, say, BigInteger.
To map various forms of numbers to your common interpretation, you'll need an adapter layer. There may be ore than one way to map a numeric type.
public interface CustomNumber<THIS extends CustomNumber<THIS>> {
THIS divide(THIS other);
}
public final class LongNumber extends CustomNumber<LongNumber> {
// (Note, you don't actually need to overload this,
// but it does prevent the likes of LongNumber.of(aDouble).)
public static LongNumber of(Long value) {
return new LongNumber(value);
}
public static LongNumber of(AtomicLong value) {
return new LongNumber(value);
}
private final Number value;
private LongNumber(Number value) {
this.value = value;
}
#Override public LongNumber divide(LongNumber other) {
return this.longValue() / other.longValue();
}
}
You might want to have an adapter for the same types that deal with, say, bankers' rounding. I don't want to even think about how to implement that. Or full on saturated arithmetic. So here's is a sign preserving alternative implementation (still does division by zero):
#Override public SignPreservingLongNumber divide(
SignPreservingLongNumber other
) {
long dividend = this.longValue();
long divisor = other.longValue();
return (
dividend == Long.MIN_VALUE &&
divisor == -1
) ? Long.MAX_VALUE : dividend/divisor;
}
I'm currently taking a Java course and have a question about polymorphism.
Given
public class A {
private int a1;
public A(){}
public A(int a1) { this.a1 = a1;}
}
class B extends A {
private int b1;
public B() {}
public B(int b1, int a1) {
super(a1);
this.b1 = b1;
}
}
class C extends B {
private int c1;
public C(){}
public C(int c1, int b1, int a1) {
super(b1, a1);
this.c1 = c1;
}
}
What would be the best way to assign to fields a1, b1, and c1, all in one swoop? My first guess would be to make an instance of C and call its three-arg constructor.
But what happens when each class contains 10s or 100s of data fields? Wouldn't this approach mean calling constructors with huge numbers of arguments, like
C(arg1, arg2, ..., arg100), setting k of C's fields, then making a call to
B(arg1, arg2, ..., arg100-k), and so on,
all the way up to the top? Is there a better way to proceed?
Having so many parameters is a definite code smell; in all probability you want to split the object up into smaller self-contained objects and/or or collections.
On the other hand, there is the Builder pattern, where you use a helper class to set all the parameters and it constructs the object for you, possibly sanity-checking that all required fields are set and there are no conflicts.
Not in this particular case because the fields in the parent classes are declared private.
If they were protected then you could set all 3 of them from the class C constructor. However this breaks encapsulation because if the constructor for B did something else after the value was assigned you'd have to duplicate that logic in C in order to not violate it's contract, and as you can imagine that gets very messy when you have more constructors or parent classes in the type tree.
Having multiple calls chained in the manner you proposed is the safest way at the cost of having to call all those constructors up the chain. I'd recommend profiling your code to see if this is actually a problem and not just a premature optimization.
What you're suggesting would work if you set the class fields to public. Class C will have a1 and c1, but won't be able to access them due to them being private.
Problem details. I need to create a framework to perform various checks, like:
- is Date A between dates B and C?
- is Integer A greater than Integer B and smaller than Integer C?
etc.
So far, i am thinking of two possible implementations, detailed bellow.
Impl1 - using a single class to perform the checks, based on the check type.
import java.sql.Time;
import java.util.Date;
public class SearchManager {
public final static int SEARCH_TYPE_DATE = 0;
public final static int SEARCH_TYPE_INT = 1;
public final static int SEARCH_TYPE_STRING = 2;
public final static int SEARCH_TYPE_TIME = 3;
private final int searchType;
public SearchManager(int searchType) {
this.searchType = searchType;
}
public final boolean doCompare(Object minValue, Object maxValue, Object toBeCompared) {
switch (this.searchType) {
case SEARCH_TYPE_DATE: {
return compareDates((Date) minValue, (Date) maxValue, (Date) toBeCompared);
}
case SEARCH_TYPE_INT: {
return compareIntegers((Integer) minValue, (Integer) maxValue, (Integer) toBeCompared);
}
case SEARCH_TYPE_STRING: {
return compareStrings(String.valueOf(minValue), String.valueOf(maxValue), String.valueOf(toBeCompared));
}
case SEARCH_TYPE_TIME: {
return compareTimes((Time) minValue, (Time) maxValue, (Time) toBeCompared);
}
default:
return false;
}
}
private boolean compareDates(Date min, Date max, Date toBeCompared) {
boolean result = false;
// actual comparison
return result;
}
private boolean compareIntegers(Integer min, Integer max, Integer toBeCompared) {
boolean result = false;
// actual comparison
return result;
}
private boolean compareStrings(String min, String max, String toBeCompared) {
boolean result = false;
// actual comparison
return result;
}
private boolean compareTimes(Time min, Time max, Time toBeComparedDate) {
boolean result = false;
// actual comparison
return result;
}
}
Impl2 - Using an abstract class or interface, and having an implementation of the comparison method for each search type.
public abstract class AbstractSearch {
public final static int SEARCH_TYPE_DATE = 0;
public final static int SEARCH_TYPE_INT = 1;
public final static int SEARCH_TYPE_STRING = 2;
public final static int SEARCH_TYPE_TIME = 3;
public AbstractSearch() {
super(); //just for fun
}
protected abstract boolean doCompare(Object minValue, Object maxValue, Object toBeComparedValue);
}
Now, in this example, for X different search types, as you can imagine, X implementations of the AbstractSearch will be created.
Just imagine yourself that the class AbstractSearch from the 2nd implementation will need to perform additional tasks, other than the method doCompare(..) and that is why an interface is not my 1st candidate for this solution, and to write something like
public abstract class AbstractSearch implements Searcheable
would not help me a lot, since AbstractSearch or SearchManager will handle ALL the comparisons, and, if a new comparison type should be needed, an additional type/subclass implementation will be declared for corresponding super classes from Impl1 or Impl2.
My question is about which implementation is faster? And this is very important, since the comparison process will be called in loops containing thousands of elements.
Thank you for reading/answering my question.
EDIT1: Also, please have in mind the fact that minValue and maxValue will be extracted from the classes that extends the AbstractSearch, for the second example, or classes extending SearchManager, as for the 1st example. These implementation will actually be graphical components allowing the user to enter a minimum and a maximum value, and then, these value will be compared in a loop with some bean property, of objects displayed in a table.
EDIT2: I am doing some benchmarks, with dummy implementations (i just want to compare the method call time vs switch execution time). The results are..surprising:
Using AbstractSearch (500k loops): -0.047 seconds
Using SearchManager (500k loops): -0.422 seconds
Having these results, it is safe to assume that using inheritance is much faster than using a switch (or even worse an if-else test) ?
If you want to make this code as fast as possible, also try using overloaded methods like this:
public final static boolean doCompare(Date min, Date max, Date toCompare) {
// ...
}
public final static boolean doCompare(int min, int max, int toCompare) {
// ...
}
// ...and so on
At compile time, the compiler will generate a direct call to the appropriate method, based on the types which you pass. (If you are passing Object references which might point to an instance of any of the 4 types, this won't work.)
If the values which you are comparing are ints, passing them to a method which takes Object arguments will require boxing and unboxing, which adds overhead.
If performance is really important, I recommend you use static methods, since they are a bit faster in many Java implementations.
Also, rather than using compareTo, you can probably squeeze out a bit more performance by using your own inline code for the comparisons.
EDIT: You said in the edited question that min and max will actually be passed in by a subclass of SearchManager. In that case I would make SearchManager abstract, and put different implementations of doCompare in each subclass of SearchManager. What I said about static methods won't work in this case.
I would think that the best idea would be to combine both ideas (and make it more type safe) and take advantage of the fact that all the types that you provide in your example (Date, Time, String, and Integer) are Comparable
public final <A> boolean doCompare (Comparable<A> min, Comparable<A> max, A target)
{
return (min.compareTo(target) < 0) && (max.compareTo(target) > 0)
}
This is definitely a lot faster than the first implementation since it does not have to do any type checks (all checks will be done compile time) and is type safer and no slower than the second (while also being more flexible about type).
Is this just something that you can do with a comparison? (It looks like it.) Is this method essentially the same for all three implementations?
If so, just write
static <T extends Comparable<T>> boolean doCompare(T min, T max, T toCompare) {
// impl here
}
Fun question! Why don't you benchmark your two implementations?
I'm writing an expression evaluator in Java. I would like the ability to add more operators (I currently have only (, ), +, -, *, /, and ^). Currently, my code looks like this:
case '+':
return a+b;
case '-':
return a-b;
case '*':
return a*b;
...
This works for my code because I have only a few operators. However, if I were to add more operators, the code would become cluttered. I am looking for a way to map an operator (represented by a String) to a method. For example, "ln" would be mapped to Math.log(), "^" would be mapped to Math.pow(), etc.
How would I go about doing this? If it's not feasible, what are some alternatives?
Not possible unless you want to use reflection. A solution without reflection could look like this:
public interface Operation {
int apply(int... operands);
}
public abstract class BinaryOperation implements Operation {
#Override
public int apply(int... operands) {
return apply(operands[0], operands[1]);
}
abstract int apply(int a, int b);
}
Map<String, Operation> operations = new HashMap<String, Operation>() {{
put("+", new Operation() {
#Override
public int apply(int... operands) {
return operands[0] + operands[1];
}
});
put("-", new BinaryOperation() {
#Override
public int apply(int a, int b) {
return a - b;
}
});
}};
You could use template methods.
public enum Functions {
ADD() {
#Override public int execute(int a, int b) {
return a+b;
}
},
SUB() {
#Override public int execute(int a, int b) {
return a-b;
}
};
//Template method
public abstract int execute(int a, int b);
}
Then map between string and enum with Map<String, Functions> functionMap
So if you want to add you can do functionMap.put("+", Functions.ADD);
Then call functionMap.get("+").execute(a,b);
I suppose you could also use varargs if different functions take different numbers of arguments.
public abstract int execute (Integer... inputs);
This example is modified from Making the Most of Java 5.0: Enum Tricks and what #duffymo said.
Building on the Operation suggestion above, a Map<String, Operation> would manage it with a lookup.
I think your setup is the optimal setup as I cannot think of a way to do this easily in java, although in a language like c/c++ you could easily map strings to function pointers but I don't think there's an equivalent of this in Java AFAIK. The beauty of switch statements though is that they actually avoid the clutter because visually you can easily see what the case of the switch statement is and just look for the appropriate case that you want (although for strings you made need a giant if cascade since == operator is not overloaded in java for string comparison).
Edit: See Ryan Stewarts comment, they use OOP ways of doing exactly what you want. Although that seems more cluttered than your switch statement in some cases.
I am trying to create a generic class in Java that will perform operations on numbers. In the following example, addition, as follows:
public class Example <T extends Number> {
public T add(T a, T b){
return a + b;
}
}
Forgive my naivety as I am relatively new to Java Generics. This code fails to compile with the error:
The operator + is undefined for the argument type(s) T, T
I thought that with the addition of "extends Number" the code would compile. Is it possible to do this Java or will I have to create overridden methods for each Number type?
Number does not have a + operator associated with it, nor can it since there is no operator overloading.
It would be nice though.
Basically, you are asking java to autobox a descedant of Number which happens to include Integer, Float and Double, that could be autoboxed and have a plus operator applied, however, there could be any number of other unknown descendants of Number that cannot be autoboxed, and this cannot be known until runtime. (Damn erasure)
Your problem is not really related to generics, rather to operators, primitives vs objects, and autoboxing.
Think about this:
public static void main(String[] args) {
Number a = new Integer(2);
Number b = new Integer(3);
Number c = a + b;
}
The above does not compile
public static void main(String[] args) {
Integer a = new Integer(2);
Integer b = new Integer(3);
Number c = a + b;
}
The above does compile, but only because of autoboxing - which is kind of a hacky syntax glue introduced in Java 5, and only works (in compile time) with some concrete types : int-Integer for example.
Behind the scenes, the Java compiler is rewriting the last statement ("I must unbox a and b to apply the sum operator with primitive datatypes, and box the result to assign it to object c") thus:
Number c = Integer.valueOf( a.intValue() + b.intValue() );
Java can't unbox a Number because it does not know at compile time the concrete type and hence it cannot guess its primitive counterpart.
You can do something like this
class Example <T extends Number> {
public Number add(T a, T b){
return new Double(a.doubleValue() + b.doubleValue());
}
}
Yes, Nathan is correct. If you want something like this, you have to write it yourself
public class Example <T extends Number> {
private final Calculator<T> calc;
public Example(Calculator<T> calc) {
this.calc = calc;
}
public T add(T a, T b){
return calc.add(a,b);
}
}
public interface Calculator<T extends Number> {
public T add(T a, T b);
}
public class IntCalc implements Calculator<Integer> {
public final static IntCalc INSTANCE = new IntCalc();
private IntCalc(){}
public Integer add(Integer a, Integer b) { return a + b; }
}
...
Example<Integer> ex = new Example<Integer>(IntCalc.INSTANCE);
System.out.println(ex.add(12,13));
Too bad Java has no type classes (Haskell) or implicit objects (Scala), this task would be a perfect use case...
There are similar questions to this one, and the answer is you can't do it like that.
You could check if a and b are an instance of Long/Double/Integer/etc. and delegate the add to methods like:
public Integer add(Integer a, Integer b) {
return a+b; // this actually uses auto boxing and unboxing to int
}
And you would need to create one for every type that extends Number, so that's not really feasible. In other words, don't use generics for numeric operations. Number as a superclass is pretty limited.
Consider Example<Number>, how would + work on that? There is no add or similar in Number or even the likes of Integer.
Worse consider final class FunkyNumber extends Number { ... weird stuff, no add op ... }.
Even the java runtime library has this problem, most of the methods dealing with primitives have to duplicate the same functionality.
The fastest option would be to write your code for one type and then copy it and replace the type to generate the methods for the other types. A short script should be enough to do this.