I am gonna share two class and wanna learn the reason of security breach.
I am sorry there are three classes. Why the hacker is able to change private pair?
the PetPair class returns a reference to the firstPet and secondPet. the Pet class has a "setter" method that allows the name, age and weight of an instance of a Pet to be changed. therefore, as long as you have a reference to a Pet, you can always modify its name, age and weight. you can block the security breach in PetPair by always returning a "copy" (or clone) of the Pet instances that it holds. that way, any client that modifies the instance that PetPair returns will not change anything in PetPair itself - the client will only be changing the "copy" of the Pet that was returned. I hope this makes sense.
an even better solution would be to create a class called, say, ImmutablePet, that has no setter methods, and return an instance of this when getFirst() and getSecond() are called in PetPair().
to do that you would first have to extract an interface from the Pet class to represent what a Pet is. it would only contain getters.
Ok I think i got the reference part.It's sending its reference which hold the old pair's first values and with setter method we override new values to that reference.Nice. But how can i make this copy,can you explain it a little bit more?
you currently have: public Pet getFirst() { return first; } this would change to: public Pet getFirst() { return new Pet(first.getName(), first.getAge(), first.getWeight()); }
Oh great! Instead of sending the reference we just send the values this time. Thank you,asna=)
no problem - but as I suggested afterwards, a better solution would be to extract an interface that represent a Pet and return that instead. then you would not need to create any extra objects and your class would be secure.
It all depends on whether you have been taught how to use Java interfaces yet or not.
Join our real-time social learning platform and learn together with your friends!