Is it possible to violate Encapsulation by Reflection in ABAP? - oop

Is it possible to:
Read / Modify the content of a private member variable?
Call a private method?
..from a context where these are not in scope?
Not planning to do any architecture like this, i just want to know if it's possible.

ABAP is an interpreted language. So the interpreter is aware of anything anytime. Even with reflection (RTTI/RTTC) and/or dynamic calls you can not access private members out of scope.
However if you have declared friends, then the friends can access private members of course.

Since the debugger is written in ABAP and the debugger can display the contents of private members, the former is possible (if not easy - you have to do some really risky low-level stuff I'd not recommend for obvious reasons). For calling private methods, I'm not sure but I'd doubt that it's possible.

Related

Why to use access specifiers/Modifiers in Java?

I am learning Java and my question is Why to use access specifiers/Modifiers in Java? why we need to use Public, Private, Protected and Default access to class, Method or variables. If I am programmer then Obviously I know everything from program. If I am end user then I don't know what program is? Then from whom I am hiding details? Where the data hiding comes in picture? Please help me with some examples as point of programmer as well as as point of end user.
Hiding the internals of the object protects its integrity by preventing users from setting the internal data of the component into an invalid or inconsistent state.
A benefit of encapsulation is that it can reduce system complexity, and thus increases robustness, by allowing the developer to limit the inter-dependencies between software components. [1]
[1] http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming)
As point of software designer: practical and semantic reasons.
Variables describe an object instance's state. Protected variables are inherited. This is practical as classes in the inheritance chain can share structural similarities with each other. Non-inheriting variables remain private. Variables are only public when they are constants (public static final variables).
Methods describe an object's behaviour. The inheritance of protected and the usage of public methods is pretty much the same as with variables, except that while variables describe state, methods describe behaviour. One difference is the usage of package private methods, which approach is usually used inside frameworks.
If you do need a practical example, let's say the details of your FB password is stored as a private variable and your LoginID is stored as a protected variable in a FBDetails class...
Now anyone can inherit the FBDetails class to get your LoginID but apparently no one can access your password.

OOP: Should setters be private?

