Search code examples
javasetter

Call a setter of a field inside a setter of another field


I want to initialize a field immediately after initializing another field like in code below:

@Setter
class Person {
    private String fullName;
    private String shortName;

    public void setFullName(String fullName) {
        this.fullName = fullName;
        setShortName();
    }

    private void setShortName() {
        this.shortName = this.fullName.substring(0, 1);
    }
}

The approach with scrapping the shortName field and using getter, which returns the desired value is not acceptable. I need this field, because I transfer my object to frontend as a JSON object (I want to print the shortName there).

Also my class uses @Setter annotation from Lombok framework. So users of my class will be able to use the desired setter with one parameter. At the same time the setShortName() method is private (as @shmosel advised).

The question remains open: Is it a good idea to call the setter of shortName inside setFullName(String fullName)?

And what is the best approach to do this?


Solution

  • class Person {
        private String fullName;
        private String shortName;
    
        public Person(String fullName){
            this.fullName = fullName;
            this.shortName = fullName.substring(0, 1);
        }
    }