Вопрос

When designing functions inside a C++ class, I often keep testing in mind. So when I finish all the functionalists of a class, very often several functions that are only used for testing purpose are added in the class as well. Take the following example:

class SimpleClass
{
 public: 
    int a;
    int b;
    void fun1();
    void fun2();
    void testIntermediateResult();
 private:
    void _fun1();
    void _fun2();

};

In this function testIntermediateResult is only needed for testing purpose. Is it a good practice just leave the function inside the class or should I do something like that:

 class SimpleClass
    {
     public: 
        int a;
        int b;
        void fun1();
        void fun2();
#ifdef TESTING
        void testIntermediateResult();
#endif
     private:
        void _fun1();
        void _fun2();

    };

The philosophy here is when this class has been finished testing and will be given to the clients then TESTING will be defined and this function will not be inside the class. Therefore, my question is: is really needed to remove the testing function when the class is given to the client? Suppose the client will not use the testing function, what's the effect of adding several redundant testing functions inside a class? Thanks.

Это было полезно?

Решение

I'm assuming that your client is not going to be involved in testing the class that you're handing over. I would not want to add testing functions directly into the class itself as there's a possibility that they could disrupt the behaviour of the class. As for the client, I would prefer not to give them something with a test function in it since:

  • It's not necessary - it's not their job to test it.
  • They could decide to try to use it - who knows what'll happen then?

It's just simpler if they don't see it. As for using the pre-processor, this could be fraught with problems particularly if you have attributes that need to be guarded in the same way. If any of them are missed or your macro is redefined in the build process by the client then you could get run-time crashes due to class size mismatches etc.

I'd favour having a one-to-one external class to test your deliverable classes. Something like TestSimpleClass which performs the testing. There are a number of advantages to this approach:

  1. It's entirely separate from your code and not built into it so you aren't bloating code or causing any potential issues with it.
  2. It's going to test your class interface the way your client sees it (i.e. black box testing)
  3. Because it's separate, you don't have to give it to your client - they never have to know about it.

If you really want to test the internals of the class, you can always make your test class a friend of your deliverable class. It's only one line extra in the deliverable class and you still don't have to ship your test classes or libraries.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top