When writing getter/setters in classes, should the setters be private methods?
It might seem a bit redundant to have to write another method to set a variable but it seems like that might allow for a more maintainable code structure.
Setter is a method that is suppose to allow modifying internal state of an object without exposing that object directly. We can later include validation or other logic inside setter.
If your setter is private, you are missing the point. It's like having a door in your house that is always closed and doesn't even allow opening. Also inside the class you can simply access the field directly, why would you use a setter there?
Of course the real question is: should we have setters at all? The typical class these days holds a bunch of fields, auto-generated getters/setters and no logic. This is hardly a class. It's just a structure with awkward way of accessing elements. But that's not what you are asking for.
In General, I don't recommend "private" access for any member, maybe "protected". Usually, you or other programmer may require it in a descendant class.
Long Boring Descriptive Answer
Now, for accessors ("getters & setters"), its also depends on the syntax and implementation of properties on the programming language.
For Example, C++, or Java, I consider not have "real properties", and accesors, maybe required to have the same scope as the properties. (Unless using a template for properties).
C# & Delphi (Lazarus) have properties implemented, but, I don't like the way C# declare the accesors.
There are cases, where you may want a property not to be public, maybe "protected" or "package protected", and its accesors, the same access than the property.
I just work in some code in Object Pascal. Most properties where "public", and its accesors "protected", but, want to migrate that code to c++ or Java, so, I make the accesors "public", as well.
Quick Short Answer
Same access as the property, but, depends on the syntax of properties.
They should be public, if the intent is to allow them to be manipulated from an external object. That is the point of POJO implementation. (http://en.wikipedia.org/wiki/Plain_Old_Java_Object)
If you're looking to implement some other pattern, perhaps looking at the docs on Java Access Modifiers should be your first stop (http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html)
Usually you want setters/getters to be public, because that's what they are for: giving access to data, you don't want to give others direct access to because you don't want them to mess with your implementation dependent details - that's what encapsulation is about.
However there might be some cases where you want to restrict access to your data just to instances of the same class, but you still want to retain some control over the access to the data for whatever reason (bookkeeping, locking etc.) - in that case having private (or protected) setters/getters makes sense (from both code reuse and safety POV). However, you can't rely on the compiler to catch you doing something wrong then.

Where is the Friend access modifier intended to be used?

The only place I've seen the Friend modifier used is in the WinForms designer, as alluded to in Why is the modifier set to Friend in Winforms? and VB.NET: what does the 'friend' modifier do?.
The Friend modifier appears to be an almost arbitrarily wide access level that was created to solve some historic architectural problem in VB, I just wonder if anyone has a meaningful continued use for it?
I have had some desires to expose methods only to a given namespace so as to roll the functionalities of a related collection of objects together and manage any of their non-thread-safe methods, while exposing the safe public methods to a wider scope in the same assembly. This access level does not exist yet Friend does. Possibly a corollary question then, is my usage of assemblies and namespaces at odds with what is intended?
In many cases it is not possible to separate functionality into different assemblies because of the strict hierarchy that assemblies have, which leads to having groups of related but separate objects that have access to each other's unsafe methods.
Edit:
While I know the function of the modifier, I am curious as to what practical purposes people have for it as I have not come across a situation where it would be the right solution.
I use it in classes to prevent functions, methods or properties from being used outside of my assembly.
From inside an assembly, Friend and Public do the same thing, hence, it's friendly to the developer. But if the class is used from an outside assembly, everything that is marked Friend won't be available, whereas Public will be.
The C# equivalent is internal. The name internal probably gives a better definition than Friend of it's intended use.
Here is an arbitrary example. I have a DLL that contains a bunch of custom controls that all need to draw certain images:
Friend Class ControlDraw
Public Shared Sub DrawArrow(ByVal g As Graphics, ByVal r as Rectangle, _
ByVal ad As ArrowDirection, ByVal ac As Color)
//' Draw Special Arrow:
End Sub
End Class
I can use this code throughout all of the controls in my project. But when I publish the DLL and let others use it, the DrawArrow function is not available to the end user, just the controls from inside the project.
Why do this?
If it was Public, then I could never change the parameters without potentially breaking any consumers of the function. But since it's my own method, I can add another parameter for BackColor or whatever, and update all of my controls that use it from within my own project.
I am basically saying, a Friend class or function is just for me to worry about, not the end user. Once you make something Public to the outside world, you lose a little bit of control of it.
Also found this from an Eric Lippert answer on using Internal:
The point of internal is not that it makes life difficult for Bob. It's that it allows you to control what expensive promises Project A is making about features, lifetime, compatibility, and so on.
What you have is not a language problem but OOP dogma in general.
The Friend modifier might be confusing because it doesn't behave as it does in older languages such as C++. The reason why it doesn't behave the same way is because is not the same.
The Friend modifier gives access to the declared object in an assembly scope, which means that any class within the assembly can access that object but it will still not be usable for code consuming your assembly. If it helps look also at C# Internal Modifier.
As to why OOP goes against the C++ way of the Friend Modifier goes beyond my knowledge but perhaps this other SO question might help.

Should ecapsulated objects be public or private?

I'm a little unclear as to how far to take the idea in making all members within a class private and make public methods to handle mutations. Primitive types are not the issue, it's encapsulated object that I am unclear about. The benefit of making object members private is the ability to hide methods that do not apply to the context of class being built. The downside is that you have to provide public methods to pass parameters to the underlying object (more methods, more work). On the otherside, if you want to have all methods and properties exposed for the underlying object, couldn't you just make the object public? What are the dangers in having objects exposed this way?
For example, I would find it useful to have everything from a vector, or Array List, exposed. The only downside I can think of is that public members could potentially assigned a type that its not via implicit casting (or something to that affect). Would a volitile designation reduce the potential for problems?
Just a side note: I understand that true enapsulation implies that members are private.
What are the dangers in having objects exposed this way?
Changing the type of those objects would require changing the interface to the class. With private objects + public getters/setters, you'd only have to modify the code in the getters and setters, assuming you want to keep the things being returned the same.
Note that this is why properties are useful in languages such as Python, which technically doesn't have private class members, only obscured ones at most.
The problem with making instance variables public is that you can never change your mind later, and make them private, without breaking existing code that relies on directly public access to those instance vars. Some examples:
You decide to later make your class thread-safe by synchronizing all access to instance vars, or maybe by using a ThreadLocal to create a new copy of the value for each thread. Can't do it if any thread can directly access the variables.
Using your example of a vector or array list - at some point, you realize that there is a security flaw in your code because those classes are mutable, so somebody else can replace the contents of the list. If this were only available via an accessor method, you could easily solve the problem by making an immutable copy of the list upon request, but you can't do that with a public variable.
You realize later that one of your instance vars is redundant and can be derived based on other variables. Once again, easy if you're using accessors, impossible with public variables.
I think that it boils down to a practical point - if you know that you're the only one who will be using this code, and it pains you to write accessors (every IDE will do it for you automatically), and you don't mind changing your own code later if you decide to break the API, then go for it. But if other people will be using your class, or if you would like to make it easier to refactor later for your own use, stick with accessors.
Object oriented design is just a guideline. Think about it from the perspective of the person who will be using your class. Balance OOD with making it intuitive and easy to use.
You could run into issues depending on the language you are using and how it treats return statements or assignment operators. In some cases it may give you a reference, or values in other cases.
For example, say you have a PrimeCalculator class that figures out prime numbers, then you have another class that does something with those prime numbers.
public PrimeCalculator calculatorObject = new PrimeCalculator();
Vector<int> primeNumbers = calculatorObject.PrimeNumbersVector;
/* do something complicated here */
primeNumbers.clear(); // free up some memory
When you use this stuff later, possibly in another class, you don't want the overhead of calculating the numbers again so you use the same calculatorObject.
Vector<int> primes = calculatorObject.PrimeNumbersVector;
int tenthPrime = primes.elementAt(9);
It may not exactly be clear at this point whether primes and primeNumbers reference the same Vector. If they do, trying to get the tenth prime from primes would throw an error.
You can do it this way if you're careful and understand what exactly is happening in your situation, but you have a smaller margin of error using functions to return a value rather than assigning the variable directly.
Well you can check the post :
first this
then this
This should solve your confusion . It solved mine ! Thanks to Nicol Bolas.
Also read the comments below the accepted answer (also notice the link given in the second last comment by me ( in the first post) )
Also visit the wikipedia post

When do you write a private method, versus protected? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
If I'm writing a class, when do I make a method private, versus protected? In other words, how I can know in advance that a client programmer would never ever need to override a method? In a case where it's something that has external considerations, like a database connection?
public and protected methods form the 'interface' to your object, public for developers using (delegating to) your class, and protected for developers wishing to extend the functionality of your object by subclassing it.
Note that it's not necessary to provide protected methods, even if your class will be subclassed.
Both public and protected interfaces need careful thought, especially if this is an API to be used by developers outside your control, since changes to the interface can break programs that make assumptions about how the existing interface works.
private methods are purely for the the author of the object, and may be refactored, changed and deleted at will.
I would go for private by default, and if you find you need to expose more methods, have a careful think about how they will be used - especially if they are virtual–what happens if they are replaced completely with an arbitrary alternative function by another developer–will your class still work? Then design some appropriate protected which are useful for developers subclassing your object (if necessary), rather than exposing existing functions.
In other words, how I can know in
advance that a client programmer would
never ever need to override a method?
You cannot. And you don't need to. It is not your job to anticipate IF a developer might want to override a method, let alone how. Just assume he wants to and enable him to do so without having to touch your code. And for this reason, do not declare methods private if you don't have to.
If a developer feels he needs to adjust some functionality of your classes, he can pick from a number of structural and behavioral patterns to do so, e.g. Decorators, Adapters or by subclassing. Using these patterns is good, because it encapsulates the changes into the developer's own class and leaves your own code untouched. By declaring methods private, you make sure the developer will monkey with your class. And that is bad.
A perfect example is Zend Framework's DB adapter. They discourage the use of persistent connections and their adapters provide no mean to this end. But what if you'd want to have this nonetheless and the adapter method was marked private (it isn't, but what if)? Since there is no way to overwrite the method, you would (yes, you would) change the adapter code right within it's class or you'd copy & paste the code into your own adapter class, effectively duplicating 99% of the class just to change a single function call. Whenever there is an update to this adapter, you either would lose your changes or you wouldn't get it (in case you c&p'd). Had it been marked protected (as it is), you could just have written a pConnectAdapter subclass.
Moreover, when subclassing, you are effectively saying subClass is a parentClass. Thus, you can expect the derived class to have the same functionality as the parentClass. If there is functionality in the parentClass that should not be available in the subClass, then disabling it conceptually belongs to the subClass.
This is why I find it much better practise to default all methods and properties to protected visibility and only mark those methods (not properties though) supposed to allow interaction with my class from another class or script as public, but only a few things private. This way, I give the developer the choice of using my class as I intended it to be used and the option to tweak it. And if he breaks something in the process, it is very likely his fault then, not mine.
Update: since I wrote this four years ago I have come to the conclusion that defaulting things to protected instead of private often leads to suboptimal subclasses. This is because people will start to use whatever you provided as protected. This in turn means you have to consider all these methods as API and may not change them at will. As such, it's better to carefully consider what extensions points you want to provide and keep the everything else private. See http://fabien.potencier.org/article/47/pragmatism-over-theory-protected-vs-private for a similar view.
I typically will start at the lowest level. If you're unsure make it private. Then as needed you can make things protected or public.
The idea being it is not a breaking change to go from private to protected but it could be a breaking change to go the other way.
Don't think of the private/protected/public thing as if a programmer would ever "need" a method. Think of it as if you want to allow them access to it.
If you think they should be allowed to change the DB Connection String then make it public.
I always make all methods private as default. This is to keep the interface clean and easy to maintain.
It is much harder to change or hide an already visible method than to make a private method more visible. At least if you need to be compatible with existing client code.
In other words, how I can know in
advance that a client programmer would
never ever need to override a method?
If you don't know assume they will need to. If that's fine by you (ie, if you think they should be able to) then use protected; otherwise use private.
Private members are used to encapsulate the inner workings of your class. Use them to hold data that only you want to be able to access. For example, let's say you have a field called _name and a getter/setter named GetName()/SetName(name). Maybe you want to do some syntax checking on name before you allow the SetName to succeed, else you throw an exception. By making _name private, you ensure that this syntax checking will occur before any changes to name can occur (unless you yourself change _name in your own class, in your own code). By making it protected, you're saying to any potential future inheritor of your class, "go ahead and monkey with my field."
In general, protected is used sparingly and only in specialized cases. For example, you might have a protected constructor that exposes some additional construction functionality to child classes.
I typically just make everything private and refactor when I need to call it from a base class.
Except when I feel lazy and do everything protected that isn't definitely dangerous.