In what kind of scenarios would we declare a member function as a 'friend function' ?..What exact purpose does 'friend function' which defies one of central concept of 'Encapsulation' of OOP serve?
You would use a friend function for the same sort of reasons that you would use a friend class, but on a member function (rather than entire class) basis. Some good explanations are in this thread.
While friend functions and classes do violate encapsulation, they can be useful in some scenarios. For example, you may want to allow a test harness to access class internals to allow you to do whitebox testing. Rather than opening up the entire class to the test harness, you could open up a particular function which accesses the internals required by the test harness. While this still violates encapsulation, it's less risky than opening up the entire class.
Also see this article for some more information about friend classes and functions.
Friend functions and classes do not violate encapsulation when you are trying to build an abstraction or interface that must physically span multiple C++ classes or functions! That is why friend was invented.
Those types of cases don't come up often, but sometimes you are forced to implement an abstraction or interface with disparate classes and functions. The classic example is implementing some type of complex number class. The non-member operator functions are given friendship to the main complex number class.
I also recall doing this when programming with CORBA in C++. CORBA forced me to have separate classes to implement CORBA servants. But for a particular part of our software, I needed to marry these together as one interface. Friendship allowed these two classes to work together to provide a seamless service to one part of our software.
Having the ability to mark a particular member function on another class as a friend to your class may seem even stranger, but it is just a way of tightly controlling the friendship. Instead of allowing the entire other class "in" as your friend, you only allow one of its member functions access. Again, this isn't common, but very useful when you need it.
See C++ FAQ Lite:
Sometimes friends are syntactically better (e.g., in class Fred, friend functions allow the Fred parameter to be second, while members require it to be first). Another good use of friend functions are the binary infix arithmetic operators. E.g., aComplex + aComplex should be defined as a friend rather than a member if you want to allow aFloat + aComplex as well (member functions don't allow promotion of the left hand argument, since that would change the class of the object that is the recipient of the member function invocation).
Sometimes public/private/protected protection level is not quite enough for real world situations. So thus we give a small get-out clause that helps without having to make methods publicly accessible.
I personally use this the same way that Java uses the 'Package' protection level.
If I have a class in the same package that needs access I will consider using friend. If it is a class in another package then I will wonder why on earth is this other class needing access and look at my design.
One point that I find relevant: member classes have access to the private parts of the containing class. This may sometimes be a better alternative to "friend".
class A
{
private:
int b;
public:
class MemberNotFriend {
public:
static void test() {
A a;
a.b = 0;
}
};
};
void test()
{
A::MemberNotFriend::test();
}
Here is a simple, concrete example of how I am using a friend function:
I have a game where each sprite object stores its info like X,Y position as private members.
However, I wish to separate the game objects from the rendering: a game object does not need the exact details of how it is rendered. A game object only stores game state, and this game state may be rendered in a number of different ways.
Thus the game object class has a friend function: render(). The render() function is implemented outside the game object class, but it can access the X,Y position position membefrs as needed to render the game object.
Related
I'm working on the graphics code for a game library in Java. I made package called com.engine.graphics. In this package, I have a lower-level class called VertexArrayObject. This class is used by "client-level" classes that clients will use; however, I do not want to give clients access to VertexArrayObject, since it would only serve to complicate their understanding of my library. Thus, I gave VertexArrayObject the default access specifier; that way, only classes within com.engine.graphicshave access to it, and also tells clients that they do not need to know what it is.
Just like there is this standard convention for Java, I figured there must be some standard convention for C++ for dealing with this; however, my internet searches have yielded no results.
So, my question is, what is the convention? And if there isn't one, what is the best approach?
C++ does not have a notion of 'package' thus no 'package-protection' is technically possible. (There is a proposition for modules, but it will not be included even in the upcoming C++17 standard).
There are many ways of hiding the class from external world or restricting access to it, on syntax level you can resort to:
nested classes which may be declared private (you should be familiar with them from Java, except they are "static" by default and cannot access non-static enclosing class members) link;
friend classes that can access any private members of the given class link;
friend functions if you want to restrict access to only certain functions, including member functions of another class;
private/protected inheritance where only the class members are aware of the inheritance link.
Having a lot of friend classes and functions is a mess, but there is a reason for requiring explicit listing of those: they break the encapsulation principle.
Finally, you can use either "private implementation" idiom (aka pimpl, aka opaque pointer) that consists in defining a visible class holding a pointer to the implementation class and forwarding all calls while the implementation class is defined in a separate cpp file or the façade design pattern.
Chose whatever seems appropriate for the given class relation. Standard library tends to prefer nested classes while Qt, a popular graphic library, relies on pimpl.
In the book The C++ Programming Language, by Bjarne Stroustrup, the author introduces
a class Matrix which has to implement a function inv(). In section 11.5.1, he talks
about two possibilities of doing that. One is to make a member function and other is to
make a friend function inv(). Then towards the end of section 11.5.2, where he talks about
making the choice of whether to use a friend or a member function, he says:
If inv() really does invert Matrix m itself, rather than returning a new Matrix that
is the inverse of m, it should be a member.
Why is it so? Can't a friend function change the state of the Matrix and return the
reference to that matrix? Is it because of the possibility of passing a temporary matrix
when we call the function?..
To be honest, I think the only reasons to make such a decision are syntactic convenience and tradition. I'll explain why by showing what are (not) the differences between the two and how these differences matter when making a decision.
What differences are there between non-member friend functions and public member functions? Not much. After all, a member function is just a regular function with a hidden this parameter and access to the class's private members.
// what is the difference between the two inv functions?
// --- our code ---
struct matrix1x1 { // this one is simple :P
private:
double x;
public:
//... blah blah
void inv() { x = 1/x; }
friend void inv(matrix1x1& self) { self.x = 1/self.x; }
};
matrix1x1 a;
// --- client code ---
// pretty much just this:
a.inv();
// vs this:
inv(a);
void lets_try_to_break_encapsulation(matrix1x1& thingy) {
thingy.x = 42; // oops, error. Nope, still encapsulated.
}
They both provide the same functionality, and in no way do they change what other functions can do. The same internals get exposed to the outside world: there's no difference in terms of encapsulation. There's absolutely nothing that other functions can do differently because there's a friend function that modifies private state.
In fact, one could write most classes with most functions as non-member friend functions (virtual functions and some overloaded operators must be members) providing the exact same amount of encapsulation: users cannot write any other friend function without modifying the class, and no function other than the friend functions can access private members. Why don't we do that? Because it would be against the style of 99.99% of C++ programmers and there's no great advantage to be taken from it.
The differences lie in the nature of the functions and the way you call them. Being a member function means you can get a pointer to member function from it, and being a non-member function means you can get a function pointer to it. But that's rarely relevant (especially with generic function wrappers like std::function around).
The remaining difference is syntactic. The designers of the D language decided to just unify the whole thing and say that you can call a member function directly by passing it an object like inv(a), and call a free function as a member of its first argument, like a.inv(). And no class suddenly got badly encapsulated because of that or anything.1
To address the particular example in the question, should inv be a member or a non-member? I'd probably make it a member, for the familarity argument I outlined above. Non-stylistically, it doesn't make a difference.
1. This is unlikely to happen in C++ because at this point it would be a breaking change, for no substantial benefit. It would, for an extreme example, break the matrix1x1 class I wrote above because it makes both calls ambiguous.
The encapsulation philosophy inherent to OOD (which C++ tries to promote) dictates that object state can only be modified from within.
It is syntactically correct (the compiler allows it) but it should be avoided.
It is error prone to let elements throughout the system alter each other without using predefined interfaces.
Object storage and functionality could change and looking around for code (that might be huge) that uses a specific part of an object would be a nightmare.
There are two opposing arguments regarding using friends:
One side says friends reduces encapsulation because now you're letting external entities access the internals of a class and the internals should only be modified by member methods.
The other side says that friends could actually increase encapsulation, since you can give access to the internals of a class to a small set of external entities, thus obviating the need to make internal class attributes public to everyone so these external entities can access/manipulate them.
Both sides could be argued, but I tend to agree with the first option.
As for your question, its as PherricOxide mentioned in his comment: If the internal attributes of a class need to be modified, its better that that be done by a member method, thus enforcing encapsulation. This is inline with the first option mentioned above.
This question title is taken from the title of item #23 in Effective C++ 3rd Edition by Scott Meyers. He uses the following code:
class WebBrowser {
public:
void clearCache();
void clearHistory();
void removeCookies();
//This is the function in question.
void clearEverything();
};
//Alternative non-member implementation of clearEverything() member function.
void clearBrowser(WebBrowser& wb) {
wb.clearCache();
wb.clearHistory();
wb.removeCookies();
};
While stating that the alternative non-member non-friend function below is better for encapsulation than the member function clearEverything(). I guess part of the idea is that there are less ways to access the internal member data for the WebBrowser if there are less member functions providing access.
If you were to accept this and make functions of this kind external, non-friend functions, where would you put them? The functions are still fairly tightly coupled to the class, but they will no longer be part of the class. Is it good practice to put them in the class's same CPP file, in another file in the library, or what?
I come from a C# background primarily, and I've never shed that yearning for everything to be part of a class, so this bewilders me a little (silly though that may sound).
Usually, you would put them in the associated namespace. This serves (somewhat) the same function as extension methods in C#.
The thing is that in C#, if you want to make some static functions, they have to be in a class, which is ridiculous because there's no OO going on at all- e.g., the Math class. In C++ you can just use the right tool for this job- a namespace.
So clearEverything is a convenience method that isn't strictly necessary. But It's up to you to decide if it's appropriate.
The philosophy here is that class definitions should be kept as minimal as possible and only provide one way to accomplish something. That reduces the complexity of your unit testing, the difficulty involved in swapping out the whole class for an alternate implementation, and the number of functions that could need to be overridden by sub-classes.
In general, you shouldn't have public member functions that only invoke a sequence of other public member functions. If you do, it could mean either: 1) you're public interface is too detailed/fine-grained or otherwise inappropriate and the functions being called should be made private, or 2) that function should really be external to class.
Car analogy: The horn is often used in conjunction w/ slamming on your brakes, but it would be silly to add a new pedal/button for that purpose of doing both at once. Combining Car.brake() and Car.honk() is a function performed by Driver. However, if a Car.leftHeadLampOn() and Car.rightHeadLampOn() were two separate public methods, it could be an example of excessively fine grained control and the designer should rethink giving Driver a single Car.lightsOn() switch.
In the browser example, I tend to agree with Scott Meyers that it should not be a member function. However, it could also be inappropriate to put it in the browser namespace. Perhaps it's better to make it a member of the thing controlling Web browser, e.g. part of a GUI event handler. MVC experts feel free to take over from here.
I do this a lot. I've always put them into the same .cpp as the other class member functions. I don't think there is any binary size overhead depending where you put them though. (unless you put it in a header :P)
If you want to go down this route the imlementation of clearEverything should be put in both the header (declaration) and implementation of the class - as they are tightly coupled and seems the best place to put them.
However I would be inclined to place them as a part of the class - as in the future you may have other things to clear or there may be a better or faster implementation to implement clearEverythingsuch as droppping a database an just recreate the tables
A class having a member function which does not operate on the class's data members ( directly or indirectly), is it decreased encapsulation, tighter coupling, or lower cohesion? Why?
EDIT:
class Data
{
private:
int value_;
public:
Data(int value) : value_(value) {}
int compute(int coef)
{
check(coef);
return coef * value_;
}
void check(int n)
{
if (n < 0 || n > 344) {
throw string("Invalid coef");
}
}
};
The check member functionn verifies the validity of the parameter passed to the compute member function but it has nothing to do with the data members of Data
It is all three. You decrease encapsulation because the function could operate on the class's data members. You give it access to doing so even though it is unnecessary, thereby violating encapsulation. And for much the same reason, it results in lower cohesion and tighter coupling (the class becomes a grouping of functionality that seemingly has little reason to be grouped together.
In C++, free (non-member) functions are generally preferred in cases like this.
I'd say decreased encapsulation, because you give this class a member function which really doesn't belong there. Other two choices are more related to class vs other classes behaviour.
Anyway, I think it's highly debatable.
If a member function does not operate on class's data members then either it should be static or it should not be a member of the class.
In a case like this, you should ask yourself: "Why is this function a member of the class?" If it does something that only makes sense in the context of this particular class, then you make it static or at least const, and maybe even private.
On the other hand, if the function makes sense outside the context of the class, or, worse, if it is used outside the context of the class, then it reduces cohesion and increases coupling. It reduces cohesion, because it does not logically belong to the class of which it is a member. It increases coupling because while it may be used outside the context of its class, that class must nevertheless be known to the caller of the function. In this case, the function should simply not be a member of the class. Then there is no impact on cohesion or coupling.
I don't think it has any impact on encapsulation, though, since it does not expose any class members that are not already exposed.
Edit:
In your particular case check() should be private and either static or const. compute() should be const.
I'll give an example
Let's say you build a class called Angle to haul around angles in different units.
Having a sin() function on the class would be worthless and just bloat the class interface whereas that function should simply be a separate free function.
Read this link on the Interface Principle: http://www.gotw.ca/publications/mill02.htm
That depends. If the method needs access to anything private or protected then it needs to be a member or a friend of the class. That being said, you should always limit as much as possible the number of entities having access to the class' internals, because each entity can introduce bugs. Sometimes you can eliminate a private or protected member, and if that eliminates the original method's need for privileges then you can extract it outside the class.
If a method belongs in the class (something only you can judge) then it should be part of the class' interface. Remember though that being part of the class' interface doesn't imply being a member of the class. What reduces cohesion and encapsulation is not a method being a member but a method having more privileges than it needs. The same holds for increasing coupling and reduced information-hiding.
And yet that being said, there is an interesting debate about the tradeoffs between humane interfaces and minimal interfaces. This relates here, in that you might have a function that serves as a mere inline (alias) call for another function, in making an interface more intuitive. Such a function doesn't need any member access whatsoever but in C++ it's needed for an intuitive call as a member -- should you value intuitive interfaces and be part of the humane interface school of thought.
In your revised question (with the code), the magic numbers in check should be static const int in the class (and check should be a static member).
Another option would be to construct the class with constraints as parameters, and private members. Then check would not be static but again it would need to access class members.
You need to post an example that both exhibits good design and meets your stated limitations. I doubt that can be done. To me, what you have described is a code smell as such a function should always be free.
As all three expressions proposed "decreased encapsulation", "tighter coupling" and "lower cohesion" are a mesure of a program change (there is source before and a source after), it's not possible to answer your question.
Basically I'm saying Tighter coupling than what ? Duh ?
If you are asking about your proposed version and the use of an external function for check instead, I believe others have already answered.
About coupling and Cohesion you may want to read that
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
When should you use 'friend' in C++?
I was brushing up on my C++ (I'm a Java developer) and I came across the friend class keyword which I had forgotten about for a while. Is this one of those features that's just part of the kitchen sink, or is there a good reason for doing this rather than just a vanilla getter? I understand the difference in that it limits who can access the data, but I can't think of a scenario when this would be necessary.
Note: I've seen a similar question, but specifically I'm asking, is this just an advanced feature that adds no real value except to confuse people looking at you're code until they realize what you're doing?
I agree with the comments that say the friend keyword can improve encapsulation if used wisely. I'd just add that the most common (legitimate!) use for friend classes may be testing. You may want a tester class to have a greater degree of access than other client classes would have. A tester class could have a good reason to look at internal details that are deliberately hidden from other classes.
In my experience, the cases when friend (or mutable, which is a little similar) to actually enhance encapsulation of data are rare compared with how often it's used to break encapsulation.
It's rarely useful to me but when I do use it it's for cases in which I've had to split a class that was formerly a single class into two separate classes that need to access some common data/functionality.
Edit to respond to Outlaw Programmer's comment: We absolutely agree on this. One other option apart from friend'ing classes after splitting them is to make public accessors, which sometimes break encapsulation! I think that some people think that friendly classes somehow breaks encapsulation because they've seen it used improperly a lot, and many people probably never see code where it's been used correctly, because it's a rare thing. I like your way of stating it though - friendliness is a good middle ground between not allowing you to split up your class and making EVERYTHING accessible to the public.
Edit to respond to David Thornley: I agree that the flexibility that C++ allows you to do things like this is a result of the design decisions that went into C++. I think that's what it makes it even more important to understand what things are generally good and bad style in flexible languages. Java's perspective is that you should never have friend classes so that these aren't provided, but as C++ programmers it's our responsibility as a community to define appropriate use of these very flexible but sometimes misused language constructs.
Edit to respond to Tom: Mutable doesn't necessarily break encapsulation, but many of the uses of the mutable keyword that I've seen in real-life situations break encapsulation, because it's much more common to see people breaking encapsulation with mutable than to actually find and understand a proper use of mutable in the first place.
When you wish that one class (Factory) be responsible for creating instances of another class (Type). You can make the constructor of the Type private and thus make sure that only the Factory can create Type objects. It is useful when you wish to delegate the checks to some other class which could serve as a validator.
Just one usage scenario.
P.S. Really missing the "friend" keyword in C#...
A concrete instance would be a class factory, where you want one class to only be created through another factory class, so you make the constructors private, and the factory class a friend of the produced class.
It's kinda' like a 2" 12-point 3/4"-drive socket - not terribly common, but when you need it, you're awfully glad you have it.
Helps with Memento design pattern
The FAQ's section about friends: here
The FQA's section about friends: here
Two different points of view about friend.
I look at the friend construct as one of those features of the language that should be used in rare occasions, but that doesn't make it useless. There are several patterns that call for making friend classes, many of them already on this site in that "Related" bar on the right. ====>
Friendship is used when you have multiple classes and/or functions that work together to provide the same abstraction or interface. The classic example is implementing some kind of numerical class, and all the non-member operator functions (*, -, +, <<, etc) are given friendship so that they can work on the private data of the numerical class.
Such use cases are somewhat rare, but they do exist, and friend is very useful.
Here is one example, of several, I'm sure, where a friend class can be legitimately used without disregarding the reasons for encapsulation.
MyClass inherits from GeneralClass. MyClass has gotten big, so you created HelperClass to encapsulate some of the function of MyClass. However, HelperClass needs access to some protected functions in GeneralClass to properly perform it's function, so you make HelperClass a friend to MyClass.
This is better than exposing the protected functions, because they don't need to be available to everybody, but it helps keep your code organized in an OOP way to keep MyClass from getting too complex. It makes sense, because although HelperClass isn't concretely related to MyClass by inheritance, it does have some sort of logical connection to it, embodied in the code, and in design, as "friend".
I always ( and only ) use friend for unit testing private methods. The only other way I can imagine to do this would be to load up the public interface with a whole lot of testing methods, which is just too messy and so I prefer to hide the test methods in a seperate test class.
Something like this:
class cMyClassTest;
class cMyClass
{
public:
.....
private:
friend cMyClassTest;
int calc(); // tricky algorithm, test carefully
};
class cMyClassTest
{
public:
int test_calc()
{
cMyClass test;
....
int result = test.calc();
if( result == 42 )
return 1;
return 0;
}
};
friend class mean we all know that is acesss the value of variable from other class so it is mainly used for use the values so we no need to return the value of other class to main function then main to needed class member function but it having the problem that is a class is friend for other class then friend class should be in below of that class