DrDobbs posted another example of why you must have proper test coverage in order to avoid introducing regressions into software releases.
Category Archives: Programming
Flat Containers in Boost
Jon Kalb posted an article on flat containers in boost.
Alex Stepanov, the STL’s creator, has been quoted as saying, “Use vectors whenever you can. If you cannot use vectors, redesign your solution so that you can use vectors.”
The Boost Container library has a family of flat_* containers that have associative container interfaces and semantics, but are implemented as sorted vectors
Filed under C++, Programming
Floating Point representation
Searching for a neat data type that can represent either a double or an error (similar to a boost::optional but where the name suggests the possibility of error and the type could hold an error string. I came across this StackOverflow page with an excellent answer by Jon Skeet:
Decimal numbers can be represented exactly, if you have enough space – just not by floating binary point numbers. If you use a floating decimal point type (e.g. System.Decimal in .NET) then plenty of values which can’t be represented exactly in binary floating point can be exactly represented.
Let’s look at it another way – in base 10 which you’re likely to be comfortable with, you can’t express 1/3 exactly. It’s 0.3333333… (recurring). The reason you can’t represent 0.1 as a binary floating point number is for exactly the same reason. You can represent 3, and 9, and 27 exactly – but not 1/3, 1/9 or 1/27.
The problem is that 3 is a prime number which isn’t a factor of 10. That’s not an issue when you want to multiply a number by 3: you can always multiply by an integer without running into problems. But when you divide by a number which is prime and isn’t a factor of your base, you can run into trouble (and will do so if you try to divide 1 by that number).
Although 0.1 is usually used as the simplest example of an exact decimal number which can’t be represented exactly in binary floating point, arguably 0.2 is a simpler example as it’s 1/5 – and 5 is the prime that causes problems between decimal and binary.
Filed under Programming
Software as Design
A LinkedIn discussion included a link to this series of essays, written twenty years ago about software as an engineering discipline – lots of it remains true today.
Filed under C++, Programming
Big Software Projects
The BaseLineScenario has posted on ObamaCare. Interesting to that they stress the importance of good people:
Consulting firms, which bill by the hour, make money by staffing projects with lots of people at relatively low cost, which is absolutely the wrong way to develop software; the productivity differentials in software are so vast that you can often get ten times as much output (of quality software) for less than twice the price, while a bad developer will do more harm than good to a project.
Filed under Programming
InterlockedIncrement
Raymond Chen blogged about the internals of InterlockedIncrement and InterlockedCompareExchange.
Filed under C++, Programming
Unit Testing with GTest and GMock
In recent years, I’ve found myself writing less user interface code and more server code (typically COM servers that are exercised on client workstations or on nodes in a compute farm). Given the lack of a UI for driving and testing the code (excepting spreadsheets), automated tests are vital to achieve a high degree of code coverage.

Given that I’ve been doing this for years now, I was surprised to learn that I haven’t been writing unit tests, as I previously supposed. According to The Art of Unit Testing, the tests I’ve been writing are typically interaction tests. These are useful too, but unless a component can be tested in isolation with tests that run without delay due to network/database interaction, it isn’t a unit test.
Since reading the book, I’ve adopted the Google Test framework for both writing unit tests and implementing mock objects to accompany the tests. Without a good library for writing mock objects, you’re dragged straight back in to writing tests that call other objects in your library. With GMock, you can easily create mock objects and inject behaviour into them in order to test your server code in various scenarios. Using GTest and GMock is easy – just call RUN_ALL_TESTS() in main, and the framework discovers all the unit test you’ve written and launches them:
#include "gmock\gmock.h"
using namespace testing;
// Start writing unit tests here!
int _tmain(int argc, _TCHAR* argv[])
{
::InitGoogleMock( &argc, argv );
return RUN_ALL_TESTS();
}
Here’s a simple example that defines a WeatherStation interface and a UserInterface class. We wish to test the UserInterface, but the weather station isn’t written yet – so we define a MockWeatherStation, and set up tests to invoke the UserInterface in different situations:
#include "gmock\gmock.h"
#include <iostream>
#include <list>
#include <memory>
class WeatherStation
{
public:
virtual ~WeatherStation(){};
typedef enum
{
North, South, East, West
} Direction;
typedef enum
{
Optimistic, Pessimistic
} Outlook;
// NB Semantics on wind deliberately ugly to show a neat feature in gmock
virtual void wind( Direction* pDirection, double* strength ) const = 0;
virtual double rainfall() const = 0;
virtual std::string prediction( Outlook outlook ) const = 0;
};
class UserInterface
{
public:
UserInterface( const std::shared_ptr<WeatherStation>& weather_station ) :
weather_station_( weather_station )
{
}
typedef enum
{
Heavy, Medium, Light
} Range;
Range rain()
{
auto rainfall = weather_station_->rainfall();
if ( 0.0 <= rainfall && rainfall < 2.0 ) return Light;
else if ( 2.0 <= rainfall && rainfall < 4.0 ) return Medium;
else return Heavy;
}
Range wind()
{
WeatherStation::Direction direction;
double strength;
weather_station_->wind( &direction, &strength );
if ( 0.0 <= strength && strength < 5.0 ) return Light;
else if ( 5.0 <= strength && strength < 10.0 ) return Medium;
else return Heavy;
}
std::pair<std::string, std::string> predict_range()
{
return std::make_pair(
weather_station_->prediction( WeatherStation::Optimistic ),
weather_station_->prediction( WeatherStation::Pessimistic ) );
}
private:
std::shared_ptr<WeatherStation> weather_station_;
};
using namespace testing;
class MockWeatherStation : public WeatherStation
{
public:
MOCK_CONST_METHOD0( rainfall, double() );
MOCK_CONST_METHOD2( wind, void(WeatherStation::Direction*, double*) );
MOCK_CONST_METHOD1( prediction, std::string( WeatherStation::Outlook ) );
};
TEST( WeatherStationUserInterface, rain_should_be_heavy )
{
auto weather_station = std::make_shared<MockWeatherStation>();
// GMock: specify a simple return value using Return(x)
// Here, part of the test is that the Mock should be called once,
// hence the 'WillOnce' call (more than one call would be an error).
// If multiple calls should happen during the test,
// use 'WillRepeatedly' instead.
EXPECT_CALL( *weather_station, rainfall() )
.WillOnce( Return(5.0) );
UserInterface ui( weather_station );
EXPECT_EQ( UserInterface::Heavy, ui.rain() );
}
TEST( WeatherStationUserInterface, wind_should_be_light )
{
auto weather_station = std::make_shared<MockWeatherStation>();
// GMock: specify out parameter values using SetArgPointee
EXPECT_CALL( *weather_station, wind(_,_) )
.WillOnce( DoAll( SetArgPointee<0>( WeatherStation::North ),
SetArgPointee<1>( 0.5 )) );
UserInterface ui( weather_station );
EXPECT_EQ( UserInterface::Light, ui.wind() );
}
TEST( WeatherStationUserInterface, predictions_are_displayed )
{
auto weather_station = std::make_shared<MockWeatherStation>();
// GMock: inject more complex logic using C++11 lambdas,
// and pattern match on the input value
EXPECT_CALL( *weather_station, prediction(WeatherStation::Optimistic) )
.WillOnce( Invoke( []( WeatherStation::Outlook _ ) -> std::string
{
return "Sunny";
}) );
EXPECT_CALL( *weather_station, prediction(WeatherStation::Pessimistic) )
.WillOnce( Invoke( []( WeatherStation::Outlook _ ) -> std::string
{
return "Overcast";
}) );
UserInterface ui( weather_station );
auto predicted_range = ui.predict_range();
EXPECT_EQ( "Sunny", predicted_range.first );
EXPECT_EQ( "Overcast", predicted_range.second );
}
When you run the executable, it’s easy to spot if the tests pass or fail:

As a bonus, Visual Studio 2012 has neat integration for GoogleTest:

See also
Filed under C++, C++ Code, Programming
C++: Race conditions and Data races
According to this discussion on Stack Overflow, we should make a distinction between race conditions and data races. This blog post defines the terms and gives a neat example where the code is modified to exhibit zero, one or both behaviours.
Here’s an example of a race condition – the ordering of the execution affects the outcome (this can occur if one thread checks a value then performs an action, giving another thread the change to mutate the variable in between):
if (x == 5) // The "Check"
{
y = x * 2; // The "Act"
// If another thread changed x in between "if (x == 5)" and "y = x * 2" above,
// y will not be equal to 10.
}
And here’s an example of a data race – a variable is mutated by multiple threads without synchronisation:
// Execute this function on five threads simultaneously
for ( int i = 0; i < 10000; i++ )
{
x = x + 1;
}
In both cases, use of a synchronisation object across all the threads involved (e.g. a mutex) would address the issue.
Filed under C++, C++ Code, Programming
C++: Function overload preferences
The function overload rules in C++ are sometimes surprising. Herb Sutter wrote an excellent Guru of the Week article on function overload rules some time ago, but here’s some code to differentiate between some of the common overloads:
#include <iostream>
#include <string>
template<typename T>
void foo(T t)
{
std::cout << "Generic Template function: " << t << "\n";
}
template<>
void foo<int>(int i)
{
std::cout << "Function template specialization for int: " << i << "\n";
}
template<>
void foo<bool>(bool b)
{
std::cout << "Function template specialization for bool: " << b << "\n";
}
void foo( double d )
{
std::cout << "Non-template overload for double: " << d << "\n";
}
void foo( int i )
{
std::cout << "Non-template overload for int: " << i << "\n";
}
int main()
{
std::string s = "Hello, World";
foo(s); // Calls generic template
bool b = true;
foo(b); // Calls template specialization
double d = 1.0;
foo(d); // Exact match to non-template overload
int i = 0;
foo(i); // Exact match (better than template specialization)
short sh = 255;
foo(sh); // Not exact match, calls generic template
return 0;
}

Filed under C++, C++ Code, Programming
C++: functional programming and type classes
Functional C++ posted an article introducing type classes for C++.
Filed under C++, Programming