DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • User-Friendly API Publishing and Testing With Retrofit
  • Composite Design Pattern in Java
  • State Design Pattern In Java
  • Iterator Design Pattern In Java

Trending

  • Artificial Intelligence, Real Consequences: Balancing Good vs Evil AI [Infographic]
  • Comprehensive Guide to Property-Based Testing in Go: Principles and Implementation
  • AI's Dilemma: When to Retrain and When to Unlearn?
  • Unlocking Data with Language: Real-World Applications of Text-to-SQL Interfaces
  1. DZone
  2. Coding
  3. Languages
  4. Modern State Pattern Using Enums and Functional Interfaces

Modern State Pattern Using Enums and Functional Interfaces

Learn more about modern state patterns in this Java post!

By 
Niklas Schlimm user avatar
Niklas Schlimm
·
Feb. 12, 19 · Presentation
Likes (19)
Comment
Save
Tweet
Share
18.7K Views

Join the DZone community and get the full member experience.

Join For Free

It's often the case that the behavior of an object should change depending on the objects state. Consider an ShoppingBasketobject. You can add articles to your basket as long the order isn't submitted. But once it's submitted, you typically don't want to be able to change that order anymore. So, there are two states in such a shopping basket object: READONLY and UPDATEABLE. Here is the ShoppingBasket class.

// without state pattern always updateable
public class ShoppingBasket {
     private String orderNo;
     private List<String> articleNumbers = new ArrayList<>();
     public void add(String articleNumber) {
         articleNumbers.add(articleNumber);
     }
     public String getOrderNo() {
         return orderNo;
     }
     public void setOrderNo(String orderNo) {
         this.orderNo = orderNo;
     }
     public void order() {
         // some ordering logic and if succeeded, should change state
     }
 }


In such a class, you can add articles and maybe you can perform an order. Once you've performed an order, the client of such an object would still be able to change that order object, which should not be possible. To prevent clients from updating the order that was already submitted, we want to change the behavior of the ShoppingBasket. It should not be possible to add articles or change the orderNo field once the order is submitted. What's an intelligent object-oriented modern Java solution to such a problem? What I usually do in such cases is I use an enum to implement a GoF state pattern. Here is such an enum:

public enum UpdateState {
     UPDATEABLE(()->Validate.validState(true)), READONLY(()->Validate.validState(false));
     private Runnable action;
     private UpdateState(Runnable action) {
         this.action=action;
     }
     public <T> T set(T value) {
         action.run();
         return value;
     }
 }


My UpdateState enum takes an Runnable object as a constructor argument. You can use more complicated functional interfaces to suit specific needs; the sky is your limit in terms of complexity here. But for now, it's an ordinary Runnable interface. The UpdateState enum has exactly two states: UPDATEABLE and READONLY. The UPDATEABLE enum value does validate to true, always, and the READONLY enum value always evaluates to false, which results in an InvalidStateException (using the Apache Commons Lang Validateclass). The UpdateState enum has a method called set(), which takes an argument and returns exactly that given argument. But before returning the argument, the set() method runs the state-dependent,  Runnable action. Now, why all that hassle?

// shopping basket using modern state pattern
public class ShoppingBasket {
     private String orderNo;
     private List<String> articleNumbers = new ArrayList<>();
     private UpdateState state = UpdateState.UPDATEABLE;
     public void add(String articleNumber) {
         articleNumbers.add(state.set(articleNumber));
     }
     public String getOrderNo() {
         return orderNo;
     }
     public void setOrderNo(String orderNo) {
         this.orderNo = state.set(orderNo);
     }
     public void order() {
         // some ordering logic and if succeeded, change state
         state = UpdateState.READONLY;
     }
 }


The ShoppingBasket now has a state field of the enum type UpdateState. That state field defaults to UPDATEABLE because when you create the ShoppingBasket, it's always updateable, meaning that the order wasn't submitted yet. When you fire the order through the order() method, the state changes to READONLY. Since the state changed to read-only, the ShoppingBasket will change its behavior, specifically when clients try to access the class fields. Let's look at the setOrderNo() method for instance. ThesetOrderNo()method does not assign the order number directly to the orderNo field anymore; instead, it calls theUpdateState enumsset()method, which returns the given value you want to set. That return value is assigned to your orderNo field. Theset()method of the UpdateState enum always checks whether updates are allowed. So when your ShoppingBaskets state is UPDATEABLE, the  set()method will succeed, but when it's READONLY, then the set()method of that state will result inIllegalStateException. This was exactly what we've wanted to achieve in the beginning — make that object read-only if the order is submitted.

Notice that you can make such a state pattern implementation as complex as required. It's a very elegant, short option to drive your object's behavior by objects state. And it saves you a lot if-else typing non-object-oriented logic in all the accessor methods. Consider classes that have 20 fields; you don't want to check state each time in all the methods. That would clearly clutter up your class code. Using the demonstrated state pattern, you save lines of code and your place looks quite tidy. Change the functional interface used in the UpdateState enum and you'll realize the great potential of state-dependent behavior that can be implemented with very few lines of code.

State pattern Interface (computing) Object (computer science)

Opinions expressed by DZone contributors are their own.

Related

  • User-Friendly API Publishing and Testing With Retrofit
  • Composite Design Pattern in Java
  • State Design Pattern In Java
  • Iterator Design Pattern In Java

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: