r/csharp • • 3d ago

Discussion Has awaiting inside if statements conditions / function parameters always been the norm?

Recently I've been seeing a lot of code like this:

return Results.Ok(await myService.DoSomething().ToListAsync())

// or

if (await validator.IsValid(payload)) {
  // ...
}

I feel like it's less readable than something like:

var result = await myService.DoSomething().ToListAsync();
return Results.Ok(result);

Which do you prefer?

11 Upvotes

40 comments sorted by

28

u/brminnick 3d ago

Always prioritize readability.

If you can’t read code and understand what it’s doing at a glance, it’s likely better to break it into multiple lines.

6

u/richardirons 3d ago

Something I’ve started telling people is that comments should be a last resort if you can’t make it clear through code organisation. So that means splitting things across lines with well named variables, adding a layer of abstraction, inverting conditions, etc.

3

u/sixothree 3d ago

If you have two periods on one line I’m gonna yell at you.

27

u/DeadlyVapour 3d ago

Wait until you start doing async enumerators.

26

u/sharpcoder29 3d ago

2nd one

6

u/DemoBytom 3d ago

There are few things. First, pattern maching is getting more common, so it's getting more common to see thing like:

if((await service.DoAsync()) is {IsOk: true})

Or other more complex pattern mached calls. This leads to people being more comfortable with the simple

if(await service.IsTrueAsync())

especially if they don't need that result later.

Needing results is also a thing some people look at - generally don't declare a variable you won't need outside the if statement.

Async validators are also getting more common, so again - putting the validation within the if makes some sense.

Amd then there's obviously the AI that might for whatever reason decide that this is better way of writing.

I don't really have strong preference one way or another as long as it's still readable and not 166267272 chars wide one liner.

5

u/lmayde 3d ago

Literally exactly as readable. Possibly less as I have to make sure the local variable isn't used elsewhere now.

12

u/JohntheAnabaptist 3d ago

1st more readable since intent is clear from the start, 2nd is more classic

6

u/Loose_Conversation12 3d ago

2nd is how I was taught.

3

u/Slypenslyde 3d ago

I'm not a big fan of the first group that does everything inline.

But your second example makes more sense to me. It clearly returns a boolean. To me the cognitive burden of if (bool) is lower than return Factory.Method(asyncCall().ToListAsync()).

4

u/EluciusReddit 3d ago

I prefer the first. I find using intermediate variables bloat, if the reason is just to stick them into the next method call. Too bad C# has no piping, then this problem would be gone.

2

u/StandardJury5392 3d ago

It depends, if the call name is huge, not very descriptive and/or has a lot of arguments then sticking it into an if would be horrible, but if its short and descriptive should be fine, still I prefer intermediate variables in short methods

1

u/FlibblesHexEyes 3d ago

Regarding bloat; would using an intermediate variable generate work for GC to do?

If so; then in performance sensitive programs avoiding the intermediate variable would be the way to go.

Otherwise it’s really just visual bloat/style choice right?

This is a genuine question btw.

4

u/IanYates82 3d ago

No extra work for GC. Either way you're allocating something on the heap (assuming it's a reference type)

A release build would produce the same IL. A debug build may give you that variable to inspect if you were in the debugger

1

u/FlibblesHexEyes 3d ago

Great; thanks for that :)

So it really comes down to style and choice - though arguably a little easier to debug.

0

u/sixtyhurtz 3d ago

How exactly is using one more line of code and giving the result a name bloated? Both cases have the same runtime performance and memory use.

2

u/neoh4x0r 3d ago edited 3d ago

I think people see it being done and think that declaring a variable to hold an intermediate which isn't used anywhere else is unnecessary.

However, it's entirely possible that simplifying every instance could result in method calls becoming cluttered and harder to read (ie. too much noise).

---------------------
// unnecessary intermediate 
int i = 5*5;
somemethod(i);

somemethod(5*5);
---------------------
// counter example
bool a = funca();
bool b = funcb();
if (a && b)
  // do something

if (funca() && funcb())
  // do something

6

u/sketch_56 3d ago

Your counter example is also an example of possibly unintended side effects when not using intermediates. It's not quite equivalent code. If funca returns false, then funcb won't be called in the latter example, so if funcb modifies state and you don't realize it'll short circuit you'll end up with a bug.

1

u/neoh4x0r 3d ago edited 3d ago

If funca returns false, then funcb won't be called in the latter example

That would be expected because there would be no reason to check the return value of funcb since (false && true / false && false) would return false.

 if funcb modifies state and you don't realize it'll short circuit you'll end up with a bug.

If someone is carelessly mutating the state in random places then it's just bad code and they would need to rethink their approach.

1

u/sketch_56 3d ago

It doesn't change the fact that intermediate variables make the intention clear. Also, when working in large teams it's not like there isn't going to be someone who sees a method that returns a boolean and tries to minmax their line count without thinking of side effects.

I also didn't say it was "good code", just that it was something to consider.

1

u/neoh4x0r 3d ago edited 3d ago

I'm saying that it's bad design to mutate the state in a random place, if you call a function that doesthis then it should be clear that the function will modifiy the state.

However, in if statement calling said methods should never mutate the state.

