Roles of Member Var in An Object
Link
Here is a typical class definition to show different roles of member variables:
Config
Config is relatively simple. It is usually primitive values, like strings, numbers, booleans, etc. Or is is a composition of primitive values, like a JSON style object.
It is read-only and not changeable at runtime. Usually set up in the constructor.
Since it is read-only, it's safe to share across objects, like passing it to the constructor of other objects.
And since it is primitive, we can use it without worrying about memory management. Just pass it around and let GC to do its job.
Borrowed resources
Borrowed resources are usually shared across objects. They may be initialized globally, and shared with all objects. Or may be initialized in some object and borrowed by other objects.
When an object borrows a resource from another object, it does not own it. It does not need to call
close()
to destroy it.However the object need to make sure the resource is available when it needs to use it, That means its lifecycle must be within the owner's lifecycle. The owner object must be alive when the borrower object is alive, and the borrower object must be destroyed before the owner object is destroyed.
Owned resources
As previously described, owning a resource means the object is responsible for its lifecycle. It needs to call
close()
to destroy it.States
The word "state" can contain all informations that make up the object. However, we define it here to be a subset of owned resources. It is owned by the object and not shared with others.
The state only serves the object itself. It is frequently modified by the object's methods. In contrast, the configs and resources are usually set in the constructor, and not modified afterwards.
Although we may call a mutable method of a resource, it is changing the state of the resource, not the state of the object itself.
You may notice that the state of a owned resource is also a kind of state of the object itself. But we still separate them for clarity. It is a "sub-state".
Children objects
Children objects can also be considered as a kind of owned resources or states. The parent object is responsible for its lifecycle.
A child object can have its own states, and as mentioned above, they are sub-states of the parent object.
A child object can own its resources, or borrow resources from the parent object. That is intuitive, because its lifecycle is managed by the parent object, so it is naturally within the parent's lifecycle.
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.