Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Do you write comments in your code? If you ever have a long function that like

    ....
    // Here's where we apply coupon codes 
    ...
    
It makes sense to me to break that out into it's own function, preferably one with no side effects that I can write a test for if I need to. I can give it a name related to the business logic.

Inevitably there will come a new special case where, for example, where Gold Members will get to use double coupon codes on Thursday. You'll start by looking in `checkout()` where you'll see either 1000 lines of other special cases, or maybe 30 lines with function calls like `foo = applyCouponCode(shoppingCart, couponCode)`.

For me, it's easier to see where to start with the latter.



Comments are perfectly fine on their own. It's common that a block of code can be given a higher level explanation in a comment, but wouldn't be a good standalone function because it depends on the context too much and so the function has absolutely no chance of ever being used a second time.


It's okay if a function is only used once. It's worth it to separate it from the context it doesn't need.

Well, twice, including the test. If a block is complex enough to warrant a high level explanation, you might as well capture that intent in a test too.

Edit: in my example, `applyCouponCode` takes in a `shoppingCart` and a `couponCode`, so you know that's all you need to apply a coupon code. You'd change it to something like `applyCouponCode(shoppingCart, couponCode, user.memberStatus)` so you can tell at a glance that `memberStatus` has something to do with how coupons work. You wouldn't want to pass in the whole `user`, because giving the function more than it needs makes it hard to infer what context the function needs and, therefore, what it does.


Tests are code. If the function is easy to test then it's more likely to really be worth having.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: