Mar-12-2021, 11:38 PM
Depends on what you're optimizing for. If you have one task that will never be repeated or extended, and it's not huge, then creating a complex class isn't very useful. The code you've shown appears to be written as an example to show the basics of OOP, not to solve a particular problem.
As the task grows larger, with more components (and especially more authors), the benefits of cleaner separation between the parts of the code become greater and OOP practices can help with that.
That being said, the code looks horrible to me as an example of python OOP. It's using both regular and hidden attributes. Yes, they're possible to do, but I wouldn't recommend a python class to look like that, especially as an example for someone looking to learn it.
Your script is relatively fine for a quick script, but my concerns would be:
To "optimize" or "improve" it requires some metric to optimize against. Do you want it to be able to run faster? Have more understandable code? Be able to use as an example of OOP programming?
As the task grows larger, with more components (and especially more authors), the benefits of cleaner separation between the parts of the code become greater and OOP practices can help with that.
That being said, the code looks horrible to me as an example of python OOP. It's using both regular and hidden attributes. Yes, they're possible to do, but I wouldn't recommend a python class to look like that, especially as an example for someone looking to learn it.
Your script is relatively fine for a quick script, but my concerns would be:
- You're performing input both inside and outside the function. I'd rather do it in one place.
- You're handling errors by recursion rather than a simple loop. Unlikely to be a huge problem, but not a good habit. Recursion has memory and depth limits that are smaller than some other cases. Don't invoke it arbitrarily. This case could be replaced with a loop and remove the recursion.
- Minor (and done in the example as well), but you're truncating inputs to int(). I see no reason to do so. This could handle float() input just as easily.
To "optimize" or "improve" it requires some metric to optimize against. Do you want it to be able to run faster? Have more understandable code? Be able to use as an example of OOP programming?