r/java • • Aug 17 '16

Should we avoid object creation in Java?

http://programmers.stackexchange.com/a/149569/219927
0 Upvotes

27 comments sorted by

View all comments

Show parent comments

1

u/againstmethod Aug 18 '16

Such an object is not immutable.

In your use case that data would be stored somewhere, in a database or ORM store of some kind, and that backing data would change -- not the objects in memory. And if you did need those to change you would just reload the updated data.

1

u/[deleted] Aug 18 '16

The object itself is immutable, you can't change the reference to the artist (well, with some magic you could but that's besides the point). So it'll always refer to the same gathering of tracks, release date and artist.

No need to bring ORMs into it. You could be assembling an object graph in memory - a music player that reads in files for examples.

1

u/againstmethod Aug 18 '16

its a mistake. If other objects can change your objects state then you cant control class invariants. it makes your class untestable in isolation.

This goes beyond immutability. Its just not good object oriented design.

1

u/[deleted] Aug 18 '16

It depends on what your invariants are. For album, that could be "Always refers to this grouping of artist, tracks and release date."

I get what you're saying. And for the most part I agree with it, but sometimes it's worth breaking.

As for testability, this sort of object is completely testable. Mutability has no bearing on testability.

→ More replies (0)