Skip to content

inefficient code example #31983

Closed
Closed
@DickBaker

Description

@DickBaker

in "Encapsulating data" section at https://learn.microsoft.com/en-us/dotnet/architecture/modern-web-apps-azure/work-with-data-in-asp-net-core-apps#encapsulating-data the code sample is inefficient since the update case would require TWO scans of the Items collection, so IMHO better to code the
var existingItem = Items.FirstOrDefault(i => i.CatalogItemId == catalogItemId);
and then test that nullable object
if(existingItem==null){_items.Add(new BasketItem{..}} else existingItem.Quantity+=quantity;
so eliminating 2nd scan, the Any() and the return statement.

Example used here of in-memory database perhaps not too bad, but devs should realise that multiple scans of a real remote relational db could incur 2 roundtrips. doh!

Actually I also quarrel with using the public Items wrapper rather than the private underlying _items List
surely this code should manipulate its private List to avoid List BCL having to brew-up a wrapper [again]?


Document Details

Do not edit this section. It is required for learn.microsoft.com ➟ GitHub issue linking.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions