Record of experiments, readings, links, videos and other things that I find on the long road.
Registro de experimentos, lecturas, links, vídeos y otras cosas que voy encontrando en el largo camino.
Showing posts with label Cpp. Show all posts
Showing posts with label Cpp. Show all posts
Saturday, March 29, 2014
Interesting Talk: "The Care and Feeding of C++'s Dragons"
I've just watched this interesting talk by Chandler Carruth about the amazing LLVM clang tools for C++:
Tuesday, March 25, 2014
Using C++11 to split strings without using the boost library
Recently I did the StringCalculator kata in C++.
In order to be able to split a string using several alternative delimiters of one or more characters I used the following function: which is using several functions from the boost library: boost::algorithm::split_regex, boost::regex and boost::join.
Yesterday I managed to use some C++11 features to get the same functionality without using the boost library. This is the resulting code which uses C++11 regex and lambdas: These are the StringUtils tests where you can see how the split and join functions work: You can find all the code in this repository.
In order to be able to split a string using several alternative delimiters of one or more characters I used the following function: which is using several functions from the boost library: boost::algorithm::split_regex, boost::regex and boost::join.
Yesterday I managed to use some C++11 features to get the same functionality without using the boost library. This is the resulting code which uses C++11 regex and lambdas: These are the StringUtils tests where you can see how the split and join functions work: You can find all the code in this repository.
Friday, March 7, 2014
Some resources about Object-Oriented Design, Testability and Legacy Code
These are some resources about Object Oriented Design, testability and legacy code that I collected for the developers at Tecnatom.
I hope that you'll find them useful.
OOP
Testing and Testability
Ports and Adapters
Legacy Code
I hope that you'll find them useful.
OOP
Testing and Testability
- Writing testable code
- Design for Testability Talk by Miško Hevery
- The Magic Tricks of Testing Talk by Sandi Metz
- Integration tests are scams Talk by J. B. Rainsberger (blog)
Ports and Adapters
Legacy Code
Some resources about the physical structure of C++ projects
These are several links about the physical structure of C++ projects that I collected for the C++ developers at Tecnatom.
I hope that you'll find them useful.
I hope that you'll find them useful.
Some resources about continuous integration for C++ projects on Windows
These are several links about continuous integration for C++ projects on Windows that I collected for the C++ developers at Tecnatom.
I hope that you'll find them useful.
C++ Continuous Integration (CI)
C++ Tools that might be interesting to use from Jenkins or on their own
I hope that you'll find them useful.
C++ Continuous Integration (CI)
C++ Tools that might be interesting to use from Jenkins or on their own
- Cppcheck (static code analysis)
- DrMemory (memory leak detector)
- Is there a good Valgrind substitute for Windows?
- C++ open source plugin for Sonar
- Visual Leak Detector for VS 2008/2010/2012
- Google’s cppclean
Thursday, March 6, 2014
Kata: Small step by step TDD kata using C++ and GoogleMock
I've just made a small TDD kata in C++ using GoogleMock.
I committed the existing code after each green and after each refactoring step.
Check the step by step process in GitHub.
I committed the existing code after each green and after each refactoring step.
Check the step by step process in GitHub.
Wednesday, March 5, 2014
Extracting reusable C++ templated functions from StringCalculator code
I've recently coded a solution to the StringCalculator kata in C++ using GoogleMock,
(you can check its code in GitHub).
In one of the refactoring steps, I extracted the code that filters out not numeric tokens to a separated helper method: filterOutNotNumericTokens:
Once all the kata requirements were satisfied, I refactored this method a little bit more using C++11 copy_if algorithm:
We can use the same technique to refactor the method that ignores numbers greater than 1000, ignoreTooBig, from this:
to this:
Notice that we had to make notTooBig a free function in order to pass it to copy_if.
To keep it as a member function we'd need to write this less readable version:
which uses the bind1st and mem_fun functions from functional.
In this case, I think it's probably better to use a lambda:
In the two previous examples we eliminated duplication using the copy_if algorithm.
We can improve the readability of this code introducing a helper templated functions, filter:
Notice that filter works only for vector, copy_if is more general. But this leads to a bit more readable code for filterOutNotNumericTokens and ignoreTooBig:
We can also use filter to refactor the getNegatives method:
The same procedure can be applied to have a map templated function that uses the transform algorithm which can then be used to refactor the convertToInts method:
This map and filter functions that we'd refactored out from the StringCalculator code are pure functions that are highly reusable and will help us to avoid duplication in another projects.
In one of the refactoring steps, I extracted the code that filters out not numeric tokens to a separated helper method: filterOutNotNumericTokens:
Once all the kata requirements were satisfied, I refactored this method a little bit more using C++11 copy_if algorithm:
We can use the same technique to refactor the method that ignores numbers greater than 1000, ignoreTooBig, from this:
to this:
Notice that we had to make notTooBig a free function in order to pass it to copy_if.
To keep it as a member function we'd need to write this less readable version:
which uses the bind1st and mem_fun functions from functional.
In this case, I think it's probably better to use a lambda:
In the two previous examples we eliminated duplication using the copy_if algorithm.
We can improve the readability of this code introducing a helper templated functions, filter:
Notice that filter works only for vector, copy_if is more general. But this leads to a bit more readable code for filterOutNotNumericTokens and ignoreTooBig:
We can also use filter to refactor the getNegatives method:
The same procedure can be applied to have a map templated function that uses the transform algorithm which can then be used to refactor the convertToInts method:
This map and filter functions that we'd refactored out from the StringCalculator code are pure functions that are highly reusable and will help us to avoid duplication in another projects.
Monday, March 3, 2014
Kata: Small step by step refactoring kata in C++
I've just made a small refactoring kata in C++.
Some of the tests in the initial code* were very slow because their code had to sleep some time in order for them to pass. Some other tests relied on having certain environment variable set to a given value.
The behavior that checked the environment variable and the one related to time were embedded in the Course class.
Through refactoring this behavior was isolated and extracted so that it could be injected into Course and then two fake classes were created to isolate Course in tests
Check the step by step refactoring in GitHub*.
Thanks to Leo Antoli for passing me the initial code in C#.
---------------------------
* This C++ code example works only for Windows.
Some of the tests in the initial code* were very slow because their code had to sleep some time in order for them to pass. Some other tests relied on having certain environment variable set to a given value.
The behavior that checked the environment variable and the one related to time were embedded in the Course class.
Through refactoring this behavior was isolated and extracted so that it could be injected into Course and then two fake classes were created to isolate Course in tests
Check the step by step refactoring in GitHub*.
Thanks to Leo Antoli for passing me the initial code in C#.
---------------------------
* This C++ code example works only for Windows.
Sunday, March 2, 2014
Kata: StringCalculator in C++ step by step using GoogleMock and Boost.Regex
I've just coded the StringCalculator kata in C++ using GoogleMock and Boost.Regex.
I commited it step by step. Check the resulting code in Github.
--------------------------
Update:
I did some refactorings to my solution in order to a) reduce some duplication and b) avoid having to use Boost.Regex.
They're explained, respectively, in the two following posts:
I commited it step by step. Check the resulting code in Github.
--------------------------
Update:
I did some refactorings to my solution in order to a) reduce some duplication and b) avoid having to use Boost.Regex.
They're explained, respectively, in the two following posts:
Thursday, February 27, 2014
Video: Required settings to use googlemock in a Visual Studio 2013 Ultimate project
I've recorded a video to show how to configure Visual Studio 2013 Ultimate project to work with googlemock:
Friday, February 21, 2014
Building GoogleMock to use it with Visual Studio 2013 Ultimate
This post explains how to build GoogleMock to use it with Visual Studio 2013 Ultimate.
First download the last version (1.7.0 when I wrote this) of GoogleMock from the GoogleMock download list.
Then extract the content of the downloaded zip on a folder of your choice. I did it inside c:\src\
Now use Windows Explorer to enter into the msvc\2010\ folder under the gmock-1.7.0 folder. There you'll find a solution file called gmock.sln, open it with Visual Studio 2013 Ultimate.
Since this solution was created with Visual Studio 10, Visual Studio 2013 will ask you to upgrade all the project files within the solution. Click Ok.
Then you'll probably see this message:
This happens because the project files have read-only permissions.
Select the Make Writable option for each of the three project files.
Once the solution is open, you'l see three projects inside the solution:
Build the solution in Debug Version pressing F7 and ignore all the warnings.
Once built, to check that everything is ok, go to the Debug folder under msvc\2010\ the you'l find an executable file called gmock_test.exe which runs the tests for the googlemock code.
Open a command line prompt, go to the Debug folder and run the tests.
You should see that all of them pass.
First download the last version (1.7.0 when I wrote this) of GoogleMock from the GoogleMock download list.
Then extract the content of the downloaded zip on a folder of your choice. I did it inside c:\src\
Now use Windows Explorer to enter into the msvc\2010\ folder under the gmock-1.7.0 folder. There you'll find a solution file called gmock.sln, open it with Visual Studio 2013 Ultimate.
Since this solution was created with Visual Studio 10, Visual Studio 2013 will ask you to upgrade all the project files within the solution. Click Ok.
Then you'll probably see this message:
This happens because the project files have read-only permissions.
Select the Make Writable option for each of the three project files.
Once the solution is open, you'l see three projects inside the solution:
- gmock
- gmock_main
- gmock_test
Build the solution in Debug Version pressing F7 and ignore all the warnings.
Once built, to check that everything is ok, go to the Debug folder under msvc\2010\ the you'l find an executable file called gmock_test.exe which runs the tests for the googlemock code.
Open a command line prompt, go to the Debug folder and run the tests.
You should see that all of them pass.
Friday, January 31, 2014
Strategy pattern and higher-order functions?
As a practice, I'm implementing different design patterns in different languages.
I'm using the examples in the great Head First Design Patterns book as the basis for this implementations.
The book examples are written in Java, so I'll use other languages.
I've started with the Strategy pattern.
"The Strategy Pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it."
The first implementation is written in C++:
I modified the book example to make it shorter. In this case the Duck class has only one configurable behavior: quacking.
This behavior is injected through its constructor but can also be modified afterwards using a setter: changeHowToQuack.
Since C++ is statically typed like Java, we need to create a base type for all the different behaviors or strategies. In this case the QuackBehavior abstract class (this would work as a Java interface).
The Duck class has a field, howToQuack, which is a pointer to an object that implements the QuackBehavior interface. When Duck's quack() method is called, it delegates the quacking responsibility to its howToQuack collaborator.
This is one of the implementations of QuackBehavior:
You can find the rest of them in this Bitbucket repository: StrategyPatternExampleCpp.
This is an example of how this code can be used:
And this would be its result:
Quack! Squeak! << Silence >>
Using this pattern we've encapsulated the quacking behavior and made it possible to change how the duck quacks without changing its code just by injecting new variants of the behavior. The code respects the Open-Closed Principle for the quack behavior because it's Open to extension (by creating new types of QuackBehavior) and Closed to variation (we don't need to change the Duck class).
This way of implementing the Strategy pattern in C++ or Java has to do with two facts:
- They are both statically typed languages.
- Functions are not first-class citizens in any of them.
In languages like Ruby or Python we wouldn't need to use an interface like QuackBehavior. We'd just need to make the different behaviors (Quack, Squeak and MuteQuack) have a common interface: quack().
Moreover, since functions are first-class citizens in these languages, we wouldn't even need classes for the different types of behaviors. In this case, functions would suffice, as you can see in this other example of the Strategy pattern in Ruby (much less verbose than the C++ or Java ones):
The Strategy pattern relies on composition. I can't avoid thinking that it's a way to compose behavior that is very similar to what you do when you're using higher-order functions in functional programming.
This last example in Racket has the same functionality as the previous two:
Even though there are no objects here, you can notice some similarities.
It's also applying the Open/Closed principle because it's injecting a behavior as a function parameter, how-to-quack, that has several variations inside a higher-order function, quack, in order to change the function behavior without having to change its code. To get a new behavior, you just need to create a new type of quack function (a different quack behavior) and pass it to quack as a parameter.
Well I hope this makes you see the Strategy pattern from a little bit different perspective.
---------------------
PS: If you're interested in JavaScript, check this implementation of the Strategy pattern by Tomás Corral.
---------------------
Update:
A functional JavaScript version (very similar to Racket's one):
Tuesday, July 23, 2013
A Double Dispatch example in C++ using Igloo
To practice I've coded an example of the Double Dispatch implementation pattern I read about first in Rebecca Wirfs-Brock's Object Design: Roles, Responsibilities, and Collaborations and later in Kent Beck's Implementation Patterns.
I used the pattern to implement the rules of the Rock-paper-scissors hand game.
I drove the code using TDD.
Having a "dense day", I painted myself into a corner, but I finally managed to refactor my way to a solution.
I used the Igloo C++ BDD framework, which the more I use, the more I like.
I put the resulting code in this repository. I committed after each new test was made to pass and after each refactoring, so you can follow all the process (including my silly initial mistakes).
I used the pattern to implement the rules of the Rock-paper-scissors hand game.
I drove the code using TDD.
Having a "dense day", I painted myself into a corner, but I finally managed to refactor my way to a solution.
I used the Igloo C++ BDD framework, which the more I use, the more I like.
I put the resulting code in this repository. I committed after each new test was made to pass and after each refactoring, so you can follow all the process (including my silly initial mistakes).
Sunday, June 9, 2013
Encapsulating collections
I'm working on a protein energy landscape exploration program written in C++.
In the program each explorer can react to its environment in several ways: stopping the simulation, changing its search parameters or jumping to a more favorable spot.
An explorer knows about its environment through its sensors and then evaluates a series of conditions to know what to do next. There are conditions for each kind of action to happen.
Our code was suffering from a case of primitive obsession in the form of using raw STL collections for the conditions and sensors. That meant that there was a bunch of code that dealt with those concepts that was spread all over the place, particularly in the explorer's creation code.
On Friday I tried to improve the code applying the Encapsulate Collection refactoring.
I combined this refactoring with the use of the factory method pattern.
I'm happy with the results. Now the collection-handling code that was spread all over, has been attracted by the newly generated collections-like classes (ExitConditions, JumpingConditions and Sensors). Moreover, I've been able to give that functionality proper names to improve its readability and also to remove a bunch of getters that were bothering me and a class that didn't make sense anymore.
Regarding the refactoring process, it was pretty easy to introduce ExitConditions and JumpingConditions in tiny steps staying in green most of the time.
The real challenge was to introduce Sensors because the sensors related code was being used in many places, mainly for building conditions and reporting sensor values.
I tried to refactor it in tiny steps but got to a point where I got stucked. So I decided to plow ahead (I always had the possibility of using SVN to go back to where I started) and see. Well, three hours were gone before I could run the tests again...
While in the end all tests were green, I'm not proud of how I did it. I spent too much time in red and it could have easily gone badly.
Even though I'm sure I need more practice with this refactoring technique, I think it's always going to be very difficult to apply it when the problem has already spread too much.
In that case, I think that I have two options: a reactive one, learning more powerful large scale refactoring techniques like Mikado method; or, better a preemptive one, not letting the problem spread by applying the Encapsulate Collection refactoring more often.
As Xavi Gost said once:
A couple of days after writing this post I realized that I could merge JumpingConditions and ExitConditions classes in just one: Conditions.
This has simplified the code further.
In the program each explorer can react to its environment in several ways: stopping the simulation, changing its search parameters or jumping to a more favorable spot.
An explorer knows about its environment through its sensors and then evaluates a series of conditions to know what to do next. There are conditions for each kind of action to happen.
Our code was suffering from a case of primitive obsession in the form of using raw STL collections for the conditions and sensors. That meant that there was a bunch of code that dealt with those concepts that was spread all over the place, particularly in the explorer's creation code.
On Friday I tried to improve the code applying the Encapsulate Collection refactoring.
I combined this refactoring with the use of the factory method pattern.
I'm happy with the results. Now the collection-handling code that was spread all over, has been attracted by the newly generated collections-like classes (ExitConditions, JumpingConditions and Sensors). Moreover, I've been able to give that functionality proper names to improve its readability and also to remove a bunch of getters that were bothering me and a class that didn't make sense anymore.
Regarding the refactoring process, it was pretty easy to introduce ExitConditions and JumpingConditions in tiny steps staying in green most of the time.
The real challenge was to introduce Sensors because the sensors related code was being used in many places, mainly for building conditions and reporting sensor values.
I tried to refactor it in tiny steps but got to a point where I got stucked. So I decided to plow ahead (I always had the possibility of using SVN to go back to where I started) and see. Well, three hours were gone before I could run the tests again...
While in the end all tests were green, I'm not proud of how I did it. I spent too much time in red and it could have easily gone badly.
Even though I'm sure I need more practice with this refactoring technique, I think it's always going to be very difficult to apply it when the problem has already spread too much.
In that case, I think that I have two options: a reactive one, learning more powerful large scale refactoring techniques like Mikado method; or, better a preemptive one, not letting the problem spread by applying the Encapsulate Collection refactoring more often.
As Xavi Gost said once:
#YodaModeOnUpdate:
Encapsulate in objects your collections you must.
#YodaModeOff
A couple of days after writing this post I realized that I could merge JumpingConditions and ExitConditions classes in just one: Conditions.
This has simplified the code further.
Kata: "StringCalculator" in C++ using Igloo
Today I've worked in the StringCalculator kata in C++.
It's been perfect to start using Igloo, the BDD framework I talked about in my last post.
Here it's the code. It's incomplete. I still have to do the steps 7, 8 and 9 that deal with multiple delimiters and delimiters of any length.
It's been perfect to start using Igloo, the BDD framework I talked about in my last post.
Here it's the code. It's incomplete. I still have to do the steps 7, 8 and 9 that deal with multiple delimiters and delimiters of any length.
Playing with Igloo, a BDD framework for C++
Today I've been playing with Igloo which is a BDD framework for C++.
I like it. The specs are very readable and, as it is implemented as a set of header files, it's really easy to use in your project. Its documentation is also ok.
Its author, Joakim Karlsson, has done several screencast where you can see him using Igloo. You might also have a look at Igloo's source code.
I like it. The specs are very readable and, as it is implemented as a set of header files, it's really easy to use in your project. Its documentation is also ok.
Its author, Joakim Karlsson, has done several screencast where you can see him using Igloo. You might also have a look at Igloo's source code.
Wednesday, January 16, 2013
How to access the first element of an Json::Value array
To access the first element of an Json::Value array the following code may not work:
... double x = point[0].asDouble() ...Instead you have to write:
... double x = point[0u].asDouble() ...To find out why just check the following fragment of the Json::Value documentation:
const Value & operator[] (int index) const
Access an array element (zero based index)
You may need to say 'value[0u]' to get your compiler to distinguish this from the operator[] which takes a string.
Saturday, January 5, 2013
Embedding Python in C++: Hello World
This afternoon I've been "procrastiworking" (working on something that isn't mandatory to postpone doing something mandatory) a bit.
As a result I end up watching this talk by Michael Fötsch:
I just couldn't get to the end of the talk.
When I saw the "Hello world" example, I had to stop the video and try it myself.
This is the code snippet of the experiment:
This is just the tip of the iceberg. To learn more about embedding Python in C++ watch Michael's talk.
He also has more advanced material in his blog:
There's also more information in Python's Documentation:
and in this Jun Du's tutorial:
Now you also have material to procrastiwork for a while.
Have fun!
As a result I end up watching this talk by Michael Fötsch:
I just couldn't get to the end of the talk.
When I saw the "Hello world" example, I had to stop the video and try it myself.
This is the code snippet of the experiment:
#include <Python.h> int main(int argc, char* argv[]) { Py_Initialize(); PyRun_SimpleString( "print 'Hello world!'" ); Py_Finalize(); return 0; }This is how I compiled it:
$ g++ -o helloWorld helloWorld.cpp -I/usr/include/python2.6/ -lpython2.6And this is the result of running it:
$ ./helloWorld Hello world!Nice!!
This is just the tip of the iceberg. To learn more about embedding Python in C++ watch Michael's talk.
He also has more advanced material in his blog:
There's also more information in Python's Documentation:
and in this Jun Du's tutorial:
Now you also have material to procrastiwork for a while.
Have fun!
Traversing members of a JsonCpp's Json::Value object (2)
This morning I learned how to traverse the members of a Json::Value object using its iterators.
This is the same example I used in my previous post, but using iterators instead of the list of member names:
Ok, so, I compiled it doing:
This is the same example I used in my previous post, but using iterators instead of the list of member names:
#include <iostream> #include "jsoncpp/json.h" using namespace std; int main(int argc, char **argv) { Json::Value change; Json::Value minParameters; Json::Value minParametersAnm; minParameters["MinimumRMS"] = 0.2; minParameters["sgbUpdated"] = true; change["Minimizer"] = minParameters; minParametersAnm["MinimumRMS"] = 0.5; minParametersAnm["sgbUpdated"] = false; change["Minimizer::ANM"] = minParametersAnm; cout<<"Traverse members of: "<<endl <<"\"change\":"<<endl <<change.toStyledString()<<endl<<endl; Json::Value::iterator it = change.begin(); cout<<"List of members:"<<endl; for(Json::Value::iterator it = change.begin(); it !=change.end(); ++it) { Json::Value key = it.key(); Json::Value value = (*it); cout<<"Key: "<<key.toStyledString(); cout<<"Value: "<<value.toStyledString(); } return 0; }Note the use of the key() method to get the key of the Json::Value from the iterator. Also note how we need to dereferentiate the iterator to get the Json::Value from the iterator.
Ok, so, I compiled it doing:
g++ -o test_iterator_members test_iterator_members.cpp -ljson_linux-gcc-4.4.5_libmtAnd I executed it and got this result:
Traverse members of: "change": { "Minimizer" : { "MinimumRMS" : 0.20, "sgbUpdated" : true }, "Minimizer::ANM" : { "MinimumRMS" : 0.50, "sgbUpdated" : false } } List of members: Key: "Minimizer" Value: { "MinimumRMS" : 0.20, "sgbUpdated" : true } Key: "Minimizer::ANM" Value: { "MinimumRMS" : 0.50, "sgbUpdated" : false }
Friday, January 4, 2013
Traversing members of a JsonCpp's Json::Value object (1)
Today I needed to traverse the members of a Json::Value object.
After having a quick look at the documentation, I found the getMemberNames method, which returns a list with the member names, and did this little experiment:
This will be material for a future post, though.
After having a quick look at the documentation, I found the getMemberNames method, which returns a list with the member names, and did this little experiment:
#include <iostream> #include "jsoncpp/json.h" using namespace std; int main(int argc, char **argv) { Json::Value change; Json::Value minParameters; Json::Value minParametersAnm; minParameters["MinimumRMS"] = 0.2; minParameters["sgbUpdated"] = true; change["Minimizer"] = minParameters; minParametersAnm["MinimumRMS"] = 0.5; minParametersAnm["sgbUpdated"] = false; change["Minimizer::ANM"] = minParametersAnm; Json::Value::Members memberNames = change.getMemberNames(); cout<<"Traverse members of: "<<endl <<"\"change\":"<<endl <<change.toStyledString()<<endl<<endl; cout<<"List of members:"<<endl; for(unsigned int i=0; i<memberNames.size(); ++i) { string memberName = memberNames[i]; Json::Value value = change[memberName]; cout<<"Key: "<<memberName<<endl; cout<<"Value: "<<value.toStyledString()<<endl; } return 0; }I compiled it:
g++ -o test_traverse_members test_traverse_members.cpp -ljson_linux-gcc-4.4.5_libmtAnd this is what I got:
$ ./test_traverse_members Traverse members of: "change": { "Minimizer" : { "MinimumRMS" : 0.20, "sgbUpdated" : true }, "Minimizer::ANM" : { "MinimumRMS" : 0.50, "sgbUpdated" : false } } List of members: Key: Minimizer Value: { "MinimumRMS" : 0.20, "sgbUpdated" : true } Key: Minimizer::ANM Value: { "MinimumRMS" : 0.50, "sgbUpdated" : false }We could get the same result using Json::value's iterators.
This will be material for a future post, though.
Subscribe to:
Posts (Atom)