2

Basically I am trying to figure out how to avoid having a lot of arguments in a constructor in javascript. The reason is that I am making a space based game with a friend for fun, and the ships are module based. At the moment they can have a engine and many sensors, weapons and colony modules. More will probably come. Each ship is built from a spec, so to make a ship you just give it a spec and the constructor of the ship handles the rest. But when making a spec I need to provide the modules. What I want to avoid is doing this:

ShipSpec = function(civ, name, hull, engine, sensors, weapons, colony, ...) {}

And I am not sure what the best solution is. At the moment I have a visitor pattern solution, where each module has a "register" method. This method has one argument and will then register itself with that argument (if the module is a weapon it calls the method for registering a weapon, if its a sensor it calls the method for registering a sensor etc). So then I can do:

ShipSpec = function(civ, name, hull, engine, modules) {}

However, I feel like it might be a bit complicated. Maybe. I have an unfortunate ability to complicate things a bit sometimes. Would it be better to create a spec and then add the modules to it after its creation? Or is this solution fine? Is there another solution to this problem?

And we plan to make so the player can create specs and maybe modify existing specs, so I want to make it easy to do so in a good way.

Take care, Kerr

1 Answer 1

12

Consider using an spec object as a constructor argument:

var spec = {
  civ: "...",
  name: "...",
  hull: "...",
  ...
};
ShipSpec = function(spec) {}

This way:

  • Constructor arguments are named, so it's much simpler to grasp.
  • Arguments may be given in any order.
  • You can ommit some arguments.
Sign up to request clarification or add additional context in comments.

4 Comments

for a lack of better syntax, this is the best we can get in javascript.
Thanks for the idea. A question, though. Should I put every argument in the constructor in an object like that or just the optional ones?
@Kerr - it's up to you, basically. Personally, I would decide based on example on the number of mandatory arguments. If it's small (like 2, 3 or 4), I could put them as a separate arguments. If there's more than a few mandatory arguments, moving them to the spec object makes more sense in my opinion, as the code would be much more readable.
Ok. There wont be that many mandatory arguments, just the civ, name, hull and engine (all ships need an engine, after all :p), so I think I can keep them as seperate arguments. Thanks :D.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.