One thing that I find most annoying about OOP is that whenever you need a new variable in a member function, and you need that this variable “attaches” the object on which this function is called, you have basically no choice but creating a new private field. This is ugly in my opinion, because this mean that the variable is initialized at object instantiation (and you can possibly never make use of it if you don’t call the method that needs it), it’s not hidden from the other entities that can access the private members of the object, and on top of all this means can clutter your class definition (think about C++ classes, which most often come with an header with the entire definition of the fields in it).
Speaking in the C++ lingo, I want the behaviour of the static modifier on a variable in a global function, but in member functions, and the storage must be in the object.
I don’t know that many languages, but I have the feeling that in dynamic programming languages it’s easier to do it. I can think of Lua: I would just add a new index in the current table. This doesn’t hide the new “field” from the rest of the world, but unless you tamper the metatable, everything in Lua is public, so it is not really a problem in the Lua mindset. But the problem of initialization is addressed.
So, my question is: is there any static programming language (i.e., one in which the layout of an object is known at compile time) where this thing is possible?
And by the way, is there a neat workaround in C++ to get a similar result?
As the general idea in object oriented programming is to encapsulate behaviour as a set of methods (functions) and the data as a set of instance variables, this behaviour is not present in any static programming language that I can think of.
However, the idea to separate the concerns of a single class into multiple units (as to make it less monolithic) has been considered in a few languages. The idea is to separate the various concerns within the single class of object. Although the variable is not created at runtime (this would make the type non static), it can be declared in a unit separate from other units.
This is actually sort of available in C#. Although the implementation is purely cosmetic, you can declare a single class as multiple partial classes. One of the benefits is to separate concerns to avoid a single big declaration of everything encapsulated by the class (another use is code generation scenarios).
This lets you do the following:
File1:
File 2: