I am just beginning to understand the concept of Enumeration in Java, but I'm still kind of skeptical of my understanding.
For something such as: Direction, I can understand its use, where I use numbers to represent a direction, but never really need to do arithmetic with it.
However, given something like sizes, where the sizes are constants, but I will need to do arithmetic, would final declarations be more appropriate? Or attempting to do an enum with
public int getSize()
{
return size;
}
Here is my code for my current declarations:
private static class Size
{
private static final int BOX = 5; //5 pixels
private static final int GRID = 30; //amount of boxes
private static final int GAME = BOX * GRID; //total size in pixels
}
Note that this is a private nested class,
I also use these values when doing drawing, and a parameter is an integer, I simply do Size.BOX, however, is Enumeration still more appropriate for this? and how should I go about it?
The entire point of enums is to make your code more readable and maintainable. You should use them anytime you need to represent an enumerated set of elements.
However, in this case, final/constant is more appropriate since you are representing a value (number of boxes, and number of pixels) not an enumerated set. If, say, you wanted to store types of boxes (metal box, cardboard box, ect) then you would use enums.
You are correct in believing that enums are inappropriate when dealing with arithmetic values. Enums are useful for representing a set (in the programming and the mathematical sense) of uniquely defined items that relate to each other.
Using an enum to replace a size value in this way is nonsensical in context. If your item is 30 units large, then you need to represent it as such, using an integer or the like.
An example of where to use an enum in a similar context would be if you had 5 strictly defined types of items of different sizes - in this case, you could make each of the 5 an instance of your enum - but they would still have a size variable internally, with a different value for each.
Takes a bit of interface chicanery, but this works. Not necessarily the best approach in your situation, but this was a neat little exercise.
/**
<P>{#code java EnumXmpl}</P>
**/
public class EnumXmpl {
public static final void main(String[] igno_red) {
System.out.println("BOX: " + eShape.BOX.getSize());
System.out.println("GRID: " + eShape.GRID.getSize());
System.out.println("GAME: " + eShape.GAME.getSize());
}
}
interface ShapeConstants {
int iBOX_PXLS = 5;
int iGRID_BOXES = 30;
}
enum eShape implements ShapeConstants {
BOX(iBOX_PXLS),
GRID(iGRID_BOXES),
GAME(iBOX_PXLS * iGRID_BOXES);
private final int iSz;
eShape(int i_size) {
iSz = i_size;
}
public final int getSize() {
return iSz;
}
}
Output:
[C:\java_code\]java EnumXmpl
BOX: 5
GRID: 30
GAME: 150
Related
How do I implement void add(Number number) so it adds number to the object instance
public interface Numbers {
static int toIntValue();
static void fromIntValue(int value);
default void add(Number number) {
// what do i write here
}
}
You mostly cannot do this; interfaces do not have any state, and the notion of 'add a number' strongly implies that you wish to update the state.
This is one way to go:
public interface Number /* Isn't Numbers a really weird name? */ {
int toIntValue();
default int add(int otherValue) {
return toIntValue() + otherValue;
}
}
Here no state is changed; instead a new int is returned.
Another problem here is that the whole notion of abstracting away a numeric type is that there is no default implementation of add.
That's just basic math. Complex numbers are a kind of number; it is clearly impossible to write code that can add 2 complex numbers together without knowing anything about complex numbers beforehand.
What you CAN do is create add out of other primitives, except, 'add' is generally the convenient primitive. For example, here's a take on multiply that can work as a default method, though it is not at all efficient:
public interface Number {
Number plus(Number a); /* an immutable structure makes more sense, in which case 'plus' is a better word than 'add' */
default Number multiply(int amt) {
if (amt == 0) return Number.ZERO; // Define this someplace.
Number a = this;
for (int i = 1; i < amt; i++) a = a.plus(this);
return a;
}
}
Here you've defined multiply in terms of plus.
Note that java already has an abstract number concept (java.lang.Number) and it indeed can do almost nothing, because trying to abstract math like this is hard in any language, and particularly so in java.
Let's say you have a class of object with three
integer fields that you want to possibly change, all in the same way, with one method.
Let's keep it simple and say all that the method does is add 1 to the parameter passed to it.
That is to say, the desired behavior is that by the time the method has completed, the relevant field has increased by 1.
This is impossible to achieve in Java using the primitive type "int" for those fields.
I know about how Java is "always" pass by value, and not pass by reference,
- and - i've heard whisperings on the internet that this is one reason that the Integer class exists, along with other object "wrapper" classes
for ordinarily primitive types such as int and double.
Sending an object as an argument to a method should, in theory, provide a way to [effectively, if not technically] pass by reference, since the value that is passed, is supposedly the value of the reference to the object.
Very tricky. BUT - and this is where my annoyance comes in - I've tried achieving this very simple task by passing an Integer argument instead of an
int, and the desired behavior was still not accomplished. 1 was not added to the relevant field.
And yet, when I made my very own object, which consisted of just one field, an int value, and passed an instance of this object as an argument
to an appropriate method which would simply add 1 to the passed parameter, the desired behavior was in fact accomplished. 1 was added to the relevant field.
So the questions orbiting around this query are - Is it really going to be necessary to craft my own homemade class just to carry a simple integer value
every time I want to achieve this desired behavior? Can the existing tool provided by Java, Integer, really not perform this simple task?
Instead of having one nice, neat method to handle all three of the hypothetical integer fields i mentioned in the beginning, I felt compelled (in a separate, similar project that ultimately provoked this line of thinking) to make a separate method corresponding to each of the three fields, with essentially the same exact code in each one. This seems very inefficient.
It may not seem like a big deal, on the surface, to write three similar methods instead of one, but to clarify why this dismays me - imagine instead of an object with three integer fields as I stated, there are say, i don't know, four thousand. It would be so much better to write just one thing to perform the same kind of behavior, instead of copying and pasting (and changing whatever little bits necessary) four thousand times.
So I suppose the ultimate question is,
Why doesn't Integer function in a reasonable way? What's the point of wrapping a primitive in an Object at all, if it doesn't even help perform something this simple? Am I missing something simple about how to get Integer to function in the desired way? (Hopefully so) The answer seems close yet infuriatingly out of reach since "RInteger" produces the desired behavior, yet "Integer" doesn't.
The entire source code I used while trying to figure out how to construct this painstaking question is below.
package r9mp;
import javax.swing.SwingUtilities;
public class RefTest2 {
//[main m]
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
public void run(){
new RefTest2();
}
});
}
//[fields]
int i;
Integer I;
RInteger RI;
//[constr]
public RefTest2(){
intTest();
IntegerTest();
RIntegerTest();
display();
}
//[methods]
private void intTest(){
i = 100;
intMethod(i);
}
private void IntegerTest(){
I = 100; //boxing? auto?
IntegerMethod(I);
I = 100; //just in case.
IntegerMethod2(I);
}
private void RIntegerTest(){
RI = new RInteger(100);
RIntegerMethod(RI);
}
private void intMethod(int ipar){
ipar = ipar + 1;//no change. expected.
}
private void IntegerMethod(Integer IPar){
IPar = IPar + 1;//no change. frustrating.
pln("From inside IntegerMethod: IPar = " + IPar );
pln("From inside IntegerMethod: I = " + I );
}
private void IntegerMethod2(Integer IPar){
IPar = new Integer(IPar+1);//still no change. there are no set methods for Integer, or I'd try them.
}
private void RIntegerMethod(RInteger riPar){
riPar.value = riPar.value + 1;
}
private void display(){
pln(
"Display... \n" +
"i: " + i + "\n" +
"I: " + I + "\n" +
"RI: " + RI + "\n" +
"--------"
);
}
private void pln(){
pln("");
}
private void pln(String s){
System.out.println(s);
}
//[internal class]
private class RInteger{
int value;
public RInteger(int v){
value = v;
}
public String toString(){
return ""+value;
}
}
}
And, here is the output...
How about one method for primitives and their wrappers?
private int incInteger(int value)
{
return value + 1;
}
and call for it:
int intVal = 100;
intVal = incInteger(intVal);
Integer integerVal = 200;
integerVal = incInteger(integerVal);
First of all, you need to read up on immutability to find out why it is a very good thing to have. There even exist entire languages (functional, mostly) that capitalize on it.
Once you have read about that, then read Eric Lippert's series of articles on immutability. Start here: https://blogs.msdn.microsoft.com/ericlippert/2007/11/13/immutability-in-c-part-one-kinds-of-immutability/ Mind = blown.
But to give you a quick hint as to why primitive wrappers like Integer are immutable, let me just say that these classes are often used as keys in Hash Maps, and a key must be immutable, so that its hashCode will never change, otherwise the hash map will fail with very difficult to track down behaviour. Mutable keys in hashmaps are nasty bugs.
You can achieve what you want with a class of your own devise which plays the role of a reference, or by simply passing an array and modifying the element at array[0].
My personal preferences are as follows:
I would try to do as much as possible with return values.
When return values are inapplicable, (as the case is with invokeLater,) then inner/nested/anonymous classes that have access to the fields of the enclosing class are my next preference.
When that's not an option either, then special classes crafted precisely for the application at hand are my next option. (MyMutableNumberWrapper.)
And when I just want something quick and dirty, then general-purpose classes like Ref<T> (or even single-element arrays) would be my final option.
I had the following field in my code:
private static final int NUM_NANOSECONDS_IN_MILLISECOND = 1000000;
I was told that I should be using an enum for this for type safety. This is not something I am familiar with. But if this is the case, I don't know when it would ever be appropriate to use the final keyword on a field.
When should I use the final keyword instead of enums?
Constants are just that, constants with a name.
Enums are literal constants that have a value. I explain...
Consider:
public final static int NORTH = 0;
public final static int SOUTH = 1;
public final static int EAST = 2;
public final static int WEST = 3;
and
public enum Direction {
NORTH, SOUTH, EAST, WEST
}
From a readability standpoint it kinda looks the same:
if(direction == NORTH)
or with enums:
if(direction == Direction.NORTH)
Where things might go wrong is that with the final constant, you can also do
if(direction == 0)
Now it's more difficult to understand the code even though it does the same thing. With enums, you just can't do that so it's let problems.
Similarly, when expecting a direction as a method argument:
with final static:
public void myMethod(int direction)
and with enums:
public void myMethod(Direction direction)
It's clearer, and less opportunities for problems.
This is just a beginning. Enums can actually have methods that help you better manage the information they contain. Read up here for a clean explanation.
Example:
public enum Direction {
NORTH (0, 1),
SOUTH (0, -1),
EAST (1, 0),
WEST (-1, 0)
private int xDirection, yDirection;
Direction(int x, int y) {
this.xDirection = x;
this.yDirection = y;
}
public Vector2D getTranslation() {
return new Vector2D(this.xDirection, this.yDirection);
}
}
So then in your code:
public void moveThePlayer(Player p, Direction d) {
p.translate(d.getTranslation());
}
moveThePlayer(p, Direction.NORTH);
This becomes really hard to do with final static. Or at least, it gets very unreadable.
All this being said, with the particular case you are working with there, if there's only one numeric constant value, I'd keep the final static. No point using an enum if there's a single value.
Using an enum avoids using an int, not final. Using a dedicated enum provides type safety, so you can have clearer method signatures and avoid bugs. final is used to prevent changing a value once set, and is a generally good practice regardless of the variable's type.
In this case however I'm not sure what value an enum gives you. NUM_NANOSECONDS_IN_MILLISECOND doesn't seem like it should be a dedicated type, and as #BoristheSpider suggests, you shouldn't need this field at all. Perhaps your associate was suggesting using an enum for the unit (e.g. NANOSECOND, MILLISECOND, etc) rather than storing ratios like this. In that case, the existing TimeUnit enum is definitely your friend.
It honestly depends on what you need. enum as its name shows stands for enumeration.
Enumerations have multiple elements like so
public enum Colors {
CYAN, MAGENTA, YELLOW, BLACK
}
You could even give them numerical values or so! Because enums are cool.
public enum RGBColors {
RED(0xFF0000), GREEN(0x00FF00), BLUE(0x0000FF);
private int hexacolor;
private RGBColors(int hexacolor) {
this.hexacolor = hexacolor;
}
public int getColorValue() {
return hexacolor;
}
}
Your case is just a numerical constant. A single numerical constant.
public static final long SUCH_NUMERICAL_VALUE = 12367160L;
This is just a constant. This is not an enumeration. There is also no reason for it to be an enumeration, as you are just using it as a number.
The biggest advantage (in my opinion) of an enum is that you can iterate on every element of its type.
for(RGBColors rgbColor : RGBColors.values()) {
... //do things with rgbColor for each of them
}
You cannot do that with public static final int. I even wrote an enum wrapper around a bunch of public static final properties here because of this problem: https://stackoverflow.com/a/28295134/2413303
More importantly, you can easily read what value stands for what without having to go deep into the source:
RGBColors red = RGBColors.RED;
Now let's see this with int:
int red = RGBColors.RED;
I could just say
int red = 0; //red color
Who will tell what on earth that is later? Who knows!
Anyways, the short answer is, enums are great when you're specifying enumerations, aka multiple elements (or you're creating enum singletons), and these elements need to have extra methods or properties.
public enum MySingleton { //this is an enum singleton
INSTANCE;
public void doThings() {
System.out.println("hello!");
}
}
MySingleton.INSTANCE.doThings(); //hello!
Constants (public static final) are great when you use them as exactly that: constants.
I would say that the general use case for enums would be when you have a small finite set of values that form some set you are modeling and you are going to enumerate each one. They can also help ensure that a field that should contain one of these values does not contain some other value.
In this case, neither seems to apply. You could just as well have NUM_NANOSECONDS_IN_MICROSECOND, NUM_NANOSECONDS_IN_SECOND, NUM_NANOSECONDS_IN_PI_MILLISECONDS, and so on, and you aren't going to enumerate each one. Furthermore, it would seem that the variables you are going to be storing these values in probably shouldn't be restricted to the values of the defined constants.
When writing source code it is best to rely on the compiler as much as possible to help you find logic errors. One way is to use variable and constant types so that if you use the wrong constant for a method, the compiler will flag this as an error.
The advice is not really about using final versus enum since those are really two different programming concepts. It is instead using an enum to create an explicit and unique type versus using an int which is much less explicit and unique. If you use int as part of the method signature for a function that is supposed to take nanoseconds then any int value will be accepted by the compiler. If you instead use an enum then only those values that are specified in the enum are allowed. Using anything else will cause the compiler to issue an error.
The final keyword is a way of making sure that the variable can not be overriden or modified so that the variable acts like a constant. wikipedia article on final.
The values specified in an enum are constants so you can choose between using what you have, a constant, or using an enum, a constant, however using the enum will provide a safety check from the compiler so that only the specified values of the enum can be used in a method call or variable assignment for nanoseconds.
Here is an explanation of final with additional links from that stack overflow. Java method keyword final and its use also provides some additional information.
See What is the purpose of Enum for some explanation about enum.
I tried googling and searching for this question but somehow couldn't find anything relevant about it. I'm wondering if there is a bbest-practise guide on when to use attributes in a class and when not, but rather use parameters to the single methods.
Many cases are clear to me, e.g.
public class Dog
{
private name;
public setName(...) {....}
}
But sometimes it's not clear to me what's better to use.
E.g. the following, either use:
public class calculation
XYZ bla;
public calculation(XYZ something)
{
this.bla = something;
}
public void calc1()
{
// some calculations with this.bla
}
public void calc1()
{
// some more calculations with this.bla
}
public XYZ getBla()
{
return this.bla;
}
}
or maybe do:
public class calculation
public calculation() {}
public static XYZ calc1(XYZ bla) // maybe static, if not dependant on other attributes/instance-variables etc
{
// some calculations with bla
return bla;
}
public static XYZ calc1() // maybe static, if not dependant on other attributes/instance-variables etc
{
// some more calculations with bla
return bla;
}
}
I mean you can argue for both cases. I see advantages and maybe disadvantages for both different styles, but somehow I prefer the second one as far as long as there are not too many arguments/parameters needed. Sure, if I need many many more attributes etc., then the first one will be better, simpler etc. because I dont need to pass so many parameters to the method...
Just a question of personal style?
Or how to decide for one approach?
Thanks
EDIT: A better example: I'm curently doing much image processing and the question would be wether to store the image internally in the state of the object or not. I'm currently NOT doing it because I'm using static methods, and psasing the image itself I to each method:
public class ImageProcessing
{
/**
*
*/
public static Mat cannyEdges(Mat I, int low, int high)
{
// ...
return I;
}
public static Mat cannyEdges(Mat I)
{
return ImageProcessing.cannyEdges(I, ContourDetection.CANNY_LOWTHRES, ContourDetection.CANNY_HIGHTHRES);
}
/**
*
*/
public static Mat getHoughLines(Mat Edges, ...some_conf_vars...)
{
// ...
return I;
}
}
and then I'm calling it from the outside like this e.g.:
// here: read image to I...
Mat edges = ImageProcessing.cannyEdges(I, 20, 100);
Mat lines = ImageProcessing.getHoughLines(I);
// draw lines...
question is: Does I belong to the state of the object? Would it make sense to convert to non-static and then use for example:
// here: read image to I...
ImageProcessing IP = new ImageProcessing(I);
IP.cannyEdges(20, 100); // CHANGE OF cannyEdges: Also save `edges` internally as property!?
IP.calcHoughLines(); // also save the lines internally maybe?
Mat lines = IP.getLines();
// draw lines...
is this nicer?
The question arising is then again: Should I for example store the result of getHoughLines() (i.e. the lines) internally or should I directly return it to the caller!?
I can use some examples:
public class Multiplier {
private int number;
public Multiplier(int number) {
this.number = number;
}
public int multiply(int other) {
return number * other;
}
}
This class could be instantiated like:
Multiplier multiplyByTwo = new Multiplier(2);
I could use it to multiply many elements on a list by 2.
But I could need to multiply pairs of numbers. So the following class could be what I neeed:
public class Multiplier {
public static int multiply(int number, int other) {
return number * other;
}
}
I could make it static since no state is needed.
This example could be used like this on a list:
for (int x:listOfInts) {
print(Multiplier.multiply(x * 2));
}
But probably in this specific case the 1st example was nicer.
for (int x:listOfInts) {
print(multiplyByTwo(x));
}
or even nicer used with a Java 8 ''map''
If I need to get the elements of the multiplication and the result at many points in my code i could do.
class Multiplier {
private int x;
private int y;
public int multiply() {
return x * y;
}
// getters and setters for x and y
}
In this last case I may consider not adding setters and pass x, y in the constructor.
Every structure could be used in some specific cases.
It's not entirely a question of personal style. But nevertheless, I assume that this topic might be slightly controversial (opinion-based) and thus not perfectly suited for a Q/A-site.
However, the obvious question is: Does an object of the respective class really carry a state? That is, is there any benefit in having the state represented by an instance? If the sole purpose of the instance is to be an accumulator of variables that are modified with a sequence of set... calls and a final call to an execute() method, then there is usually no real justification for such an instance - except for avoiding to have a static method with "many" parameters.
I think that the advantages of static methods outweigh most of the potential clumsiness of calling a method with "many" parameters. One of the most important ones is probably that the approach with static methods doesn't increase the state space. Every field is another dimension in the state space, and documenting state space properly can be hard. Static methods enforce a more "functional" programming style: They don't have any side-effects, and thus, are thread-safe (which is becoming increasingly important).
(Note: All this refers to static methods that are not related to any static state - that should be avoided anyhow. And of course, this refers to methods that are not involved in or aiming at anything related to polymorphism).
And after all, one can easily call any static method from anywhere - even from within an instance method, and pass in some fields as parameters. The opposite is not so easy: When you want to call a method that depends on many instance fields, it can be a hassle when you first have to create an object and set the fields appropriately (still not knowing whether it is in a valid state to call the method). I also see the default methods of Java 8 as a nice application case where static utility methods come in handy: The default method may easily delegate to the utility method, because no state is involved.
There are a few reasons I'd go with the first option, i.e. an object with state over static functions, particularly for complex calculations but also for simpler ones.
Objects work better for the command pattern.
Objects work better for the strategy pattern.
Static methods can turn unit tests into a nightmare.
Static is an anti-pattern in OOP because it breaks polymorphism, with the side-effect that related techniques will break with it, e.g. open/closed, mocking, proxies, etc.
That's my 2c at least.
The weird part of your first example is that those calcX methods don't say anything about idempotency, so it's unclear what this.bla is when it's being manipulated. For complex computations with optional settings, an alternative is to construct an immutable object using a builder pattern, and then offer calcX methods that return the result based on fixed object state and parameters. But the applicability of that really depends on the use case, so YMMV.
Update: With your new code, a more OOP approach would be to decorate Mat. Favouring delegation over inheritance, you'd get something like
public class MyMat
{
private Mat i;
public MyMat(Mat i) {
this.i = i;
}
public Mat getBackingMat() {
return this.i;
}
public MyMat cannyEdges(int low, int high)
{
// ...
return new MyMat(I); // lets you chain operations
}
public MyMat cannyEdges()
{
return new MyMat(ImageProcessing.cannyEdges(I, ContourDetection.CANNY_LOWTHRES, ContourDetection.CANNY_HIGHTHRES));
}
public MyMat getHoughLines(...some_conf_vars...)
{
// ...
}
}
MyMat myMat = new MyMat(I);
lines = myMat.cannyEdges(20, 100).calcHoughLines();
This is just a guess, cause I have no idea what those things mean. :)
When not to use static:
If the result that will be returned is dependent on other variables (state) that make up your "calculation" class then static cannot be used.
However, if you are simply doing calculations on a variable, as the example implies, static is probably the way to go as it requires less code (For example to perform calc1 and then calc2 on a variable by the first method you would have to do:
calculation calc = new calculation(x)
calc.calc1();
calc.calc2();
XYZ y = calc.getBla();
while with the second example you could do
static import ...calculation.*;
...
XYZ y = calc2(calc1(x));
The first one is enum class
enum coffeeSize{
BIG(8), HUGE(10), OVERWHELMING(16);
private int ounces;
coffeeSize(int ounces ){
this.ounces = ounces;
}
public int getOunces(){
return ounces;
}
}
This is class CoffeeTest1 and main
public class CoffeeTest1 {
coffeeSize size;
public static void main (String args[]) {
CoffeeTest1 drink1 = new CoffeeTest1();
drink1.size = coffeeSize.BIG;
System.out.println(" " + drink1.size.getOunces());
}
}
The below is output
8
My question :
I don't understand the how drink1.size.getounces() manage to output 8. I haven't given constructor coffeeSize(8) object (ex: coffeeSize somex = new coffeeSize(BIG)). I want to know this simple subtle logic behind. Can someone help me understand please?
I dont understand the how "drink1.size.getounces() " manage to output 8.
[...]
I want to know this simple subtle logic behind.
To understand the logic behind this, you can think of your enum as a regular class (which is actually how it is compiled), and
BIG(8)
as an instance of this class similar to
new coffeesize(8);
It should now be clear why drink1.size.getOunces() prints 8: BIG is just an instance of the coffeesize enum, for which you set ounces to 8 when constructing it.
One suggestion: find, learn, and follow the Sun Java coding standards. It'll improve your code's readability.
It outputs 8 because that's the size, in ounces, for BIG coffee size, according to your enum. That's the value that you passed into the BIG constructor.
drink1 is the instance of the class, which has a package visible data member of type coffeeSize named size. Every coffeeSize instance has a method getOunces that returns the integer value that you passed into its constructor.
There's nothing subtle about it.
You will notice the getOunces method is defined on the enum. Enum values can themselves have properties and methods, in Java.
It is implied that CoffeeTest1 has a field that references the enum value.
So drink1 is an instance of that class..
the size property is set to the BIG instance of the enum..
Big has ounces 8.
When you specifies BIG(8) you are creating it passing 8 to its constructor (10 or 16). When you use it coffeeSize.BIG.getOunces() you are invoking its method getOunces. BIG, HUGE and OVERWHELMING are the possible values for a coffeeSize, each one with its own state.
enum Colour {
Black,White,Red,Green,Yellow,Grey
}
public class EnumExample {
public static void main(String[] args) {
Colour colour;
colour = Colour.Black;
System.out.println("Selected "+colour+" Colour");
colour = Colour.Yellow;
System.out.println("Selected "+colour+" Colour");
}
}