Search code examples
c++lambda

When is it appropriate to use lambda functions and when is it not?


There are some clear situations where lambdas are appropriate:

  • when passing lightweight functions as arguments to other functions (eg. for custom ordering of values when using std::sort or other standard library functions)

There are also some clear situations where lambdas are not appropriate:

  • when implementing member functions or global functions specified in header file
  • when writing functions for use in different functions / contexts

However there are also more ambiguous case. Example: we have a member function that is responsible for setting up a GPIO module on a board. Inside this function a helper function is called to calculate an address (helper function is only used in this function once). The helper function itself contains another helper function.

Code example without lambdas (... means some code):


uint32_t getAPartOfAddress(...) 
{
    ...
}

uint32_t getSomeAddress() 
{
    auto part = getAPartOfAddress(...);
    if (...)
        return part;
    return getAPartOfAddress(...);
}

void SomeClass::initGPIO() 
{
    auto someAddress = getSomeAddress();

    ...
}

Code example with lambdas:

void SomeClass::initGPIO() 
{
    auto getSomeAddress = []() -> uint32_t 
    {
         auto getAPartOfAddress = [](...) -> uint32_t 
         {
              ...
         }
         auto part = getAPartOfAddress(...);
         if (...)
            return part;
         return getAPartOfAddress(...);
    };

    auto someAddress = getSomeAddress();

    ...
}

The logic inside getSomeAddress and getAPartOfAddress is not very extensive (say not more than 10 lines), however not that lightweight either, which makes me wonder whether I should use lambdas. On the other hand I would go for lambdas because the functions are local to the initGPIO function (not used elsewhere), and lambdas show that better and are also easier to see when going through initGPIO.

I would be happy to get recommendation about both my example and the general case when one is not sure about using lambdas.


Solution

  • As far as I understand it, the only difference is code clarity.

    Personally, I'd go for separate functions outside the main function body, because there's less nesting and weird symbols which make it look confusing and intimidating to me. Also, when you declare a lambda, I sort of expect you are going to use it for some grand purpose such as passing it to another function. Immediately calling it just like that feels a little anti-climactic to me and makes me wonder: "Why is he doing this? Did I miss something?"

    On the other hand, as you say, lambdas make it clear you aren't using them anywhere else.

    So, there are pros to both approaches :)