5 ms·
My question was: Why would you create a function that does something you could access as a built in language feature ? What is the benefit of using a function a
by ashray 14y ago
My question was: Why would you create a function that does something you could access as a built in language feature ? What is the benefit of using a function as opposed to just evaluating the result of i%3==0 ?
Looking at a function call for "multiple_of_3" I would actually expect it to do more than i%3==0 since that could've been done just right there.
I'm just trying to understand if there are benefits of doing it this way and not directly. So far I've just encountered snarky remarks and no real arguments either way.
- danielweber 14y agoBefore I quit The Daily WTF, the joke answer to your question would be "because it's resilient against someone changing the value of 3."
- AccordionGuy 14y agoI created the convenience functions "multiple_of_3" and "multiple_of_5" for a couple of reasons: 1. To make it clear to the interviewer that I "get" the problem. 2. To prevent myself from making any dumb mistakes. I'm only a half-decent coder, so I've made it a habit of putting such "Mollyguards" (http://en.wiktionary.org/wiki/molly-guard http://en.wiktionary.org/wiki/molly-guard) in my code as a precaution. 3. To show a little Ruby coding style. The convention in Ruby is to favour lots of concise little routines over big-ass ones. See "Eloquent Ruby" for the guideline and Shopify's ActiveMerchant library for an example of such Ruby in actual production code.
- irahul 14y ago> To show a little Ruby coding style. The convention in Ruby is to favour lots of concise little routines over big-ass ones. Writing small, concise components(classes, methods, functions, modules...) is a generally a good practice in any language. However, moving i % 3 in a separate method is not a good practice. As another commenter pointed out, your names are hardly apt. It would better serve to name them fizz?(multiple_of_3) and buzz?(multiple_of_5). But even then, if all fizz? is doing is i % 3, let it be inline. True that in the future you might need additional processing for fizz?(not for this particular eg; I am talking real world), but re-factor it when you need it. It's not like if you have i%3 inline, it makes it harder to re-factor it into a fizz? method later. Also, since you are talking ruby conventions, shouldn't your predicates be named multiple_of_3? instead of multiple_of_3?