-1

I've been struggling conceptually with the design of my large program. The general layout is something like this:

def mainFunc(parm_1, parm_2, ..., parm_n):
  # do step 1
  # do step 2
  # ...
  # do step m

My question is this: Should I make each step its own function? I'd never want to call any step as a function outside of mainFunc. So, alternatively, would it be better to make each step a snippet? What's the practical difference between calling a function and executing a snippet which does the same thing? (Assuming of course that any unneeded variables are deleted at the end of the snippet.)

I truly don't know which approach is better in the long run. Any suggestions would be greatly appreciated.

jjet
  • 155
  • 2
  • 7
  • 1
    There's almost no difference between calling outer function and pasting code in-place - so forget it. The reason to group code into functions/methods is to make code reusable (if you need to repeat the step few times it should be definitely extracted to function) and to divide huge block of code to many smaller blocks - you need to decide whether your `mainFunc` will be big enough – m.antkowicz Dec 22 '16 at 13:36
  • 1
    This is quite broad question. In most cases it depends on your needs... Python is OOP language, so there are also classes.. A lot of times I have class `class MyApp()` with methods and then `run` method, which calls the methods of the class. And then I use it as `MyApp().run()`.. But it is just one of many, many concepts.. – quapka Dec 22 '16 at 13:36
  • 1
    You should also consider that other people (which is also you in 3 months' time after not looking at the code) will likely have to read and maintain your code. In this way, it's much easier to communicate what each of the parts do with docstrings and functions that take inputs in a predictable format, do an easily identifiable thing, and give an output in a set format. If you have one giant function that "does everything" then this is lost. – roganjosh Dec 22 '16 at 13:42
  • @roganjosh good points. I began implementing this with the snippet approach and was constantly getting lost *myself*. I can only imagine someone else troubleshooting my code. – jjet Dec 22 '16 at 13:47
  • 1
    Exactly. It's also a nice roadmap when you first start building the project. Break down the components of the task ("read a file", "process data", "display on UI") and create placeholder functions/classes for each task that simply `pass`. You can then start populating these functions one by one and verify that each component functions as expected (or handles exceptions) before moving on to the next part. – roganjosh Dec 22 '16 at 14:15

1 Answers1

1

If each step makes sense on its own, then it might be better to make functions. In that way you can document on each function what it does and it will also be easier to isolate bugs. In summary, I believe using functions makes the code easier maintain.

Nogoseke
  • 969
  • 1
  • 12
  • 24