Can we pass objects to enum abstract methods and do a computation in enums? Here is a scenario, I have four constants and each one have their own value assigned to it. Based on the constants I will do the computation in my method.. Instead I would like to do the computation in enum and would like to get the response. To do the computation in enum I have to pass two/three reference objects to the enum methods...
ex: Consider school as enum, constants are TEACHER(LOWLEVELACCESS), STUDENT(NOACCESS), OFFICEADMIN(OFFICEACCESS).
In enum, I have abstract method process which is receiving USER POJO , strings as arguments and update some fields in the object and return the same USER POJO (with updated) to the caller. By this I can sync up the constants and their logic in enum itself.
So my question,
Is it alright to have this implementation in enum? (I have seen most of the examples treat enums to store constant values not using them for any computation)
This computation can be done by using methods in classes, what is the benefit if I do the computation in enum methods?
Is it possible to create getter/setter method in enum?
Thanks In Advance!!
IMHO:
Is it alright to have this implementation in enum?
Yes - I do it all the time.
enum Ops implements Op {
Nop{
#Override
public int filter(int old, int now) {
// Unchanged.
return now;
}
},
Diff{
#Override
public int filter(int old, int now) {
return a(now)
| (Colour.MidGrey + (r(now) - r(old))) << 16
| (Colour.MidGrey + (g(now) - g(old))) << 8
| (Colour.MidGrey + (b(now) - b(old)));
}
};
}
This computation can be done by using methods in classes, what is the benefit if I do the computation in enum methods?
The code for the functionality is in one place. This is always a good thing.
Is it possible to create getter/setter method in enum?
Yes - but don't. Remember that there is one instance of each enum for the lifetime of your code. Adding/removing functionality on a global object is very likely to hurt you later.
Is it alright to have this implementation in enum?
It is a design choice.
Enum brings some advdantanges to provide service operations.
Enum values are singletons out of the box, these are self explanatory, there are memory efficient, etc... but have also some limitations, you cannot directly derive from an enum, so you should introduce an interface behind the enum if you want to be able to test your code and avoid coupling the client classes that do the computation with the enum ... if later you change your mind about the enum usage.
This computation can be done by using methods in classes, what is the
benefit if I do the computation in enum methods?
You reason in terms of objects. You don't need to create a service and indirection in the code since the enum that is a domain object does the computation.
The enum values and the processings associated make part of the same concern. So, gathering them is not necessary a bad smell.
Nevertheless, be aware if you start to write a lot of processing that do very different things in the enum methods, you should probably get them out the enum.
This is a bad smell as the enum should not become a god object.
Is it possible to create getter/setter method in enum?
Providing data, yes but setting data of the enum : no, you must not.
Otherwise you build a stateful service and you risk to finish with synchronization concerns.
Enums are defined to be final. Computations are allowed as far as the result is equal for the same input.
You also can modify the input instance, but you should not define any setter in your enum due the enum is not immutable in that case.
See also Example 8.9.2-4 here
Related
Is there any difference between this declaration
Thread.State state = Thread.State.NEW;
and that
Enum<Thread.State> state = Thread.State.NEW;
in Java? Instead of the second option is a bit longer?
It's the same case as comparing between:
Child o = someChild;
and
Parent o = someChild;
Enum is the parent class of all enum types. Therefore, with the second line, the code cannot contain references to specific members of Thread.State, specifically the members described in this section of the language spec.
Is there any difference ....
In practice, in this particular case, probably no.
In theory, Thread.State is a subtype of Enum<Thread.State>. If Thread.State declared (non-private) fields or methods, then you could use them via the first declaration of state, but not the second one.
In general, the first form is preferable ... for that reason.
Also, I don't think you would be able to see an enum's static methods values() and valueOf via the variable declared in the second declaration; e.g.
state.valueOf("BLOCKED")
However, calling a static method via an instance reference is bad style.
Two practical differences (as opposed to language-lawyerly reasons) that come to mind:
If you declare state as an Enum<Thread.State>, then you won't be able to pass it to any methods that expect a Thread.State.
If you declare state as an Enum<Thread.State>, you'll leave the reader — whoever needs to touch this code in the future — wondering why you've written it that way.
Neither of these is a terribly deep reason; we could easily imagine a parallel universe where most people used Enum<Thread.State> instead of Thread.State, just as (in our universe) most people use List<...> instead of ArrayList<...> (when possible). But since most people don't do that in our universe, you're better off just following the common pattern, to minimize the risk of confusion and accidental incompatibility.
Incidentally, in case this is going to be your next question . . . the main situation where you would use Enum is when you want to write something generic that works for many different enum types. An example of this in the JDK is EnumMap<K extends Enum<K>,V>, which is a special map implementation that gets space and performance benefits out of knowing that its keys are enum values.
(And note, incidentally, that you can't write EnumMap<Enum<Thread.State>, String>, because Enum<Thread.State> doesn't extend Enum<Enum<Thread.State>>. Instead, you must write EnumMap<Thread.State, String>. So this is an example of difference #1 that I mentioned above: if you declare state as an Enum<Thread.State>, then you can't use it as a key in an enum-map.)
Assuming we have an object inside an object, inside another object, what is the best way to retrieve the value of a private variable outside the two objects?
The simplest way seems to be to do something like this:
object1.object2.object3.getvalue();
Is this acceptable? Or would it be better to call a method which calls a method, which calls a method?
The second option seems unnecessarily laborious, considering you would basically be having the same method created in 3 different classes.
use getter to get any object
ex: Object obj = object1.getObject2().getObject3();
It depends on your definition of "acceptable". It may be acceptable in your case. It is hard to tell without proper context.
However, there are something you may consider, level-by-level:
1. Use of getters
Although such kind of getters are still far from satisfactory, it is still better than using direct property access
i.e. Instead of accessing object1.object2 by direct field access, provide Object2 getObject2() in Object1, so that the code looks like:
object1.getObject2().getObject3().getValue()
2. Null handling
Usually when we chained such kind of property navigation, we will have problem that in some level, null is returned, which makes object1.getObject2().getObject3().getValue() throwing NPE.
If you are using Java 8, consider returning Optional<>. e.g. in Object1, getter of object2 should look like Optional<Object2> getObject2()
With such change, your code can be made null-safe by something like:
Value value = object1.getObject2()
.flatMap(Object2::getObject3)
.map(Object3::getValue)
.orElse(Value.emptyValue())
3. Law of Demeter
In order to make a more loosely-coupled design, you may want to provide access to that value in API of Object1, instead of exposing multiple levels of indirection. Hence:
Value value = object1.getFooValue();
(Keep using Optional<> if it fit your need)
for which internally it retrieve the value from Object3. (Of course, Object2 may also want to do something similar)
4. Getter is evil
Always remember you should try to avoid providing internal representation of your object. Your objects should provide meaningful behavior instead of simply act as a value object for you to get or set data. It is hard to give an example here but ask yourself, why do you need to get the value for? Is that action more appropriate to be provided by your object itself?
The best way is to not think of your objects as data stores. A class should be defined to have some work to do, some cluster of related responsibilities. In order to perform that work to fulfill those responsibilities some internal data may be kept, and some nested objects contained. Serving out data should not be the goal of your objects, generally speaking.
Encapsulation
The whole idea of encapsulation in object-oriented programming is to not expose that internal data and nested objects. Instead publish the various available chores by declaring methods on your higher/outer object. Encapsulation frees you to change those internals without breaking the outside calling code – avoiding fragility is the goal.
For example, an Invoice object can contain a collection of LineItem objects. In turn each LineItem object contains other objects for product, quantity, price, extended cost, taxability, tax rate, tax amount, and line cost. If you want to know the total amount of sales tax added across the items, instead of asking the Invoice for the LineItem, and then asking the LineItem for TaxAmount object, define this chore as a method on Invoice, getTotalTaxAmount. Let that method figure out (and keep to itself!) how to go through the contained objects to collect the relevant information.
If you absolutely must expose that nested data, again define a method at the highest level that returns a copy of the desired data or a collection of the desired objects (probably copies of those objects). Again, the goal is to avoid exposing the objects within objects within objects.
Then, within that highest method, as the correct Answer by Raaga stated, define a getter that calls a getter.
Getter Methods versus Direct Member Access
In a very simple structure of data you could access the objects directly. But generally better to use getter methods. Again the reason is encapsulation. Having a getter method allows you the flexibility of redefining the implementation details of the stored data.
For example, presently you could store the "Sex" variable as a String with values of "F" or "M". But later you may decide to take advantage of Java's nifty enum feature. So you replace those single-character "F" & "M" strings with enum instances Sex.FEMALE and Sex.MALE. Having a getter provides a level of insulation, so the Strings can be replaced internally with enums. The getter method continues to return a String (and internally translating the enum to an "F" or "M" String to be returned). This way you can work on restructuring your class without breaking those dependent outside objects.
object1.object2.object3.getvalue();
This chaining seems incorrect...Object chaining under such scenario is always object1.someMethod().someOtherMethod(). Or something like suggested above in an answer using getter object1.getObject2().getObject3().
I hope it helps.
What you described may be the simplest way (if object2 and object3 are accessible) but it is definitely not the way to go. As Raaga pointed out getters are a lot better to retrieve members of a class and these members should then be private or protected to prevent errors.
If you can do
object1.object2.object3.getvalue();
you can also do something like
object1.object2 = null;
which is most likely not what you want to allow. This is one of the basic concepts of object oriented programming. Classes should handle their implementation details / secrets and not directly offer them to the outside! This is what getters/setters are for.
This way you have more control over the access and what can be done and what can't. If you should only be able to retrieve object2 from object1 but not be able to change it, you can only offer a getter and no setter.
If you should also be able to change it, it is also better to use setter for more control, because you can do checking in your setter to prevent my example where I put a null pointer as your object2
And just in case you worry about efficiency that calling a method might not be as efficient as directly accessing a member, you can rely on Java to internally optimize your method call that it is not any slower than the direct access.
I have never worked with enum State before and recently came across it, I've found that to define a FSM where YOU, the programmer, knows the states the code is something like this:
enum States {state0, state1, state2}; //an example of a state machine with 3 states as defined by the programmer.
but I want to be able to define a FSM where the user decides how many and what states there are, is there a way to do this?
You cannot use enums here, which have a fixed size, but I guess you can do something like this :
public class StateMachine {
// it is up to you to define what a State and a Transition are
private Set<State> possibleStates;
private Set<Transition> transitions;
private State currentState;
// methods for adding and removing states
// ...
// methods for adding and removing transitions
// ...
}
Unfortunately, there is no great way to make run-time enums. There are, however a few other options:
Use an int to represent your state. This is simple and efficient, but can be confusing and difficult to understand later, as an int doesn't tell you much about what the state means. This can be partially mitigated by storing a map from Integer(state) to String (description of that state)
Create an immutable class to represent a state, or wrap an existing one like String. Make instances of the class only available through a static factory method which restricts the states given out to the subset you need, and internally keep a set of all instances, providing them when the same state is asked for twice from the factory method.This will allow equality comparison by reference, and creates similar semantics to enums.
There is the separate problem (which arises on both options) of deciding on action based on state, because the state is only defined at runtime, you cannot use a switch statement. A linear search, equivalent to chained if statements, scales poorly with the number of states. This problem can be solved by creating a hash table (or binary tree, if you wish) from states to whatever code you want to execute: (Java 8)
HashMap<State, Function<State, State> stateTransitions;
This system provides enum-like semantics at runtime, with reasonably good (constant time "switch") efficiency.
Having come across the concept of immutable objects recently, I would like to know the best practices for controlling access to the state. Even though the object oriented part of my brain makes me want to cower in fear at the sight of public members, I see no technical issues with something like this:
public class Foo {
public final int x;
public final int y;
public Foo( int x, int y) {
this.x = x;
this.y = y;
}
}
I would feel more comfortable declaring the fields as private and providing getter methods for each but this seems overly complex when the state is explicitly read only.
What is the best practice for providing access to the state of an immutable object?
It depends entirely on how you're going to use the object. Public fields aren't inherently evil, it's just bad to default everything to being public. For example the java.awt.Point class makes its x and y fields public, and they aren't even final. Your example seems like a fine use of public fields, but then again you might not want to expose all of the internal fields of another immutable object. There is no catch-all rule.
I have thought the same in the past but usually end up making variables private and using getters and setters so that later on I'll still have the option of making changes to the implementation while keeping the same interface.
This did remind me of something I read recently in "Clean Code" by Robert C. Martin. In chapter 6 he gives a slightly different perspective. For example, on page 95 he states
"Objects hide their data behind abstractions and expose functions that operate on that data. Data structure expose their data and have no meaningful functions."
And on page 100:
The quasi-encapsulation of beans seems to make some OO purists feel better but usually provides no other benefit.
Based on the code sample, the Foo class would seem to be a data structure. So based on what I understood from the discussion in Clean Code (which is more than just the two quotes I gave), the purpose of the class is to expose data, not functionality, and having getters and setters probably does not do much good.
Again, in my experience, I have usually gone ahead and used the "bean" approach of private data with getters and setters. But then again, no one ever asked me to write a book about how to write better code so maybe Martin has something to say.
If your object is of local-enough usage that you don't care about the issues of breaking API changes for it in the future, there is no need to tack getters on top of the instance variables. But this is a general subject, not specific to immutable objects.
The advantage of using getters comes from one extra layer of indirection, which may come in handy if you are designing an object which will be widely used, and whose utility will extend into unforseeable future.
Regardless of immutability, you're still exposing the implementation of this class. At some stage you'll want to change the implementation (or perhaps produce various derivations e.g. using the Point example, you may want a similar Point class using polar coordinates), and your client code is exposed to this.
The above pattern may well be useful, but I'd generally restrict it to very localised instances (e.g. passing tuples of information around - I tend to find that objects of seemingly unrelated info, however, either are bad encapsulations, or that the info is related, and my tuple transforms into a fully-fledged object)
The big thing to keep in mind is that function calls provide a universal interface. Any object can interact with other objects using function calls. All you have to do is define the right signatures, and away you go. The only catch is that you have to interact solely through these function calls, which often works well but can be clunky in some cases.
The main reason to expose state variables directly would be to be able to use primitive operators directly on these fields. When done well, this can enhance readability and convenience: for example, adding Complex numbers with +, or accessing a keyed collection with []. The benefits of this can be surprising, provided that your use of the syntax follows traditional conventions.
The catch is that operators are not a universal interface. Only a very specific set of built-in types can use them, these can only be used in the ways that the language expects, and you cannot define any new ones. And so, once you've defined your public interface using primitives, you've locked yourself into using that primitive, and only that primitive (and other things that can be easily cast to it). To use anything else, you have to dance around that primitive every time you interact with it, and that kills you from a DRY perspective: things can get very fragile very quickly.
Some languages make operators into a universal interface, but Java doesn't. This is not an indictment of Java: its designers chose deliberately not to include operator overloading, and they had good reasons to do so. Even when you're working with objects that seem to fit well with the traditional meanings of operators, making them work in a way that actually makes sense can be surprisingly nuanced, and if you don't absolutely nail it, you're going to pay for that later. It is often much easier to make a function-based interface readable and usable than to go through that process, and you often even wind up with a better result than if you'd used operators.
There were tradeoffs involved in that decision, however. There are times when an operator-based interface really does work better than a function-based one, but without operator overloading, that option just isn't available. Trying to shoehorn operators in anyway will lock you into some design decisions that you probably don't really want to be set in stone. The Java designers thought that this tradeoff was worthwhile, and they might even have been correct about that. But decisions like this don't come without some fallout, and this kind of situation is where the fallout hits.
In short, the problem isn't exposing your implementation, per se. The problem is locking yourself into that implementation.
Actually, it breaks encapsulation to expose any property of an object in any way -- every property is an implementation detail. Just because everybody does this doesn't make it right. Using accessors and mutators (getters and setters) doesn't make it any better. Rather, the CQRS patterns should be used to maintain encapsulation.
I know only one prop to have getters for final properties. It is the case when you'd like to have access to the properties over an interface.
public interface Point {
int getX();
int getY();
}
public class Foo implements Point {...}
public class Foo2 implements Point {...}
Otherwise the public final fields are OK.
The class that you have developed, should be fine in its current incarnation. The issues usually come in play when somebody tries to change this class or inherit from it.
For example, after seeing above code, somebody thinks of adding another member variable instance of class Bar.
public class Foo {
public final int x;
public final int y;
public final Bar z;
public Foo( int x, int y, Bar z) {
this.x = x;
this.y = y;
}
}
public class Bar {
public int age; //Oops this is not final, may be a mistake but still
public Bar(int age) {
this.age = age;
}
}
In above code, the instance of Bar cannot be changed but externally, anybody can update the value of Bar.age.
The best practice is to mark all fields as private, have getters for the fields. If you are returning an object or collection, make sure to return unmodifiable version.
Immunatability is essential for concurrent programming.
An object with public final fields that get loaded from public constructor parameters effectively portrays itself as being a simple data holder. While such data holders aren't particularly "OOP-ish", they are useful for allowing a single field, variable, parameter, or return value to encapsulate multiple values. If the purpose of a type is to serve as a simple means of gluing a few values together, such a data holder is often the best representation in a framework without real value types.
Consider the question of what you would like to have happen if some method Foo wants to give a caller a Point3d which encapsulates "X=5, Y=23, Z=57", and it happens to have a reference to a Point3d where X=5, Y=23, and Z=57. If the thing Foo has is known to be a simple immutable data holder, then Foo should simply give the caller a reference to it. If, however, it might be something else (e.g. it might contain additional information beyond X, Y, and Z), then Foo should create a new simple data holder containing "X=5, Y=23, Z=57" and give the caller a reference to that.
Having Point3d be sealed and expose its contents as public final fields will imply that methods like Foo may assume it's a simple immutable data holder and may safely share references to instances of it. If code exists that make such assumptions, it may be difficult or impossible to change Point3d to be anything other than a simple immutable data holder without breaking such code. On the other hand, code which assumes Point3d is a simple immutable data holder can be much simpler and more efficient than code which has to deal with the possibility of it being something else.
You see this style a lot in Scala, but there is a crucial difference between these languages: Scala follows the Uniform Access Principle, but Java doesn't. That means your design is fine as long as your class doesn't change, but it can break in several ways when you need to adapt your functionality:
you need to extract an interface or super class (e.g. your class represents complex numbers, and you want to have a sibling class with polar coordinate representation, too)
you need to inherit from your class, and information becomes redundant (e.g. x can be calculated from additional data of the sub-class)
you need to test for constraints (e.g. x must be non-negative for some reason)
Also note that you can't use this style for mutable members (like the infamous java.util.Date). Only with getters you have a chance to make a defensive copy, or to change representation (e.g. storing the Date information as long)
I use a lot constructions very similar to the one you put in the question, sometimes there are things that can be better modeled with a (sometimes inmutable) data-strcuture than with a class.
All depends, if you are modeling an object, an object its defined by its behaviors, in this case never expose internal properties. Other times you are modeling a data-structure, and java has no special construct for data-structures, its fine to use a class and make public all the properties, and if you want immutability final and public off course.
For example, robert martin has one chapter about this in the great book Clean Code, a must read in my opinion.
In cases where the only purpose is to couple two values to each other under a meaningful name, you may even consider to skip defining any constructors and keep the elements changeable:
public class Sculpture {
public int weight = 0;
public int price = 0;
}
This has the advantage, to minimize the risk to confuse the parameter order when instantiating the class. The restricted changeability, if needed, can be achieved by taking the whole container under private control.
Just want to reflect reflection:
Foo foo = new Foo(0, 1); // x=0, y=1
Field fieldX = Foo.class.getField("x");
fieldX.setAccessible(true);
fieldX.set(foo, 5);
System.out.println(foo.x); // 5!
So, is Foo still immutable? :)
As by design an enum constant in java is a singleton, and for sake of concurrent usage I normally create stateless enum instances and use method parameters to inject the data as needed.
Example:
Currently I am creating a REST service which has Operations (implemented as an enum using a variant of the strategy pattern).
public enum Operation {
DO_THIS() {
public Result doSomething(Object theData) {
}
} ,
// Other Operations go here
;
public abstract Result doSomething(Object theData);
}
Now I want to collect data about how often an operation has been called and how often it succeeded and the like.
I could save the state externally when using the enum instance but it rather seems that the state should be saved in the Operation as the operation should contain it's own state.
Now my general question is:
Is a stateful enum instance (besides from concurrency issues) a bad design?
I think it violates the Principle of Least Astonishment.
People expect the common usage of enums as they were originally designed - as constants or tokens, and not as general purpose classes with state.
Yes. And by 'yes' I mean 'Always'.
If you want to collate stats on the number of operations called, implement some observability.
Any form of mutable static is a sin. (Well, you might get away with non-leaky caches, some lazy initialisation and forms of logging.)
A stateful enumeration is an oxymoron, even an anti-pattern!
http://en.wikipedia.org/wiki/Enumeration
An enumeration is a collection of items that is a complete, ordered listing of all of the items in that collection. The term is commonly used in mathematics and theoretical computer science to refer to a listing of all of the elements of a set. In statistics the term categorical variable is used rather than enumeration. The precise requirements for an enumeration (for example, whether the set must be finite, or whether the list is allowed to contain repetitions) depend on the branch of mathematics and the context in which one is working.
Enumerations have a finite number of values, which are supposed to be constant, which they are.
However, the fact that they are "first class" Java Objects totally goes against the grain of the intention or spirit of an enumeration.
If any kind of state is required, the enum (as mentioned earlier) should hold state in an Aspect or the offending enum, should at the very practical least, hold a reference to a delegate class holding state. Understanding "separation of concerns" will help.
This seems like a bad use for enums - why not just go with a base abstract class with a new subclass for each operation?
I entirely agree with mparaz that it violates the Principle of Least Astonishment. People expect enums to be constants.
You can almost certainly work round the logging thing, by something like:
DO_THIS() {
public Result doSomething(Object theData) {
MyUtilClass.doSomething(Object theData);
}
}
and put your logging in the other class.
HOWEVER if you can't work round this, the Principle of Least Astonishment is a guideline; you can violate it PROVIDED you give users of the class enough warnings about what is going on. Make sure the Enum declaration contains a BIG notice saying that it is mutable, and describing exactly what the mutability is. The Enum should still work; it's doing reference comparison against to single instance to test enum values.
There is a case which would probably justify it.
An enum can implement an interface, usually with the particular use case in mind which lets you create
on runtime/openly "some other types of the enum class" in a dynamic fashion, to name it someway.
That means that enum "singleton" instances can be forced to implement some mutable-intended method signatures (as setters), which of course, you still can hide with an empty code or a NotSupportedException.
Luckily, final methods in an interface don't allow any possibility to change state. That would have been the sole "understandable" case I could come up with.