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

Bring content to any platform with the open-source BloomReach CMS. Try for free.

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.

BloomReach CMS: the API-first CMS of the future. Open-source & enterprise-grade. - As a Java developer, you will feel at home using Maven builds and your favorite IDE (e.g. Eclipse or IntelliJ) and continuous integration server (e.g. Jenkins). Manage your Java objects using Spring Framework, write your templates in JSP or Freemarker. Try for free.

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 }}