background preloader

Enums

Facebook Twitter

Java Secret: Using an enum to build a State machine. Using Enums as Proxies/Decorators in Java - forget about switch. Every Java developer knows that you have enums in Java since Java 5.0. Enums are cool. Especially the ability of getting the right instance of an enum-class by calling the static valueOf()-method with the respective name string makes enums a nice choice in configurations. In this example I'm using an enum to determine the style of notification for an event or user. public enum NotificationType { NO_NOTIFICATION, EMAIL;} While NotificationCommand is a simple interface with implementations like DoNothingCommand, EmailNotificationCommand and SmsNotificationCommand: public interface NotificationCommand { void execute(NotificationCmdReceiver rec);} Like I said, we want to determine the type of notification by the NotificationType enum.

Most people use enums in switch-statements like this: public void notify( NotificationType type, NotificationCmdReceiver rec) { NotificationCommand cmd; cmd.execute(rec);} So this would be a better version because it eliminates the switch statement. cmd.execute(rec); } 10 examples of Enum in Java. What is Enum in Java Enum in Java is a keyword, a feature which is used to represent fixed number of well known values in Java, For example Number of days in Week, Number of planets in Solar system etc. Enumeration (Enum) in Java was introduced in JDK 1.5 and it is one of my favorite features of J2SE 5 among Autoboxing and unboxing , Generics, varargs and static import.

One of the common use of Enum which emerged in recent years is Using Enum to write Singleton in Java, which is by far easiest way to implement Singleton and handles several issues related to thread-safety and Serialization automatically. By the way, Java Enum as type is more suitable to represent well known fixed set of things and state, for example representing state of Order as NEW, PARTIAL FILL, FILL or CLOSED. Enumeration(Enum) was not originally available in Java though it was available in other language like C and C++ but eventually Java realized and introduced Enum on JDK 5 (Tiger) by keyword Enum.

Case PENNY: Enum tricks: hierarchical data structure. We Recommend These Resources Java enums are typically used to hold array like data. This tip shows how to use enum for hierarchical structures. Motivation Once upon a time I wanted to create enum that contains various operating system, i.e. 01.public enum OsType { 02. WindowsNTWorkstation, 03. 04. 05. 06. 07. 08. 09. 10. 11. 12. 13. 14. 15. I did not like this structure because I'd like to see a group of WindowsNT that contains WinNTWorkstation and WindNT server. Solutions As always there are several solutions. Class per OS Solution The obvious solution here is to create separate classes per operating system and abstract classes that represent OS groups.

But now we cannot see all operating systems together, iterate over them etc., i.e. very useful features of Java enum are missing. 02. 03. 04. 05. 06. 07. 08. 09. 10. 11. 12. 13. 14. 15. 17. private Class clazz; 18. 19. this.clazz = clazz; Hierarchical Enum 02. 03. 04. 05. 06. 07. 08. 09. 10. 11. 12. 13. 14. 15. 16. 18. return true; 21. 22. 23. 24. Making the Most of Java 5.0: Enum Example. "Hello World! " examples are great for general introductions to a concept, but often tend to lack much depth. So, as a follow-up to the original article on enums in Java 5.0, this article goes into a little more depth with a real-world example. The Container Enum Figure 1 below illustrates the enumeration of possible application servers to which an application can deploy. Why is this useful? Many organizations have more than one Java application server in different environments, and an EAR or WAR may need to be redeployed to different servers; or, you may be developing a common framework that will be used in different environments.

Figure 1: The Container enum. public enum Container { WEBSPHERE, WEBLOGIC, JBOSS, NONE; } Now, let's say the application being designed requires an application-controlled JTA TransactionManager (if, for example, the standard way of doing XA transactions cannot be used). Figure 2: The Container enum with factory methods. lookupContainer().getTransactionManager(): Putting extra state on enum constants. You are here: Home / Java / Putting extra state on enum constants I had occasion the other day to push some extra state onto my enum constants. I hadn’t done this before and it took me a while to find any good docs on it on the web. In my case I had some classes in the Strategy pattern and I wanted to create an enumerated type for the different strategies. Instead of making a map of enum value to strategy instance, I just pushed the instances into the enum values themselves.

Here’s an example with some helpful comments: public enum FightingStrategyType { // Declare each of the enum constants – comma-delimited, // terminate list with a semi-colon. // Internal attribute for each enum value private FightingStrategy strategy; // Getter method to retrieve the strategy for an enum value public FightingStrategy getStrategy() { return this.strategy; } } Person person = new Person(FightingStrategyType.KUNG_FU); Bear bear = new Bear(); person.attacked(bear); public enum ShirtSize { S, M, L, XL; Avoid switch! Use enum! « Schneide Blog. Recently I was about to refactor some code Crap4j pointed me to. When I realized most of that code was some kind of switch-case or if-else-cascade, I remembered Daniel´s post and decided to obey those four rules. This post is supposed to give some inspiration on how to get rid of code like: or an equivalent if-else-cascade.

In a first step, let’s assume the constants used above are some kind of enum you created. For example: the switch-case would then most probably look like: In this case you don’t need the switch-case at all. The switch-case then shrinks to: But what if the constants are defined by some third-party code? Which would result in a switch-case very similar to the one above and again, you don’t need it. Regarding this case there is a small stumbling block, which you have to pay attention to. There is yet another case that may occur. To cover this case, you need to alter the enum to look something like: How do you feel about this technique? Like this: Like Loading... A Finite State Machine Supporting Concurrent States. A finite state machine (FSM) models a predefined number of application states, which are changed (transitioned) according to actions that occur when triggered by runtime events.

The FSM serves as a control point for validating state transitions and initiating callbacks. A typical application will go through multiple states during a runtime session, e.g., RUNNING → PAUSED → RESTARTED, or (in the case of a data entry form) ENTER → VALIDATE → SAVE. The state transitions are initiated by runtime events, such as when a user presses an PAUSE button or hits the ENTER key after entering data in a field. The FSM determines what actions occur when an event is received, and the resulting state. The transition to a new state will invoke a change in the immediate or subsequent behavior of an application. Figure 1. The Bouncing Bomb Application The Bouncing Bomb Application uses an FSM to manage the enabling/disabling of buttons in the right button panel. Figure 2. Style="page-break-inside: avoid">