I like to divide my functions into small parts; it tends to make the code look cleaner. In most cases, the extracted parts are only used by the 'containing' function. For example in C#:
private void MyFunction()
{
// some code
FirstStep();
SecondStep();
ThirdStep();
// some code
}
private void FirstStep()
{
Console.WriteLine("I'm first.");
// some code
}
private void SecondStep()
{
Console.WriteLine("I'm second.");
// some code
}
private void ThirdStep()
{
Console.WriteLine("I'm third.");
// some code
}
JavaScript supports defining functions inside functions. So it would make sense to define FirstStep
, SecondStep
and ThirdStep
inside MyFunction
, like so:
function myFunction() {
// some code
firstStep();
secondStep();
thirdStep();
// some code
function firstStep() {
console.log("I'm first.");
// some code
}
function secondStep() {
console.log("I'm second.");
// some code
}
function thirdStep() {
console.log("I'm third.");
// some code
}
}
However when I do this, the resulting function seems huge. Visually it looks cleaner to extract the inner functions out of the calling function.
What is the best practice regarding this? Define inner functions inside the calling function or outside of it? Also, what is more common?
Aucun commentaire:
Enregistrer un commentaire