Good or bad practice? Initializing objects in getter

前端 未结 9 1779

I have a strange habit it seems... according to my co-worker at least. We\'ve been working on a small project together. The way I wrote the classes is (simplified example):<

9条回答
  •  轮回少年
    2020-12-07 08:06

    I was just going to put a comment on Daniel's answer but I honestly don't think it goes far enough.

    Although this is a very good pattern to use in certain situations (for instance, when the object is initialized from the database), it's a HORRIBLE habit to get into.

    One of the best things about an object is that it offeres a secure, trusted environment. The very best case is if you make as many fields as possible "Final", filling them all in with the constructor. This makes your class quite bulletproof. Allowing fields to be changed through setters is a little less so, but not terrible. For instance:

    class SafeClass
    {
        String name="";
        Integer age=0;
    
        public void setName(String newName)
        {
            assert(newName != null)
            name=newName;
        }// follow this pattern for age
        ...
        public String toString() {
            String s="Safe Class has name:"+name+" and age:"+age
        }
    }
    

    With your pattern, the toString method would look like this:

        if(name == null)
            throw new IllegalStateException("SafeClass got into an illegal state! name is null")
        if(age == null)
            throw new IllegalStateException("SafeClass got into an illegal state! age is null")
    
        public String toString() {
            String s="Safe Class has name:"+name+" and age:"+age
        }
    

    Not only this, but you need null checks everywhere you might possibly use that object in your class (Outside your class is safe because of the null check in the getter, but you should be mostly using your classes members inside the class)

    Also your class is perpetually in an uncertain state--for instance if you decided to make that class a hibernate class by adding a few annotations, how would you do it?

    If you make any decision based on some micro-optomization without requirements and testing, it's almost certainly the wrong decision. In fact, there is a really really good chance that your pattern is actually slowing down the system even under the most ideal of circumstances because the if statement can cause a branch prediction failure on the CPU which will slow things down many many many more times than just assigning a value in the constructor unless the object you are creating is fairly complex or coming from a remote data source.

    For an example of the brance prediction problem (which you are incurring repeatedly, nost just once), see the first answer to this awesome question: Why is it faster to process a sorted array than an unsorted array?

提交回复
热议问题