Search code examples
reusability

Is it better to handle object creation inside the function or add it to the parameter list


This question is programming language agnostic, but IMO it`s an important one.

As you know, writing reusable code is a mix of science and art, and its a crucial skill any developer must have for writing great code.

Assume I have a class which includes several functions:

class Example

def func1()

  creates objectA
  ...
  ...

def func2()

  creates objectB
  ...
  ...
def func3()

  creates objectA
  ...
  ...

def func4()

  creates objectC
  ...
  ...

In the above case, is it better to:

A. create object A inside the functions 1 and 3, so once other developers use functions 1 or 3, they won`t have to put effort on finding how to send that object as an argument (which constructor to use for creating it etc...).

In general, the more parameters the functions have, the more effort the developer needs to put in order to start using it...

OR

B. Is it better to put object A as a required parameter in functions 1 and 3, so once a developer would like to use those functions, he/she will have to create object A outside the function, and then send it as an argument to the function?

If I wrote a program which uses func1 and func3, then both functions will repeat creating the object twice (bad performance).

Who wins in this Reusable Vs performance question?

Thanks,

Qwerty


Solution

  • I accept "usr1234567" comment as the proper answer.

    Thanks,

    Qwerty