vendredi 25 mai 2012

C++11 - for_each, auto, constexpr, the begin & the end...

Auto:

It's a new keyword really usefull to code faster but it can be scary to use as it leads to more flexibility and less readability.

srand(1234);

 auto vector_size = 10;

 std::vector<int> a(vector_size);
 auto b = std::vector<int>(vector_size);

 auto lambda = [](int& i){i = abs(i);};

 std::for_each(begin(a), end(a), lambda);

 for each (auto var in a)
 {
  std::cout << var << ",";
 }
 std::cout << std::endl;

and you can also use 'auto' as return type qualifier.

int foo() { return 5; } 
       auto j = foo();

==>  Allows to avoid typos
BUT i recommend an extensive usage of VisualAssistX to change function or variable signature and unit-test improvements.

ConstExpr:

As you may know, C98 doesn't allow to declare an array with an expression.

// Comment
//constexpr int f() //Maybe available in VS'11 Final ...
//{
// return 5;
//}

const int g()
{
 return 5;
}

void ConstExpressionDemo()
{
 const int vector_size = 10;
 int A[vector_size];

 int B[g()];//C++98 cannot compile
 /*int B[f()];*///C++11 should compile if constexpr available.
 
 return;
}

Visual C++ 11: Not available.

But using the compiler static analysis, the following code couldn't compile.

// Comment
constexpr int f() //shouldn't compile ...
{
 return rand();
}


for_each and for-loop improvement:

C# and modern languages provided tools to easily iterate over list, collection or array. Before C++11 programmers who wants to iterate on containers elements wrote loops like:
const auto vector_size = 10;
std::vector<int> a(vector_size);
srand(1234);
  
auto lambda_random_init = [](int& i){i = rand();};

for (std::vector<int>::iterator it = a.begin() ; it != a.end() ;  ++it)
{
  *it = rand();
}

But now we can use auto, lambda, std::for_each and range base for to provide compact, and elegant code.
As example, with the following code we can dump vector, deque or array, in fact any container containing any kind of object supporting "cout".

template<class T> void cout_container(T _Container)
{
    for each (auto var in _Container)
    {
        std::cout << var << ",";
    }
    std::cout << std::endl;
}

cout_container<std::vector<int>>(a);

in the following example i implemented vector initialization using a lambda and several vector accumulation based on different loop-style.

const auto vector_size = 10;
    std::vector<int> a(vector_size);

    srand(1234);

    auto lambda_random_init = [](int& i){i = rand();};

    //init using begin & end 
    std::for_each(begin(a), end(a), lambda_random_init);

    cout_container<std::vector<int>>(a);

    //for_each with lambda capture by ref and return sum
    int sum_of_elems = std::accumulate(begin(a), end(a), 0);
    std::cout << sum_of_elems << std::endl;

    std::for_each(begin(a), end(a), [&sum_of_elems](int& n){ sum_of_elems += n; }); //only 1 elt by ref
    std::cout << sum_of_elems << std::endl;
    std::for_each(begin(a), end(a), [&](int& n){ sum_of_elems += n; });//all elt by ref
    std::cout << sum_of_elems << std::endl;

    int tmp = 0;
    //std::for_each(begin(a), end(a), [&sum_of_elems](int& n){ sum_of_elems += n; tmp = 0; });//cannot compile as tmp is not in the capture list!!!
    std::for_each(begin(a), end(a), [&sum_of_elems, &tmp](int& n){ sum_of_elems += n; tmp += n; });//target several output captured by value !!!
    std::cout << sum_of_elems << " " << tmp << std::endl;

    for each (int& n : A) 
    {
        sum_of_elems += n;
    }
    std::cout << sum_of_elems << std::endl;

    cout_container<std::vector<int>>(a);;

mercredi 9 mai 2012

C#: prefer LINQ instead of foreach

In this post, i want to focus in LINQ and its advantage on foreach.

In fact, i meet yesterday the following case: i had a list and i would remove some elements matching a criteria.

As you know C# provide a lots of interface like IQueryable, IEnumerable, etc.... And face to my problem i started by using my list as an IEnumerable through a foreach.... so wrong am i.

In fact if you try something like this:

 var collect = new Collection<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
 foreach (var x in collect)
 {
    if (x % 2 == 0)
    {
       collect.Remove(x);
    }
 }
You will meet an exception: System.InvalidOperationException :  .... Because you change the collection itself during the enumeration.

But some very simple solutions exists.
1) If the collection is a List of something implementing the IList Interface you can use "RemoveAll"

collect.RemoveAll(x => x % 2 == 0);


2) If your collection doesn't implement IList, you can use the following code:

 foreach (var x in collect.Where(x => x % 2 == 0).ToList())
 {
    collect.Remove(x);
 } 


  As ToList doesn't provide a new object of type List containing only the element we want to remove and we get through this new list.

No more problems !

jeudi 26 avril 2012

Switch from MSTest to NUnit.

Maybe the 1st post of a long series dedicated to the .Net Universe.

Visual Studio (VS) is well known to come with plenty of plugins or project template to create unit-test project.

But sometimes you would change the unit test framework a project used to.

Indeed it's not so easy but please found below several useful tips&tricks to move a MSTest project and code to a NUnit project.

