letting an object name itself
Show older comments
i am working on an object oriented code. i would like every object to have a property 'name' that is identical to it's workspace name. (i didn't find any way to reference the workspace name in the code, but in any case i think this way is more convenient). the only way i found to do it is to have the user input the object's name as an input parameter in the constructor. e.g Nathan=Person('Nathan',property1,property2) this way is inconvenient and if the user gives a different name by mistake (e.g Nathan=Person('Batman',property1,property2)) it causes bugs. is there a better way to do this? or at least to generate an error messege if the names are different
Many thanks
Nathan
3 Comments
Steven Lord
on 15 Sep 2020
What would you want the name property to be if the object were stored in an array or a cell array?
thePeople{42} = Person('Nathan', ...)
What would you want the name property to be if the object has no workspace name associated with it, not even a "container" in which it is stored?
steve.greet(Person('Nathan', ...)) % greet is a method of Person
How are you planning to use this information in the future? If you're planning to use it to try to manipulate the object using its name property that's generally discouraged.
Is your object a handle object? If so what should steve's name property be after executing the two lines of code below. steve and stefon refer to the same object, so is steve's name steve or stefon?
steve = Person('Steve', ...)
stefon = steve;
Nathan Blanc
on 15 Sep 2020
Stephen23
on 16 Sep 2020
The difficulties arise due to the approach of forcing meta-data into the variable names,which invariably makes code slow, complex, and buggy.
The simple, efficient, robust approach would be to correctly store the meta-data (which after all is data) in a variable, not in the variable's name. And instead of having lots of separately named variables just use one simple object array to store them all in. Then your code will be much simpler and the data will be easier to process.
Accepted Answer
More Answers (0)
Categories
Find more on Data Type Identification in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!