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.
Related
I am just starting to learn the dart programming language.
Something that I have stumbled on, is the less conventional way of doing access modifiers such as public / private (at least compared to my experience with C# , Java, and C++).
As I understand it, prefixing your member variables with with _ character, will make the private to that lib (file).
So is it common practice to just enforce a single class to a single file/lib, to enforce a behaviour similar to class level public/private?
Will that also result in all descendants of a class having to be in the same class.
If this is not common practice, how exactly do you do OOP in dart? How do you implement OOP concepts like encapsulation and composition in dart?
There is no "class private" in Dart, only "library private".
The underlying design is based on the idea that a single library is one entity, created and edited by the same people with the same goals. You should not need to defend yourself against your co-authors. After all, if you try to hide something from a co-author, they can just change your class to make it public anyway. So, a full library is the granularity of access management.
It is easy to make multiple small libraries, so you can make a library contain only things that are actually related. If you do that, then, again, you shouldn't need to prevent access between the objects, because they should be designed together, so the access is probably intended.
A library is also the granularity of implementation. A library exposes its public interfaces, but the implementation details are (library) private, so changing implementation details should not break other libraries. That makes it safe to change the implementation; as long as you only change private things, you are guranteed that no other library will break.
That is, private members can be seen as implementation details. If you need to access the implementation of another class, not just its public interface, then you are deeply interdependent on that implementation, and the code deserves to be in the same library.
Libraries with few related and interdependent classes, and sometimes a single class, is the way to go, and what people usually do.
If you then want your package library to expose a lot of classes, you can export those individual libraries.
As for descendants of a class: Dart does not have protected access restriction, so if a subclass needs access to something, it needs to either be public, or be in the same file. There are tricky workarounds, but it's usually simpler go for one of those two. Again, if another class needs access to something that is not public, then it is related to the implementation, and should be kept close to that implementation.
Encapsulation means preventing access to implementation details. You do that at the library level. Inside the library, it's your own responsibility to only do things you intend to do. Composition works like in any other OO language.
From Dart documentation:
Unlike Java, Dart doesn’t have the keywords public, protected, and private.
If an identifier starts with an underscore _, it’s private to its library.
Libraries not only provide APIs, but are a unit of privacy: identifiers that start with an underscore _ are visible only inside the library.
This answer may help you.
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.
I'm currently learning C# and I was wondering, what is the point of declaring classes / methods private? Who are we hiding / limiting access to these classes.
Because if someone was editing the source they could just change the tag from private to public. I'm not sure how a user will be able to access these methods and what problems it would cause.
tldr; What's the point of access modifiers.
Member visibility, as this feature is often called, is not a security feature. It is a convenience for the programmer, designed to help limit cross-class dependencies. By declaring a member private, you prevent other code from accessing it directly. This has two advantages:
if you find that a member variable gets manipulated in a way you did not intend, the amount of code you have to check is significantly smaller when the variable is private
you can change the inner workings of a class (everything that is declared private) without breaking the interface (everything declared public)
Member visibility is probably the most important language feature in realizing encapsulation, one of the core principles of object-oriented programming.
This is a basic OO concept - encapsulation and has mostly nothing to do with security per se. To quote from Wikipedia (emphasis mine):
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 interdependencies between software
components.
It keeps your code tidy. You separate your code into a public interface, and private internals.
That way, you can change your internals without fear of breaking code that depends on your class. You can also safely assume that no other code has modified your internal state while you weren't looking.
Access modifiers are used for encapsulation: they allow you to arrange
your code in packages and classes, and have only an "official" public
interface visible to the outside, while hiding the implementation
details (which you want to do, so that you can later change it without
telling anyone).
This is especially (only?) important, when you release code as a
library for other programmers to use. Even if the code is only used in
your own program, it helps to structure larger programs into several
packages. - Thilo
You can write code in 2 ways: designed for extension and designed for usage as it is.
You may or may not have access to source code.
Access modifiers are most important in code designed for extension where the client programmer (the programmer which extends and uses your code) needs to have access only to the API you expose - basically, to the interface you offer by using these access modifiers.
Access modifiers are used for encapsulation, so that the internals of an object/class are hidden from outside users or classes. This prevents users from accidentally or intentionally breaking an object/class by modifying its instance variables and/or functions.
Encapsulation is an important part of the Open/closed principle, which refers to a class being "open for extension" but "closed for modification". This principle allows the extension of classes without fear that the API of an class may change in the future.
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 5 years ago.
Improve this question
I've been searching and I know the theoretic difference.
public - Any class/function may access the method/property.
protected - Only this class and any subclasses may access the method/property.
private - Only this class may access the method/property. It won't even be inherited.
That's all fine and well, the question is, what's the practical difference between them? When would you use private and when would you use protected? Is there a standard or acceptable good practice over this one?
Up until now, to retain the concept of inheritance and polymorphism, I use public for anything that should be accessed from the outside (like constructors and main class functionality), and protected for internal methods (logic, helper methods etc). Am I on the right track?
(Note that this question is for me, but also for future reference as I haven't seen a question like this one SO).
No, you're not on the right track. A good rule of thumb is: make everything as private as possible. This makes your class more encapsulated, and allows for changing the internals of the class without affecting the code using your class.
If you design your class to be inheritable, then carefully choose what may be overridden and accessible from subclasses, and make that protected (and final, talking of Java, if you want to make it accessible but not overridable). But be aware that, as soon as you accept to have subclasses of your class, and there is a protected field or method, this field or method is part of the public API of the class, and may not be changed later without breaking subclasses.
A class that is not intended to be inherited should be made final (in Java). You might relax some access rules (private to protected, final to non-final) for the sake of unit-testing, but then document it, and make it clear that although the method is protected, it's not supposed to be overridden.
Let me preface this by saying I'm talking primarily about method access here, and to a slightly lesser extent, marking classes final, not member access.
The old wisdom
"mark it private unless you have a good reason not to"
made sense in days when it was written, before open source dominated the developer library space and VCS/dependency mgmt. became hyper collaborative thanks to Github, Maven, etc. Back then there was also money to be made by constraining the way(s) in which a library could be utilized. I spent probably the first 8 or 9 years of my career strictly adhering to this "best practice".
Today, I believe it to be bad advice. Sometimes there's a reasonable argument to mark a method private, or a class final but it's exceedingly rare, and even then it's probably not improving anything.
Have you ever:
Been disappointed, surprised or hurt by a library etc. that had a bug that could have been fixed with inheritance and few lines of code, but due to private / final methods and classes were forced to wait for an official patch that might never come? I have.
Wanted to use a library for a slightly different use case than was imagined by the authors but were unable to do so because of private / final methods and classes? I have.
Been disappointed, surprised or hurt by a library etc. that was overly permissive in it's extensibility? I have not.
These are the three biggest rationalizations I've heard for marking methods private by default:
Rationalization #1: It's unsafe and there's no reason to override a specific method
I can't count the number of times I've been wrong about whether or not there will ever be a need to override a specific method I've written. Having worked on several popular open source libs, I learned the hard way the true cost of marking things private. It often eliminates the only practical solution to unforseen problems or use cases. Conversely, I've never in 16+ years of professional development regretted marking a method protected instead of private for reasons related to API safety. When a developer chooses to extend a class and override a method, they are consciously saying "I know what I'm doing." and for the sake of productivity that should be enough. period. If it's dangerous, note it in the class/method Javadocs, don't just blindly slam the door shut.
Marking methods protected by default is a mitigation for one of the major issues in modern SW development: failure of imagination.
Rationalization #2: It keeps the public API / Javadocs clean
This one is more reasonable, and depending on the target audience it might even be the right thing to do, but it's worth considering what the cost of keeping the API "clean" actually is: extensibility. For the reasons mentioned above, it probably makes more sense to mark things protected by default just in case.
Rationalization #3: My software is commercial and I need to restrict it's use.
This is reasonable too, but as a consumer I'd go with the less restrictive competitor (assuming no significant quality differences exist) every time.
Never say never
I'm not saying never mark methods private. I'm saying the better rule of thumb is to "make methods protected unless there's a good reason not to".
This advice is best suited for those working on libraries or larger scale projects that have been broken into modules. For smaller or more monolithic projects it doesn't tend to matter as much since you control all the code anyway and it's easy to change the access level of your code if/when you need it. Even then though, I'd still give the same advice :-)
Stop abusing private fields!!!
The comments here seem to be overwhelmingly supportive towards using private fields. Well, then I have something different to say.
Are private fields good in principle? Yes. But saying that a golden rule is make everything private when you're not sure is definitely wrong! You won't see the problem until you run into one. In my opinion, you should mark fields as protected if you're not sure.
There are two cases you want to extend a class:
You want to add extra functionality to a base class
You want to modify existing class that's outside the current package (in some libraries perhaps)
There's nothing wrong with private fields in the first case. The fact that people are abusing private fields makes it so frustrating when you find out you can't modify shit.
Consider a simple library that models cars:
class Car {
private screw;
public assembleCar() {
screw.install();
};
private putScrewsTogether() {
...
};
}
The library author thought: there's no reason the users of my library need to access the implementation detail of assembleCar() right? Let's mark screw as private.
Well, the author is wrong. If you want to modify only the assembleCar() method without copying the whole class into your package, you're out of luck. You have to rewrite your own screw field. Let's say this car uses a dozen of screws, and each of them involves some untrivial initialization code in different private methods, and these screws are all marked private. At this point, it starts to suck.
Yes, you can argue with me that well the library author could have written better code so there's nothing wrong with private fields. I'm not arguing that private field is a problem with OOP. It is a problem when people are using them.
The moral of the story is, if you're writing a library, you never know if your users want to access a particular field. If you're unsure, mark it protected so everyone would be happier later. At least don't abuse private field.
I very much support Nick's answer.
I read an article a while ago that talked about locking down every class as much as possible. Make everything final and private unless you have an immediate need to expose some data or functionality to the outside world. It's always easy to expand the scope to be more permissible later on, but not the other way around. First consider making as many things as possible final which will make choosing between private and protected much easier.
Make all classes final unless you need to subclass them right away.
Make all methods final unless you need to subclass and override them right away.
Make all method parameters final unless you need to change them within the body of the method, which is kinda awkward most of the times anyways.
Now if you're left with a final class, then make everything private unless something is absolutely needed by the world - make that public.
If you're left with a class that does have subclass(es), then carefully examine every property and method. First consider if you even want to expose that property/method to subclasses. If you do, then consider whether a subclass can wreak havoc on your object if it messed up the property value or method implementation in the process of overriding. If it's possible, and you want to protect your class' property/method even from subclasses (sounds ironic, I know), then make it private. Otherwise make it protected.
Disclaimer: I don't program much in Java :)
When would you use private and when would you use protected?
Private Inheritance can be thought of Implemented in terms of relationship rather than a IS-A relationship. Simply put, the external interface of the inheriting class has no (visible) relationship to the inherited class, It uses the private inheritance only to implement a similar functionality which the Base class provides.
Unlike, Private Inheritance, Protected inheritance is a restricted form of Inheritance,wherein the deriving class IS-A kind of the Base class and it wants to restrict the access of the derived members only to the derived class.
Well it is all about encapsulation if the paybill classes handles billing of payment then in product class why would it needs the whole process of billing process i.e payment method how to pay where to pay .. so only letting what are used for other classes and objects nothing more than that public for those where other classes would use too, protected for those limit only for extending classes. As you are madara uchiha the private is like "limboo" you can see it (you class only single class).
I'm a student looking for resources which can help me further understand how to properly apply access modifiers to members/types as I code them.
I know (in C#) what restrictions access modifiers like private, public, protected, etc. put into place. When I code my own little projects I have a tendency to just make everything public. I'm certain this is an absolutely horrible practice as it just tosses encapsulation out the window. I just never know when it's correct to use something like internal vs. private.
Does anyone have any good resources to aid me in understanding the proper use of access modifiers?
This is an experience type question. Start from the level of least privilege and promote up as necessary.
In other words, make everything private. Until you discover that it needs to be promoted to protected or public. Over time you will get a feel for the intended and later discovered usages of your classes.
I simply make everything's access as restrictive as possible:
Private by default
Otherwise internal, if it's an API exposed to other classes within this assembly
Or, public if it's an API exposed outside the assembly
Or, protected if it's intended to be called only from subclasses.
Start putting everything private. If you feel the need, change the modifier accordingly, until you have the feeling to choose the right type.
To make things easier, try using TDD, or you might get into even more trouble when you get to write unit tests...
Any kind of tutorial or teaching material will give you the same guidance, namely the one that the other postings already gave you. So don't expect much useful information in this specific matter from "resources".
The primary resource that goes beyond that is code that other people have written. Take a large C# project (e.g. Mono, or SharpDevelop), and study how they specifically followed the principles that have been explained to you. Also, if you have a specific class to design, try to think of a similar class in the system libraries, and try to find out how it is implemented (either by looking at the Mono source, or by using the .NET reflector).
You should start by thinking about the interface of a class, that is the necessary and sufficient set of routines it needs to expose in order to achieve its purpose. Make that public. Everything else should be private.
I have a tendency to make everything protected that is not public. Leaving the freedom of my users to do whatever they want with my class. If their class breaks that would be their problem.
Every time you inherit from a class you need to know how it works even if oop is about hiding the implementation. You can hide the implementation, but you won't hide the documentation.