When you design classes you often make the properties they hold private or protected so outside code cant mess with the innards.
But what if you want to allow that – sometimes ?
This is the notion of a “friend”. Another class that you can literally say “yeah its ok I know them and it’s OK if they mess with my innards as they are my friend”. Xojo doesn’t have such a notion. So how do you make this possible ?
First off you really need to think hard about what it is you want to do and do you really need “friend”liness ? You may not. An interface or some other mechanism may be more suitable.
But if you do some to the conclusion you DO need a “friend” then you can make one using namespaces and private interfaces.
What you CAN do is
- take your class (call it AllowFriends) & put it in a module
- declare a PRIVATE class interface that class AllowFriends implements since you CAN implement an interface with private methods.
- Add classes to this module that you want to make friends of class AllowFriends
- on each class that wants to allow “friend” access implement the interface with PRIVATE methods.
- now anything in this module, classes or methods, that is a friend of class AllowFriends can cast it to the private interface & access whatever you exposed in that interface – this WILL only be methods but since you can make method pairs act like a getter/setter things should be fine.
And now you have classes in that module that can be “friends” but nothing outside the module can be since they cannot access the private methods on each class OR the private interface. The interface is restricted to only be used by classes & methods that exist in the module.
It’s not exactly “friend” from C++ but its about as close as you can get in Xojo.