- Home /
Cram variables inside class, use inheritance, or something else?
I have a Spell class that has a SpellType enum. The thing is, each type of spell has different extra variables. For example, an AOE spell would have "shape", "strength", "duration" variables, while a summon spell would have "summon type", "size", "hp", and etc. And it can go even deeper as depending on the shape of the AOE spell, it could have even more variables. For example, a cube spell has three variables, "length", "width", and "height", while a flat square spell only has "length" and "width". What do you guys think is the best way to implement this?
I know that I can create an AOESpell class (or CubeAOESpell class) that inherits from the base Spell class (while CubeAOESpell inherits from AOESpell), but I'd like to just use the Spell everywhere unless the subclasses are explicitly necessary so that I don't have to adapt my code to use the new classes.
I think this is possible if I first create the deepest class, like CubeAOESpell, then cast it to a base Spell class and throw that reference around, but this feels awfully complicated while I could just put all the possible variables a spell could ever have into the base Spell class and call it a day. The problem with cramming is scalability and readability as there'll be dozens upon dozens of different variables for each spell type if I go deep with their implementation.
Answer by yuvaansh · Jan 04 at 06:16 AM
@Manasong_
I think you should use something called as 'Structs' They are basically like small classes and they can fit into a class all together, so as you mentioned you have a AOE Spell or a Summon Spell so what you can do is find out some variables that all spells have in common for example maybe duration or how much points or I don't know magic knowledge you need to craft and cast that spell. So what you can do is assign the values in the structs or the way you want but the additional variables that all spells do not have for example the cube spell you have it has length, height and width so you can name the struct cubeSpell(For example) and you can create and assign values for those variables. You can also find tutorials for these structs on YT too.
I hope this Helps :D
Yeah, this seems like the most balanced option. Going for the class inheritance and casting trick seems like too much effort, but the structs provide some better organization to the code rather than just cram unknown numbers of variables into the class.
Your answer
Follow this Question
Related Questions
An OS design issue: File types associated with their appropriate programs 1 Answer
FPS weapons class structure 1 Answer
Calling a method of a class that is a part of another class? 1 Answer
HideInInspector with inherited variables 1 Answer
Problem using variable of type CustomStat to indicate which player statistic to change 1 Answer