Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Fluent API to create simpler and more intuitive code

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article is about how to use Fluent API to create simpler, more intuitive code. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

What is Fluent-API?

When we talk about it in the context of software engineering, fluent-API is an object-oriented API whose design is mainly based on the method chain.

This concept was created by Eric Evans and Martin Fowler in 2005 to improve code readability by creating domain-specific languages (DSL).

In practice, creating a smooth API means developing an API where you don't need to remember the next steps or methods, allowing a naturally continuous sequence as if it were an option menu.

This natural rhythm is similar to the way restaurants and even fast-food chains work, because when you put a dish together, the options vary depending on the choice you make. For example, if you choose a chicken sandwich, it will be served according to suggestions such as the dishes you choose.

Fluent API in the context of Java

In the Java world, we can think of two famous examples of such implementations.

The first is the JOOQ framework, a project led by Lukas Eder that facilitates communication between Java and relational databases. The most significant difference of JOOQ is that it is data-oriented which helps to avoid and / or reduce impedance problems or losses related to relational and object-oriented.

Query query = create.select (BOOK.TITLE, AUTHOR.FIRST_NAME, AUTHOR.LAST_NAME) .from (BOOK) .join (AUTHOR) .on (BOOK.AUTHOR_ID.eq (AUTHOR.ID)) .where (BOOK.PUBLISHED_IN.eq (1948)); String sql = query.getSQL (); List bindValues = query.getBindValues ()

Another example is a non-relational database within the enterprise Java world specification, namely NoSQL. These include Jakarta EE, the first specification of its kind and Jakarta NoSQL under Eclipse Foundation.

The purpose of this specification is to ensure smooth communication between Java and NoSQL databases.

DocumentQuery query = select () .from ("Person") .where (eq (Document.of ("_ id", id)) .build (); Optional person = documentTemplate.singleResult (query); System.out.println ("Entity found:" + person)

Generally speaking, a fluent API is divided into three parts:

The final object or result: in general, fluent-API is similar to the builder pattern, but the most powerful dynamics combine with DSL. In both cases, the result is often an instance that represents the result of the process or the new entity.

Options: in this case, it is a collection of interfaces or classes that will be used as our Interactive menu. From an action point of view, the idea is to show only the options available in the next step in intuitive order.

Result: after all this process, the answer may or may not lead to instances of entities, policies, and so on. The key point is that the result must be valid.

Fluid API practice

To demonstrate this concept, we will create a sandwich order that contains the expected results of the order with the corresponding purchase price. The process is as follows.

Of course, there are many ways to achieve this smooth API functionality, but we chose a short version.

As we have already mentioned, the three parts of API-- objects, options, and results-- we will start with the order in which the "order" interface will represent. One highlight is that this interface has some interfaces that will be responsible for showing our options.

Public interface Order {interface SizeOrder {StyleOrder size (Size size);} interface StyleOrder {StyleQuantityOrder vegan (); StyleQuantityOrder meat ();} interface StyleQuantityOrder extends DrinksOrder {DrinksOrder quantity (int quantity);} interface DrinksOrder {Checkout softDrink (int quantity); Checkout cocktail (int quantity); Checkout softDrink (); Checkout cocktail (); Checkout noBeveragesThanks () } static SizeOrder bread (Bread bread) {Objects.requireNonNull (bread, "Bread is required o the order"); return new OrderFluent (bread);}

The result of this API will be our order class. It will contain sandwiches, drinks and their respective quantities.

Quick add-ons before we return to the tutorial

The point that we will not pay attention to in this article, but it is worth mentioning, has something to do with the representation of money.

When it comes to numerical operations, it's best to use BigDecimal. That's because, based on references such as Java Effective books and blog When Make a Type, we've learned that complex types need unique types. This reasoning, coupled with the pragmatism of "Don't repeat yourself", results in the use of the Java monetary specification: The Money API.

Import javax.money.MonetaryAmount;import java.util.Optional;public class Checkout {private final Sandwich sandwich; private final int quantity; private final Drink drink; private final int drinkQuantity; private final MonetaryAmount total; / /...}

The final step of the journey is the API implementation. It will be responsible for the "ugly" part of the code to make API look beautiful.

Since we do not use databases or other data references, the price list will be placed directly in the code, and we intend to make the example as simple as possible. However, it is worth emphasizing that in the natural environment, this information will exist in the database or service.

Import javax.money.MonetaryAmount;import java.util.Objects;class OrderFluent implements Order.SizeOrder, Order.StyleOrder, Order.StyleQuantityOrder, Order.DrinksOrder {private final PricingTables pricingTables = PricingTables.INSTANCE; private final Bread bread; private Size size; private Sandwich sandwich; private int quantity; private Drink drink; private int drinkQuantity; OrderFluent (Bread bread) {this.bread = bread } @ Override public Order.StyleOrder size (Size size) {Objects.requireNonNull (size, "Size is required"); this.size = size; return this;} @ Override public Order.StyleQuantityOrder vegan () {createSandwich (SandwichStyle.VEGAN); return this;} @ Override public Order.StyleQuantityOrder meat () {createSandwich (SandwichStyle.MEAT); return this } @ Override public Order.DrinksOrder quantity (int quantity) {if (quantity)

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report