Search code examples
architecturesemantics

Is the method/function responsible for validate your call?


Why is best way to write a function/method?

1 - First way

function main() {
     back()
}

function back() {
    if(step > 0) {
          step = step - 1
     }
}

2 - Second Way

function main() {
    if(step > 0) {
          back()
     }
}

function back() {
    step = step - 1
}

I think that the second option is the best way because the function back do only one thing... that is back. But, what you think be the right way and why?


Solution

  • First, you must encapsulate the browsing behavior in a class responsible for it.

    Second, you should follow the Tell-Don't-Ask principle, in this case, the first option

    https://martinfowler.com/bliki/TellDontAsk.html