The situation: I have to handle and take action on various commands, which can be encapsulated in the command design pattern. So right now I have
class Command {
virtual void applyCommand(IFoo& foo) = 0;
virtual ~Command() = default;
};
and of course I inherit this interface into my individual command classes.
However now, I realize that just passing IFoo isn't enough. I want to be able to access private data members in my ConcreteFoo class. I justify this break in encapsulation because when it comes down to it, all these objects are basically just helper functions for my ConcreteFoo class. I'm fine with them being strongly coupled because one way or the other, I have to write these methods, and doing the CDP makes it more readable.
So, I change my class to
class Command {
virtual void applyCommand(ConcreteFoo& foo) = 0;
virtual ~Command() = default;
};
and in my ConcreteFoo class I declare
friend class Command;
However, friendship apparently is not inherited into the subclasses of Command, the classes that actually do the work. So I can't actually get access to the data I need.
My current thoughts on solving this are:
1.) Take the L and just handle this without the CDP
possible, but I don't really want to take this route if I can avoid it
2.) Make data members in ConcreteFoo public
no
3.) Make data members in ConcreteFoo protected, and somehow make Command a subclass of ConcreteFoo
no
4.) Manually declare each Command subclass a friend, so like
friend class CommandA;
friend class CommandB;
friend class CommandC;
friend class CommandD;
...
decent, but might not scale well. on the plus side, if I forget to friend, it should fail at compile time
None of these options are particularly appealing to me. Is there something else I can do?
You’re basically working on visitor pattern (your Command class is a visitor to Foo classes).
One way to go around this, you might have a public interface of Command (applyCommand non-virtual) and virtual implementation(s) (applyCommandImpl virtual). You can make Command itself a friend and Command::applyCommand could extract the necessary data and pass it to the particular applyCommandImpl.
Normally, you’d simply extract the necessary parameters and pass those. However, if you really want to access all members, then you might do this: have the members of Foo in a struct (say, Foo1DO, as in data object) and inherit from it privately to have Foo1. Then you can have a simple getter to reach Foo1DO from Foo1 in applyCommand.
Related
I currently have a class that processes files on a local file system.
Class FileProcessor
{
public:
UpdateFiles();
private:
processFiles();
checkFileIsCorrupted();
}
Now, I want to add a new functionality, where the same file processing is done on files that first needed to be downloaded, but then it would call processFiles() and checkFileIsCorrupted() as before and do the same processing.
I'm wondering what's the best way to do this is.
I could change the interface for UpdateFiles() and add a parameter do determine whether I need to download the files, but modifying the public interface is clearly not ideal.
I could add a new public interface function UpdateFilesFromRemote() and thus share the private members, though this would seem to violate the single responsibility principle, which would call for the "new" functionality to be its own class.
Make a new class. This would either duplicate all the code in processFiles() and processData(), or require a new base class where processFiles() and checkFileIsCorrupted() are protected members,and all the private member they call on would also need to be moved to protected in this base class as well. However, from what I've read so far, most people seem to consider using protected to be something to avoid.
Make a new class and make processFiles() and checkFileIsCorrupted() friends of both classes. I'm assuming this would require both functions to take FileProcessor and the new class as objects (or a base class interface), so that the private members can be accessed. Although both FileProcessor and the new class would share many private members, and so that would still require them to be protected in the base class interface. Also, having a design where checkFileIsCorrupted() needs to take a FileProcessor object as input just... doesn't feel right. After all, its not actually modifying the FileProcessor object, its just a helper function to check if a file is corrupted.
Make a new class and make processFiles() and checkFileIsCorrupted() non member, non friend functions. This would mean that internal file information that is private to both classes would need to be passed as function parameters to these non-member, non friend functions, breaking encapsulation.
Either way, no solutions seems to be "good". Is there any better way to design this?
Thanks.
I have a class let us call it Person:
class Person{
private:
void move(x,y,z);
}
I have another class called PersonController:
class PersonController{
public:
void control(){
while(some_thing){
//do some calculations
controlled_person_->move(some_values); //Wrong Accessing to a private member
}
}
private:
Person* controlled_person_;
}
Both Person and PersonController are part of the public interface of the library I am designing.
I want PersonController to be able to call move from Person. However, I do not want anyone to access this function (move) from the public interface.
The easy way to sovle the problem is add a friendship so PersonController can access private members of Person. However, as far as I read the friend keyword was not introduced to solve these kind of problems and using it here would be a bad practice.
Is this correct? Should I avoid friend here?
Does this mean my design is broken?
Any alternative suggestions?
From what you said in comments, it seems you are interested in only allowing PersonController to touch that one member function. The way to do that and only that, is to make the door public, but add a private key for it:
class Person{
public:
class MovePrivilege {
move_privilege() = default; // private c'tor
friend class PersonController; // only PersonController may construct this
};
void move(MovePrivilege, x,y,z);
};
class PersonController{
public:
void control(){
while(some_thing){
//do some calculations
controlled_person_->move(MovePrivilege{} , some_values);
}
}
private:
Person* controlled_person_;
};
The type MovePrivilege has a private c'tor. So it can only be constructed by its friends. And it is also required for calling move. So while move is public, the only classes that may call it are the friends of MovePrivilege.
This essentially gives you a fine grained control over who may call move. If this is obtrusive and you can't change move itself, a variant of the attorney client idiom may be appropriate instead.
You do have options at your disposal. Direct firend-ship is just the bluntest tool.
That is exactly the sort of problem that friend is meant for. While friendship should be minimized if your design needs it there is no reason not to use it.
I see non-use of friend a lot like the continuing dislike of 'goto', there are simply times where using it will make a design far cleaner.
Yes your design is not correct.
Classes are an expanded concept of data structures: like data structures, they can contain data members, but they can also contain functions as members. You can read more here
So PersonController (If it only control person class) should not be a class because it is not concept of data structures Check if it is possible to merge them or design another way.
There are many ways to do it.If you want to design it like what you do now you can use protected access controller for your function and Create derived class but it's not a good design again.
You can use friend function here too but it isn't an object oriented concept again(But the easiest way).
You should rethink about your design if you want to design it OO.Because you can't access private function from other class in object oriented programming ,It breaks encapsulation so C++ won't let you do that.
However your question depends on opinions too.
here im not understanding the concept very well or i am right.... So lets take this "friend" class example here:
class MyClass{
friend class AnotherClass;
private:
int secret;
}
class AnotherClass{
public:
void getSecret(MyClass mc){
return mc.secret;
}
}
So Yes... in the above code it will actually work if you do it... but in general, why cant you use getters and setters all the time instead of friend class? Is the reason of friend class usage because of "tediousness"?
friend is for when you don't want to expose getters/setters/internals to everyone, but just to a single class. So it's a tool for encapsulation.
For example, if you provided a public getSecret in MyClass, everyone could have access to that private variable even if they shouldn't know about it. This breaks encapsulation. friend is there to fix this problem, so that only those classes that need to know about secret have access to it.
As #nicomp said, "it's like giving your physical friend a key to your house but you don't know what they will do with it". So a friend class has unlimited access to all internals of the class it's friends with. This in unfortunate, but the key (no pun intended) here is to keep classes as small as possible so that this doesn't become a problem, which also would be according to the Single Responsibility Principle.
A public getter or setter permits anybody access. They have some uses, notably for maintaining class invariants when some property is changed, but a getter / setter pair that look like the following code are no better than public member variables for constraining access:
class A {
public:
int getX() const { return x; };
void setX(int x_) { x = x_; };
private:
int x;
};
The getX() and setX() functions do nothing but provide access to x. Everybody can use them, so anybody can change the value of x. There's no point making it private, then.
If, instead, only some classes or functions need to be able to change x, you can make them friends of class A. This restricts the access to only those friends, rather than giving it to everybody.
As such, friend is a tool for encapsulation, permitting the encapsulation to be wider than "just my own class" (private members) or "just my class and classes that derive from it" (protected members). A friend need not be in the same class hierarchy (it need not be a class at all; functions can be friends), but it still permits you to restrict access to only those things that actually need it.
Note that, like getters and setters, it should be used sparingly. Encapsulation is a good thing, and where possible the private members of your class should remain just that – private. friend is a tool that allows you to selectively grant access, but you should always carefully consider whether that access needs to be granted, or whether the function / class that needs it would be better off as a member of your class, instead.
Don't forget about testing and/or copying...
Friend classes / methods can be used quite successfully for checking intermediate states within class functionality.
They can also be useful for some types of copy constructors, where the class to be copied is not a direct ancestor of the target class thus precluding protected members as an option.
Consider the following use-case that I encountered recently: I refactored some code from one class into another class. This new class had to access members from the original class but I did not want to provide this via public getters to avoid other clients messing around with these. In this case, I really welcomed the C++-friendship mechanism.
However, these use cases are very seldom (hopefully, otherwise there is probably something wrong in your SW architecture) and I try to avoid it as much as I can since it is the tightest form of coupling.
I've a case in which I need to add some functions to a game engine class I'm using for a VR project without overriding the class it self:
The engine class name is AnnwaynPlayer that contains many useful methods to control the player, now I'm in the networking phase so I need to add 2 extra methods to this lib class which are setActive() and setConnected(), what is the best way to do this ?
If you can't touch the class itself then you probably want to use inheritance. This is one of the main goals of object-oriented programming -- to be able to add/change the behavior of an existing class without altering it. So you want something like:
class MyAnnwaynPlayer : public AnnwaynPlayer {
public:
void setActive();
void setConnected();
// ...
}
Now, things will be fine if AnnwaynPlayer has a virtual destructor. If it doesn't and your MyAnnwaynPlayer class has a non-trivial destructor then you have to wary of using an instance of MyAnnwaynPlayer through a pointer (be it raw or smart) of base class AnnwaynPlayer. When a pointer of the type is deleted, it will not chain through a call to your MyAnnwaynPlayer destructor.
Also consider ADL if you only need access to the public API of the base class. It's safer than inheritance, because you don't necessarily know the right class to inherit from in cases where the implementation returns something ultimately unspecified (like an internal derived class).
In essence, this would look like this:
namespace AnnwaynNamespace {
void setActive(AnnwaynPlayer& p);
void setConnected(AnnwaynPlayer& p);
};
And you could call them without using those functions (or the namespace), because ADL.
void wherever(AnnwaynNamespace::AnnwaynPlayer& p) {
setActive(p);
}
So setActive, etc, become part of the actual public API of the class, without involving any inheritance.
I have a set of classes
class myClassA{
friend class MyFatherClass;
};
class MyFatherClass{
...
};
class MySonClass : public MyFatherClass {
};
My father class can access all the methods of the class MyClassA.
I would like as well that all the class which will extend MyFatherClass will be able to call such methods.
I can see just 2 options:
at any time I go to add in myClassA the new class as a friend. ( I do not like it )
I create some protected wrapper in the father function to access the method from the class myClassA. (slightly better but i still do not like it as well because i have to create a new wrapper at any time a new method is created in myClassA)
Do you have any idea for a more elegant solution to the problem?
Thanks
First off... what does elegant mean? Less code for you to write? I suggest you don't compromise when it comes to readability.
Using friendship should not be a decision taken lightly. There are numerous threads on SO dealing with this, but here I'll just assume you already know what this implies.
Option 1) is a lot more readable. When someone sees the class, they will directly know who has access to it. Code should be expressive, and this option describes the intent perfectly.
Option 2) is a bit of an overkill. You're writing a wrapper just so you can access some functions... why not make them public to start with, since the wrapper has public access. It's just an added layer of abstraction for nothing.
You should first think about functionality (both work), expressiveness and readability (option 1 is definitely better here).
It's a bit hard to make a judgment knowing so little about the application, but if the functions should only be used by MyFatherClass and its descendents, they should be protected members (perhaps static) of MyFatherClass.
Perhaps MyClassA should be a member of MyFatherClass with no member functions of its own, just a struct to hold some data members.
class MyFatherClass {
protected:
struct myStructA {
int state;
};
static void DoSomething( myStructA &a );
…
};
Just a suggestion… it's hard to tell what's best given so little information. The general idea is that the language disallows friendship inheritance because you can always make a good design without it.