-1

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

Marcus Müller
  • 34,677
  • 4
  • 53
  • 94
Qwerty
  • 748
  • 1
  • 9
  • 25
  • 3
    Don't care about speed, write good readable, maintainable code. This is always true, until you hit performance problems and have identified the very code which is the bottleneck. But in many cases, the compiler will optimize so much, that your optimizations by hand will probably do more harm. – usr1234567 Apr 02 '15 at 22:28

2 Answers2

0

IMHO this depends on what object A is and what those methods do. If object A is a private implementation detail of those methods, that I don't expect to see them in the parameters list.

If it must be swappable or mockable for example, then you could make them an argument, variable of the Example class, or use something like dependency injection.

You could always create a new private method that handles creation of object A to reduce code duplication. Then on top of that you could add some caching or lazy instantiation to improve performance if needed.

Rengers
  • 14,911
  • 1
  • 36
  • 54
0

I accept "usr1234567" comment as the proper answer.

Thanks,

Qwerty

Qwerty
  • 748
  • 1
  • 9
  • 25