Classes Of Variables

0 views
Skip to first unread message

Tarja Hempton

unread,
Aug 5, 2024, 12:44:57 PM8/5/24
to quirintebab
WheneverI write a new class, I use quite a ton of class variables to describe the class's properties, up to the point where when I go back to review the codes I've typed, I see 40s to 50s of class variables, regardless of whether they are public, protected, or private, they are all used prominently throughout the classes I've defined.

Even though, the class variables consists of mostly primitive variables, like booleans, integers, doubles, etc., I still have this uneasy feeling where that some of my classes with large amounts of class variables may have an impact on performances, however negligible they may be.


But being rational as possible, if I consider unlimited RAM size and unlimited Java class variables, a Java class may be an infinitely large block of memory in the RAM, which the first portion of the block contains the class variables partitions, and the rest of the block contains the addresses to the class methods within the Java class. With this amount of RAM, the performance for it is very nontrivial.


But that above isn't making my feelings any easier than said. If we were to consider limited RAM but unlimited Java class variables, what would be the result? What would really happen in an environment where performance matters?


Performance has nothing to do with the number of fields an object has. Memory consumption is of course potentially affected, but if the variables are needed, you can't do much about it.Don't worry too much about performance. Make your code simple, readable, maintainable, tested. Then, if you notice performance problems, measure and profile to see where they come from, and optimize where needed.


Maintainability and readability is affected by the number of fields an object has though. 40 to 50 fields is quite a lot of fields, and is probably an indication that your classes do too much on their own, and have too many responsibilities. Refactoring them to many, smaller subclasses, and using composition would probably be a good idea.


Performance wise, if you very often need all those properties, then you're going to be saving some memory, as each object also has a header. So intead of having 5-10 classes you put everyting into one and you save some bytes.


Depending on which garbage collector you use, having bigger objects can be more expensive to allocate (this is true for the CMS garbage collector, but not for the parallel one). More GC work = less time for your app to run.


Unless you're writing a high traffic, low latency application, the benefits of having less classes (and using less memory) is going to be completely overwhelmed by the extra effort needed for maintenance.


The biggest problem I see in having a class with a lot of variables is Thread safety - it is going to be really hard to reason about the invariants in such a case. Also reading/maintaining such a class is going to be really hard.


A basic principle we are always taught is to keep cohesion high (one class is focusing on one task) and coupling low (less interdependency among classes so that changes in one doesnot effect others).


While designing a system, I will believe the focus should be more on maintainable design, performance will take care of itself. I don't think there is fixed limit on number of variables a class can have as a good practice, as this will strictly depend on your requirement.


For example, if I have a requirement where the application suggest a course to student, and algorithm needs 50 inputs (scores, hobbies etc), it will not matter whether this data is available in one class or multiple, as the whole information needs to be loaded in the RAM for a faster execution.


I will again say, take care of your design, it is both harmful to keep unnecessary variables in a class (as it will load non-required information to RAM) or split into more classes than required (more references and hence pointer movement)


4. Now after sorting everything out, if i need some other variables to work-out my class, then i need to use them, i have no choice...Moreover after all these thinking and work going into creating a class, will be hardly effected by some additional variables.


Sometimes class variables are used as static final constants to store some default strings like product name, version, OS version, etc. Or even to store product specific settings like font size, type, etc. Those static variables can be kept at class level.


Now coming to your question. As far as instance variable is concerned, java's built-in Garbage collector will work, in most cases well and truly effectively, to keep freeing memory. However, static variables are not garbage collected.


Classes provide a means of bundling data and functionality together. Creatinga new class creates a new type of object, allowing new instances of thattype to be made. Each class instance can have attributes attached to it formaintaining its state. Class instances can also have methods (defined by itsclass) for modifying its state.


(Lacking universally accepted terminology to talk about classes, I will makeoccasional use of Smalltalk and C++ terms. I would use Modula-3 terms, sinceits object-oriented semantics are closer to those of Python than C++, but Iexpect that few readers have heard of it.)


Attributes may be read-only or writable. In the latter case, assignment toattributes is possible. Module attributes are writable: you can writemodname.the_answer = 42. Writable attributes may also be deleted with thedel statement. For example, del modname.the_answer will removethe attribute the_answer from the object named by modname.


Namespaces are created at different moments and have different lifetimes. Thenamespace containing the built-in names is created when the Python interpreterstarts up, and is never deleted. The global namespace for a module is createdwhen the module definition is read in; normally, module namespaces also lastuntil the interpreter quits. The statements executed by the top-levelinvocation of the interpreter, either read from a script file or interactively,are considered part of a module called __main__, so they have their ownglobal namespace. (The built-in names actually also live in a module; this iscalled builtins.)


The local namespace for a function is created when the function is called, anddeleted when the function returns or raises an exception that is not handledwithin the function. (Actually, forgetting would be a better way to describewhat actually happens.) Of course, recursive invocations each have their ownlocal namespace.


The global statement can be used to indicate that particularvariables live in the global scope and should be rebound there; thenonlocal statement indicates that particular variables live inan enclosing scope and should be rebound there.


Class definitions, like function definitions (def statements) must beexecuted before they have any effect. (You could conceivably place a classdefinition in a branch of an if statement, or inside a function.)


then MyClass.i and MyClass.f are valid attribute references, returningan integer and a function object, respectively. Class attributes can also beassigned to, so you can change the value of MyClass.i by assignment.__doc__ is also a valid attribute, returning the docstring belonging tothe class: "A simple example class".


In the MyClass example, this will return the string 'hello world'.However, it is not necessary to call a method right away: x.f is a methodobject, and can be stored away and called at a later time. For example:


As discussed in A Word About Names and Objects, shared data can have possibly surprisingeffects with involving mutable objects such as lists and dictionaries.For example, the tricks list in the following code should not be used as aclass variable because just a single list would be shared by all Doginstances:


There is no shorthand for referencing data attributes (or other methods!) fromwithin methods. I find that this actually increases the readability of methods:there is no chance of confusing local variables and instance variables whenglancing through a method.


Often, the first argument of a method is called self. This is nothing morethan a convention: the name self has absolutely no special meaning toPython. Note, however, that by not following the convention your code may beless readable to other Python programmers, and it is also conceivable that aclass browser program might be written that relies upon such a convention.


Any function object that is a class attribute defines a method for instances ofthat class. It is not necessary that the function definition is textuallyenclosed in the class definition: assigning a function object to a localvariable in the class is also ok. For example:


The name BaseClassName must be defined in anamespace accessible from the scope containing thederived class definition. In place of a base class name, other arbitraryexpressions are also allowed. This can be useful, for example, when the baseclass is defined in another module:


Execution of a derived class definition proceeds the same as for a base class.When the class object is constructed, the base class is remembered. This isused for resolving attribute references: if a requested attribute is not foundin the class, the search proceeds to look in the base class. This rule isapplied recursively if the base class itself is derived from some other class.


Derived classes may override methods of their base classes. Because methodshave no special privileges when calling other methods of the same object, amethod of a base class that calls another method defined in the same base classmay end up calling a method of a derived class that overrides it. (For C++programmers: all methods in Python are effectively virtual.)


An overriding method in a derived class may in fact want to extend rather thansimply replace the base class method of the same name. There is a simple way tocall the base class method directly: just call BaseClassName.methodname(self,arguments). This is occasionally useful to clients as well. (Note that thisonly works if the base class is accessible as BaseClassName in the globalscope.)

3a8082e126
Reply all
Reply to author
Forward
0 new messages