Java-Style getters and setters can increase production risks
This code insight counts one violation each time a class define getter or setter (one of then or both) for a given member. If the implementation of the class contain the following pattern: self.<member> then a violation will be counted if the class defines a getter/setter mehod compliant with the following naming (case insensitive) unless the declaration of this method is preceded with the decorator @property or @xxx.setter: (get|set)_*<member>Why you should care
Python is not Java. If you need to set or get the members of a class or object, just expose the member publicly and access it directly. If you need to perform some computations before getting or setting the member, then use Python’s built-inproperty decorator.
Usage of built-in property decorator allow to associate a member access syntax (<object>.<attribute>), to a treatment implemented by a function. this is usefull because:
- there is no "private attribute" concept in python's classes. But property decorator force getters and setter decorators force to call a getter for each access to a member.
- for existing client code accessing directly to members , it is possible to add data treatment throught getter and setter without needing to modify the client code.
class P: def __init__(self,x): self.x = x@x.setter def x(self, x): if x < 0: self.__x = 0 elif x > 1000: self.__x = 1000 else: self.__x = x@property def x(self): return self.__x
Business Impacts
[nz_btn text="Production Risk" target="_self" animate="false" animation_type="ghost" color="pink" size="small" shape="rounded" type="normal" hover_normal="opacity" hover_ghost="fill" link="http://casthighlight.wpengine.com/category/product/indicators-methodology/innovation/" icon="icon-office"]CAST recommendations
References
http://docs.quantifiedcode.com/python-code-patterns/correctness/implementing_java-style_getters_and_setters.htmlAbout CAST and Highlight’s Code Insights
Over the last 25 years, CAST has leveraged unique knowledge on software quality measurement by analyzing thousands of applications and billions of lines of code. Based on this experience and community standards on programming best practices, Highlight implements hundreds of code insights across 15+ technologies to calculate health factors of a software.
For reference only. For the complete details please refer the original article
https://doc.casthighlight.com/alt_unexpectedgetter-avoid-java-style-getters-and-setters/
https://doc.casthighlight.com/alt_unexpectedgetter-avoid-java-style-getters-and-setters/
Comments