A
A
a_halala2016-07-22 13:40:11
Java
a_halala, 2016-07-22 13:40:11

How to properly develop the architecture of an object and its services?

Hello. A question for experienced OOP design connoisseurs. Let's imagine a simple system where there is a client and a service serving it.

public interface ClientService {
    void disableClient(String id);

    void sendEmailToClientWithId(String id);
}

public class Client {
    private String id;
    private String username;
    private String email;
    private Boolean isActive = true; // конструктор и куча других полей
}

We need to think about how the object and its service interact. Let's say we get all the necessary data in the controller and collect the Client object through the factory . So the question is: which is better?
1. Make an aggregation of a service and an object and provide an api to change the state of this object, for example
public class Client {
    private String id;
    private String username;
    private String email;
    private Boolean isActive = true; 

    @Autowired
    private ClientService clientService;

    public void printWelcomeMessage() {
        System.out.println(String.format("Hello, %s!", username));
    }

    public void disableClient() {
        clientService.disableClient(this.id);
        this.isActive = false;
    }

    public void printClientStatus() {
        System.out.println(this.isActive? "Active" : "Inactive");
    }

    public void sendEmail() {
        clientService.sendEmailToClientWithId(this.email);
    }
}

2. Make a service with the same methods, but the Client itself will come as a parameter (in which, accordingly, there will be getters / setters)
I.e. the question is even this: Is it correct from the point of view of OOP and design to delegate control of the state of an object to external services through getters / setters? And what are the pitfalls of each of my proposed options?
Hope my question is clear. Looking forward to your replies, thanks!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Kosarev, 2016-07-22
@a_halala

The second option from the point of view of OOP is definitely more correct. The answer to the question is yes, that's right.
In the first case, the main pitfall will be that you will need to implement a service in each entity.
Here in this book , everything is explained quite clearly.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question