Lets suppose we have some Js Widget, that includes three objects view, controller, model.
var MyWidget=function(){
this.setModel(new Model());
this.setView(new View());
this.setController(new Controller());
...
}
And I create this widget this way widget=new MyWidget();
There must be some enty point to start this widget.My question is – what is the best practise (and why) to define entry point: in constructor or in some method (run,init,etc). I mean:
widget=new MyWidget(); //to create AND start widget
vs
widget=new MyWidget() //to create
widget.run(); //to start
Would there ever be a purpose to creating your widget without “starting” it? If not, just do it all in the constructor. If there is a purpose, but it’s uncommon, consider some alternatives like using a separate class with an init/run function so that the default use case remains as simple as possible. If the purpose is common, then having an init/run function is fine.
When it comes to APIs, always try to make the most common use cases the easiest ones to get right.
This depends on how complex the widget is. You can create and start a widget as long as you pass it all information and dependencies to make it operational. If you have a complex class that relies on many other classes to do specialized work, then you need to instantiate all those helper objects in the constructor function, or pass them in as arguments. This can become cumbersome as the external dependencies for a class start increasing. At some point a “widget” ends up with this basic life cycle:
- Instantiation – Bring the object to life, e.g. call its constructor function
- Configuration – Assign dependencies and give the object all the information it needs to operate
- Initialization – The initial heavy lifting to start responding to the user. Things like event handlers are set up in this phase
- Use – The object is available to interact with the user
- Destruction – The widget is no longer needed and should be readied for garbage collection. In JavaScript, this is a manual process
If your widget doesn’t need much from the outside world, then an “init” or “run” method is just extra typing.
If you want to leverage dependency injection and inversion of control, constructor injection becomes difficult to maintain, so you might need the multi step lifecycle outlined above.