Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Don't Parse, Use Parsing Objects

DZone's Guide to

Don't Parse, Use Parsing Objects

Deserialization can be accomplished in a few ways, but which one is the ideal one? We take a look at one opinion, using parsing objects.

· Java Zone ·
Free Resource

Verify, standardize, and correct the Big 4 + more– name, email, phone and global addresses – try our Data Quality APIs now at Melissa Developer Portal!

The traditional way of integrating an object-oriented back-end with an external system is through data transfer objects, which are serialized into JSON before going out and deserialized when coming back. This way is as much popular as it is wrong. The serialization part should be replaced by printers. Here is my take on deserialization, which should be done by — guess what — objects.

La science des rêves (2006) by Michel Gondry
La science des rêves (2006) by Michel Gondry

Say there is a back-end entry point, which is supposed to register a new book in the library, arriving in JSON:

{  
    "title": "Object Thinking",  
    "isbn: "0735619654", 
    "author: "David West"
}


Also, there is an object of class Library, which expects an object of type Book to be given to its method register():

class Library {  
    public void register(Book book) {    
        // Create a new record in the database  
    }
}


Say also that type Book has a simple method isbn():

interface Book {  
   String isbn();
}


Now, here is the HTTP entry point (I'm using Takes and Cactoos), which is accepting a POST multipart/form-data request and registering the book in the library:

public class TkUpload implements Take {  
    private final Library library; 

    @Override  
    public Response act(Request req) {    
        String body = new RqPrint(     
            new RqMtSmart(new RqMtBase(req)).single("book")    
        ).printBody();    

        JsonObject json = Json.createReader(     
            new InputStreamOf(body)    
        ).readObject();    

        Book book = new BookDTO();    

        book.setIsbn(json.getString("isbn"));    
        library.register(book);  
    }
}


What is wrong with this? Well, a few things.

First, it's not reusable. If we were to need something similar in a different place, we would have to write this HTTP processing and JSON parsing again.

Second, error handling and validation are not reusable either. If we add it to the method above, we will have to copy it everywhere. Of course, the DTO may encapsulate it, but that's not what DTOs are usually for.

Third, the code above is rather procedural and has a lot of temporal coupling.

A better design would be to hide this parsing inside a new class JsonBook:

class JsonBook implements Book {  
    private final String json;  

    JsonBook(String body) {    
        this.json = body;  
    } 

    @Override  
    public String isbn() {    
        return Json.createReader(      
            new InputStreamOf(body)    
        ).readObject().getString("isbn");  
    }
}


Then, the RESTful entry point will look like this:

public class TkUpload implements Take {  
    private final Library library; 

    @Override  
    public Response act(Request req) {    
        library.register(      
            new JsonBook(        
                new RqPrint(          
                    new RqMtSmart(new RqMtBase(req)).single("book")        
                ).printBody()      
             )    
        );  
    }
}


Isn't that more elegant?

Here are some examples from my projects: RqUser from zerocracy/farm and RqUser from yegor256/jare.

As you can see from the examples above, sometimes we can't use implements because some primitives in Java are not interfaces but final classes: String is a "perfect" example. That's why I have to do this:

class RqUser implements Scalar<String> {  
    @Override  
    public String value() {    
        // Parsing happens here and returns String  
    }
}


But aside from that, these examples perfectly demonstrate the principle of "parsing objects" suggested above.

Developers! Quickly and easily gain access to the tools and information you need! Explore, test and combine our data quality APIs at Melissa Developer Portal – home to tools that save time and boost revenue. Our APIs verify, standardize, and correct the Big 4 + more – name, email, phone and global addresses – to ensure accurate delivery, prevent blacklisting and identify risks in real-time.

Topics:
parsing ,deserialization ,java ,json ,objects ,oop

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}