0

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 ?

JavaDeveloper
  • 5,320
  • 16
  • 79
  • 132
  • The first one. Otherwise you're duplicating (repeating) data. There is such a thing as Data Transfer Objects were the second might apply though. – Sotirios Delimanolis Aug 15 '13 at 21:07
  • Well it depends on what you're trying to do. If you will need your object later on to retrieve more data, I would go with the former. – Josh M Aug 15 '13 at 21:07
  • The answer depends on the circumstances of how you're using the objects. – Gabe Aug 15 '13 at 21:08

2 Answers2

0

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.

tFrisch
  • 133
  • 4
0

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).

ps-aux
  • 11,627
  • 25
  • 81
  • 128