Table of Contents for
Mastering C++ Programming

Version ebook / Retour

Cover image for bash Cookbook, 2nd Edition Mastering C++ Programming by Jeganathan Swaminathan Published by Packt Publishing, 2017
  1. Mastering C++ Programming
  2. Title Page
  3. Copyright
  4. Mastering C++ Programming
  5. Credits
  6. About the Author
  7. About the Reviewer
  8. www.PacktPub.com
  9. Why subscribe?
  10. Customer Feedback
  11. Dedication
  12. Table of Contents
  13. Preface
  14. What this book covers
  15. What you need for this book
  16. Who this book is for
  17. Conventions
  18. Reader feedback
  19. Customer support
  20. Downloading the example code
  21. Errata
  22. Piracy
  23. Questions
  24. C++17 Features
  25. C++17 background
  26. What's new in C++17?
  27. What features are deprecated or removed in C++17?
  28. Key features in C++17
  29. Easier nested namespace syntax
  30. New rules for type auto-detection from braced initializer list 
  31. Simplified static_assert 
  32. The std::invoke( ) method
  33. Structured binding
  34. If and Switch local scoped variables
  35. Template type auto-deduction for class templates
  36. Inline variables
  37. Summary
  38. Standard Template Library
  39. The Standard Template Library architecture
  40. Algorithms
  41. Iterators
  42. Containers
  43. Functors
  44. Sequence containers
  45. Array
  46. Code walkthrough
  47. Commonly used APIs in an array
  48. Vector 
  49. Code walkthrough
  50. Commonly used vector APIs
  51. Code walkthrough
  52. Pitfalls of a vector
  53. List 
  54. Commonly used APIs in a list
  55. Forward list
  56. Code walkthrough
  57. Commonly used APIs in a forward_list container
  58. Deque
  59. Commonly used APIs in a deque
  60. Associative containers
  61. Set
  62. Code walkthrough
  63. Commonly used APIs in a set
  64. Map
  65. Code walkthrough
  66. Commonly used APIs in a map
  67. Multiset
  68. Multimap
  69. Unordered sets
  70. Unordered maps
  71. Unordered multisets
  72. Unordered multimaps
  73. Container adapters
  74. Stack
  75. Commonly used APIs in a stack
  76. Queue
  77. Commonly used APIs in a queue
  78. Priority queue
  79. Commonly used APIs in a priority queue
  80. Summary
  81. Template Programming
  82. Generic programming
  83. Function templates
  84. Code walkthrough
  85. Overloading function templates
  86. Code walkthrough
  87. Class template
  88. Code walkthrough
  89. Explicit class specializations
  90. Code walkthrough
  91. Partial template specialization
  92. Summary
  93. Smart Pointers
  94. Memory management
  95. Issues with raw pointers
  96. Smart pointers
  97. auto_ptr
  98. Code walkthrough - Part 1
  99. Code walkthrough - Part 2
  100. unique_ptr
  101. Code walkthrough
  102. shared_ptr
  103. Code walkthrough
  104. weak_ptr
  105. Circular dependency
  106. Summary
  107. Developing GUI Applications in C++
  108. Qt 
  109. Installing Qt 5.7.0 in Ubuntu 16.04
  110. Qt Core
  111. Writing our first Qt console application
  112. Qt Widgets
  113. Writing our first Qt GUI application
  114. Layouts
  115. Writing a GUI application with a horizontal layout
  116. Writing a GUI application with a vertical layout
  117. Writing a GUI application with a box layout
  118. Writing a GUI application with a grid layout
  119. Signals and slots
  120. Using stacked layout in Qt applications
  121. Writing a simple math application combining multiple layouts
  122. Summary
  123. Multithreaded Programming and Inter-Process Communication
  124. Introduction to POSIX pthreads
  125. Creating threads with the pthreads library
  126. How to compile and run
  127. Does C++ support threads natively?
  128. How to write a multithreaded application using the native C++ thread feature
  129. How to compile and run
  130. Using std::thread in an object-oriented fashion
  131. How to compile and run
  132. What did you learn?
  133. Synchronizing threads
  134. What would happen if threads weren't synchronized?
  135. How to compile and run
  136. Let's use mutex
  137. How to compile and run
  138. What is a deadlock?
  139. How to compile and run
  140. What did you learn?
  141. Shared mutex
  142. Conditional variable
  143. How to compile and run
  144. What did you learn?
  145. Semaphore
  146. Concurrency
  147. How to compile and run
  148. Asynchronous message passing using the concurrency support library
  149. How to compile and run
  150. Concurrency tasks
  151. How to compile and run
  152. Using tasks with a thread support library
  153. How to compile and run
  154. Binding the thread procedure and its input to packaged_task 
  155. How to compile and run
  156. Exception handling with the concurrency library
  157. How to compile and run
  158. What did you learn?
  159. Summary
  160. Test-Driven Development
  161. TDD
  162. Common myths and questions around TDD
  163. Does it take more efforts for a developer to write a unit test? 
  164. Is code coverage metrics good or bad?
  165. Does TDD work for complex legacy projects? 
  166. Is TDD even applicable for embedded or products that involve hardware?
  167. Unit testing frameworks for C++
  168. Google test framework
  169. Installing Google test framework on Ubuntu
  170. How to build google test and mock together as one single static library without installing?
  171. Writing our first test case using the Google test framework
  172. Using Google test framework in Visual Studio IDE
  173. TDD in action
  174. Testing a piece of legacy code that has dependency
  175. Summary
  176. Behavior-Driven Development
  177. Behavior-driven development
  178. TDD versus BDD
  179. C++ BDD frameworks
  180. The Gherkin language
  181. Installing cucumber-cpp in Ubuntu
  182. Installing the cucumber-cpp framework prerequisite software
  183. Building and executing the test cases
  184. Feature file
  185. Spoken languages supported by Gherkin
  186. The recommended cucumber-cpp project folder structure
  187. Writing our first Cucumber test case
  188. Integrating our project in cucumber-cpp CMakeLists.txt
  189. Executing our test case
  190. Dry running your cucumber test cases
  191. BDD - a test-first development approach
  192. Let's build and run our BDD test case
  193. It's testing time!
  194. Summary
  195. Debugging Techniques
  196. Effective debugging
  197. Debugging strategies
  198. Debugging tools
  199. Debugging your application using GDB
  200. GDB commands quick reference
  201. Debugging memory leaks with Valgrind
  202. The Memcheck tool
  203. Detecting memory access outside the boundary of an array
  204. Detecting memory access to already released memory locations
  205. Detecting uninitialized memory access
  206. Detecting memory leaks
  207. Fixing the memory leaks
  208. Mismatched use of new and free or malloc and delete
  209. Summary
  210. Code Smells and Clean Code Practices
  211. Code refactoring
  212. Code smell
  213. What is agile?
  214. SOLID design principle
  215. Single responsibility principle
  216. Open closed principle
  217. Liskov substitution principle
  218. Interface segregation
  219. Dependency inversion
  220. Code smell
  221. Comment smell
  222. Long method
  223. Long parameter list
  224. Duplicate code
  225. Conditional complexity
  226. Large class
  227. Dead code
  228. Primitive obsession
  229. Data class
  230. Feature envy
  231. Summary

