Thursday, January 14, 2016

Day 5 - Learning clean code...and I make a thing unnecessarily recursive

Another moment of undiluted joy today: I built a recursive function, mostly from scratch.  That was one good lesson.  The other was ensuring that each function does one thing well...and generally one thing only.  That makes the function more portable, and makes code easier to understand and to troubleshoot.  

The project itself was a fairly simple exercise in opening and closing files and writing functions.  Given a file of 1000 lines, split it into two new files of 500 lines.  Doing so was pretty straightforward, and a little bit more work got it cleaned up (after a discussion of functional hygiene, so to speak).  I've had a tendency to treat functions like sub-scripts and just list a bunch of operations until a function "felt" unwieldy, then call in a new one to finish the job.  

I like this approach better.  I'm getting a better feel for how code works, and how the pieces fit together like legos.  You can build better stuff using legos, when you have lots of little pieces that each do one thing well.  Having large, unwieldy, highly-specialized pieces may let you build one thing well (like a space ship) but isn't very useful for building any of the other things you can imagine.

And yes, I went on to build a recursive version of the file-splitting program.  It will take a file of any size, and split it into files of a specified number of lines.  I know there's limitations to this approach (it's resource intensive, it's hard to read, it's slower than simpler versions that do the same thing...).  The point, though, is that I made a working recursive program, and I did it by following the arguments through the logical steps needed to make it work. I didn't give up when my script ran without errors, but terminated without producing the files I expected.  (That was an interesting new troubleshooting experience.)

So.  We're getting into recursive functions next week, formally speaking.  I'm relieved to know I can make one work.  I'm looking forward to learning the situations in which it's useful.

In other news, I woke up at 6 this morning with a great idea to make my "variable_catcher"aka "error_checker" function work better.  I had enough time to test my idea in the terminal, and it may work.  I didn't have time to play with it though.  Tomorrow is supposed to be review...so perhaps then.





No comments:

Post a Comment