Sans Pareil Technologies, Inc.

Key To Your Business

Overview


Refresher material on functions and classes.

Functions


A named section of a program that performs a specific task. In this sense, a function is a type of procedure or routine. Some programming languages make a distinction between a function, which returns a value, and a procedure, which performs some operation but does not return a value. Functions are the fundamental building blocks for most programming languages including object oriented languages.
  • may take one or more parameters and return nothing (void) or return a value.
  • may be overloaded - same name but differ in either the number or type of parameters.
  • parameters are passed in by value, pointer, reference or const variants of these. Values and pointers work similarly in the sense that copies of the arguments specified in the function invocation are sent as parameters to the function. References on the other hand behave like aliases to an existing chunk of memory, and hence behave as though an existing chunk of memory is passed directly to the function for processing. Objects are most commonly passed as const reference, unless the purpose of the function is to modify the internal state of the object.

Classes/Objects


In programming terms, an object is a self-contained component that contains properties and functions needed to make a certain type of data useful. An object’s properties are what it knows and its functions are what it can do.

In addition to providing the functionality of the application, functions ensure that an object’s data is used appropriately by running checks for the specific type of data being used. They also allow for the actual implementation of tasks to be hidden and for particular operations to be standardised across different types of objects.

A class is a blueprint or template or set of instructions to build a specific type of object. Every object is built from a class. Each class should be designed and programmed to accomplish one, and only one, thing.

C++ also supports structures (struct) from C. Structures are very similar to classes and can be used interchangeably with due regard to visibility of instance variables and member functions.

Access Specifiers


Access specifiers govern the visibility of instances variables and member functions declared in a class.
  • private - The default specifier used for class instances.
  • protected - Makes instance variables or member functions visible to sub-classes
  • public - Makes instance variables or member functions visible to the all callers. The default specifier used for struct instances.

Constructors


Constructors (CTOR) are used to create new instances of classes/structures. The compiler automatically generates a default (no argument) and copy constructor, along with a default implementation for the copy assignment operator (=) and a destructor (DTOR) function. The default constructor is not generated if a constructor is specified in the class definition.

When initialising instance variables in a constructor prefer the variable initialiser lists over the assignment technique. This prevents unnecessary initialisation of the instance variable before the assignment takes place (when the instance variables are objects). This is also the only way to initialise const instance variables.

class Circle
{
  public:
    Circle() : radius{ 0.0 } {}

  private:
    double radius;
};



or in C++11 and onwards you can initialise variables along with their declaration.

class Circle
{
  private:
    double radius{ 0.0 };
};


C++11 introduced delegation of constructors. It is now possible to delegate from one constructor to another and so on to a final target constructor.

class Circle
{
  public:
    Circle() : Circle{ 0.0 } {}
    explicit Circle( double r ) : radius{ r } {}

  private:
    double radius;
};



References



Unit Testing


In computer programming, unit testing is a software testing method by which individual units of source code, sets of one or more computer program modules together with associated control data, usage procedures, and operating procedures, are tested to determine whether they are fit for use.

One can view a unit as the smallest testable part of an application. In procedural programming, a unit could be an entire module, but it is more commonly an individual function or procedure. In object-oriented programming, a unit is often an entire interface, such as a class, but could be an individual method. Unit tests are short code fragments created by programmers during the development process. It forms the basis for component testing.

Using an automation framework, the developer codes criteria, or result that is known to be good, into the test to verify the unit's correctness. During test case execution, the framework logs tests that fail any criterion. Many frameworks will also automatically flag these failed test cases and report them in a summary. Depending upon the severity of a failure, the framework may halt subsequent testing.

As a consequence, unit testing is traditionally a motivator for programmers to create decoupled and cohesive code bodies. This practice promotes healthy habits in software development. Design patterns, unit testing, and refactoring often work together so that the best solution may emerge.

Advantages


The goal of unit testing is to isolate each part of the program and show that the individual parts are correct. A unit test provides a strict, written contract that the piece of code must satisfy. As a result, it affords several benefits.

Find problems early


Unit testing finds problems early in the development cycle. This includes both bugs in the programmer's implementation and flaws or missing parts of the specification for the unit. The process of writing a thorough set of tests forces the author to think through inputs, outputs, and error conditions, and thus more crisply define the unit's desired behaviour. The cost of finding a bug before coding begins or when the code is first written is considerably lower than the cost of detecting, identifying, and correcting the bug later; bugs may also cause problems for the end-users of the software.

In test-driven development (TDD), which is frequently used in both extreme programming and scrum, unit tests are created before the code itself is written. When the tests pass, that code is considered complete. The same unit tests are run against that function frequently as the larger code base is developed either as the code is changed or via an automated process with the build. If the unit tests fail, it is considered to be a bug either in the changed code or the tests themselves. The unit tests then allow the location of the fault or failure to be easily traced. Since the unit tests alert the development team of the problem before handing the code off to testers or clients, it is still early in the development process.

Facilitates change


Unit testing allows the programmer to refactor code or upgrade system libraries at a later date, and make sure the module still works correctly (e.g., in regression testing). The procedure is to write test cases for all functions and methods so that whenever a change causes a fault, it can be quickly identified. Unit tests detect changes which may break a design contract.

Simplifies integration


Unit testing may reduce uncertainty in the units themselves and can be used in a bottom-up testing style approach. By testing the parts of a program first and then testing the sum of its parts, integration testing becomes much easier.

Documentation


Unit testing provides a sort of living documentation of the system. Developers looking to learn what functionality is provided by a unit, and how to use it, can look at the unit tests to gain a basic understanding of the unit's interface (API).

Unit test cases embody characteristics that are critical to the success of the unit. These characteristics can indicate appropriate/inappropriate use of a unit as well as negative behaviours that are to be trapped by the unit. A unit test case, in and of itself, documents these critical characteristics, although many software development environments do not rely solely upon code to document the product in development.

Design


When software is developed using a test-driven approach, the combination of writing the unit test to specify the interface plus the refactoring activities performed after the test is passing, may take the place of formal design. Each unit test can be seen as a design element specifying classes, methods, and observable behaviour.

Disadvantages


As with all programming techniques and patterns, unit tests have disadvantages associated with them. These however should not be used as an excuse to avoid unit testing.

Decision problem


Testing will not catch every error in the program, because it cannot evaluate every execution path in any but the most trivial programs. This problem is a superset of the halting problem, which is undecidable. The same is true for unit testing. Additionally, unit testing by definition only tests the functionality of the units themselves. Therefore, it will not catch integration errors or broader system-level errors (such as functions performed across multiple units, or non-functional test areas such as performance).

Not integration testing


An elaborate hierarchy of unit tests does not equal integration testing. Integration with peripheral units should be included in integration tests, but not in unit tests. Integration testing typically still relies heavily on humans testing manually; high-level or global-scope testing can be difficult to automate, such that manual testing often appears faster and cheaper.

Combinatorial problem


Software testing is a combinatorial problem. For example, every Boolean decision statement requires at least two tests: one with an outcome of "true" and one with an outcome of "false". As a result, for every line of code written, programmers often need 3 to 5 lines of test code. This obviously takes time and its investment may not be worth the effort. There are also many problems that cannot easily be tested at all – for example those that are nondeterministic or involve multiple threads. In addition, code for a unit test is likely to be at least as buggy as the code it is testing.

Realism


Another challenge related to writing the unit tests is the difficulty of setting up realistic and useful tests. It is necessary to create relevant initial conditions so the part of the application being tested behaves like part of the complete system. If these initial conditions are not set correctly, the test will not be exercising the code in a realistic context, which diminishes the value and accuracy of unit test results.

Record keeping


To obtain the intended benefits from unit testing, rigorous discipline is needed throughout the software development process. It is essential to keep careful records not only of the tests that have been performed, but also of all changes that have been made to the source code of this or any other unit in the software. Use of a version control system is essential. If a later version of the unit fails a particular test that it had previously passed, the version-control software can provide a list of the source code changes (if any) that have been applied to the unit since that time.

Sustainability challenges


It is also essential to implement a sustainable process for ensuring that test case failures are reviewed daily and addressed immediately. If such a process is not implemented and ingrained into the team's workflow, the application will evolve out of sync with the unit test suite, increasing false positives and reducing the effectiveness of the test suite.

Platform differences


Unit testing embedded system software presents a unique challenge: Because the software is being developed on a different platform than the one it will eventually run on, you cannot readily run a test program in the actual deployment environment, as is possible with desktop programs.

Frameworks


There are plenty of unit testing frameworks for C++. The following are a few popular ones:

Catch is one of the most popular frameworks, and will be used in this course.

References


https://web.stanford.edu/~ouster/cgi-bin/cs190-spring15/lecture.php?topic=testing
http://dbmanagement.info/Books/MIX/Best_Practices_in_Unit_Testing_Automation.pdf