I'm a beginner in programming and I was wondering what is the better practice when entering method values in OOP.
Would it be better to pass in the variables externally using parameters like this:
def add(number_1, number_2):
return number_1 number_2
number_1 = float(input("Enter the first number: "))
number_2 = float(input("Enter the second number: "))
print("Sum =", add(number_1, number_2))
Or to have both the input and the output in the method like this:
def add():
number_1 = float(input("Enter the first number: "))
number_2 = float(input("Enter the second number: "))
print("Sum =", number_1 number_2)
add()
CodePudding user response:
It really depends on your program, if you want to add further operations like subtraction, multiplication or division etc. in future then it's better to go with the 1st approach since you might want to do multiple operations with the same set of numbers. Even if you don't want to then also you have a way to do that. But if you're sure that you won't be adding any further operations then the 2nd one is good. But, Generally the 1st one is better.
CodePudding user response:
Unfortunately I won't agree with Chatresh. There is a SOLID principle, where S states for Single-responsibility principle. Sometimes it's hard to have one function indeed do one thing, but your case is good example for that.
Function add
should just add numbers, asking for an input, getting values, converting them is much much beyond the scope of that function. If I would read the code and see add
function I wouldn't expect all of that.
Saying that, I do not recommend second variant, unless it's only for quick, draft code.
CodePudding user response:
It is a task specific choice.
However, for your specific function here option 1 seems better, because usually you want to make it as modular as possible.
Explaination: Imagine you want to write a automatic test within a test pipeline, e.g. pytest. Your version 1 can be easiliy tested and resused also for other tasks. Option 2 will make both much harder.