Question

I have long of code function about 100 lines. It's hard to read.

Which is cleaner or better way to separate the function?

First way

function main() {
    func1();
    func2();
    func3();
    func4();
    func5();
}

Second way

function main() {
    // more code here
    func1();
}

function func1() {
    // more code here
    func2();
}

function func2() {
    // more code here
    func3();
}

function func3() {
    // more code here
    func4();
}

If no one better, when I should use second way instead of first way?

Was it helpful?

Solution

It's a good thing that you are bothering about this. It's always good to keep functions dedicated to a single conceptual purpose, and reasonably short.

The body of a function is structured as either:

  • A sequence of actions.
  • A loop.
  • A conditional branching.

If you can think of what the function is doing as a sequence of actions, then use the sequence of statements, i.e. the first method.

If the way you explain what the function does makes you realize that some step is actually part of a greater step, then structure those steps accordingly, one inside the other.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top