Reputation: 14119
I couldn't really think of a clear title for the question; feel free to reword if if you like. I want to make a simulator for the three-body problem (physics): three objects are given initial positions, velocities, masses (constant), etc, and said positions change based on the gravitational forces exerted by each of them on each of the other bodies. I am faced with two choices:
a) Create an object that holds all of the data (position, velocity, acceleration vectors, etc) for the bodies, then get them to interact with each other through functions outside of the object:
var system = {};
function init(array) {
// loads data into window.system from input array
blah blah blah
}
function doThis() {
// does This
}
function doThat(params) {
// does That
}
function wait(t) {
// wait for time t, adjusting vectors accordingly, then recalculate
doThat();
doThis(foo);
blah blah blah
}
// more code that executes wait() over and over again
blah blah blah
b) Create a single class that serves as a template for an object that holds all the data, but has all of the functions (and everything else related to the system) inside it:
function System(array) {
// init
// loads data from array into vectors etc
blah blah blah
function.doThis() { // private function
blah blah blah
}
this.doThat = new function(params) { // public function
blah blah blah
}
this.wait(t) {
doThis();
blah blah blah
}
this.output() { // outputs data into an array to be parsed by whatever (e.g. a visual renderer)
blah blah blah
return data;
}
}
// how to use
var systemA = new System(someData);
systemA.doThat(foo);
setInterval(1000, function() {
systemA.wait(1);
var data = systemA.output();
renderGraphics(data);
});
// create more systems if I want
var systemB = new System(whatever);
// etc
Which method would be the smarter way to go (easier, less complications in the long run, scalability, etc)?
Upvotes: 0
Views: 34
Reputation: 664579
The approaches seem to be pretty equivalent - both have a constructor (or init
function) and a bunch of methods to interact with the system
object.
Only in the first snippet, all functions are littered over the file, while in the second they can be easily be identified as belonging to that class.
Upvotes: 1