#Can you create a defensive copy of an object/instance of a class?

1 messages · Page 1 of 1 (latest)

flat tapir
#

Findbugs keep giving my error about may expose internal...

thorny roostBOT
#

This post has been reserved for your question.

Hey @flat tapir! Please use /close or the Close Post button above when you're finished. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

turbid cradle
#

If you have a class saving something and want other classes to be able to read that data:

public class SomeClass{
    private List<Something> data=new ArrayList<>();
    public List<Something> getData(){
        return data;
    }
}
#

but maybe other classes shouldn't change that

#

other code might do

SomeClass o=new SomeClass();
//...
List<Something> data = o.getData();
data.clear();
``` or similar
#

and you modified data you haven't modified

#

you can change getData to return a copy

#

so that the code using it doesn't modify the original

#
public List<Something> getData(){
    return new ArrayList<>(data);
}
#

Then, others would just operate on a copy and cannot just change it

#

this is called a defensive copy

#

as it protects against (accidental or unsafe) modifications

flat tapir
#

That's ok but for example I have a controller where I store in a array all the inputs from the keyboard, then linked to this controller another class, in this class I create things like entities that have to get that array of inputs, I cannot pass the controller or that class directly

turbid cradle
#

If it shouldn't be modified by others, you should probably be using a defensive copy

#

if it is supposed to be modified by others, don't use a defensive copy

#

just because it is a warning, it doesn't mean you have to do what it suggests

flat tapir
#

I need to fix all the warnings too :/

turbid cradle
#

Why?

brittle urchin
#

rogue PM maybe

flat tapir
#

Maybe not, I'll ask

#

So for example, if I have a game class where I create all the entities etc. every entity has some components, one of them is an input component that needs the array with all input component, how can I get it without setting the game class into the entities?

#

I can't pass while creating cuz it updates every frame not something static

thorny roostBOT
#

💤 Post marked as dormant

This post has been inactive for over 300 minutes, thus, it has been archived.
If your question was not answered yet, feel free to re-open this post or create a new one.