Jotta esim JSON serialisointi saadaan toimimaan kivutta, tehdään Interface / Class määrittelyt seuraavalla tavalla.
Voit katsoa esimerkin Stash:sta example/todo-list domain luokat (TodoItemDTO, PersonDTO sekä niiden rajapinnat)
Sekä rajapinnat että toteuttavat luokat lisätään aina "api" moduliin. Toteuttavien luokkien nimet päättyvät aina "DTO" (Data Transfer Object).
Palvelukerros-koodissa käytetään aina rajpintoja eikä esim castata konkreettisiin DTO luokkiin. Jos halutaan muokata kenttiä luodaan uusi instanssi "copy constructoria" käyttämällä.
Code Block | ||
---|---|---|
| ||
public interface TodoItem { String getId(); String getTitle(); String getDescription(); Date getCreatedDateTime(); Date getCompletedDateTime(); // Huomaa interface tässä! Person getCreatedBy(); } |
Code Block | ||
---|---|---|
| ||
public class TodoItemDTO implements TodoItem { private String id; private String title; private String description; private Date createdDateTime; private Date completedDateTime; // tässä taas on konkreettinen luokka private PersonDTO createdBy; ... // "Copy constructorissa" luodaan uusi "DTO" luokka alla olevalla tavalla. public TodoItemDTO(TodoItem item) { id = item.getId(); title = item.getTitle(); description = item.getDescription(); createdDateTime = item.getCreatedDateTime(); completedDateTime = item.getCompletedDateTime(); createdBy = new PersonDTO(item.getCreatedBy()); // HUOM! } ... // Get ja Set metodit toimivat myös interfacella, sekä setteri kopioi annettavan parametrin public Person getCreatedBy() { return createdBy; } public void setCreatedBy(Person createdBy) { if (createdBy != null) { this.createdBy = new PersonDTO(createdBy); } else { this.createdBy = null; } } |