TDD in action

Let's see how to develop an Reverse Polish Notation (RPN) calculator application that follows the TDD approach. RPN is also known as the postfix notation. The expectation from the RPN Calculator application is to accept a postfix math expression as an input and return the evaluated result as the output. 

Step by step, I would like to demonstrate how one can follow the TDD approach while developing an application. As the first step, I would like to explain the project directory structure, then we'll move forward. Let's create a folder named Ex2 with the following structure:

Figure 7.19

The googletest folder is the gtest test library that has the necessary gtest and gmock header files. Now libgtest.a is the Google test static library that we created in the previous exercise. We are going to use the make utility to build our project, hence I have placed a Makefile in the project home directory. The src directory will hold the production code, while the test directory will hold all the test cases that we are going to write.  

Before we start writing test cases, let's take a postfix math "2  5  *  4  +  3  3  *  1  +  /" and understand the standard postfix algorithm that we are going to apply to evaluate the RPN math expression. As per the postfix algorithm, we are going to parse the RPN math expression one token at a time. Whenever we encounter an operand (number), we are going to push that into the stack. Whenever we encounter an operator, we are going to pop out two values from the stack, apply the math operation, push back the intermediate result into the stack, and repeat the procedure until all the tokens are evaluated in the RPN expression. At the end, when no more tokens are left in the input string, we will pop out the value and print it as the result. The procedure is demonstrated step by step in the following figure:

