Search code examples
javascriptjavascript-objectsprocessing.jskhan-academy

Why have multiple object methods without parameters?


I had recently begun learning and implementing objects in JavaScript. But it made me think, if the functionality of an object can be put into one method, then why use multiple methods like Example.prototype.update = function() with Example.prototype.draw = function() if one of these methods were to not require arguments? I could just define and then call on one method like Example.prototype.do = function() and put all of the functionality the two methods had. It's easier and less code, but maybe it's better to have a structure in my object with several, specific methods? Thank you.

EDIT: I ask this about methods without parameters because if you grouped all of the functionality of several methods with parameters it would be too much tedious work inputting a dozen arguments into one function.

Thanks for downvoting!


Solution

  • There are different reasons:

    Overview

    In Clean Code: A Handbook of Agile Software Craftsmanship, Robert Martin says:

    The first rule of functions is that they should be small. The second rule of functions is that they should be smaller than that. Functions should not be 100 lines long. Functions should hardly ever be 20 lines long.

    Along with that comes also the maintainability, I mean if the function is long, the human understanding of the coding begins to lack.

    Reusability

    The whole point about function is to reuse them. So imagine a function that calls another function of the same object several times. To merge it you potentially need to duplicate your coding.

    Other Reasons

    1. Performance: Maybe you don't want to do all the things at the same time (maybe because it's time consuming or you only want to do it when you need it...) or you don't want to do some things at all?
    2. Logic: Some things just don't belong together like a drawing method and a erasing method. Just makes no sense to merge them to a single function.
    3. Encapsulation: Every function has it's own scope, so if you would only use one function you would probably mess up the scope