C
C#5mo ago
Adam

Structure of system with polymorphism

I have a Grid with Cells, each Cell has a CellEntities list of CellEntity. Each CellEntity has a data object called CellEntityData. Classes that derive from CellEntity will have different functions, they could have different types of CellEntityData, but the way I have things set up right now that's not necessary, but might be in the future. But the important part is to be able to differentiate between different CellEntity classes because I want Cell to do different things depending on the CellEntity (namely Instantiate different GameObjects in unity, among other things) What is the best way to go about implementing entities with this framework? Should CellEntity and CellEntityData be interfaces? Abstract classes?
13 Replies
Angius
Angius5mo ago
1. Do you ever expect a CellEntity to be instantiated on its own? If not, use an interface or an abstract class. 2. Does the CellEntity class contain any functionality or data that is shared to its children? If yes, use an abstract class
Adam
AdamOP5mo ago
1. no 2. yes if i use an abstract class, how do i differentiate between the classes that inherit from CellEntity in Cell?
Angius
Angius5mo ago
You can use pattern matching, for example
void DoStuff(Cell cell)
{
if (Cell is FooCell fc)
{
fc.Blah();
}
else if (Cell is BarCel bc)
{
bc.Blep();
}
}
void DoStuff(Cell cell)
{
if (Cell is FooCell fc)
{
fc.Blah();
}
else if (Cell is BarCel bc)
{
bc.Blep();
}
}
Adam
AdamOP5mo ago
that was my first thought but i was thinking there has to be a better way of doing it
Angius
Angius5mo ago
Why?
Adam
AdamOP5mo ago
idk people tend to avoid big if else statements it feels a bit awkward inelegant maybe is the right word
Angius
Angius5mo ago
Could use a switch expression where appropriate Other than that... not really any other way of calling different code based on the subtype
Adam
AdamOP5mo ago
okay gotcha tyty i'll look at implementing this now in Cell i have a PopulateCell function that takes in a list of EntityData and goes through and instantiates and initialises each Entity with its EntityData to load the world from a save how do i differentiate between different EntityData ? maybe make it abstract as well and have each Entity have a different type of data, or maybe through an enum?
Angius
Angius5mo ago
The same or similar way Pattern matching, an enum discriminator also works, sure
Adam
AdamOP5mo ago
ok tyty nice pfp btw s2 when
Angius
Angius5mo ago
Still waiting lol
jiniux
jiniux5mo ago
perhaps you want to use the visitor pattern https://refactoring.guru/design-patterns/visitor
Visitor
Visitor is a behavioral design pattern that lets you separate algorithms from the objects on which they operate.
Adam
AdamOP5mo ago
oh interesting i'll check it out ty
Want results from more Discord servers?
Add your server