Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

5
  • 1
    Well with option one you can extract that to a function or a method, which you can then easily unit test. So I consider that a major upside. Commented Jun 24, 2024 at 10:55
  • Is this about TypeScript? Commented Jun 24, 2024 at 17:21
  • 1
    With option 2, you must have an existing instance of Foo that you can lambda-capture. If your class Bar had fields foo and foo1, and you used the wrong one (say, by copy-pasting the code and forgetting to edit it), would that cause a problem? With option 1, you can write the callback anywhere in the code, without having an instance, and you have control over what is passed in as the Foo parameter, and when. The lambda capture is fine for ad hoc stuff; here, since "the user of the class instance is expected to do stuff on the instance itself", option 1 is a more natural way to model that. Commented Jun 24, 2024 at 20:43
  • @Bergi My application is in typescript (hence the ts sample code), but the question is really language agnostic. Commented Jun 25, 2024 at 8:07
  • @doca I'd argue that there is no language-agnostic best practice, rather conventions depending on the ecosystem and application area. For example, in the DOM and libraries like jQuery, event handlers are called with the target instance as the this argument as well as the .currentTarget property of the event argument. Commented Jun 25, 2024 at 13:09