This is a very simple example where accessing directly could be dangerous
class Something{
public static final int MAX=123;
private int prop;
final void riskyMethod()
{
this.prop=800; //this is wrong
}
final void safeSetProp(int x)
{
if(x<MAX)
{
prop=x;
}
}
}
I know it could be done encapsulating “prop” in another class,
and defining it there as private, but that’s a lot of useless code overhead!
Is there a way to force the use of methods to access same class properties?
a keyword? any trick?
I confess I have done things like this to avoid accidental access by the same class
private int IKWIDprop; //IKWID = I Know What I am Doing
I am sure you could know a better approach =)
Regards!
This is your class, come on! You always know what you are doing. If you don’t, write tests. I understand you want to force the usage of getter instead of raw field in case at some point in the future the getter will be equipped with some extra logic. But because this is your class, you are fully responsible and capable of maintaining this code.
Bizzare Hungarian notation only clutters the code. Unit test your class to make sure nobody damages your work (including yourself). Nobody reads documentation and Javadocs, not to mention nobody will understand
TIASCWIAFDPUGIage(thisIsASpecialCaseWhenIAccessFieldDirectlyPleaseUseGetterInstead_Age), including you after a while.BTW if you force the usage of encapsulating getter inside your class, how does the getter itself access the field? So go back to earth and be reasonable. Having a strong suite of unit tests is much more helpful, reliable and provides better documentation.
UPDATE: Actually, there is a (sort of) clean way. You can use AspectJ, with few clever pointcuts, will catch raw private field access excluding some special cases. It can be executed at compile time to fail the build or at runtime. The pointcut would say something like: “each private field access from a method that is not annotated with
@ThisIsASettershould generate compile time error. Maybe somebody more fluent with AspectJ can write this?