Encapsulation and Getters

后端 未结 4 1866
青春惊慌失措
青春惊慌失措 2020-12-19 23:56

I was reading this article on why getter and setters are evil. The article doesn\'t say not to use them ever, but, it\'s telling y

4条回答
  •  一生所求
    2020-12-20 01:01

    You can create three kind of classes:

    1. Entity, classes that represents a business concept and have only one unique id, like Client class with Id the username. It is usually a mutable class. You should have all the business logic here. You should not open his data with getters and setters.

    2. Value object, classes that represents a business concept but not have an unique id, like Email class. It is usually an imm.utable class. You should have all the business logic here.

    3. Data structure (kind of DTO), classes to save data only, without behavior, maybe you have setters and getters to access those datas.

    What can I do if I need to access all Client data if I do not have accesors? Well, you should transform Client to a DTO. You can use a framework like Orika. Or you can create a method into Client class to ask for information (mediator pattern).

    I like second option but it implies more work:

    class Client{
        private String name;
        ...
       public void publishInfo(ClientInfo c){
          c.setName(name);
          ...
        }
    }
    
    class ClientInfo{
        private String name;
        //GETTERS
        //SETTERS
    }
    

提交回复
热议问题