Class A {
String x;
}
I have 2 interfaces I1 and I2.
Class C1 implements I1
Class C2 implements I2
Is there any way to only allow Class C2 to update x of Class A? i.e. is there any way by which classes implementing a particular interface update the members of Class A?
Classes implementing I1 should only be able to read the members of class A and they should not be allowed to update the members of class A.
I could see there are multiple checks that you will have to implement.
State of the object should be immutable when referenced using getter method. For e.g. if your getter method is returning object or collection, it shouldn't be modifiable. Otherwise whatever protection you provide at setter level can be defeated very easily.
Try to segregate authorization constraint from actual object. Possibly use Proxy pattern
.
Use StackTraceElement to identify calling class/method. Can be derived using Thread.currentThread().getStackTrace()
. This also protects your code from deceiving setter method by passing instance of authorised class.
On the whole, whether it's design flaw or necessity, if you decide in future to rectify this, you will be able to do that without leaving any footprints. The calling programs, won't have to undergo a change.