1) Remove the MSTest Framework reference

2) Add nunit.framework instead.

3) Use the following side by side attribute dictionary to replace all MSTest attribute by their equivalent in the NUnit framework.

4) build & load your assembly with nunit... Every should work! IBut...

5) try to start nunit from your VS and now VS claims that there is no test inside!

6) So edit your vcproj file and search for the <ProjectTypeGUID>. If you found 2 GUID inside, goto to this page to lean more about the existing project type and their GUID. Remove the test GUID {3AC096D0-A1C2-E12C-1390-A8335801FDAB}, save, and reload the project.

And... THE END !

jeudi 15 mars 2012

Book review: Extreme programming Explained

Extreme programming Explained
Embrace change 2nd Edition
Written Kent Beck with Cynthia Andrea & Forewords by Eric Gamma
ISBN-13: 978-0-321-27865-4


My opinion... 6/10. I like & follow some XP practices since at least 6 years at work and in my homework.....But, let's get started with more details about the book, i hope it help you deciding if you would read it or not!

The author presents XP in 3 steps. First he presents XP's values. This part looks very long but they are the reason why XP is. And Values & Principles are notions that you can take in your bag for your own lifestyle improvement! Too much psychological to me (but maybe it can push for change like a hidden message)

Communication,Simplicity,Feedback,Courage,Respect are basic XP values.

Chapter about Principles was quick & full of interest. They are: Humanity, Economics, Mutual Benefit, Self-Similarity, Improvement, Diversity, Reflection, Flow, Opportunity, Redundancy, Failure, Quality, Baby Steps and Accepted Responsibility. In fact they are just global notions to give a better view of what the practices are intended to accomplish.

I read the chapter about Practices really easily. Author describes team & resources organization, "Sit together" or in other words build a comfortable open space while maintaining place for personal space,
install place for project informations (to quickly see how projects goes).

About "pair programming", it give some advice that we could follow. In my own experience of "pairing", i was a bit frustrated at the end of day. I felt i should have make much more. But after, reading i think i could plan more dev in pair!

Stories definition is also really good. And it was follow by cycles definition. The "quick iteration" and the "quarterly cycle". Priority management of user stories and how put in place a slack of task that the team can made (refactoring, optimization, design, research on a future topic) without interfering with new features development.

Ten-minute build is something we should work. The quicker you have feedback, the quicker you can change or fix! Continuous integration, Test-First are also something i use but being more Extreme could help!

Incremental Design is the last but not the least as XP is about change. It explain why we try to start with a basic & simple design and every time we need, we improve it based on experience & feedback.

The corollary practices are: customer involvement, incremental deployment, Team continuity, Shrinking teams, root cause analysis, shared code, code & test, single code base, daily deployment.

A chapter talk about roles in XP team.But in the end of this book the 2 most interesting chapters from my developer point of view are 13 and 14. Chapter 13 talk of testing (first, early and often) of test automation 

I think that deploy a beta version at the end of each iteration or at least at the end each important user story implementation to use & demonstrate, is a target i should keep in my mind.

And 14 is about design (it's funny as we are talking about design at work those last days...). The author recall that design for design is not a good thing and that perfection is not in this world. Even if you start with 2 weeks of design, you will have to rework it a some point because of change. So use basic principles, KISS, DRY, but don't procrastinate yourself when, based on experience, feedback and need, you have to modify the design!

I had a look for the remaining chapter but they are more for manager, describing how XP can scale when team or organization grows, how measure XP usage and effectiveness.

mardi 6 mars 2012

_MSVC_VER and its value in the last decade.

You may suspect that there is logic behind that but the _MSV_VER value for cl.exe (cl.exe /?) in VS'2011 is 1700.

The old are:
MSVC++ 10.0 _MSC_VER = 1600
MSVC++ 9.0 _MSC_VER = 1500
MSVC++ 8.0 _MSC_VER = 1400
MSVC++ 7.1 _MSC_VER = 1310
MSVC++ 7.0 _MSC_VER = 1300
MSVC++ 6.0 _MSC_VER = 1200
MSVC++ 5.0 _MSC_VER = 1100

lundi 5 mars 2012

Today 5 AM, i was looking how i could easily migrate some old VS'2008 solution to the VS'11 Beta for testing.

The common upgrade method worked (devenv.exe /upgrade .sln) BUT.....
I used the several vsprop files a.k.a "Visual Studio Property Sheet" to store several properties relative to my computer. Include path to boost, and all the externals library, framework i used were in those files. But for them the upgrade result was a lit bit surprising.

For  each .vsprop file i used, it create a new one call .prop. They was not empty, but they doesn't really contained what i expected. Both .vsprop and .prop are xml file but they have different syntax & schema.

It look like Visual Studio Dev Team didn't automatically translate the old  format into the new.

But it can be easy to fix. As you can browse for those files through the VS Property editor and add all the include you need, all the specific setting you want and that per configuration. Save those file and if you share them across multiple solution, you do it only one times.

I missed the jump from VS'2008 to 2010 and that change is bit weird, but I suppose it lead to a better per project configuration instead of letting user using the old IDE VC++ folder configuration. It comes more easy to share project and 'build' configuration.