October 22, 2024
Chicago 12, Melborne City, USA
java

How to instantiate variables in a class while adhering to SOLID principles in Java?


I am working on a game in java to understand SOLID principles through application, my Entity class code currently looks something like this

public abstract Entity() {
    
    Point worldCoord;
    /*
    * Other variable declarations...
    */
    public void Entity() {
      worldCoord = new Point();
      // Other variables...
    }
    /*
    * Other variable declarations...
    */
} 

I believe this violates SOLID as if I need to add a new attribute, say Rectangle attackRange, then I would have to add the line attackRange = new Rectangle(); into the constructor and this would be modifying the class, and therefore violating SOLID.

One way I’ve thought of tackling the problem is to instantiate the variable inside the setter function, but that ‘feels’ wrong. So I would like to know where I am going wrong and what’s the proper way to instantiate class variables while adhering to SOLID principles.

Thanks.



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video