My question refers to:
Using a lambda expression versus a private method
Now that lambda functors are part of C++, they could be used to unclutter a class' interface. How does lambda use vs private method use compare in C++? Do there exist better alternatives to unclutter class interfaces?
A lambda expression is a short form for writing an anonymous class. By using a lambda expression, we can declare methods without any name. Whereas, Anonymous class is an inner class without a name, which means that we can declare and instantiate class at the same time.
Lambda expression is an anonymous method that you can use to create delegates or expression tree types.
Private methods are typically used when several methods need to do the exact same work as part of their responsibility (like notifying external observers that the object has changed), or when a method is split in smaller steps for readability.
Private methods are useful for breaking tasks up into smaller parts, or for preventing duplication of code which is needed often by other methods in a class, but should not be called outside of that class.
Although lambdas can definitely replace some private member functions, thinking of them as means to uncluttering the interface of a class is taking too narrow a view of both lambdas and private member functions.
Private member functions (and functions in general) are the basic units of code reuse. They let you write a piece of logic once, and then hide it behind the name of the function.
Although lambdas can replace a private member function in certain context, they could replace an object of which that function is a member along with it, which is a whole lot more. Due to lambda's ability to capture the context around them, you get a way of creating code blocks that take not only your object with it, but also the state of your local variables. Before lambdas you needed to create a special class for that; lambdas let you create such classes on the fly, for much better readability.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With