Figure 7.20

To start with, let's take a simple postfix math expression and translate the scenario into a test case:

Test Case : Test a simple addition
Input: "10 15 +"
Expected Output: 25.0

Let's translate the preceding test case as a Google test in the test folder, as follows:

test/RPNCalculatorTest.cpp

TEST ( RPNCalculatorTest, testSimpleAddition ) { 
         RPNCalculator rpnCalculator; 
         double actualResult = rpnCalculator.evaluate ( "10 15 +" ); 
         double expectedResult = 25.0; 
         EXPECT_EQ ( expectedResult, actualResult ); 
}

In order to compile the preceding test case, let's write the minimal production code that is required in the src folder, as follows:

src/RPNCalculator.h

#include <iostream>
#include <string>
using namespace std;

class RPNCalculator {
  public:
      double evaluate ( string );
};

As the RPN math expression will be supplied as a space-separated string, the evaluate method will take a string input argument:

src/RPNCalculator.cpp

#include "RPNCalculator.h"

double RPNCalculator::evaluate ( string rpnMathExpression ) {
    return 0.0;
}

The following Makefile class helps run the test cases every time we compile the production code:

Figure 7.21

Now let's build and run the test case and check the test case's outcome:

Figure 7.22

In TDD, we always start with a failing test case. The root cause of the failure is that the expected result is 25, while the actual result is 0. The reason is that we haven't implemented the evaluate method, hence we have hardcoded to return 0, irrespective of any input. So let's implement the evaluate method in order to make the test case pass.

We need to modify src/RPNCalculator.h and src/RPNCalculator.cpp as follows:

Figure 7.23

In the RPNCalculator.h header file, observe the new header files that are included to handle string tokenizing and string double conversion and copy the RPN tokens to the vector:

Figure 7.24

As per the standard postfix algorithm, we are using a stack to hold all the numbers that we find in the RPN expression. Anytime we encounter the + math operator, we pop out two values from the stack and add them and push back the results into the stack. If the token isn't a + operator, we can safely assume that it would be a number, so we just push the value to the stack.

With the preceding implementation in place, let's try the test case and check whether the test case passes:

Figure 7.25

Cool, our first test case has passed as expected. It's time to think of another test case. This time, let's add a test case for subtraction:

Test Case : Test a simple subtraction
Input: "25 10 -"
Expected Output: 15.0

Let's translate the preceding test case as a Google test in the test folder, as follows:

test/RPNCalculatorTest.cpp

TEST ( RPNCalculatorTest, testSimpleSubtraction ) { 
         RPNCalculator rpnCalculator; 
         double actualResult = rpnCalculator.evaluate ( "25 10 -" ); 
         double expectedResult = 15.0; 
         EXPECT_EQ ( expectedResult, actualResult ); 
}

With the preceding test case added to test/RPNCalculatorTest, it should now look like this:

Figure 7.26

Let's execute the test cases and check whether our new test case passes:

Figure 7.27

As expected, the new test fails as we haven't added support for subtraction in our application yet. This is very evident, based on the C++ exception, as the code attempts to convert the subtraction - operator into a number. Let's add support for subtraction logic in our evaluate method:  

Figure 7.28

It's time to test. Let's execute the test case and check whether things are working:

Figure 7.29

Cool! Did you notice that our test case failed in this instance? Wait a minute. Why are we excited if the test case failed? The reason we should be happy is that our test case found a bug; after all, that is the main intent of TDD, isn't?

Figure 7.30

The root cause of the failure is that the Stack operates on the basis of Last In First Out (LIFO) whereas our code assumes FIFO. Did you notice that our code assumes that it will pop out the first number first while the reality is that it is supposed to pop out the second number first? Interesting, this bug was there in the addition operation too; however, since addition is associative, the bug was kind of suppressed but the subtraction test case detected it.

Figure 7.31

Let's fix the bug as shown in the preceding screenshot and check whether the test cases will pass:

Figure 7.32

Awesome! We fixed the bug and our test case seems to certify they are fixed. Let's add more test cases. This time, let's add a test case to verify multiplication: 

Test Case : Test a simple multiplication
Input: "25 10 *"
Expected Output: 250.0

Let's translate the preceding test case as a google test in the test folder, as follows:

test/RPNCalculatorTest.cpp

