Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Design patterns - Data to object

Suppose I have some data in a file or maybe database. It could be JSON, XML, YAML, CSV, String[], etc.

I'd like to create a model object with this data. For example:

Data:

{
    "name": "John Doe",
    "age": "30"
}

Model (Pseudocode):

class Person {
    Person(name, age) {
        this.name = name;
        this.age = age;
    }
    // business logic
}

Some code that creates Person objects from JSON data (Pseudocode):

peopleArray = [];
recordSet = aJSONReader.read('file');
for (recordSet as r) {
    peopleArray.add(new Person(r[0], r[1]));
}

What would you use to build model objects from given data? In my example I'd start supporting JSON. What if I'd like to change it or support new data formats? How do I decouple this code? Which design pattern fit here?

like image 234
Thom Thom Thom Avatar asked Apr 10 '14 10:04

Thom Thom Thom


People also ask

Which design pattern works on data?

Explanation: Command pattern is a data driven design pattern.

Is DTO a design pattern?

Although the DTO pattern is a simple design pattern, we can make a few mistakes in applications implementing this technique. The first mistake is to create different DTOs for every occasion.

What is DAO and DTO?

DAO is a class that usually has the CRUD operations like save, update, delete. DTO is just an object that holds data. It is JavaBean with instance variables and setter and getters. The DTO is used to expose several values in a bean like fashion.

What is DAO design pattern?

DAO Design Pattern is used to separate the data persistence logic in a separate layer. This way, the service remains completely in dark about how the low-level operations to access the database is done. This is known as the principle of Separation of Logic.


1 Answers

Use the strategy pattern (see here). You want to provide different methods to parse data. A method would parse JSON, another method would parse XML and another method would read a database. Each method can be seen as a strategy to parse data and generate data objects.

Create a common interface, let's say IDataObjectParser with a single method like public List<DataObject> parse(). Each parser would implement this interface. Then you can exchange the parser whenever you want, e.g. during runtime or according to a configuration file.

like image 73
Thomas Uhrig Avatar answered Sep 22 '22 23:09

Thomas Uhrig