Is it bad practice to make a setter return “this”?

前端 未结 27 1038
抹茶落季
抹茶落季 2020-11-27 09:39

Is it a good or bad idea to make setters in java return \"this\"?

public Employee setName(String name){
   this.name = name;
   return this;
}
27条回答
  •  天涯浪人
    2020-11-27 10:01

    Yes, I think it's a good Idea.

    If I could add something, what about this problem :

    class People
    {
        private String name;
        public People setName(String name)
        {
            this.name = name;
            return this;
        }
    }
    
    class Friend extends People
    {
        private String nickName;
        public Friend setNickName(String nickName)
        {
            this.nickName = nickName;
            return this;
        }
    }
    

    This will work :

    new Friend().setNickName("Bart").setName("Barthelemy");
    

    This will not be accepted by Eclipse ! :

    new Friend().setName("Barthelemy").setNickName("Bart");
    

    This is because setName() returns a People and not a Friend, and there is no PeoplesetNickName.

    How could we write setters to return SELF class instead of the name of the class ?

    Something like this would be fine (if the SELF keyword would exist). Does this exist anyway ?

    class People
    {
        private String name;
        public SELF setName(String name)
        {
            this.name = name;
            return this;
        }
    }
    

提交回复
热议问题