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.

Required fields*

5
  • readability wise this is nice. feels a lot better than the 3 argument version. perhaps im missing something, but as the thenDo method still returns a value by directly evaluating the provided function, why would i ever put something in an anonymous function there, and just return "value * 4" directly? so I could dynamically throw in other functions in there or ..? Commented Dec 6, 2023 at 20:18
  • 1
    it allows lazy evaluation of the code in case for example you want to execute an expensive function on the thenDo. With only the Then and Else you are required to precalculate the results of the two branches and sometimes you just want to avoid that Commented Dec 28, 2023 at 13:05
  • 1
    Imagine, for example, that you want to call an endpoint if a certain condition is true. Calling the endpoint inside the Then would execute the call in any case, whether the condition is true or false. Calling it in the ThenDo would only execute the call if the condition is true Commented Dec 28, 2023 at 13:09
  • What you can possibly do is reorder things. It will then look like a Python ternary expression. For instance: Return(value).When(value > 0).Else(1), Answer(func()int { return value * 4 }).When(value > 0).Else(1). I've taken the "answer" part from Mockito, as it also supports this ordering, starting with doReturn, doAnswer, doThrow, etc. Commented Aug 27, 2024 at 15:37
  • This is absolutely brilliant but it fails for something like this: When[int*](somePtrRecord != nil).Then(&somePtrRecord.intVal).Else(nil) because the Then value is evaluated Commented Sep 18, 2024 at 7:08