javaapplication-design

Use same data throughout application or copy it?


Let's say I have a class ChatDataProvider which communicates with a Server and contains a List of objects of type Chat (containing objects of type Post etc.). If I want to transfert this chats to another class (in order to display them), I have a couple of possibilities:

  1. Send a reference to the List object
  2. "Shallow" copy the data: Create a new List that contains references to the original objects
  3. Deep copy the data

I guess 1. & 2. would be regarded as bad design since the data is not encapsulated. But it also has the benefits of:

Keepting the data consistent throughout the application creates a big implementation overhead that is prone to errors. And since this is an enclosed application, no "unauthorized" changes in the data would occur that should not be propagated (automatically).

So which one would you choose and why? Are both opions valid?

There are probably answers to this question, but I don't really know what to search for. So if someone knows some links/resources, that's fine.


Solution

  • It all narrows down to the design of the project you use.

    1)If your application needs to use the object in many other packages use shallow copy to clone instead of deep copy method to duplicate. As maintaining the same data by, recreating the operations performed in one object ,through out will cost your performance ,memory and also being a tedious effect . I would avoid it.

    2)If you are performing operations on the same object concurrently , It is prone to error and it is not a good design as well.

    So, go for shallow copy/referencing if you just have to access the object or for Deep copy if you are performing any operations concurrently !!!