0

I have the following scenario:

  • My .NET Core API has two Endpoints CreateProduct and UpdateProduct.
  • The only difference between the two will be that UpdateProduct will need to know the ID of the Product to update

Is it bad style to create a common CreateOrUpdateModel with a nullable property for the ID that will be set only in case of an Update?

Since the models need to be validated, I'd like to avoid to create two almost identical validators where the only difference is that one additionally validates the ID while the other doesn't. This could be easily solved with a condition in the validator.

3
  • What .NET language are you using for this? It could influence the answer.
    – GHP
    Feb 18, 2022 at 14:48
  • @Graham .NET 6 with C# 10
    – Dario
    Feb 18, 2022 at 15:11
  • Or just don’t provide a generic update endpoint, but use case specific endpoints. The description and price of a product rarely change at the same time.
    – Rik D
    Feb 18, 2022 at 19:11

2 Answers 2

1

It can be a pain in your rear end if you actually enable null-safety. Because as a developer, you know when your ID should or should not be null in your program, but you failed to communicate that to your compiler and now you have tons of warnings about null safety. Then you will go and add lots of ! to tell your compiler you know it better. And then... null safety isn't what it is supposed to be, when your code is sprinkled with hints to disable it.

It would be better to have one of those options:

  • Two models, one without ID. Not ideal.
  • One model without ID and one inheriting this and having an ID. Not my favorite, but works
  • One model without ID and one composition of this model with an ID. This would be my favorite, solving all your problems.

So for example:

class ProductData
{
    public string Name { get; set; } 
    public decimal WeightInKilograms { get; set; }
}

class ExistingProduct
{
    public Guid Id { get; set; }
    public ProductData Data { get; set; }
}

So then you can have:

ExistingProduct CreateProduct(ProductData data);

and

ExistingProduct UpdateProduct(ExistingProduct product);
0

It seems reasonable to have a "Product" model which has an optional ID, and then ValidateForCreate()/ValidateForUpdate() where the Update checks the ID and then calls ValidateForCreate() which validates the rest of the fields.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.