TEST ( RPNCalculatorTest, testSimpleMultiplication ) { 
         RPNCalculator rpnCalculator; 
         double actualResult = rpnCalculator.evaluate ( "25 10 *" ); 
         double expectedResult = 250.0; 
         EXPECT_EQ ( expectedResult, actualResult ); 
}

We know this time the test case is going to fail, so let's fast forward and take a look at the division test case:

Test Case : Test a simple division
Input: "250 10 /"
Expected Output: 25.0

Let's translate the preceding test case as a google test in the test folder, as follows:

 

test/RPNCalculatorTest.cpp

TEST ( RPNCalculatorTest, testSimpleDivision ) { 
         RPNCalculator rpnCalculator; 
         double actualResult = rpnCalculator.evaluate ( "250 10 /" ); 
         double expectedResult = 25.0; 
         EXPECT_EQ ( expectedResult, actualResult );
}

Let's skip the test result and move forward with a final complex expression test case that involves many operations:

Test Case : Test a complex rpn expression
Input: "2  5  *  4  + 7  2 -  1  +  /"
Expected Output: 25.0

Let's translate the preceding test case as a google test in the test folder, as shown here:

test/RPNCalculatorTest.cpp

TEST ( RPNCalculatorTest, testSimpleDivision ) { 
         RPNCalculator rpnCalculator; 
         double actualResult = rpnCalculator.evaluate ( "250 10 /" ); 
         double expectedResult = 25.0; 
         EXPECT_EQ ( expectedResult, actualResult );
}

Let's check whether our RPNCalculator application is able to evaluate a complex RPN expression that involves addition, subtraction, multiplication, and division in a single expression with the following test case:

 

test/RPNCalculatorTest.cpp

TEST ( RPNCalculatorTest, testComplexExpression ) { 
         RPNCalculator rpnCalculator; 
         double actualResult = rpnCalculator.evaluate ( "2  5  *  4  +  7  2 - 1 +  /" ); 
         double expectedResult = 2.33333; 
         ASSERT_NEAR ( expectedResult, actualResult, 4 );
}

In the preceding test case, we are checking whether the expected result matches the actual result to the approximation of up to four decimal places. If the values are different beyond this approximation, then the test case is supposed to fail.

Let's check the test case output now:

Figure 7.33

Great! All the test cases are green. 

Now let's take a look at our production code and check whether there is any room for improvement:

Figure 7.34

The code is functionally good but has many code smells. It is a long method with the nested if-else condition and duplicate code. TDD is not just about test automation; it is also about writing good code without code smells. Hence, we must refactor code and make it more modular and reduce the code complexity.  

We can apply polymorphism or the strategy design pattern here instead of the nested if-else conditions. Also, we can use the factory method design pattern to create various subtypes. There is also scope to use the Null Object Design Pattern.  

The best part is we don't have to worry about the risk of breaking our code in the process of refactoring as we have a sufficient number of test cases to give us feedback in case we break our code.

First, let's understand how we could refactor the RPNCalculator design shown in Figure 7.35:

Figure 7.35

Based on the preceding design refactoring approach, we can refactor RPNCalculator as shown in Figure 7.36:

Figure 7.36

If you compare the RPNCalculator code before and after refactoring, you'll find that code complexity has reduced to a decent amount after refactoring. 

The MathFactory class can be implemented as shown in Figure 7.37:

Figure 7.37

As much as possible, we must strive to avoid if-else conditions, or in general, we must try to avoid code branching when possible. Hence, STL map is used to avoid if-else conditions. This also promotes the reuse of the same Math objects, irrespective of the complexity of the RPN expression.  

You will get an idea of how the MathOperator Add class is implemented if you refer to Figure 7.38:

Figure 7.38

The Add class definition looks as shown in Figure 7.39:

Figure 7.39

The subtract, multiplication, and division classes can be implemented in the similar fashion, as an Add class. The bottom line is that after refactoring, we can refactor a single RPNCalculator class into smaller and maintainable classes that can be tested individually.

Let's take a look at the refactored Makefile class in Figure 7.40 and test our code after the refactoring process is complete:

Figure 7.40

If all goes well, we should see all the test cases pass after refactoring if no functionalities are broken, as shown in Figure 7.41:

Figure 7.41

Cool! All the test cases have passed, hence it is guaranteed that we haven't broken the functionality in the process of refactoring. The main intent of TDD is to write testable code that is both functionally and structurally clean.