Mohamed Mohamed - 22 days ago 6
C# Question

Can a class behave differently based on the context it's used within?

My problem is that I want to use one class in two classes but there will be properties that shouldn't exist in one of them. For example a warehouse ships items to the branches, the item in the branch should have

DiscountPercentage
property but it doesn't exist in the warehouse. Also there is a connection between the two instances of items in both classes (
Warehouse
and
Branch
): when items are added to a branch the quantity should be subtracted from the quantity (property) in the warehouse.

I'm thinking of the OOP concepts, how it can help, but I'm totally confused.
I created a class for the Item:

public class Item
{
public Item()
{
this.Categories = new HashSet<Category>();
}
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public int Quantity { get; set; }
[Required]
public decimal Price { get; set; }
[Range(0, 100), Display(Name = "Discount Percentage"), RegularExpression("([1-9][0-9]*)", ErrorMessage = "Enter only numeric number")]
public double? DiscountPercentage { get; set; } = 0;
public ICollection<Category> Categories { get; set; }
public ICollection<Order> Orders { get; set; }
public ICollection<Branch> Branches { get; set; }
}

public class Branch
{
public int Id { get; set; }
public string Location { get; set; }
public ICollection<Item> Items { get; set; }
}

public class Warehouse
{
public int Id { get; set; }
public ICollection<Item> Items { get; set; }
public ICollection<Branch> Branches { get; set; }
}


The problem in my code is that the item in the warehouse is the same as in the branch's, which is not true and also not wrong, how OOP can handle this situation?

Answer

In proper class design, the DiscountPercentage is not a property of the item. It’s also not a property of the branch. Instead, it’s a property of the relation between the branch and an item:

UML diagram of explained class relationships

So what you would do is create some BranchItem type which essentially just sits between them and defines the relationship including additional properties:

public class BranchItem
{
    public Branch Branch { get; set; }
    public Item Item { get; set; }

    public double DiscountPercentage { get; set; }
}