views:

66

answers:

2

Hello all,

My first question here so be gentle.

I would like arguments for the following code:

public class Example {
    private String name;
    private int age;

    ...

    // copy constructor here
    public Example(Example e) {
        this.name = e.name; // accessing a private attribute of an instance
        this.age = e.age;
    }

    ...
}

I believe this breaks the modularity of the instance passed to the copy constructor. This is what I believe to be correct:

public class Example {
    private String name;
    private int age;

    ...
    // copy constructor here
    public Example(Example e) {
        this.setName(e.getName());
        this.setAge(e.getAge());
    }

    ...
}

A friend has exposed a valid point of view, saying that in the copy construct we should create the object as fast as possible. And adding getter/setter methods would result in unnecessary overhead.

I stand on a crossroad. Can you shed some light?

+1  A: 

Access is class based, not object based.

The rationale for making a member private is that the ther classes should not know the details of implementation outside of well defined API, so as to make the rest of the system tolerate the change of implementation. However, the copy constructor is not "the rst of the system" - it is your own class.

DVK
Hey DVK, what does it mean "the rst of the system"?I did understand your point of view, and I got the same answer from a programming teacher.
Pedro Magueija
The rest of the system - any code/classes which are outside of your class.
DVK
+1  A: 

The first example is not copying a private attribute of an instance, because they are bot instances of the same class.

However, if you add access methods/properties, any decent compiler should optimise them away to simple "inlines", in which case the second method is cleaner code (all accesses go via your access function) but both approaches should end us as be equally efficient (probably identical) memberwise copies.

If you really want a copy constructor to be efficient, then a lower level binary copy will be faster than a memberwise copy. But significantly "dirtier".

In general I prefer to access all member fields via properties/accessors as that encapsulates them better, allowing you to change the underlying implementation/storage of a field without having to change any of the code that accesses it, except for the property/accessor itself.

Jason Williams