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
Please enter at least three characters to search
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

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

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

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

  • MySQL to PostgreSQL Database Migration: A Practical Case Study
  • Navigating Change Management: A Guide for Engineers
  • Role of Cloud Architecture in Conversational AI
  • Building Resilient Networks: Limiting the Risk and Scope of Cyber Attacks
  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
Oops! Something Went Wrong

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:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!