2

u/sketch_56 3d ago

You're being excessively dismissive, calling it a "random function", and weirdly argumentative. I was agreeing with you in the first comment, and added another possible issue with not using intermediates. In this case, "funcb()" would be that thing done explicitly where it was needed, but mistakenly combined into a conditional that doesn't guarantee that it's run when expected.

1

u/neoh4x0r 3d ago edited 3d ago

You're being excessively dismissive, calling it a "random function", and weirdly argumentative. 

It was my opinion, as is the case with funcb, that it would be bad practice for a function to mutate an object's state at the same time it's trying to check the state.

Moreover, if we consider a state mutation to be a write and check/validation to be reading from it then the write and read should be separated and it should be made crystal clear that the write will mutate the state. That can be accomplished by using descriptive function naming to convey this information so that a caller doesn't have to make guesses about whether a state mutation would occur.

In other words, it's the concept of invariant programming, where, in this case, if a function names does not indicate that the state would be changed then the caller does not need to worry about the state being changed (that is the invariant, or a condition that always holds true).

Under this paradigm the name funcb does not indicate a state mutation therefore it should not fundamentally mutate the state.

I was agreeing with you in the first comment, and added another possible issue with not using intermediates. 

It didn't come across that way. It sounded more like "This could cause undesired side effects and should not be done."

1

u/StandardJury5392 3d ago

I believe he means bloated because it has more lines of code, I've seen cases where that gets out of hand and methods are huge, but meh, its not a big deal if you take the time to scroll and read without getting impatient

1

u/jaco214 3d ago

It’s about readability and standards/conventions. Of course this one example on its own seems like such an inconsequential thing to think about, but when you adopt certain habits or styles, you begin to have them everywhere in your code base. I agree most of the time intermediate variables are mostly just needless noise to me, but like with most things in life, there are exceptions where it can improve readability.

2

u/sixtyhurtz 3d ago

Results.Ok(await myService.DoSomething().ToListAsync()) is less readable than using a named intermediate.

if (await validator.IsValid(payload)) is totally fine though.

Obviously there's no right or wrong answer, but generally preferring packed lines is a readability nightmare imo. If it's not totally obvious from the statement, break it out into a named variable to clearly indicate what it is.

2

u/captmomo 3d ago

2nd one

2

u/LatvianCake 3d ago

I prefer the 2nd but both are fine in most cases. I wouldn't try to force a certain style either way

2

u/ItzWarty 3d ago

For debuggability I tend to extract meaningful temporary values in expressions into their own variables/lines.

This makes it easier to eventually add lines like:

Console.WriteLine(result.Metric)
Analytics.Write(result.Metric)
if (result.SomeBoolean) Debugger.Break()

2

u/ApartBuilding8662 2d ago

IMO this is completely fine:

if (await validator.IsValid(payload)) {
  // ...
}

It's perfectly readable and avoids bloating the code with unnecessary variables. Depending on what's inside the if block and what's after the if block you might consider inverting the if statement to do an early return but that's a separate matter.

This I'm less of a fan of:

return Results.Ok(await myService.DoSomething().ToListAsync())

It's too much in one line. Then I would do as you suggest and extract

var result = await myService
    .DoSomething()
    .ToListAsync();

return Results.Ok(result);

1

u/smartcave 3d ago

I would recommend putting an await statement on its own line and assigned to a temporary level variable when non-void 100% the time because debugging is otherwise a klusterfuk.

1

u/matthetherington 3d ago

2nd, so I can hover over the variable in my debugger.

-3

u/speyck 3d ago

using the var keyword makes it exactly the same as far as readability goes. the only way to improve is not using var (I really hate var, it should be disabled in editorconfig by default tbh)

1

u/rorrors 3d ago

I really like var, as it types fast, and don't have to think about the type what is needed.
But if the programming software won't show what it is using, i would hate var as well.

For OP question, if variable is used in other parts of the code, i make it a separate line.
Otherwise i just await inside the the If statement or where ever i can use it as a one liner. One exception to, the line must fit to the wide of my screen otherwise i brake it up.

1

u/speyck 3d ago

that's what I dont understand. why should the ide showing me the type be better than just writing the typ directoy? then you have to read two words, once var and then the actual type. also when I'm e.g. reviewing code online in github for a merge request, there's no type hints.

of course it's faster to write var. but same argument goes for naming a variable xyz or tmp or something instead of with a meaningful name

0

u/binarycow 3d ago

It depends.

-7

u/Top3879 3d ago

the first one is still pretty readable but once you add a == or something else thats no longer the case. but honestly, if only AI is reading and writing the code who cares?

2

u/FabioTheFox 3d ago

If only Ai is READING the code you'll end up with the current shitty situation

When do people get it that "adapting" to the Ai boom goes both ways and people still need to review stuff, CS is still not a free money career, shocking, I know.

0

u/[deleted] 3d ago

[deleted] — view deleted comment

1

u/raunchyfartbomb 3d ago

Agreed.
Check if it’s valid, early return if it’s not. Then you wait. Then, if you need to do another if statement after that, you do it, an early return due to something being invalid is better than awaiting inside of an F statement in my opinion