Dependency object be saved as instance variable or just the values obtained from getters? [closed]

StackOverflow https://stackoverflow.com/questions/18261839

  •  24-06-2022
  •  | 
  •  

Question

Consider an example of a simple 'MyCalendar' class with 3 getters 'getDay, getMonth, and getYear'. If I pass 'MyCalendar' object to my another class which of the following options would be a good approach.

OPTION 1: Call required parameters through injected object's getters when needed.

class Foo {
    MyCalendar mycal;
    class Foo(MyCalendar mycal) {
        this.mycal = mycal
    }
}

OR

OPTION 2: Assign the values obtained from injected object's getter as part of initialization.

class Foo {
    Day d;
    Month m;
    Year y;
    class Foo(MyCalendar mycal) {
        d = myCal.getDay();
        m = myCal.getMonth();
        y = myCal.getYear();
    }
}

If the answer is choice 1 then : if a field needs to be accessed mutiple times like in a loop: for (..some imaginary usecase) { mycal.getDate(); } In this case does it benefit to have a local copy ?

Was it helpful?

Solution

Use option 1. It is the sound option oriented approach. You can just delegate tasks to the calendar object that you already have created. The only reason I could see to make a copy is if the original data is mutable and you do not want the field in foo to change, even then I would preserve it in object form, but make a copy.

OTHER TIPS

I would say it depends on more factors and situation.The main I can think of are:

  • Whether the passed object and its is mutable or not.
  • Whether you want values in the new object to be mutable.

If you are passing a date object (possibly via net) I think the best would be to pass only Date or long values and get day of month, month of year etc...at the client or using some util class (alternatively using Joda Time which is better than classic java date/calendar api).

I would not however pass the reference to calendar object (if so, then day) at all. It does not make sense. While calendar is designed to be variable and to point to certain time. Day, mont, year are just 'outputs' form calendar at certain point in time with certain settings of calendar object.
Simply two approaches you showed here are for two different situations and it depends what you want to achieve (save the state or refer to changing values).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top