I have read documentation, there is no need to explain, how we can access non-static felds in BeforeAll method etc. I am looking for an answer - why TestInstance(PER_CLASS) solve static in the method signature BeforeAll method? In other words - how does it internally works? There is no explaination about it in official docs, just said
#BeforeAll methods must have a void return type, must not be private, and must be static by default. Consequently, #BeforeAll methods are not supported in #Nested test classes or as interface default methods unless the test class is annotated with #TestInstance(Lifecycle.PER_CLASS)
And that is all. It is not clear, not obvious. Suppose, I do not understand something.
Related
When should I mark the static method of a specific class as private other than public?
What aspects should I consider when making such considerations.
What are the advantages for mark the static method as private?
Any simple example would be appreciated, which could help me fully understand this matter.
UPDATE:
As per this answer, which says that[emphasise mine]:
This function could easily have been made freestanding, since it doesn't require an object of the class to operate within. Making a function a static member of a class rather than a free function gives two advantages:
It gives the function access to private and protected members of any object of the class, if the object is static or is passed to the function;
It associates the function with the class in a similar way to a namespace.
How to fully understand the statements above?
The general rule for methods (static or otherwise) is to make them private if possible — i.e. unless you absolutely need them to be callable from other classes (which is to say, you need them to be part of your class’s public API)
The reason for making as much as possible private is simple: in the future, you’ll be able to change anything that is private, without breaking a bunch of other classes that were written to call the old version of the method. Changing a public method is more problematic, because other classes might be depending on it.
Is there any way in C++ by which we can declare virtual method un-overridable just like final methods in Java.
I know by making default constructor private of class I can make class final but what about just virtual method ?
Thanks
If you declare your method virtual like so:
virtual myMethod();
Then they can be overriden. Remove virtual to make them "un-overidable"
Since C++11, you can also use final with virtual like so:
virtual myMethod() final;
Final keyword
Starting from C++ 11, there is as well a final keyword which can be used both on classes and methods.
It's to my knowledge not possible to do this with prior versions.
See https://en.wikipedia.org/wiki/C%2B%2B11#Explicit_overrides_and_final
Despite the fact that C++11 and later allows method to be declared final, I dare say it is not a good thing to do. Do not seal down your class! Users of it might have inventive scenarios, and they might need to tweak it a bit. Why deprive them of this option?
If you look into standard library implementation (one of the best sources of really good programming in terms of both efficiency and style) you will see that members are never final, nor are the classess themselves.
How to make a final class in C++ versions before C++11:
https://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Final_Class
if I have a class with a helper (private member) class within it, like this
class Obj;
class Helper {
friend class Obj;
private:
int m_count;
Helper(){ m_count = 0;}; // Note this is a private constructor
void incrementCount(){
++m_count;
};
};
class Obj {
Helper *m_pHelper;
// note that this is a private getter
int getHelperCount() { return m_pHelper->m_count; };
// the public API starts here
public:
Obj() { m_pHelper = new Helper(); };
void incrementCount(){ m_pHelper->incrementCount(); };
};
So how may I TDD such a system?
auto obj = new Obj();
obj->incrementCount();
// what to assert???
That is my question and the following is just some background.
Response to some answers and comments.
If noone outside the class should be interested, then your tests should not be interested either. – Arne Mertz
If nobody is interested in the value outside the class, why are you – utnapistim
Even if no one outside needs the value, I may still want to know that if it's set correctly, as it is used by other self contained internal method of the class that use that value. Maybe the value is the speed where the controller will use it to update the model. Or maybe it's the position where the view will use it to draw something on the screen. And in fact all other components of Obj would be able to access that variable. It may be a bad design issue, and in this case I would like to know what better alternatives I can have. The design is listed in the background section at the bottom of this post.
define private public - Marson Mao
Love this ingenious abuse of keywords haha. But may not be concluded as the best solution just yet.
You need to "expose" the friendship relation in the header of your class. Thus you have to acknowledge there the existence of a class used to test yours.
If you use the pImpl idiom, you could make the members of the pImpl itself all public, the pImpl itself private and give your unit tests access to the pImpl - CashCow
Does this mean that I should friend the test in my original class? Or add extra "test" methods to it?
I just started TDD very recently. Is it common (or better is it good) to intrude the original class with test class dependency? I don't think I have the appropriate knowledge to judge. Any advice on this?
Miscellaneous: AFAIK TDD is not just writing test, but instead a development process. I have read that I should only write tests to the public interface. But the problem is, like the situation in question, most of the codes etc are contained within private class. How may I use TDD to create these codes?
Background
FYI if you would like to know why I am making a private class:
I am developing a game from cocos2dx. The game engine adopts a Node tree structure for the updates, rendering etc and every game object would inherit from a Node class provided in the engine. Now I want to implement the MVC pattern on a game object. So for each object I basically created a Object class with 3 helper classes corresponding to each of the MVC components named ObjectModel, ObjectView, ObjectController. Theoretically no one should access the MVC classes directly and would only be accessed somehow through the Object class so I make the 3 of them private. The reason of making the MVC components explicitly as classes is because the View and Controller are updating at different rates (more specifically the Controller performs frame dependent updates, while the View do a simple interpolation based on the model data). The Model class is created purely for religious reasons lol.
Thanks in advance.
How to test friend functions of private class?
Thou shalt not!
A class (or module or library or whatever) exposes a public interface for a reason. You have the public interface (which is geared for client use, so it has invariants, preconditions, postconditions, side-effects, whatever - which can and should be tested) and implementation details, that allow you to implement the public interface, easier.
The point of having a private implementation, is that you are allowed to change it as you please, without affecting other code (without affecting even tests). All tests should pass after you change your private implementation, and client (and test) code should (by design) not care at all that you changed the private implementation.
So how may I TDD such a system?
TDD your public interface only. Testing implementation details means you end up coding to an implementation, instead of an interface.
Regarding your comment:
The problem is I don't even have a getter in the public interface. So how can my test check that the value is 0 or 1? And the getter is intentionally made private as no one should be interested in the value outside the class
If nobody is interested in the value outside the class, why are you (i.e. why would you wish to test for it?)
The #define private public trick can have side effects with the way some compiler are mangling function symbols (Visual c++ compiler is including access specifier in its name mangling)
You can also change visibility with the using statement :
struct ObjTest : public Obj
{
using Obj::incrementCount;
}
But like other people said, try to not test private stuff if possible.
I have encounter such problem when I was writing unit test as well.
After some searching I decided the most effective way is to add this in your Test.cpp:
#define private public
NOTE: add this before your desired include file, maybe your Obj.h, for example.
I think this method looks crazy but it's actually reasonable, because this #define only affect your test file, so all other people using your Obj.h is totally fine.
Some reference:
Unit testing of private methods
I vote, as #Marson Mao says, for #define private public.
If you want to control what to make private or public a bit more, you can do this in yourtests.cpp
#define private public
#include "IWantAccessViolationForThis.h"
#undef private
#include "NormalFile.h"
This way you can have a bit more control and try to do this trick in as few places as possible.
Another nice property of this approach is that it is non-intrusive, meaning that you don't need to clutter your real implementation and header files with #ifdefs for testing and not testing modes.
Your friend has full access to the class that it is a friend of. This might be done for many reasons and one of those could well be for unit-testing purpose, i.e. you want to be able to write a unit test that can call private members of the class and check the internal variables show what you would expect them to show, but you do not want that to be part of the public API.
You need to "expose" the friendship relation in the header of your class. Thus you have to acknowledge there the existence of a class used to test yours. No worries, you develop in the real world and classes are tested.
In order to write a unit test you will want to implement that class to provide protected member functions (probably static ones) that call all the relevant private functions or get the private members, and then you write classes that derive from yours. Note that those will not have direct access as friendship is not inherited, thus the static protected members.
If you use the pImpl idiom, you could make the members of the pImpl itself all public, the pImpl itself private and give your unit tests access to the pImpl (through the same model as above). This is now simpler as you only need to create one method for your "tester".
With regards to data members of a class, in recent years I have been known to put all these into a struct, i.e. have them all public, and then for the class to have a private instance of that struct. It can be easier for handling this kind of thing, and also serialisation / factories to your class, where they can create the struct which is all public, then construct your class from it.
I have a question about static member of class in c++, since the static member belongs to the class not any instance of class, so should the static member be declared as public, private?
Whether or not to declare a member public or private has nothing to do with whether it is static or not. You can have a static member be either public or private; both uses are acceptable depending on the situation.
Basically, if you want or need components outside of the class to have direct access to the static member, make it public. Otherwise, make it private.
Actually the static member is shared by all instances of the class. If it was a data member for example you could use is to count how many instances of the class were created. You can declare it either private or public or protected depending on your needs.
You're talking about making some static class members private to the class, so that instances of the class can't access them. Unfortunately I don't think c++ has any syntactical mechanism that you can use to enforce that at compile time. You might be able to pull off a runtime check, but it would be convoluted to say the least.
Really, I'm not sure why you would want to do what your asking. If you are already in ownership of and editing the class, you are also able to edit all the instance methods to ensure they don't use the static member. If you want to try to enforce it you'll have to put a big heavy comment next to your static member saying "Instance methods shouldn't use this" and make sure your team knows it. In general, you don't have to be religious about accessor modifiers like public/private in order to write good code so I would simply say don't worry about trying to enforce what you suggested.
Other object-oriented languages could provide what you are asking for as they draw more of distinction between classes and instances. e.g. Scala, Smalltalk.
is there a standard in order of functions in cpp file?
there are:
global functions
constructors
destructors
getters
setters
algoritmic functions
if qt, slots
if a derived class, overrided functions
static functions
any function type that i can not name...
in cpp file, is there any good way to order?
i order them as i wrote in the list above.
i know that it does not change anything but i care about good looking code...
how do you order?
my personal order is given by the order inside the class declaration:
class MyClass
{
public:
MyClass();
~MyClass();
void start();
protected:
static void init(MyClass *);
private:
int m_iCounter; ///< counter variable for....
};
would look like this in .cpp:
MyClass::MyClass() :
m_iCounter(0)
{
...
}
MyClass::~MyClass() {
...
}
void MyClass::start() {
...
}
void MyClass::init(MyClass *) {
...
}
The order is defined as followed:
Constructors + Destructors
(only for Qt projects:) signals
public methods - ordered by importance, e.g. first comes start() and stop(), then getters and setters
protected methods ordered by importance
protected members
private methods
private members
Hope that helps.
ciao,
Chris
This may seem silly, but I try to order my public methods by "order of 'normal' use", so constructors come first, then public doStuff methods, then close methods... the exception to this "rule" is the ~destructor, which comes after the last constructor.
Last comes any private "helper" methods.
I use this same approach in all languages... (C++, Java, C#, Perl, sh, or whatever) and nobody has actually shot-me for it (yet).
Cheers. Keith.
The way I'm used to ordering is from the Symbian platform where the order is:
public, protected, private methods
public, protected, private variables
The reason for this was guided by rules for extending already released interfaces for backwards compatibility. As the most likely thing to add is a private variable, they are placed at the end of the class so that adding a new one won't change the location of any other variables in the class. Things that change the interface then come before this in the order 'public, protected'. The ordering is then copied for the class methods although these won't change the memory location of any variables in an instance of the class.
And don't ask about the guidelines for virtual functions ;)
This is far less important now than it used to be. All decent IDEs these days have (or should have) the ability to go to a definition or reference with a right-click or other simple gesture. Searching through the code is a waste of time.
I typically order them:
Constructor
Destructor
Whatever order I implement the rest
I then go back and group logical/related functionality together
It is probably more important to group related things/order things in a header file for readability than it is in a cpp file.
Inside of a class, there is no strict rule by the language. Outside of the class you need to ensure that a declaration precedes a definition when the two are separate.
In general, you will find that the team you work with will set forth any format rules regarding source files. This is just aesthetics, however, as it has no effect on the actual execution of the program.
Our company's standard is:
constructors
destructors
public methods (sorted alphabetically)
private methors (sorted alphabetically)
From the most important to the lowest:
Private Variables (not kidding, they reveal most of the inner workings of your the class)
Constructors
Public Methods
Protected Methods
Private Methods
The methods themselves should be ordered by their "level of abstraction": higher level: up, lower level: down, in other words, structure your methods so that they call only methods below.
Sometimes it's handy to have a few local helper functions in an unnamed namespace (aka anonymous namespace) within the CPP file. If so, I'd recommend having those functions on top (within the CPP file), just to be sure that they are defined before any other function that would call them.
I use my IDE to goto the functions in my cpp file, and it orders it alphabetically, or i do a search, and with search while you type, this is very fast.
So for me there is absolutely no difference in workflow depending on the order of functions in the .cpp file...