How to properly utilize generics to practice interface based programming for decoupling parts of the system?

I’m trying to create a hypothetical system with restaurants, products, options and product IDs.

The restaurant can have two types of product IDs: integer and string. Therefore, I need to take this into account. That’s why the product ID is wrapped to accommodate external systems that send products with string or integer IDs (some integrations store ids in UUID format and some in integer).

I have a shipping system that gets any restaurant that implements the interface (which also has Product, Option, and ProductId – they all need to implement their respective interfaces).

I have doubts about my solution, because it has too much generic code, which makes it difficult to write (imagine having to write this kind of code for more than 20 restaurants), and it also has an error. Therefore, I cannot proceed because of the error.

Currently, I don’t think that it is necessary to use an adapter class for each restaurant (with casts inside), or to have a shipping system that uses generics in the class definition (because I can retrieve restaurants at runtime – I will not be able to create a shipping system with the respective restaurant types – I simply don’t have them at runtime without reflection and I need to avoid reflection at all costs because shipping would be done at runtime (not startup) and reflection is not justified in terms of speed and throughput).

I think the main problem is my lack of understanding of generics and how to use them in real-world project scenarios. Can you help me?

Here is the code (fiddle link available too: https://dotnetfiddle.net/xzi10f ):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

public interface IProductId { }

public interface IProductId<out TId> : IProductId {
  public TId GetIdValue();
}

public interface IOption {
  public string GetName();
  public float GetPrice();
}

public interface IProduct<out TProductId, TOption> where TProductId : IProductId where TOption : IOption {
  public TProductId GetId();

  public string GetName();

  public float GetPrice();

  public void AddOption(TOption option);

  public TOption[] GetOptions();
}

public interface IRestaurant<TProductId, TOption, TProduct>
  where TProductId : IProductId
  where TOption : IOption
  where TProduct : IProduct<TProductId, TOption> {

  public void AddProduct(TProduct product);

  public TProduct[] GetProducts();
}


// Real implementation

public abstract class FastfoodRestaurantOption(string name, float price) : IOption {
  private readonly string name = name;
  private readonly float price = price;

  public string GetName() => name;

  public float GetPrice() => price;
}

public class BurgerOption(string name, float price) : FastfoodRestaurantOption(name, price) {
  private bool fried = false;

  public bool Fry() => fried = true;

  public bool IsFried() => fried;
}

public class FastfoodRestaurantProductId : IProductId<string> {
  public required string Id { private get; init; }

  public string GetIdValue() => Id;
}

public class Burger : IProduct<FastfoodRestaurantProductId, FastfoodRestaurantOption> {
  private float discount = 1;

  public float GetPrice()
    => (10 + (GetOptions().Sum(o => o.GetPrice()))) * discount;

  public string GetName() => "Burger";

  public void ApplyDiscount(float discount) => this.discount = discount;

  private readonly List<BurgerOption> options = [];

  public void AddOption(FastfoodRestaurantOption option) {
    var burgerOption = (BurgerOption)option;

    if (burgerOption.IsFried()) Console.WriteLine($"Burger option named {burgerOption.GetName()} is fried!");

    options.Add(burgerOption);
  }

  public FastfoodRestaurantOption[] GetOptions() => [.. options.Cast<FastfoodRestaurantOption>()];

  public FastfoodRestaurantProductId GetId() {
    return new FastfoodRestaurantProductId {
      Id = "some_product_id"
    };
  }
}

public class FastfoodRestaurant
  : IRestaurant<IProductId<string>, FastfoodRestaurantOption, IProduct<FastfoodRestaurantProductId, FastfoodRestaurantOption>> {

  private bool discountDay = false;

  public void MakeDiscountDay() => discountDay = true;

  private readonly List<IProduct<FastfoodRestaurantProductId, FastfoodRestaurantOption>> products = [];

  public void AddProduct(IProduct<FastfoodRestaurantProductId, FastfoodRestaurantOption> product) {
    if (discountDay) {
      if (product is Burger burger) {
        Console.WriteLine("Product is burger applying discount!");

        burger.ApplyDiscount(0.8f);
      }
    }
    products.Add(product);
  }

  public IProduct<FastfoodRestaurantProductId, FastfoodRestaurantOption>[] GetProducts() => products.ToArray();
}

public class ProductShipper {
  public void ShipProductsFromRestaurant(
    IRestaurant<IProductId, IOption, IProduct<IProductId, IOption>> restaurant
  ) {

    foreach (var product in restaurant.GetProducts()) {
      var id = product.GetId();
      
      if (id is IProductId<string> stringId) {
        Console.WriteLine($"Product ID is STRING: {stringId.GetIdValue()}. Storing in one table...");
      } else if (id is IProductId<int> intId) {
        Console.WriteLine($"Product ID is INT: {intId.GetIdValue()}. Storing in another table...");
      }

      Console.WriteLine($"Shipping product named {product.GetName()} with price: {product.GetPrice()}");

      foreach (var option in product.GetOptions()) {
        Console.WriteLine(
          $"Product has option: {option.GetName()}"
        );
      }
    }
  }
}

internal static class PlaygroundGenerics {
  public static void Main() {
    var fastfoodRestaurant = new FastfoodRestaurant();

    var burger = new Burger();

    var lettuce = new BurgerOption("Lettuce", 10);
    lettuce.Fry();

    var cheese = new BurgerOption("Cheese", 20);

    burger.AddOption(lettuce);
    burger.AddOption(cheese);

    fastfoodRestaurant.AddProduct(burger);

    var shipper = new ProductShipper();

    shipper.ShipProductsFromRestaurant(fastfoodRestaurant); // Error here. cannot convert from 'FastfoodRestaurant' to 'IRestaurant<IProductId, IOption, IProduct<IProductId, IOption>>'
  }
}

public static class Program {
  public static int Main() {
    PlaygroundGenerics.Main();

    return 0;
  }
}

4

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật