RickiG
Junior Member
Offline
Posts: 81
Re: boat has-a boatBrain AND boatBrain has-a boat?
Reply #7 - Mar 7th , 2009, 2:05pm
Hi My thoughts on it is that I always avoid, where possible, to instantiate variables in the global scope or in the constructor. When instantiating in the global scope these objects will take up memory even before they are used and the same goes for putting things in the constructor. I will often have an init() method and lots of getters and setters below my constructor, so that I can instantiate an object(being "empty"), but wait to later on to actually fill it with data. This goes for my external classes, setup is different... Design patterns and use of private/public methods like getters and setters will simplify both the way you design classes and the memory footprint you use up. A local variable will only take up memory when the method gets called, a global will not release memory when you are done with it. I think of the setup() as the constructor of a sketch, but a constructor that you must run, a sort of main(). So I will define the fields I need as this: PImage i1, i2; PVector v1, v2; setup() { i1 = new PImage(); v1 = new PVector(); } just the way sw01 does it. As PhiLho writes: some methods and fields are not available before setup has been executed. So MyObject mo = new MyObject() before setup() can be suspicious as we dont know what the constructor of MyObject() will utilize? will it access frameCount(), width or other fields and methods not currently available? The error messages you will get when doing instantiating before setup(), when something goes wrong, are also crazy and not the least bit helpful (an important subject that is often left out is how to code to help the debugger help you :) ). I don't have a deep understanding of how the processing environment works, so the above is just from my experience and what I believe to be good coding conventions in general. When doing the boatBrain -> boat and boat -> boatBrain you are sending references all over the place and coupling these object strongly, this means that later on you can not have a boat or boatBrain exist without the other. Probably not an issue....for now :) Maybe something like at "composite pattern" or "strategy pattern" if more algorithms are involved, would simplify things.