Helper Functions

Hello! I have been recently trying to do some research on the concept of helper functions but am finding the topic slightly confusing. Would anyone be able to provide a clear example/use-case of a helper function?

Thanks in advance!

Hi,

In general, it’s good to have functions that have one specific role (hence the name: function). This is not a mandate, but a conceptual ideal that’s aimed for (in some paradigms more than others).

Sometimes, when composing a function, you might find that you are doing something that has nothing to do intrinsically with the role your function is about, so for cohesion you can separate this logic into another function.

def peel(object): #this function is the helper
    object.remove(layer)
    return object

def eat_orange(orange):
    peel(orange)
    for slice in orange:
        slice.eat()

In the above example, if you think about it. the act of peeling has nothing to do with the act of eating. (You can peel paint, clothes, skin etc.) So, in terms of definition, it would be inaccurate to define what it means to peel only in terms of the orange (you might want to use it elsewhere after all!).

If we wanted to get super granular, you could say that the act of of peeling the orange could be subdivided into other branches of options (divvy up slices to share, squeeze into orange juice, etc). The point is not to be literal. And as this pedantic tangent shows, when employing paradigms, it’s helpful to reflect just up to what point it’s worth breaking things down.

In any case, benefits of helper functions are that they can increase readability, help with debugging, and generally organize your code if done properly. Additionally there are some times in recursive solutions to problems where it really is necessary to have a helper function serve as an anchor of sorts but that is a topic for another thread.

4 Likes

Thank you for the excellent explanation. Your example helped clarify my understanding!