Page 1 of 2 12 LastLast
Results 1 to 20 of 21
Like Tree1Likes

Thread: Copy constructors

  1. #1
    radiodave is offline Member
    Join Date
    May 2015
    Posts
    13
    Rep Power
    0

    Default Copy constructors

    I'm coming from C/C++, and I know what a copy constructor does. Also understand what references to objects are. I have a class called Coordinate, with integer members xSector, ySector, xQuadrant, yQuadrant. I have a copy constructor:


    Java Code:
    Coordinate(Coordinate in)
    {
    this.xSector = in.xSector;
    this.ySector = in.ySector;
    this.xQuadrant = in.xQuadrant;
    this.yQuadrant = in.yQuadrant;
    }
    If I have a loop where I want to copy off an existing coordinate, compute a new coordinate, and if that new coordinate is bogus, the loop stops and the last known good coordinate is used, then is it preferred to use the copy constructor at each loop iteration, or would it be better to make a method to just set the members of that object?

    Java Code:
    Coordinate tempPosition = new Coordinate(currentPosition);
    Coordinate oldPosition;
    do
    {
    oldPosition = new Coordinate(tempPosition);
    /*compute new tempPosition*/
    if(check(tempPosition))
    badCoordinate = true;
    }while (badCoordinate == false);

  2. #2
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    13

    Default Re: Copy constructors

    When you can, you should strive for immutable classes. Assuming I understand you goal, you could put a method in the coordinate class that returns a new coordinate instance based on the supplied argument. It will either return a new instance of the modified coordinate or the current instance of the unchanged one.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  3. #3
    radiodave is offline Member
    Join Date
    May 2015
    Posts
    13
    Rep Power
    0

    Default Re: Copy constructors

    Thanks, I found the bit about concurrency and immutability on the Oracle site. I guess it makes sense, though it's a new concept to me. Creating a new instance of an object just to change a value? Seems like overkill if concurrency isn't involved.

  4. #4
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    13

    Default Re: Copy constructors

    Quote Originally Posted by radiodave View Post
    Thanks, I found the bit about concurrency and immutability on the Oracle site. I guess it makes sense, though it's a new concept to me. Creating a new instance of an object just to change a value? Seems like overkill if concurrency isn't involved.
    Arguably the one of the most used classes in Java is the String class. It has a lot of functionality and ways to alter a string. Yet it is immutable. Every time you make a change you create a new object. I believe the primitive wrapper classes are all immutable too. Immutable classes can be very important in a single threaded environment. Consider when they are used as keys to a map. It could be disastrous and a hard bug to find if a spurious reference to a hash key was inadvertently changed.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  5. #5
    radiodave is offline Member
    Join Date
    May 2015
    Posts
    13
    Rep Power
    0

    Default Re: Copy constructors

    Quote Originally Posted by jim829 View Post
    Arguably the one of the most used classes in Java is the String class. It has a lot of functionality and ways to alter a string. Yet it is immutable. Every time you make a change you create a new object. I believe the primitive wrapper classes are all immutable too. Immutable classes can be very important in a single threaded environment. Consider when they are used as keys to a map. It could be disastrous and a hard bug to find if a spurious reference to a hash key was inadvertently changed.

    Regards,
    Jim
    Not doubting that CString is immutable, but what is the perceived benefit to making it immutable? Maybe it keeps you from wantonly assigning a value via a reference, but how is this better than say, using a setter to set a private member? Is it intended to throw up an exception if something tries to access the stale object without knowing that something came along and changed it unexpectedly? Maybe that's more desirable than having the program malfunction in other more subtle ways, but it doesn't mean you wouldn't have to write better code to avoid doing it.

  6. #6
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    13

    Default Re: Copy constructors

    Quote Originally Posted by radiodave View Post
    Not doubting that CString is immutable, but what is the perceived benefit to making it immutable? Maybe it keeps you from wantonly assigning a value via a reference, but how is this better than say, using a setter to set a private member?
    In the example I gave it isn't better. When you use a setter to set a value, then you expect that value to change the behavior of the object. You would also expect the hashCode and equals to change which means the original key may not be able to find the object in the map.

    For more info, read about immutability here -> Java Practices -> Immutable objects

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  7. #7
    radiodave is offline Member
    Join Date
    May 2015
    Posts
    13
    Rep Power
    0

    Default Re: Copy constructors

    Quote Originally Posted by jim829 View Post
    In the example I gave it isn't better. When you use a setter to set a value, then you expect that value to change the behavior of the object. You would also expect the hashCode and equals to change which means the original key may not be able to find the object in the map.

    For more info, read about immutability here -> Java Practices -> Immutable objects

    Regards,
    Jim
    Between the Oracle and Javapractices site, they seem to imply that you should NEVER permit members to change and you should ALWAYS make classes immutable. Trouble is they do a poor job of explaining these perceived benefits. Making them immutable makes them thread safe. That's great! How so, and how does it benefit a single-threaded application? They don't need a copy constructor. Why not? Seems like they don't expect member variables should ever be allowed to change, which obviously wouldn't make much sense. In my case, the text-based Star Trek game I'm making (Google "Super Star Trek") wouldn't be very interesting if the Enterprise wasn't expected to move around, and I do actually have to make sure it's not colliding with stars, Klingons, planets, etc..

    Interesting, I have the O'Reilly book, "Learning Java", and out of 975+ pages it only has a few sentences about immutability, what it means and how CString is immutable. Doesn't really describe why it's a good thing and certainly doesn't seem to promote that it's necessary.

    Sorry, I just haven't had the "A ha!" moment on why all classes should be immutable. In your hashcode example, it's a foregone conclusion that if it has bad data it won't work. Is it ever allowed to change? No? Makes complete sense to make it immutable. It is allowed to change? Oh, then you must de-allocate and re-allocate memory to change one datum. Yeah, that's efficient.

  8. #8
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    13

    Default Re: Copy constructors

    Quote Originally Posted by radiodave View Post
    How so, and how does it benefit a single-threaded application? They don't need a copy constructor. Why not?
    My idea of a copy constructor is one where if you pass in an array, you copy the contents to a new array. This maintains the immutability because there is no reference to the immutable data. Immutable objects may also have methods which offer changed copies based on some operation. String has many methods which do this. So you are not changing the values of the String but changing an internal copy which is then returned as a new, immutable, String object.

    Seems like they don't expect member variables should ever be allowed to change, which obviously wouldn't make much sense. In my case, the text-based Star Trek game I'm making (Google "Super Star Trek") wouldn't be very interesting if the Enterprise wasn't expected to move around, and I do actually have to make sure it's not colliding with stars, Klingons, planets, etc..
    Of course it doesn't make sense to make all objects immutable. If you look at the Swing architecture and the class hierarchies, they can be changed. One should just strive for immutability if it makes sense.

    Interesting, I have the O'Reilly book, "Learning Java", and out of 975+ pages it only has a few sentences about immutability, what it means and how CString is immutable. Doesn't really describe why it's a good thing and certainly doesn't seem to promote that it's necessary.
    First, there are no CString's in Java. I gave you an example (immutable keys vs mutable keys and hashmaps). Did you read the link above. They also gave some examples.

    Oh, then you must de-allocate and re-allocate memory to change one datum. Yeah, that's efficient.
    First, efficiency can manifest itself in a variety of ways. Being able to cache a hashCode since the state can't change. Checking the invariants once at creation time. And the waste of time tracking down bugs that could have been prevented by using immutable classes.

    I also suggest you read up on Java garbage collection.

    Perhaps someone else on this forum can do a better job of explaining the value of immutable classes.

    Regards,
    Jim
    Last edited by jim829; 06-16-2015 at 08:53 PM.
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  9. #9
    radiodave is offline Member
    Join Date
    May 2015
    Posts
    13
    Rep Power
    0

    Default Re: Copy constructors

    Thanks for trying to explain though, I appreciate it. My foggy C++ memory was showing with the CString class, you are quite right, I meant the String class. It will all probably make more sense eventually, just not at the moment. Thanks!

  10. #10
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    26

    Default Re: Copy constructors

    Rubbish single thread example alert!

    Java Code:
    import java.util.Date;
    
    public class Booking {
        ... some attributes ...
        private Date bookingDate;
    
        public void setBookingDate(Date bookingDate) {
            if (bookingDate.before(new Date()) {
                throw new RubbishDataException("Thrrrrrrp");
            }
            this.bookingDate = bookingDate;
        }
    
        public Date getBookingDate() {
            return bookingDate;
        }
    }
    So we have a Booking above that has a rule that says the Date cannot be before now, otherwise we throw an exception.
    All well and good.
    And, no, this isn't about how Booking should be immutable...this is about a poor design decision for the old Date framework.

    What happens here:
    Java Code:
    void someMethod(Booking aBooking) {
        Date d = aBooking.getDate();
        d.setTime(0);
    }
    Oh dear.
    Because Date is not immutable I have accidentally broken my Booking object.
    It is now no longer valid, and good luck finding exactly where that's happened.
    gimbal2 likes this.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  11. #11
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    5,114
    Rep Power
    12

    Default Re: Copy constructors

    Love the example, especially because the mutability problem is made far worse by the fact that you can, for completely understandable human reasons, misinterpret what "setTime()" means.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  12. #12
    Gotcha is offline Member
    Join Date
    Jun 2015
    Location
    America
    Posts
    29
    Rep Power
    0

    Default Re: Copy constructors

    In your specific case say someone comes along behind you to add functionality and since your class is not immutable the old coordinates value is inadvertently not saved... For example DistanceToNewCoordinatesByTrainAndCab(){/** Alters OldCoordinates */}. Your entire app depended on checking BadCoordinates there really isn't much protection after that point. For weeks you are chasing a bug that could have been prevented by immutability, enforcing a contract how to use your class and maybe poor hiring choices.. :)

  13. #13
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    5,114
    Rep Power
    12

    Default Re: Copy constructors

    Immutability or any kind of restrictive code design is not going to prevent poor hiring choices from mucking up your day.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  14. #14
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    12,059
    Rep Power
    25

    Default Re: Copy constructors

    Quote Originally Posted by gimbal2 View Post
    Love the example, especially because the mutability problem is made far worse by the fact that you can, for completely understandable human reasons, misinterpret what "setTime()" means.
    Not to mention misunderstanding what Date represents.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  15. #15
    radiodave is offline Member
    Join Date
    May 2015
    Posts
    13
    Rep Power
    0

    Default Re: Copy constructors

    Quote Originally Posted by Tolls View Post
    Rubbish single thread example alert!

    Java Code:
    import java.util.Date;
    
    public class Booking {
        ... some attributes ...
        private Date bookingDate;
    
        public void setBookingDate(Date bookingDate) {
            if (bookingDate.before(new Date()) {
                throw new RubbishDataException("Thrrrrrrp");
            }
            this.bookingDate = bookingDate;
        }
    
        public Date getBookingDate() {
            return bookingDate;
        }
    }
    So we have a Booking above that has a rule that says the Date cannot be before now, otherwise we throw an exception.
    All well and good.
    And, no, this isn't about how Booking should be immutable...this is about a poor design decision for the old Date framework.

    What happens here:
    Java Code:
    void someMethod(Booking aBooking) {
        Date d = aBooking.getDate();
        d.setTime(0);
    }
    Oh dear.
    Because Date is not immutable I have accidentally broken my Booking object.
    It is now no longer valid, and good luck finding exactly where that's happened.
    Ahhh... Now I see the problem. Date object being a member of BookingDate, someMethod went and got a reference to aBooking's Date object, and messed with it. I concede that if some yahoo came along and wrote something like someMethod, not realizing the implications of what he's doing even though it seems to make sense, it would certainly break things. Thank you, that makes sense, I hope I interpreted it correctly.

  16. #16
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    13

    Default Re: Copy constructors

    Quote Originally Posted by radiodave View Post
    Ahhh... Now I see the problem. Date object being a member of BookingDate, someMethod went and got a reference to aBooking's Date object, and messed with it. I concede that if some yahoo came along and wrote something like someMethod, not realizing the implications of what he's doing even though it seems to make sense, it would certainly break things. Thank you, that makes sense, I hope I interpreted it correctly.
    Yes you did! Perhaps now my earlier statement makes more sense:

    "Immutable classes can be very important in a single threaded environment. Consider when they are used as keys to a map. It could be disastrous and a hard bug to find if a spurious reference to a hash key was inadvertently changed."

    Next time I will include an example.

    Regards,
    Jim
    Last edited by jim829; 06-18-2015 at 01:59 AM.
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  17. #17
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    26

    Default Re: Copy constructors

    Quote Originally Posted by DarrylBurke View Post
    Not to mention misunderstanding what Date represents.

    db
    If only they'd done a proper Date framework from the word go...then again, I expect they had enough to do just getting Java out the door.
    I await the day that JDBC (or even just JPA) catches up and provides support for the new date time stuff. Admittedly hell is likely to have frozen over before then.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  18. #18
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    5,114
    Rep Power
    12

    Default Re: Copy constructors

    Quote Originally Posted by Tolls View Post
    If only they'd done a proper Date framework from the word go...
    Yeah hello, Java was invented when the internet was just kicking off. Dating sites did not even exist yet.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  19. #19
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    12,059
    Rep Power
    25

    Default Re: Copy constructors

    Quote Originally Posted by Tolls View Post
    If only they'd done a proper Date framework from the word go...then again, I expect they had enough to do just getting Java out the door.
    I await the day that JDBC (or even just JPA) catches up and provides support for the new date time stuff. Admittedly hell is likely to have frozen over before then.
    You do have java.sql.Date#toLocalDate() and valueOf(LocalDate date). Also java.sql.Timestamp#from(Instant instant), toInstant(), toLocalDateTime() and valueOf(LocalDateTime dateTime)

    db
    Last edited by DarrylBurke; 06-18-2015 at 10:40 AM.
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  20. #20
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    26

    Default Re: Copy constructors

    Quote Originally Posted by DarrylBurke View Post
    You do have java.sql.Date#toLocalDate() and valueOf(LocalDate date). Also java.sql.Timestamp#from(Instant instant), toInstant(), toLocalDateTime() and valueOf(LocalDateTime dateTime)

    db
    True, but I don't think they're wired up to Hibernate.
    Or can you declare a field as a Localdate?

    SOmething to look up.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

Page 1 of 2 12 LastLast

Similar Threads

  1. Copy Constructor with Shallow Copy
    By Wnt2bsleepin in forum New To Java
    Replies: 1
    Last Post: 04-11-2012, 12:42 AM
  2. Collections copy constructors guaranteed shallow?
    By kjkrum in forum Advanced Java
    Replies: 3
    Last Post: 01-23-2012, 07:34 AM
  3. On references and copy constructors
    By guest_user in forum New To Java
    Replies: 4
    Last Post: 05-25-2011, 12:27 PM
  4. Replies: 1
    Last Post: 05-25-2011, 09:01 AM
  5. Need help with constructors
    By tpfaff in forum New To Java
    Replies: 10
    Last Post: 10-22-2010, 04:33 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •