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
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
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

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • Embracing Reactive Programming With Spring WebFlux
  • Avoiding Pitfalls With Java Optional: Common Mistakes and How To Fix Them [Video]
  • The Beauty of Java Optional and Either
  • What Is Applicative? Basic Theory for Java Developers

Trending

  • Java Parallel GC Tuning
  • Send Your Logs to Loki
  • CI/CD Docker: How To Create a CI/CD Pipeline With Jenkins, Containers, and Amazon ECS
  • AWS vs. Azure vs. Google Cloud: Comparing the Top Cloud Providers
  1. DZone
  2. Coding
  3. Java
  4. Refactor “if” statements - functional programming style

Refactor “if” statements - functional programming style

Dror Helper user avatar by
Dror Helper
·
Nov. 22, 11 · News
Like (0)
Save
Tweet
Share
8.67K Views

Join the DZone community and get the full member experience.

Join For Free
Have you ever seen code that look like this:
public string GetStatusDescription(Model model)
{
    if(model.HasProblemReports)
    {
        return "Errors";
    }

    if(model.SystemState.WorkingMode == WorkingMode.NotManaged)
    {
        return "Manual";
    }

    if(model.SystemState.IsInitializing)
    {
        return "Initialize";
    }

    if(!model.SystemState.InService)
    {
        return "Not in service";
    }

    if(model.SystemState.WorkingMode == WorkingMode.Paused)
    {
        return "Paused";
    }

    if(model.Storage.Objects.Any(obj => obj.IsMoving))
    {
       return "Movement in storage";
    }

    return string.Empty;
}
I know I have – yesterday, I’ve changed the variable names and removed a bit of plumbing code but in essence this is a real function I had to work with.

The problem with this kind of code that it start out simple but quickly becomes hard to read and maintain. Because the ordering of the “if” statements matters as much as the condition itself.

One solution is to use the well known Chain of Responsibility pattern. although it would probably work in this case, I’ve noticed that developers shy from using it in code similar to this example. It’s as if they feel that they “waste” good code by creating a”whole class for two lines of code”. Another reason not to use CoR is that in this case I don’t want to encapsulate the logic of this method in a lot of classes – I just want to be able to easily understand what the method does and add/remove/update it easily.

I literally felt pain writing each new “if” statement until I could take it no more and so I’ve decided to refactor it.

First I’ve created a class to hold each condition:
class ModelToMessage
{
    private Func<Model, bool> _predicate;

    public ModelToMessage(Func<model ,="" bool=""> predicate, string message)
    {
        _predicate = predicate;

        Message = message;
    }

    public bool IsValid(Model model)
    {
        return _predicate(model);
    }

    public string Message{get; private set;}
}
Using this new class I was able to declare the following list and refactor my method:
private List<modeltomessage> _messageCreators = new List<modeltomessage>
    {
        new ModelToMessage(model => model.HasProblemReports, "Errors"),
        new ModelToMessage(model => model.SystemState.WorkingMode == WorkingMode.NotManaged, "Manual"),
        new ModelToMessage(model => model.SystemState.IsInitializing, "Initialize"),
        new ModelToMessage(model => !model.SystemState.InService, "Not in service"),
        new ModelToMessage(model => model.SystemState.WorkingMode == WorkingMode.Paused, "Paused"),
        new ModelToMessage(model => model.Storage.Objects.Any(obj => obj.IsMoving), "Movement in storage"),
        new ModelToMessage(model => true, string.Empty),
    };

public string GetStatusDescription(Model model)
{
   var messageCreator = _messageCreators.First(mc => mc.IsValid(model));

    return messageCreator.Message;
}
The last item on the list is the “default” item that is always true and return an empty string.

I really like the fact that it’s easy to understand which message comes before which message and it’s easy to add new conditions and change their priority.
Functional programming

Published at DZone with permission of Dror Helper, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Embracing Reactive Programming With Spring WebFlux
  • Avoiding Pitfalls With Java Optional: Common Mistakes and How To Fix Them [Video]
  • The Beauty of Java Optional and Either
  • What Is Applicative? Basic Theory for Java Developers

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • 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: