[Date Index] [Thread Index] [Author Index]
Re: Suggestions for Maintaining "Object" State?
Carey Sublette wrote: > I am starting to develop a fairly complex simulation using Mathematica 6 and > am confronting a basic issue that I am unsure how best to resolve: "How to > preserve the state of an object?" > > Physical objects represented in a simulation have internal state that is > preserved and affects how they respond to stimulus from the simulation > environment. > > Possible ways of implementing this behavior includes creating modules > representing objects and: > * exporting state to the session (or other enclosing scope) as a list of > values, which either exists as a global variable or is passed in as a > parameter; > * using UpValues or Tags to assign object state to symbols(?). > > At the moment the objects in the simulation have a 1-to-1 relationship, > there is only one of each type, which simplifies the problem, though in the > future I may need to maintain state for multiple objects of the same type. > > Does anyone have recommendations for how to do this, optimized either for > convenience or efficiency? > > Obviously everyone is going to give a different answer to this - there is no right answer! Personally, I would not attempt to follow the style of an existing OO language, but try to use what comes naturally in Mathematica. I suggest every one of your objects would be represented by a symbol (probably created with Unique): pl=Unique["Plane"] fl=Unique["Flight"] etc. Once you have an object, you could attach properties to it: plane[fl]=pl; TypeOf[pl]="707"; etc. Passing an object around would simply consist of passing the relevant symbol. There are a few things to consider early on: Is the simulation going to carry on so long that the number of objects might be a problem. If so, you will need to supply a function to perform a cleanup when a "flight" has completed. Another minor consideration is to figure out a good naming convention for the properties before everything gets big and complicated. Since you will create a lot of function names, you need to avoid clashing with future Mathematica names. I do that by using the \[Breve] character (which acts as a letter and looks a bit like an underscore) to space out words: Is\[Breve]A\[Breve]Kind\[Breve]Of I could just not capitalise the first word, but I think that looks ugly. Full OO includes the concept of polymorphism - i.e. a function f will have different definitions for each possible type of argument. You could always implement that by using the TypeOf property and adding an IsAKindOf function to create the hierarchy: IsAKindOf["707"]:="Plane" I have used strings for the types of things, but thinking about it, fixed symbol names might be better: Obj\[Breve]707 I hope this gives you a few ideas! David Bailey http://www.dbaileyconsultancy.co.uk