There are a bunch of methods in a class that I want to clean up. These just build up a data structure (with different values) over and over again and add them to a container passed in, like so:
SomeClass::Foo(ContainerType& cont)
{
AnotherType dataItem;
dataItem.item1 = true;
dataItem.item2 = 42;
// blah blah
cont.addItem(dataItem);
// ... snip ...
AnotherType newItem;
newItem.item1 = false;
newItem.item2 = 128;
// blah blah
cont.addItem(newItem);
}
It is rather convenient (relevant code within same function, so easy to get to and read) to have a lambda function local to each method and call it instead (future changes will be limited to one place), like so:
SomeClass::Foo(ContainerType& cont)
{
auto buildData = [](ContainerType& cont, bool flag, int value){
AnotherType dataItem;
dataItem.item1 = true;
dataItem.item2 = 42;
// blah blah
cont.addItem(dataItem);
};
buildData(cont, true, 42);
// ... snip ...
buildData(cont, false, 128);
}
rather than adding a new private member function for doing the same:
SomeClass::Foo(ContainerType& cont)
{
buildData(cont, true, 42);
buildData(cont, false, 128);
}
SomeClass::buildData(ContainerType& cont, bool flag, int val)
{
// blah blah
}
Given that the internals of how to build AnotherType
objects is not useful/necessary outside the method SomeClass::Foo()
, here are the questions I seek guidance for:
- Are there any other cleaner/better solutions to this?
- Are there any non-obvious pitfalls to using the local lambda approach over the new private member approach?
Currently, I've used the local lambda approach and cut a lot of the repeating code out. I just want to ensure that this is an acceptable way to go.
&cont
inside the square brackets [], it closes over that variable, making it available inside the lambda without having to pass it to every call.