Code Review: Polygon area calculator

Hi all,

I have built this ‘Polygon area calculator’ in Python.
I would love to get feedback on this project. I would also like to hear some new ideas which will improve the efficiency of the project.

https://repl.it/@nehaYagnesh/boilerplate-polygon-area-calculator

Thanks and Regards,
Neha

1 Like

Things I’ve noticed and some other tips. Some of these can be applied to more than one place.

Class Rectangle

  • Regarding lines:
    width = 0
    height = 0

This is creating class variables, those would be the same for every instance created and would be accessible with syntax ClassName.variable, in this case they aren’t required nor needed in any way.

Regarding lines:

    def set_width(self, width):
        self.width = width
        self.side = width

Creation of not needed self.side variable.

  • Regarding lines:
    def get_area(self):
        area = self.width * self.height
        return area

If method is short, it doesn’t require any more complex operations and basically is just one variable assigned just to return it the next line, it’s often possible to skip the variable assignment as well. Resulting in return being just: return self.width * self.height

Regarding line:

r_pattern += ''.join('*')

join method is obsolete here, it basically doesn’t do anything in this case.

Class Square

  • Regarding lines:
    def __init__(self, side):
        self.width = side
        self.height = side
        self.side = side

Part of this is repeating __init__ function from the parent class. Take a look at super() function it allows for easy usage of original methods from the parent class (which might have been overridden in the child class). Using it you can simply use the __init__ method from Rectangle class to set self.width and self.height instance variables. Consider also whether the explicit third variable for self.side is needed or if it might be enough to just use self.width and self.height.

  • Regarding lines:
    def set_side(self, side):
        self.side = side
        self.width = side
        self.height = side

    def set_width(self, side):
        self.side = side

Notice that using set_width method would change self.side, while leaving self.width and self.height unchanged. Remember that other methods can be called from specific method too. This allows to make one method doing all necessary changes and then just call it from different methods that also should be able to perform these changes.

1 Like

Hey,

Thank you again. I am really grateful to you for sharing tips with me.
This helped me understand the power of inheritance using super.

Here is my refactored code: https://repl.it/@nehaYagnesh/boilerplate-polygon-area-calculator#shape_calculator.py

Again, thanks a ton! You are a rockstar!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.