Hi, I've been coding on and off my whole life. I've mostly coded Perl, but also some Java, PHP, C, C++. I've even took a stab at Emacs Lisp, and I've done the occasional shell script. However, I've never actually engaged the subject to gain any kind of expertise – other things have had higher priorities for me. I don't consider myself to be really proficient in any language but Perl, and also now Haskell which I'm taking a course in right now.
Lately, I've been thinking about my style of coding. Not the style of the actual code; as a CS student I only do projects for fun or for school, which enables me to write what in my opinion is beautiful code almost always. One question in particular has been troubling me. It's a rather curious thing, but still something I would like to hear other opinions about.
Here's the thing: I find myself taking a fair amount of time to name my functions and variables to the most easily understood names I can possibly think of. Sometimes this task can be very tedious, even when not taking into account the difficulty of finding a variable name that conveys the meaning of a piece of code. For example, right now I'm making a function that looks like this.
This is Haskell code but the meaning should be quite clear. (It's exact meaning isn't that important so if you want to, just skip the code and read on.)
-- return the row with least number of Nothing values
bestRow :: [[Maybe Int]] -> Int -> Maybe (Int,Int)
bestRow [] _ = Nothing
bestRow (row:rows) thisIndex
| nextRow == Nothing && thisFilled > 8 = Nothing
| nextRow == Nothing = Just (thisIndex,thisFilled)
| thisFilled >= nextFilled = Just (thisIndex,thisFilled)
| thisFilled < nextFilled = nextRow
where thisFilled = length $ filter (/= Nothing) row
nextRow = bestRow rows (thisIndex + 1)
(nextIndex,nextFilled) = fromMaybe (-1,-1) nextRow
I couldn't decide on the variable names. The function did it's task well but it wasn't as clear as it could be. Once I settled on a solution, I spent 15 minutes on naming and renaming the variables. Should I go with curIndex, nextIndex || index, nextIndex || ind, indN etc? 15 minutes after I decided I was done, I realized this function wasn't needed after all: I found a much better solution to my problem. BOOM I had lost a lot of time simply cleaning code to no use to anyone, least of all to me. Or at least it felt that way.
This is something which has happened to me more than once, and is quite frustrating, mostly because it makes me feel dumb. What are your thoughts on this subject? Is this something you've experienced, something wrong with my way of doing things or simply something unavoidable?
Are there "perfect" variable names, or is it "ok" if they at least doesn't obfuscate your code?
Thanks,
Stefan Kangas