Search code examples
javascriptdomrefactoringreadability

Code smell - passing boolean control argument to function


Below is the code fragment, there is something which I don't like:

function insert(el, child, before){
  if ( before ) {
    el.insertBefore(child, el.childNodes[0]);
  } else {
    el.appendChild(child);
  }
}

Why not instead have two separate methods like insertBefore and insertAfter? what are the pros and cons of this and other approach?

Update:

I got this nice article explaining what I wanted.


Solution

  • The whole purpose of this function is to avoid having to put an if statement in all the places where you call the function. So if you have lots of places that look like:

    if (something) {
        foo.insertBefore(bar, foo.childNodes[0]));
    } else {
        foo.appendChild(bar);
    }
    

    You can simplify all of them to:

    insert(foo, bar, something);
    

    With your two methods, it would become:

    if (something) {
        insertBefore(foo, bar);
    } else {
        insertAfter(foo, bar);
    }
    

    which isn't too much better than the original.