This question already has answers here:
How do I test a class that has private methods, fields or inner classes?
(58 answers)
Closed 5 years ago.
Today I had a discussion with a colleague on whether to test or not to test private members or private state in the class. He almost convinced me why it makes sense. This question does not aim to duplicate already existing StackOverflow questions about the nature and reason of testing private members, like: What is wrong with making a unit test a friend of the class it is testing?
Colleagues suggestion was in my opinion a bit fragile to introduce the friend declaration to the unit test implementation class. In my opinion this is a no-go, because we introduce some dependency of tested code to the test code, whereas test code already depends on tested code => cyclic dependency. Even such innocent things like renaming a test class results in breaking unit tests and enforces code changes in tested code.
I'd like to ask C++ gurus to judge on the other proposal, which relies on the fact that we are allowed to specialize a template function. Just imagine the class:
// tested_class.h
struct tested_class
{
tested_class(int i) : i_(i) {}
//some function which do complex things with i
// and sometimes return a result
private:
int i_;
};
I don't like the idea to have a getter for i_ just to make it testable. So my proposal is 'test_backdoor' function template declaration in the class:
// tested_class.h
struct tested_class
{
explicit
tested_class(int i=0) : i_(i) {}
template<class Ctx>
static void test_backdoor(Ctx& ctx);
//some function which do complex things with i
// and sometimes return a result
private:
int i_;
};
By adding just this function we can make the class' private members testable. Note, there is no dependency to unit test classes, nor the template function implementation. In this example the unit test implementation uses Boost Test framework.
// tested_class_test.cpp
namespace
{
struct ctor_test_context
{
tested_class& tc_;
int expected_i;
};
}
// specialize the template member to do the rest of the test
template<>
void tested_class::test_backdoor<ctor_test_context>(ctor_test_context& ctx)
{
BOOST_REQUIRE_EQUAL(ctx.expected_i, tc_.i_);
}
BOOST_AUTO_TEST_CASE(tested_class_default_ctor)
{
tested_class tc;
ctor_test_context ctx = { tc, 0 };
tested_class::test_backdoor(ctx);
}
BOOST_AUTO_TEST_CASE(tested_class_value_init_ctor)
{
tested_class tc(-5);
ctor_test_context ctx = { tc, -5 };
tested_class::test_backdoor(ctx);
}
By introducing just a single template declaration, which is not callable at all, we give the test implementer a possibility to forward test logic into a function. The function, acts on type safe contexts and is only visible from inside the particular test compilation unit, due to anonymous type nature of test context. And the best thing is, we can define as many anonymous test contexts as we like and specialize tests on them, without ever touching the tested class.
Sure, the users must know what template specialization is, but is this code really bad or weird or unreadable? Or can I expect from C++ developers to have the knowledge what C++ template specialization is and how it works?
Elaborating on using friend to declare unit test class I don't think this is robust. Imagine boost framework (or may be other test frameworks). It generates for every test case a separate type. But why should I care as long I can write:
BOOST_AUTO_TEST_CASE(tested_class_value_init_ctor)
{
...
}
If using friends, I had to declare each test case as a friend then... Or end up introducing some test functionality in some common type (like fixture), declare it as a friend, and forward all test calls to that type... Isn't that weird?
I would like to see your pro and cons practicing this approach.
I think unit testing is about testing the observable behavior of the class under test. Therefore there is no need to test private parts as they themselves are not observable. The way you test it is by testing whether the object behaves the way you expect it (which implicitly implies that all private internal states are in order).
The reason for not to be concerned about the private parts is that this way you can change the implementation (e.g. refactoring), without having to rewrite your tests.
So my answer is don't do it (even if technically possible to) as it goes against the philosophy of unit tests.
Pros
You can access the private members to test them
Its a fairly minimal amount of hack
Cons
Broken encapsulation
Broken encapsulation that is more complicated and just as brittle as friend
Mixing test with production code by putting test_backdoor on the production side
Maintance problem ( just like friending the the test code, you've created an extremely tight coupling with your test code )
All of the Pros/Cons aside, I think you are best off making some architectural changes that allow better testing of whatever complex stuff is happening.
Possible Solutions
Use the Pimpl idiom, put the complex code in the pimpl along with the private member, and write a test for the Pimpl. The Pimpl can be forward declared as a public member, allowing external instantiation in the unit test. The Pimpl can consist of only public members, making it easier to test
Disadvantage: Lots of code
Disadvantage: opaque type that can be more difficult to see inside of when debugging
Just test the public/protected interface of the class. Test the contract that your interface lays out.
Disadvantage: unit tests are difficult/impossible to write in an isolated manner.
Similar to the Pimpl solutions, but create a free function with the complex code in it. Put the declaration in a private header ( not part of the libraries public interface ), and test it.
Break encapsulation via friend a test method/fixture
Possible variation on this: declare friend struct test_context;, put your test code inside of methods in the implementation of struct test_context. This way you don't have to friend each test case, method, or fixture. This should reduce the likelyhood of someone breaking the friending.
Break encapsulation via template specialization
What will follow is not technically speaking a straight answer to your
question as it will still make use of the "friend" functionality
but it does not require modification of the tested entity itself
and I think it addesses the concern of breaking the encapsulation
mentioned in some of the other answers; it does though require
writing some boilerplate code.
The idea behind it is not mine and the implementation is
entirely based on a trick presented and explained by litb on his
blog(coupled with this Sutter's gotw for just a little bit
more context, at least for me) - in short CRTP, friends, ADL and pointers to members
(I must confess that to my dismay the ADL part I still don't
get it entirely, but I'm relentesly working in figuring it out 100%).
I tested it with gcc 4.6, clang 3.1 and VS2010 compilers and it
works perfectly.
/* test_tag.h */
#ifndef TEST_TAG_H_INCLUDED_
#define TEST_TAG_H_INCLUDED_
template <typename Tag, typename Tag::type M>
struct Rob
{
friend typename Tag::type get(Tag)
{
return M;
}
};
template <typename Tag, typename Member>
struct TagBase
{
typedef Member type;
friend type get(Tag);
};
#endif /* TEST_TAG_H_INCLUDED_ */
/* tested_class.h */
#ifndef TESTED_CLASS_H_INCLUDED_
#define TESTED_CLASS_H_INCLUDED_
#include <string>
struct tested_class
{
tested_class(int i, const char* descr) : i_(i), descr_(descr) { }
private:
int i_;
std::string descr_;
};
/* with or without the macros or even in a different file */
# ifdef TESTING_ENABLED
# include "test_tag.h"
struct tested_class_i : TagBase<tested_class_i, int tested_class::*> { };
struct tested_class_descr : TagBase<tested_class_descr, const std::string tested_class::*> { };
template struct Rob<tested_class_i, &tested_class::i_>;
template struct Rob<tested_class_descr, &tested_class::descr_>;
# endif
#endif /* TESTED_CLASS_H_INCLUDED_ */
/* test_access.cpp */
#include "tested_class.h"
#include <cstdlib>
#include <iostream>
#include <sstream>
#define STRINGIZE0(text) #text
#define STRINGIZE(text) STRINGIZE0(text)
int assert_handler(const char* expr, const char* theFile, int theLine)
{
std::stringstream message;
message << "Assertion " << expr << " failed in " << theFile << " at line " << theLine;
message << "." << std::endl;
std::cerr << message.str();
return 1;
}
#define ASSERT_HALT() exit(__LINE__)
#define ASSERT_EQUALS(lhs, rhs) ((void)(!((lhs) == (rhs)) && assert_handler(STRINGIZE((lhs == rhs)), __FILE__, __LINE__) && (ASSERT_HALT(), 1)))
int main()
{
tested_class foo(35, "Some foo!");
// the bind pointer to member by object reference could
// be further wrapped in some "nice" macros
std::cout << " Class guts: " << foo.*get(tested_class_i()) << " - " << foo.*get(tested_class_descr()) << std::endl;
ASSERT_EQUALS(35, foo.*get(tested_class_i()));
ASSERT_EQUALS("Some foo!", foo.*get(tested_class_descr()));
ASSERT_EQUALS(80, foo.*get(tested_class_i()));
return 0;
}
I am sorry to advice this, but it helped me when most methods in those answers are not achievable without strong refactoring: add before the header for the file with the class whose private members you wish to access,
#define private public
It is evil, but
doesn't interfere with production code
does not break encapsulation as friend / changing access level does
avoids heavy refactoring with PIMPL idiom
so you may go for it...
Testing private members is not always about verifying the state by checking if it equals some expected values. In order to accommodate other, more intricate test scenarios, I sometimes use the following approach (simplified here to convey the main idea):
// Public header
struct IFoo
{
public:
virtual ~IFoo() { }
virtual void DoSomething() = 0;
};
std::shared_ptr<IFoo> CreateFoo();
// Private test header
struct IFooInternal : public IFoo
{
public:
virtual ~IFooInternal() { }
virtual void DoSomethingPrivate() = 0;
};
// Implementation header
class Foo : public IFooInternal
{
public:
virtual DoSomething();
virtual void DoSomethingPrivate();
};
// Test code
std::shared_ptr<IFooInternal> p =
std::dynamic_pointer_cast<IFooInternal>(CreateFoo());
p->DoSomethingPrivate();
This approach has the distinct advantage of promoting good design and not being messy with friend declarations. Of course, you don't have to go through the trouble most of the time because being able to test private members is a pretty nonstandard requirement to begin with.
I don't usually feel the need to unit test private members and functions. I might prefer to introduce a public function just to verify correct internal state.
But if I do decide to go poking around in the details, I use a nasty quick hack in the unit test program:
#include <system-header>
#include <system-header>
// Include ALL system headers that test-class-header might include.
// Since this is an invasive unit test that is fiddling with internal detail
// that it probably should not, this is not a hardship.
#define private public
#include "test-class-header.hpp"
...
On Linux at least this works because the C++ name mangling does not include the private/public state. I am told that on other systems this may not be true and it wouldn't link.
I used a function to test private class members which was just called TestInvariant().
It was a private member of the class and, in debug mode, was called at the beginning and end of every function (except the beginning of the ctor and end of the dctor).
It was virtual and any base class called the parent version before it's own.
That allowed me to verify the internal state of the class all of the time without exposing the intenals of the class to anyone. I had very simple tests but there is no reason why you could not have complicated ones, or even set it on or off with a flag etc.
Also you can have public Test functions which can be called by other classes which call your TestInvariant() function. Therefore when you need to change inner class workings you do not need to change any user code.
Would this help?
I think the first thing to ask is: Why is friend considered to be something that must be used with caution?
Because it breaks encapsulation. It provides another class or function with access to the internals of your object, thus expanding the visible scope of your private members. If you have a lot of friends, it's much harder to reason about the state of your object.
In my opinion, the template solution is even worse than friend in that regard. Your main stated benefit of the template is that you no longer need to explicitly friend the test from the class. I argue that, on the contrary, this is a detriment. There are two reasons for that.
The test is coupled to the internals of your class. Anyone changing the class should know that by changing the privates of the object that they may be breaking the test. friend tells them exactly what objects might be coupled to the internal state of your class, but the template solution doesn't.
Friend limits the scope expansion of your privates. If you friend a class, you know that only that class may access your internals. Thus, if you friend the test, you know that only the test can read or write to private member variables. Your template back door, however, could be used anywhere.
The template solution is ineffective because it hides the problem rather than fixing it. The underlying issue with the cyclic dependency still exists: someone changing the class must know about every use of the back door, and someone changing the test must know about the class. Basically, the reference to the test from the class was removed only by making all private data into public data in a roundabout way.
If you must access private members from your test, just friend the test fixture and be done with it. It's simple and understandable.
There's a theory that if it's private it shouldn't be tested alone, if it needs so then it should be redesigned.
For me that's Shi'ism.
On some project people create a macro for private methods, just like:
class Something{
PRIVATE:
int m_attr;
};
When compiling for test PRIVATE is defined as public, otherwise it's defined as private. that simple.
Related
In the 2017 cppcon videos, I came across a talk by Klaus Iglberger which was entitled "Free Your Functions!".
In this talk, the speaker talked about how switching to free functions could
easy up the process of testing private methods (See at 19:00). The idea is that you pull the
private method out of the class (you make it a free function) and it becomes testable.
At first, I found the idea interesting, but then the
more I thought about it, the less I understood how this is actually supposed to work. For example,
let's say I have the following (dummy) class:
class SomeClass
{
public:
SomeClass();
~SomeClass();
void someTask();
private:
void someComplexTask();
void someOtherComplexTask();
};
void SomeClass::someTask()
{
someComplexTask();
someOtherComplexTask();
}
// private tasks implementations...
Then someComplexTask() and someOtherComplexTask() are private methods. This means that they
are implementation details, i.e. that they can only be called inside SomeClass (or friends). It
seems to me that if you make them free functions, yes they become testable, but they are no longer
private, nor a mere implementation detail specific to SomeClass. In fact, they can be called from anywhere in the code...
So my question is: why is Mr. Iglberger's point valid?
This is a clear indication that you have a design flaw. If you have a
private function that you need to test and you have to bend backwards
to make it work then something is wrong. You have missed something.
Your design doesn't work.
His point is not to just make private functions free. He is not saying: "get all your private functions and make them free functions". He is saying that functionality that needs to be tested shouldn't be an implementation detail because if you need to test it that is an indication the functionality is useful.
Please pay close attention to the transformation he does to the code:
initial code:
class X
{
public:
void doSomething( ... ) {
...
resetValues();
...
}
...
private:
void resetValues() {
for( int& value : values_ )
value = 0;
}
std::vector<int> values_;
};
He pulls resetValues out of X but it makes it operate on a std::vector<T>, not on X:
void resetValues( std::vector<int>& vec )
{
for( int& value : vec )
value = 0;
}
Now resetValues is a functionality that can be reused and tested. As it truly has nothing to do with X, but with resetting all values of a vector it is a valid design to make it a free function instead of a private X method.
I like how Rann Lifshitz put it in his comment:
I think the better way to go here is to understand that some private
functions are, in fact, common utility functions
I have watched the video too. But, I have a few disagreements.
1- Does your method require accessing fields? If not, it does not belong to the class. But if it does, they need the fields. The free functions do not have access to the fields unless you pass them as function arguments. Please consider that free functions should not be looked as public function.
2- Not everything is supposed to be free function. But it is a good practice to avoid putting everything in the class when they are not necessary.
3- Private function are not often supposed to be tested. But if you insist, you might be able to perform such as invalid hack (which not always works as mentioned in the comments):
#define class struct
#define private public
#define protected public
#include "library.h"
#undef class
#undef private
#undef protected
Freeing your function is neater but not more feasible.
I would like to ask question regarding internal helper class in C++. What is the best way to structure this?
Let me clarify what do I mean by internal helper class by example.
// MyClass.h
class MyClass
{
int myData;
bool isSomething;
...
public:
void DoSomething();
};
// MyClass.cpp
// This is what I mean by internal helper function. Helper function that's only visible int the implementation file (.cpp) but requires access to the private members of the class.
static void DoSomethingInternal( MyClass *myClass )
{
// Access myClass private members
}
void MyClass::DoSomething()
{
...
DoSomethingInternal(this);
...
}
I know that declaring friend function can be a solution. However, it makes the class declaration ugly. In addition, for every new helper function, I have to add a friend function.
Is there an idiom/design pattern for this? I have been searching in the Internet, but didn't find any.
Thank you in advance. Your answers are greatly appreciated.
In my experience, a lot of dev teams have no problem with static local helper functions, it helps reduce header bloat, helps keep the formally exposed interface smaller, and so forth. It has the advantage of being lightweight, it has the disadvantage that it can lead to friend bloat/pollution if you are using lots of private members and no accessors.
But within the discussion community it is generally frowned upon in favor of the following.
Declaring helpers as private member functions.
This has the advantage of clearly associating fn _doThingsForFoo(Foo*) with Foo, and saving you from a lot of headaches exposing private members.
It has the downside of basically showing your underwear to everyone who needs to #include your header.
Using the Pimpl idiom.
You declare a second class, the "Private Implementation" (https://en.wikipedia.org/wiki/Opaque_pointer, Is the pImpl idiom really used in practice?) and you put all of the private stuff you don't want in the main header into that.
It has the advantage of allowing you to hide your stuff, it has the disadvantage of adding an extra pointer to feed, store and traverse (oh and free).
There are couple of ways to accomplish that.
Use a helper class/function in the .cpp file if the helper functions don't need access to the data directly. I would recommend this method ahead of the next method.
In the .cpp file:
// Create a namespace that is unique to the file
namespace MyClassNS
{
namespace HelperAPI
{
void DoSomethingInternal(MyClass* obj) { ... }
}
}
using namespace MyClassNS;
void MyClass::DoSomething()
{
...
//
HelperAPI::DoSomethingInternal(this);
...
}
Use the pimple idiom. When using this idiom, you can add any number of helper functions in the private data class without touching the public interface of the class.
The design pattern is simple: don't use helper classes. If a class should do something, let it do it itself.
As per the upvoted answer given by StenSoft, you should implement the methods inside the class. However, if that is not an option for some reason, then use helpers. If even that is not an option, then use reflection. If even that is not an option, then use a command listener inside your class. If even that is not an option, then watch a tutorial.
You can read these following sites for this purpose PIMPL, Opaque pointer. With this you only need to have one member variable and you can put all private things into the private class.
your header:
class PrivateClass;
class Class
{
public:
// ...
private:
PrivateClass* m_Private;
};
your source:
class PrivateClass
{
// ...
};
Class::Class
: m_Private( new PrivateClass )
{
// ...
}
UPDATE: I forgot to tell mention to delete the private member in the desctructor.
Class::~Class
{
delete m_Private;
// ...
}
// ...
This is really a question of good form/best practices. I use structs in C++ to form objects that are designed to basically hold data, rather than making a class with a ton of accessor methods that do nothing but get/set the values. For example:
struct Person {
std::string name;
DateObject dob;
(...)
};
If you imagine 20 more variables there, writing this as a class with private members and 40-something accessors is a pain to manage and seems wasteful to me.
Sometimes though, I might need to also add some sort of minimal functionality to the data. In the example, say I also sometimes need the age, based on dob:
struct Person {
std::string name;
DateObject dob;
(...)
int age() {return calculated age from dob;}
}
Of course for any complex functionality I would make a class, but for just a simple functionality like this, is this "bad design"? If I do use a class, is it bad form to keep the data variables as public class members, or do I just need to accept it and make classes with a bunch of accessor methods? I understand the differences between classes and structs, I'm just asking about best practices.
I think there are two important design principles to consider here:
Hide a class's representation through an interface if there is some invariant on that class.
A class has an invariant when there is such thing as an invalid state for that class. The class should maintain its invariant at all times.
Consider a Point type that represents a 2D geometric point. This should just be a struct with public x and y data members. There is no such thing as an invalid point. Every combination of x and y values is perfectly fine.
In the case of a Person, whether it has invariants depends entirely on the problem at hand. Do you consider such things as an empty name as a valid name? Can the Person have any date of birth? For your case, I think the answer is yes and your class should keep the members public.
See: Classes Should Enforce Invariants
Non-friend non-member functions improve encapsulation.
There's no reason your age function should be implemented as a member function. The result of age can be calculated using the public interface of Person, so it has no reason to be a member function. Place it in the same namespace as Person so that it is found by argument-dependent lookup. Functions found by ADL are part of the interface of that class; they just don't have access to private data.
If you did make it a member function and one day introduced some private state to Person, you would have an unnecessary dependency. Suddenly age has more access to data than it needs.
See: How Non-Member Functions Improve Encapsulation
So here's how I would implement it:
struct Person {
std::string name;
DateObject dob;
};
int age(const Person& person) {
return calculated age from person.dob;
}
In C++, Structs are classes, with the only difference (that I can think of, at least) being that in Structs members are public by default, but in classes they are private. This means it is perfectly acceptable to use Structs as you are - this article explains it well.
In C++, the only difference between structs and classes are that structs are publicly visibly by default. A good guideline is to use structs as plain-old-data (POD) that only hold data and use classes for when more functionality (member functions) is required.
You may still be wondering whether to just have public variables in the class or use member functions; consider the following scenario.
Let's say you have a class A that has a function GetSomeVariable that is merely a getter for a private variable:
class A
{
double _someVariable;
public:
double GetSomeVariable() { return _someVariable; }
};
What if, twenty years down the line, the meaning of that variable changes, and you have to, let's say, multiply it by 0.5? When using a getter, it is simple; just return the variable multiplied by 0.5:
double GetSomeVariable() { return 0.5*_someVariable; }
By doing this, you allow for easy maintainability and allow for easy modification.
If you want some data holder then prefer struct without any get/set methods.
If there is more to it, as in this case "Person".
It models real world entity,
Has definite state and behaviour,
Interacts with external world,
Exhibits simple/complex relationship with other entities,
it may evolve overtime,
then it is a perfect candidate for a class.
"Use a struct only for passive objects that carry data; everything else is a class."
say google guidlines, I do it this way and find it a good rule. Beside that I think you can define your own pragmatics, or deviate from this rule if it really makes sense.
I don't want to sparkle a holy war here; I usually differentiate it in this way:
For POD objects (i.e., data-only, without exposed behavior) declare the internals public and access them directly. Usage of struct keyword is convenient here and also serves as a hint of the object usage.
For non-POD objects declare the internals private and define public getters/setters. Usage of class keyword is more natural in these cases.
For just clearing the confusion for some! And easy picking! Here some points!
In struct! you can have encapsulation and visibility operators (make private or public)! Just like you do with classes!
So the statement that some say or you may find online that say: one of the differences is that structures have no visibility operator and ability to hide data, is wrong!
You can have methods just like in classes!
Run the code bellow! And you can check it compiles all well! And run all well! And the whole struct work just like class!
Mainly the difference is just in the defaulting of the visibility mode!
Structures have it public! Classes privates by default!
#include<iostream>
#include<string>
using namespace std;
int main(int argv, char * argc[]) {
struct {
private:
bool _iamSuperPrivate = true;
void _sayHallo() {
cout << "Hallo mein Bruder!" << endl;
}
public:
string helloAddress = "";
void sayHellow() {
cout << "Hellow!" << endl;
if (this->helloAddress != "") {
cout << this->helloAddress << endl;
}
this->_sayHallo();
}
bool isSuperPrivateWorking() {
return this->_iamSuperPrivate;
}
} testStruct;
testStruct.helloAddress = "my Friend!";
testStruct.sayHellow();
if (testStruct.isSuperPrivateWorking()) {
cout << "Super private is working all well!" << endl;
} else {
cout << "Super private not working LOL !!!" << endl;
}
return 0;
}
In memory they are the same!
I didn't check myself! But some say if you make the same thing! The compiled assembly code will come the same between a struct and a class! (to be checked!)
Take any class and change the name to typedef struct ! You'll see that the code will still works the same!
class Client {
}
Client client(...);
=>
typedef struct Client {
....
} Client;
Client client(...);
If you do that all will works the same! At least i know that does in gcc!
YOu can test! In your platform!
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
When should you use 'friend' in C++?
I have come to a stumbling block because of lack of documentation on friend classes. Most books just explain it briefly, e.g an excerpt from C++: the Complete Reference:
Friend Classes are seldom used. They are supported to allow certain special case situations to be handled.
And frankly, I have never seen a friend class in any good code made by an experienced C++ programmer. So , here is my list of problems.
Do Inherited Classes have the same friends as there base classes? e.g, if I declare class foo as a friend of class base, will class der (derived from base) also have foo as a friend?
What are the special case situations when a friend class should be used?
I am making a winapi wrapper in which I want to make class WinHandle a friend of class Widget (to access some protected members). Is it recommended? Or should I just access them using the traditional Get/Set functions?
Friend is used for granting selective access, just like the protected access specifier. It's also hard to come up with proper use case where use of protected is really useful.
In general, friend classes are useful in designs where there is intentional strong coupling: you need to have a special relationship between two classes. More specifically, one class needs access to another classes's internals and you don't want to grant access to everyone by using the public access specifier.
The rule of thumb: If public is too weak and private is too strong, you need some form of selected access: either protected or friend (the package access specifier in Java serves the same kind of role).
Example design
For instance, I once wrote a simple stopwatch class where I wanted to have the native stopwatch resolution to be hidden, yet to let the user query the elapsed time with a single method and the units to be specified as some sort of variable (to be selected by user preferences, say). Rather than, have say elapsedTimeInSeconds(), elapsedTimeInMinutes(), etc. methods, I wanted to have something like elapsedTime(Unit::seconds). To achive both of these goals, I can't make the native resolution public nor private, so I came up with the following design.
Implementation overview
class StopWatch;
// Enumeration-style class. Copy constructor and assignment operator lets
// client grab copies of the prototype instances returned by static methods.
class Unit
{
friend class StopWatch;
double myFactor;
Unit ( double factor ) : myFactor(factor) {}
static const Unit native () { return Unit(1.0); }
public:
// native resolution happens to be 1 millisecond for this implementation.
static const Unit millisecond () { return native(); }
// compute everything else mostly independently of the native resolution.
static const Unit second () { return Unit(1000.0 / millisecond().myFactor); }
static const Unit minute () { return Unit(60.0 / second().myFactor); }
};
class StopWatch
{
NativeTimeType myStart;
// compute delta using `NativeNow()` and cast to
// double representing multiple of native units.
double elapsed () const;
public:
StopWatch () : myStart(NativeNow()) {}
void reset () { myStart = NativeNow(); }
double elapsed ( const Unit& unit ) const { return elapsed()*unit.myFactor; }
};
As you can see, this design achieves both goals:
native resolution is never exposed
desired time unit can be stored, etc.
Discussion
I really like this design because the original implementation stored the multiple of native time units and performed a division to compute the elapsed time. After someone complained the division was too slow, I changed the Unit class to cache the dividend, making the elapsed() method (a little) faster.
In general, you should strive for strong cohesion and weak coupling. This is why friend is so little used, it is recommended to reduce coupling between classes. However, there are situations where strong coupling gives better encapsulation. In those cases, you probably need a friend.
Do Inherited Classes have the same friends as there base classes? e.g if i declare class foo as a friend of class base, will class der (derived from base) also have foo as a friend?
The rule with friend keyword is:
Friendship attribute is not inherited.
So No friend of base class will not be friend of Derived class.
What are the special case situations when a friend class should be used?
Frankly, (IMHO) using friend classes is mostly done to achieve some things for rather ease of usage. If a software is designed taking in to consideration all the requirememtens then there would practically no need of friend classes. Important to note perfect designs hardly exist and if they do they are very difficult to acheive.
An example case which needs friend class:
Sometimes there may be a need for a tester class(which is not part of the release software) to have access to internals of classes to examine and log certain specific results/diagnostics. It makes sense to use friend class in such a scenario for ease of usage and preventing overhead of design.
I am making a winapi wrapper in which I want to make class WinHandle a friend of class Widget (to access some protected members). Is it recommended? Or should I just access them using the traditional Get/Set functions?
I would stick to the traditional setter/getter. I rather avoid using friend where I can get working through usual OOP construct. Perhaps, I am rather paranoid about using friend because if my classes change/expand in future I perceive the non inheritance attribute of friend causing me problems.
EDIT:
The comments from #Martin, and the excellent answer from #André Caron, provide a whole new perspective about usage of friendship, that I had not encountered before & hence not accounted for in the answer above. I am going to leave this answer as is, because it helped me learn a new perspective & hopefully it will help learn folks with a similar outlook.
friend usually accounts for where you would normally use one single class, but you have to use more because they have different life-times or instance counts, for example. friendship is not transferred or inherited or transitive.
Get/Set is quite terrible, although better than it could be. friend allows you to limit the damage to just one class. Usually you will make an intermediary class which is friended.
class MyHandleIntermediary;
class MyHandle {
friend class MyHandleIntermediary;
private:
HANDLE GetHandle() const;
};
class MyWidget;
class MyHandleIntermediary {
friend class MyWidget;
static HANDLE GetHandle(const MyWidget& ref) {
return ref.GetHandle();
}
};
class MyWidget {
// Can only access GetHandle() and public
};
This allows you to change the accessibility of friendship on a per-member level and ensures that the extra accessibility is documented in a single place.
One of the cases where I applied the "friend classes", is where one class is composed or referenced by other (objects) classes, and the composing objects, require access to the internals of the main class.
enum MyDBTableButtonBarButtonKind {
GoFirst,
GoPrior,
GoNext,
GoLast
}
class MyDBTableButtonBarButtonWidget;
class MyDBTableButtonBarWidget {
friend class MyDBTableButtonBarButtonWidget;
// friend access method:
protected:
void GoFirst();
void GoPrior();
void GoNext();
void GoLast();
void DoAction(MyDBTableButtonBarButtonKind Kind);
};
class MyDBTableButtonBarButtonWidget {
private:
MyDBTableButtonBarWidget* Toolbar;
public:
MyDBTableButtonBarButtonWidget(MyDBTableButtonBarWidget* AButtonBar) {
this ButtonBar = AButtonBar;
}
MyDBTableButtonBarButtonKind Kind;
public:
virtual void Click() { Buttonbar->DoAction(this Kind); };
};
void MyDBTableButtonBarWidget::DoAction(MyDBTableButtonBarButtonKind Kind)
{
switch (Kind)
{
case MyDBTableButtonBarButtonKind::GoFirst:
this.GoFirst();
break;
case MyDBTableButtonBarButtonKind::GoLast:
this.GoLast();
break;
}
}
In this example, there is a widget control that is a bar composed of buttons, the buttonbar is referenced to a D.B. table, and has several buttons for a specific action,
like select the first record of the table, edit, move to the next.
In order to do so, each button class has friend access to private & protected methods, of the given control. As previous answer in this post, usually friend classes act a single class, decomposed in several smaller classes.
It's not a finished example, its only a general idea.
I have a simple, low-level container class that is used by a more high-level file class. Basically, the file class uses the container to store modifications locally before saving a final version to an actual file. Some of the methods, therefore, carry directly over from the container class to the file class. (For example, Resize().)
I've just been defining the methods in the file class to call their container class variants. For example:
void FileClass::Foo()
{
ContainerMember.Foo();
}
This is, however, growing to be a nuisance. Is there a better way to do this?
Here's a simplified example:
class MyContainer
{
// ...
public:
void Foo()
{
// This function directly handles the object's
// member variables.
}
}
class MyClass
{
MyContainer Member;
public:
void Foo()
{
Member.Foo();
// This seems to be pointless re-implementation, and it's
// inconvenient to keep MyContainer's methods and MyClass's
// wrappers for those methods synchronized.
}
}
Well, why not just inherit privatly from MyContainer and expose those functions that you want to just forward with a using declaration? That is called "Implementing MyClass in terms of MyContainer.
class MyContainer
{
public:
void Foo()
{
// This function directly handles the object's
// member variables.
}
void Bar(){
// ...
}
}
class MyClass : private MyContainer
{
public:
using MyContainer::Foo;
// would hide MyContainer::Bar
void Bar(){
// ...
MyContainer::Bar();
// ...
}
}
Now the "outside" will be able to directly call Foo, while Bar is only accessible inside of MyClass. If you now make a function with the same name, it hides the base function and you can wrap base functions like that. Of course, you now need to fully qualify the call to the base function, or you'll go into an endless recursion.
Additionally, if you want to allow (non-polymorphical) subclassing of MyClass, than this is one of the rare places, were protected inheritence is actually useful:
class MyClass : protected MyContainer{
// all stays the same, subclasses are also allowed to call the MyContainer functions
};
Non-polymorphical if your MyClass has no virtual destructor.
Yes, maintaining a proxy class like this is very annoying. Your IDE might have some tools to make it a little easier. Or you might be able to download an IDE add-on.
But it isn't usually very difficult unless you need to support dozens of functions and overrides and templates.
I usually write them like:
void Foo() { return Member.Foo(); }
int Bar(int x) { return Member.Bar(x); }
It's nice and symmetrical. C++ lets you return void values in void functions because that makes templates work better. But you can use the same thing to make other code prettier.
That's delegation inheritance and I don't know that C++ offers any mechanism to help with that.
Consider what makes sense in your case - composition (has a) or inheritance (is a) relationship between MyClass and MyContainer.
If you don't want to have code like this anymore, you are pretty much restricted to implementation inheritance (MyContainer as a base/abstract base class). However you have to make sure this actually makes sense in your application, and you are not inheriting purely for the implementation (inheritance for implementation is bad).
If in doubt, what you have is probably fine.
EDIT: I'm more used to thinking in Java/C# and overlooked the fact that C++ has the greater inheritance flexibility Xeo utilizes in his answer. That just feels like nice solution in this case.
This feature that you need to write large amounts of code is actually necessary feature. C++ is verbose language, and if you try to avoid writing code with c++, your design will never be very good.
But the real problem with this question is that the class has no behaviour. It's just a wrapper which does nothing. Every class needs to do something other than just pass data around.
The key thing is that every class has correct interface. This requirement makes it necessary to write forwarding functions. The main purpose of each member function is to distribute the work required to all data members. If you only have one data member, and you've not decided yet what the class is supposed to do, then all you have is forwarding functions. Once you add more member objects and decide what the class is supposed to do, then your forwarding functions will change to something more reasonable.
One thing which will help with this is to keep your classes small. If the interface is small, each proxy class will only have small interface and the interface will not change very often.