How much code should one put in a constructor?

前端 未结 9 2208
一整个雨季
一整个雨季 2020-12-15 05:34

I was thinking how much code one should put in constructors in Java? I mean, very often you make helper methods, which you invoke in a constructor, but sometimes there are s

9条回答
  •  情歌与酒
    2020-12-15 06:03

    Your class may need to be initialized to a certain state, before any useful work can be done with it.

    Consider this.

    public class CustomerRecord
    {
        private Date dateOfBirth;
    
        public CustomerRecord()
        {
            dateOfBirth = new Date();
        }
    
        public int getYearOfBirth()
        {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(dateOfBirth);
            return calendar.get(Calendar.YEAR);
        }   
    }
    

    Now if you don't initialize the dateOfBirth member varialble, any subsequent invocation of getYearOfBirth(), will result in a NullPointerException.

    So the bare minimum initialization which may involve

    1. Assigning of values.
    2. Invoking helper functions.

    to ensure that the class behaves correctly when it's members are invoked later on, is all that needs to be done.

提交回复
热议问题