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

  • What Is Applicative? Basic Theory for Java Developers
  • What Is a Monad? Basic Theory for a Java Developer
  • Redefining Java Object Equality
  • Java vs. Scala: Comparative Analysis for Backend Development in Fintech

Trending

  • Simpler Data Transfer Objects With Java Records
  • Assessing Bias in AI Chatbot Responses
  • How Can Developers Drive Innovation by Combining IoT and AI?
  • Navigating Double and Triple Extortion Tactics
  1. DZone
  2. Coding
  3. Java
  4. Exception-Free Code Using Functional Approach

Exception-Free Code Using Functional Approach

Read on to see a solution to the exceptions caused by functional programming with Java, and examples of how to implement it in your code.

By 
Paweł Szeliga user avatar
Paweł Szeliga
·
Jul. 11, 17 · Tutorial
Likes (18)
Comment
Save
Tweet
Share
22.0K Views

Join the DZone community and get the full member experience.

Join For Free

Checked Exceptions and Java 8

Defining custom exceptions (both checked and unchecked) is a common approach to handling errors in Java applications. It usually leads to creating a new class for every different type of error, marking methods with the throws keyword or wrapping code with try-catch blocks. This can lead to code which is hard to read since every block adds another level of complexity. 

Lambdas in Java 8 started the boom for a functional approach to writing code. Developers are now more familiar with these concepts and seeing -> in the code has become a daily thing. Unfortunately, functional programming doesn't play well with Java exceptions- especially checked ones. 

The main drawback is that method cannot be matched to functional interfaces from java.util.function if it throws a checked exception. This makes developers create custom functional interfaces with throws clauses, duplicating the code from JDK or write nasty try-catch block in lambdas. You can use RuntimeException type to model your custom exceptions but then the information about possible failure is lost and handling it is not required by compiler anymore. 

Result monad

The solution I suggest uses a custom Result class, which is similar to the Optional monad. Optional is a box for objects that may exist- Optional keeps a reference to that object- or not- Optional keeps null. Result, on the other hand, can be a Success - the code was executed correctly and the value is ready- or Failure- some error occurred. Here is the fragment of the Result interface:

public interface Result<T> {

    boolean isSuccess();

    T getResult();

    ErrorType getError();

    String getOptionalErrorMessage();

    ...
}


Success implementation:

public final class Success<T> implements Result<T> {

    private final T result;

    ...

    public boolean isSuccess() {
        return true;
    }

    @Override
    public ErrorType getError() {
        throw new NoSuchElementException("There is no error in Success");
    }

    @Override
    public String getOptionalErrorMessage() {
        throw new NoSuchElementException("There is no optional error message in Success");
    }

    @Override
    public T getResult() {
        return result;
    }
}


Failure implementation:

public final class Failure<T> implements Result<T> {

    private final ErrorType error;

    private final String optionalErrorMessage;

        ...

    @Override
    public boolean isSuccess() {
        return false;
    }

    @Override
    public ErrorType getError() {
        return error;
    }

    @Override
    public String getOptionalErrorMessage() {
        return optionalErrorMessage;
    }

    @Override
    public T getResult() {
        throw new NoSuchElementException("There is no result is Failure");
    }
}


ErrorType is a type which represents a predefined error condition. It sometimes comes with the optional error message. We could actually store Exception type instead of ErrorType but custom class gives more flexibility. Similarly to Optional, Result has get* methods which allow access to the internal state. They shouldn't be used without the isSuccess method because they could result in throwing a NoSuchElementException. 

Nothing fun so far. Let's have a look at the rest of the Result interface:

public interface Result<T> {

     ...

    default <R> Result<R> map(Function<? super T, ? extends R> mapper) {
        return isSuccess() ?
                Success.of(mapper.apply(getResult()))
                (Failure<R>) this;
    }

    default <R> Result<R> flatMap(Function<? super T, Result<R>> mapper) {
        return isSuccess() ?
                mapper.apply(getResult())
                (Failure<R>) this;
    }

    default <R> R fold(Function<? super T, ? extends R> successFunction, Function<Failure<R>, ? extends R> failureFunction) {
        return isSuccess() ?
                successFunction.apply(getResult()) :
                failureFunction.apply((Failure<R>) this);
    }
}


More about these methods later. Now, let's put it to use. When using libraries that declare checked exceptions, we would like to map every successful method call to Success and every cached exception to Failure. So the code like this:

public String getNameById(int id) throws DatabaseAccessException {
        try {
            return dbClient.getNameById(id);
        } catch (DatabaseAccessException e) {
            throw new CustomException(e);
        }
    }


will become:

 public Result<String> getNameById(int id) {
        try {
            return Success.of(dbClient.getNameById(id));
        } catch (DatabaseAccessException e) {
            return Failure.of(PREDEFINED_DB_ERROR, e.getMessage());
        }
    }


(There are existing solutions like Scala's/vavyr's Try, which skip the try - catch block totally and operate on the Exception type. I prefer to use my custom ErrorType but you are free to use a different approach. By using ErrorType you will also save some time by not wrapping the exception in a custom one, which uses costly Throwable.fillInStackTrace). 

Result Usage in Business Code

Now suppose we would like to use it in our business code. Here is the interface from the persistence layer interface modeled with the usage of Result:

public interface DbConnector {

    Result<String> getNameById(int id);

    Result<Integer> getAgeByName(String name);

}


Suppose we want to use it in our business code:

class BusinessClass {

    private final DbConnector dbConnector;

    ...

    public Result<Boolean> isAdult(int userId) {
        return dbConnector.getNameById(userId)
                .flatMap(userName -> dbConnector.getAgeByName(userName)) // or simpler: .flatMap(dbConnector::getAgeByName)
                .map(userAge -> userAge >= 18);
    }

}


The method isAdult pulls the user's name from the database and then uses it to fetch the age of that person (weird API, but that's just an example). Finally, it maps the age of that person to the boolean which indicates whether this person is an adult or not. What is important here is that there are two calls which can result in Failure, sequenced using flatMap. The final invocation of map cannot fail because the predicate 'userAge >=18' will not be applied if the result from flatMap is Failure. The same way, the function passed to flatMap will not be applied if getNameById returns a Failure - this Failure will be passed down the invocation stream to the caller of isAduld. Both map and flatMap will only invoke the passed method if the Result is Success. This way we can model the business flow, but what if we want to unwrap the value inside, for example, to return it to the client?:

    Result<Boolean> isAduld = isAduld(userId);
    String response = isAduld.fold(
            userIsAdult -> "adult: " + userIsAdult,
            failure -> "error occurred: " + failure.getError().show());


Fold will reduce the Result to the single value using provided functions- first if it's Success or second if it's Failure. Remember not to use just the get method instead. 

Summing Up

map - applies a function to the value inside if it's Success, otherwise does nothing.

flatMap - applies a function which returns Result to value inside if it's Success, otherwise does nothing.

fold - applies a success function to the value inside if it's Success, otherwise applies a failure function to the ErrorType - reduces Result to a single value.

That's it. The source code can be found here: https://github.com/pszeliga/functional-java. Other methods from Result will be discussed in future posts.

Java (programming language) Functional programming Monad (functional programming)

Published at DZone with permission of Paweł Szeliga. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • What Is Applicative? Basic Theory for Java Developers
  • What Is a Monad? Basic Theory for a Java Developer
  • Redefining Java Object Equality
  • Java vs. Scala: Comparative Analysis for Backend Development in Fintech

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!