To Lambda or not?

I was just wondering why in the LevelGrid.cs code, for:

public bool HasAnyUnitOnGridPosition(GridPosition gridPosition)

Why this was made into a method instead of continuing to use the lambda style. ex:

    public bool HasAnyUnitOnGridPosition(GridPosition gridPosition)
    {
        GridObject gridObject = gridSystem.GetGridObject(gridPosition);
        return gridObject.HasAnyUnit();
    }

vs

public bool HasAnyUnitOnGridPosition(GridPosition gridPosition) => gridSystem.GetGridObject(gridPosition).HasAnyUnit();

The method calls above where this is placed used the lambda method, so I was wondering if there was some other consideration here.

They both do effectively the same thing.

Ok, Thank you. That’s what I was leaning to, but wanted to see if there was another reason it was done differently then the others it was grouped with.

It’s not something that you see in every language, code that makes use of operators not often seen is often considered harder to read.

Much like the ternary operator: What do you think is easier to read?

if (a > b)
{
  c = 1;
}
else
{
  c = 2;
}

or

c = a > b ? 1 : 2;

It depends if you’re familar with it or not. Personally, I don’t see what’s so hard with either. I like code that makes code shorter without adding complexity.

1 Like

they are equivalent, but…
lambdas are often used when passing a function as a parameter (anonymous function).

labelsArr = objArr.Select(v => v.label).ToArray();

using them as you have above for a getter is just a style / readability choice.

i also often uses them when im direclty passing data though one class from another…

public bool IsValidPos(pos: GridPosition) => this.grid.IsValidPos(pos);
1 Like

Gotta love Linq. Don’t see it used nearly enough in Unity.

1 Like

Yes mainly just personal preference.
I like to limit that shorthand to very very simple use cases, mainly just a passthrough function.
If you’re calling a function to then call another function on the returning object then I feel that is too much complexity to use the shorthand method so I prefer to use a regular function instead.

5 Likes

I tend to agree. Pass throughs are a great useage of the => operator. Complex operations can be difficult to debug or error check.
That’s not saying that either is wrong. Assuming that the GridPosition has been sanity checked before this operation is called, you shouldn’t run into an issue where gridSystem.GetGridObject(gridPosition) returns null, in which case acting on the reference should be ok. If we wanted to sanity check (IsValidGridPosition) the GridPosition or null reference check the resulting gridObject, this would require unpacking the method chained lambda expression.

5 Likes

Privacy & Terms