I know it sounds like a stupid question, but how safe is your API if you can access private properties and change them?
views:
88answers:
7That's right, its not totally safe, but reflection can also be immensely useful. But you can still only set a property if it has a setter, so it isn't all "bad".
Well, in .NET at least, you can disallow reflection by using .NET permissions.
Also, the purpose of visibility levels in classes and class members is not only the access security. It is also a means to organize and document your code: when you see a private member you know that it is not intended to be used outside the class, and while maybe you can use it via reflection, you will normally not do it as it can cause unexpected behavior in your application.
Anyway I find this question sort of like "What's the purpose of doors having locks if I can smash them with a big enough hammer?" :-)
Eventhough reflection is very useful indeed, it's considered an indirect method of changing properties and not nesseserily a method that should be endorsed or supported by your API.
Having said that, by setting a private property, ensures that it won't be changed by those accessing it by normal means
In a language not supporting reflection there's always a possibility of circumventing API through direct memory access.
Encapsulation is not about protecting your API from misuse, it is about hiding away parts of code that are subject of change. If client code uses official interface - it will continue to work after such a change. If not, it was author of this code who just have shoot his foot.
What's the point of having locks on your door when people can just kick the door down? Using reflection requires more skill and more effort. For the most part the code is fine. Reflection doesn't work well in non full trust environments anyway.
The use of private properties is with reflection the same as without it, but if one considers using reflection to access private members in a third-party class, he should be very sure to know what he does - and he sure knows that this can break operability.
You can prevent access to private properties by installing a SecurityManager. So if you need it, you can really make it private (and pay the price: some 3rd party libraries won't work anymore).
Like laws, private
are a price tag. They say "if you don't follow the rules which I impose, there'll be a price to pay." It doesn't mean you must follow the rules (just like outlawing killing people didn't stop murder).