How to Write a Great Function, Part 2 - Return Types

| No TrackBacks
You can learn a lot about great functions by looking at horrible functions.  What's one of the antipatterns we see in horrible functions all the time?  How about this: the return type of the function is completely insane.  Yeah, I'm looking at you, Mr. Hash of Hashes!  This is a particularly huge problem when it comes to calling APIs whose code you can't actually read.

Last time, I talked about how the function name is the best spot to communicate the intent of a function.  Return type also comes in very handy there, because it's the proof that the function does what it claims to do.

Imagine you see a function called CalculateSubtotal in an API.  You think to yourself, "A-ha, this calculates a subtotal!"  And then you look a little closer at this function and you see that it's void, it doesn't actually return anything.  Wait, calculate what for the who-now?  Intent destroyed, dogs and cats are living together, and chaos reigns supreme!

Returning void from the function is usually too simple, but perhaps an even bigger problem is returning something too complex.  Imagine now that CalculateSubtotal returns an array of guids.  What in the world do those values correspond to?  They correspond to something, I realize, and perhaps I'm supposed to do something with them, but what and how?  Are these guids identifiers for something in the database?  Maybe they're lookup codes for errors in the logs?  Maybe they're just really beautiful guids that you thought I, a fellow data type enthusiast, would enjoy looking at?

What's the only way to actually see what those complex return-types from a closed API correspond to?  You have to run the code through a debugger.  When you do that, you're delivering a kick to the groin to the stated purpose of a good function: to encapsulate complexity.  Complexity is no longer encapsulated when I, the caller of the function, must first analyze your code to see what in the hell you are doing.  (I am harping on this because I am probably the world's worst offender here.)

There are many times when you will have to return a hash of hashes, or something equally complex, from your function.  What do you do then?  You should create a class.  It'll be an incredibly simple class that a monkey could write between glasses of Tang.  At the very least though, the OrderIDsToLineItemIDs class (or something along those lines) makes much more sense to the rest of Planet Earth than the monstrous, beastly hash of hash of hash of hashes you may be thinking about.

No TrackBacks

TrackBack URL: http://www.codypowell.com/mt/mt-tb.cgi/8

About the Author

The Art of Delightful Software is written by Cody Powell. I'm a dad, husband, software developer, and entrepreneur. I'm a cofounder at Famigo, where we make mobile work for families.

Twitter: @codypo
LinkedIn: codypo's profile
Personal blog: Goulash
Email: firstname + firstname lastname dot com

Categories