Jump to content

Writing a new class - what to put in the constructor and what not?


wayfinder
 Share

Recommended Posts

From looking at the way Phaser is set up, I gather that a class constructor takes the smallest amount of parameters possible to create a valid object, adds default values in the constructor for everything else and lets people handle their object configuration and "advanced" properties themselves. Great!

 

My Problem: I'm trying to write a new class for certain objects, which can be one of several subtypes, each with their own, different, parameter sets but also a lot of common properties and methods. Now, should I be writing ...

 

- separate classes for each subtype of object (duplicate code for the common stuff)?

- a single class with a constructor that creates an object of the simplest type, and that simple type's parameters (to be discarded in case that's not actually the type I want)?

- a single class that takes a "type" parameter and the minimal amount of parameters for every type (lots of "0, 0, null, null, 0, null, null" in the constructor call)?

- a single class that takes a config Object?

- something else entirely?

 

I would love to hear your thoughts! 

Link to comment
Share on other sites

  • 2 weeks later...

I'd personally go the config object route if you are doing construction in the create function or something similar.   In an scenario like an update, the config object route might be too slow (because of the way JavaScript accesses object properties) and it would be better to have explicit parameters or use one of your other approaches.

 

Another possibility you did not list is to have a single class with a simple constructor, and then a separate config method with explicit parameters to flesh out initialization.  This could be wrapped in some sort of factory method or object to make it seem more like normal object creation.

 

There are lots of ways to skin this cat. :)

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...