search

Home  >  Q&A  >  body text

Java 代码不写getter, setter, 转化为 public, 有什么弊端?

PHP中文网PHP中文网2806 days ago1384

reply all(9)I'll reply

  • 高洛峰

    高洛峰2017-04-18 10:37:44

    Well, there are actually a lot of things you can do by operating with methods, especially when combined with OO thinking - Type is an important piece of information.

    In addition, this is a standard, Java Beanis just that, the "normal operation" of many frameworks and third-party libraries (the most famous one is Spring) also relies on it. You can search for articles related to "Java beans in Java Empire".

    Strongly object to answers like Setter writing logic. Such code is extremely misleading. Experienced people know that you cannot write logic to the "bean" layer (usually corresponding to the Model layer), but at least to the Service layer (according to the common three-layer architecture). Therefore, the Setter in this case is not so important. To sum up, the answers about writing logic in Setter are all incorrect.

    Finally, let me comment on the person who said Existence is reasonable, I hope he can understand "Existence is reasonable"what exactly does it mean.


    I would like to formally respond to the people who criticized me——There are some people who talk about logicin Setter, and there are also people who rely on "fallacious theories"

    to persuade others.

    Tell me a story, when I first came to the community a year ago. I once saw a signature plate written by a master with a relatively high score saying Trash SF! , I noticed his reputation record (at that time, the reputation record was somewhat similar to GitHub's commit record, but it was not as long as 1 year), Almost all issues had been downvoted , obviously - ​​This was malicious The

    .

    After being in the community for more than a year, I occasionally encounter situations like this. But the means are not so bad. Likewise, I admit that I am still very good at it. If I am not sure about some issues, I may be misleading others. If I get stepped on, I will be stepped on!

    Now this situation is intolerable to me - if you are wrong, you are wrong, and you still have to mislead others. It would be such a pity if other people were screened out due to failure in such a basic question during the interview !

    Finally, I want to tell all:

    1. I will not quit the community because I was disliked, even if it was maliciously disliked. Because I have to answer more questions to prevent more novices from being misled by "terrible beginners". Similarly, In order to maintain the quality of the community, I will never let go of extremely misleading answers.

    2. If you don’t believe me, please tell the interviewer during the interview that you often write logic in the Setter of Java Bean!

    3. I scanned all the answers carefully just now. Fortunately, there are users like @kevinz here. I voted for him to prevent "terrible beginners" from knocking him down.

    4. +1 point for answering, only 1 point for following the trend. Being stepped on is 2 points. And as there are more and more answers like this, the quality of the community will become worse and worse. By then, even if you have a reputation of 1W, if you say it proudly when you chat or communicate, others will just sneer: That community? The quality is not high, they are all just following the trend.

    reply
    0
  • 怪我咯

    怪我咯2017-04-18 10:37:44

    Each language has a different philosophy. Java is completely object-oriented and advocates a high degree of flexibility and scalability of code when coding. And like Go语言提倡的又是代码极致的简洁性,所以只需要像下面的方式定义struct it’s ok.

    type S struct {
        A string
        B int
    }

    But obviously you cannot use this library in the Java中你还是应该遵守规范为javabean定义get/set方法,因为你遵守规范才来享受规范为你带来的好处,比如你接入第3方库的时候,要使用reflect的方式来操作javabean时他们大多数都是采用get/set方法来实现的。如果你的javabean此时没有get/set method.


    From personal experience, the simplicity of the code is more important than the flexibility and scalability of the code. So java中也出现了像lombokThis toolkit can simplify the code very well.

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-18 10:37:44

    The people above have said so much, but they have missed one point. Methods are polymorphic, but attributes are not polymorphic. How do you understand this? For example, Person is the parent class, Man is the subclass, both the parent class and the subclass have the Name attribute (although this is very rare), and the names in the parent class and the subclass are both public. Please see the following code:

    Person p = new Man();
    p.name = "person";
    Print(p.name);
    Print(p.getName());
    

    The answer will be output
    person
    null

    reply
    0
  • 迷茫

    迷茫2017-04-18 10:37:44

    This is a good question! Why don't we just make this private field public instead of using cumbersome setters and getters? There are several reasons:

    Never trust customer input

    Let’s assume this class:

    class Bicycle {
        public int speed;
        
        // ...
    }
    
    public class BicycleTest{
        public static void main(String[] args){
            Bicycle b = new Bicycle();
            b.speed = 300000; //什么?自行车这么快?不科学啊?自行车车速不超过120吧。
            // 可是作为程序员的我怎么办呢?只能在文档里告诉用这个类的人:超过120罚款?
            // WTF!写这个类的程序员该死。
            b.speed = -30; // 这个?负的速度,高中物理?我勒个去。
        }
    }
    

    Would it be better if we changed it to this:

    class Bicycle {
        private int speed;
        
        public int setSpeed(int speed) {
            if(speed > 120){
                this.speed = 120;
            } else if(speed < 0){
                this.speed = 0;
            } else{
                this.speed = speed;
            }
        }
        public int getSpeed() {
            return speed;
        }
    }
    
    public class BicycleTest{
        public static void main(String[] args){
            Bicycle b = new Bicycle();
            b.speed = 300000; 
            System.out.println(b.getSpeed()); // 显示120
        }
    }
    

    Easy to modify

    Suppose the required speed is now between 0-40. Without getters and setters, all the code would have to be rewritten, and it would be impossible to complete in less than an hour. With this setter, it's simple. Just change the logic of the setter. If it doesn't finish in 1 minute, the programmer can start it.

    public int setSpeed(int speed) {
            if(speed > 40){
                this.speed = 40;
            } else if(speed < 0){
                this.speed = 0;
            } else{
                this.speed = speed;
            }
        }

    reply
    0
  • 黄舟

    黄舟2017-04-18 10:37:44

    My understanding is that the pros and cons are relative. For a "small program", there are no cons, because you and other maintainers can clearly see and control the changes in parameter values. At this time, because you can completely To control every corner of the program, just public甚至“利大于弊”,因为没有了setter&getter,减少了不少代码量。但当程序“大“到一定规模程度的时候,是不是应该要考虑程序的可维护性呢,比如a.moneya.getMoney(),突然有一天加入了一个a.action因子来影响money,如何保证每一个money的调用者都能知道因子影响规则,显然直接a.money就不那么可靠了。从写程序的角度来说,应该多写方法,这是我大学计算机程序课老师教我的,数据很枯燥,唯方法能让你形象地知道程序在干什么。从面向对象的角度来说,对象应该提供操作对象的方法,所以,还是方法,setter和getter就是体现了这一思想。从Java特性来说,setter和getter体现了封装特性的思想,就上面的例子,当另外一个money使用者需要调用money时,调用者本不需要知道还有一个action因子在那里,他只要getMoney()拿到正确的money, the variables are private and public methods for operating variables are provided. At this time, the advantages outweigh the disadvantages. Those who have little talent and little knowledge, speak from the same family, and accept criticism and correction if they understand anything inappropriate.


    In addition, regarding the logic problem within setter&getter, I think it is a question of "should it be", rather than a question of "can it be done". For the latter, I would say yes, why not! For the former, you have to weigh the pros and cons. When your program logic and risk control are good, it will be convenient for you to write! Those excellent frameworks are not written in this way, and it must be based on pros and cons (expansion, etc.). It is normal to put the logic in the logical processing layer.

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 10:37:44

    First of all, the translation of method is method.


    Then let me understand your confusion

    But do you really have to think so much about the future

    In fact, the main reason why you don’t do this is because it is very troublesome.

    But in fact, you will have those fields (fields, attributes) that must use getter setters, such as read-only fields, so 1⃣️, for the consistency of the overall code, it is better to use all getters and setters.
    2⃣️, using the help of ide actually doesn’t take much effort to complete.
    3⃣️, this is basically a normative thing, there is no need to think about whether it is necessary to do this.
    4⃣️, in some cases, getters and setters are indeed not needed. If you are confident that the data here is very simple, just make it public.


    About another question

    If a private field provides getters and setters, then it is considered public, which is inconsistent and public should be used

    What is the purpose

    First of all, a private field may only have a getter and a setter, which is naturally not considered public. If there are both setters and getters, it is not as simple as you think. Because the getter setter you wrote yourself does not have any processing logic, but you think about this

    private String name;
    
    public void setName(String name) {
        this.name = name.trim();
    }
    
    public String getName() {
        return name;
    }

    If you have the same needs as this example, you need to remove the extra spaces when saving the name. (By the way, I can’t guarantee that the syntax of the above code is correct. I haven’t written Java for a long time.


    Regarding the question of whether it would be more comfortable to call open fields, in fact, the open fields of python you mentioned are not open fields, right? The actual storage field is _name, and the getter and setter are name. This is only different in syntax from Java, but the essence is the same.

    I will put two more pieces of code to show the benefits of getters and setters.

    private int userId;
    
    public User getUser();
    
    public void setUser(user);

    Another example

    private Map data;
    
    public User getUser();
    
    public int getStatus();

    reply
    0
  • 高洛峰

    高洛峰2017-04-18 10:37:44

    class GoodDog {
        private int size;
        
        public int getSize() {
           return size;
        }
    
        public void setSize(int s){
           size = s;
        }
    }

    There is an issue of encapsulation and control here. Suppose you directly access the property goodDog.size; suddenly one day, you may need to filter out something for each size, or for a certain size, what should you do? Then you have to add filtering mechanisms everywhere where goodDog.size appears. If you use the getSize() method, then I will filter it in this method and it will be OK. In fact, the overall idea is to do things from an object-oriented perspective. If you want something, just tell me and I will come to the house to get it for you, but you can't go directly into the house to get it. In case you are not familiar with my home. What should I do if my family is messed up?

    It is not safe if goodDog .size=12 is set directly like this. What if the value of size is less than 10?
    Is it necessary to verify every property setting? In order to prevent this from happening, Java has unified Change the value and control the range during the set method, so that you don’t have to look for places around the world where goodDog .size is used when the needs change in the future

    Methods with parameters and methods without parameters depend on the specific use of the method. The set method and get method are to reflect the encapsulation idea of ​​object-oriented programming. Setting member variables as private can only be modified and accessed through specific methods, ensuring the security of the program.

    There is also the answer above, like java beans or hibernate, when removing attributes, it does not take the attribute size you defined, but takes your getSize, and then removes the lower case S of the get method to get the size.

    Or if you still don’t understand, remember this: Existence is reasonable. One day, when writing a certain piece of code, you will suddenly understand.

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-18 10:37:44

    Public can be used in simple scenarios. The setters and getters are mainly used to seal off the outside world. You can add some unified processing to the setters and getters, which is also convenient for reconstruction.

    reply
    0
  • 怪我咯

    怪我咯2017-04-18 10:37:44

    I would like to add that when hiding visibility, settergettermethods do not necessarily directly access values, and some processing logic can also be added.

    reply
    0
  • Cancelreply