257 points · by grimwall · 6y ago · 259 comments
Sometimes after finishing a big implementation, I just go back and read my own code ... and I like it! I feel proud that I translated some kind of abstract problem solving into a concrete solution, and somehow it works!
I feel like I created something that flows according to my ideas and it’s a joy to look at. Are there analogous feelings in other creative pursuits you practice?
Of course not everything is like this, only novel problems I encountered have potential to give this feeling, CRUD back-end endpoints are routine by now. Also I don't feel like an exceptional programmer, feel more like an impostor, so please don't read this as bragging.
The old joke is about us looking at code we wrote six months ago, and being horrified at what we see. And I've had more than my share of that.
But what's ALSO happened, many times, is I look at old code I wrote... and I'm IMPRESSED. Just blown away by the beautiful elegance and power of the abstractions I came up with, the sheer intelligence of the approach, the insight and lucidity oozing from the code.
"Wow, I wrote THAT?!" Because I was deep in a coding trance when I wrote it. So deep "in the zone", that when I come out, it's not easy to recapture where I was. Not even the next day, and certainly not months later.
Interesting how it works!
> "Wow, I wrote THAT?!" Because I was deep in a coding trance when I wrote it. So deep "in the zone", that when I come out, it's not easy to recapture where I was. Not even the next day, and certainly not months later.
I attribute code I wrote in this way to "the other me".
A huge problem I encountered when hitting the working world was this: common features at corporate shops, such as open-plan offices and Scrum, seem almost calculated to stifle "the other me" from coming out. It's as if the company doesn't want a programmer to rely on their other self to write the damn code, and by reducing everybody to the exact same kind of gibbering idiot and training that gibbering idiot to write code, programmers become easier to hire (because any gibbering idiot will do), and more replaceable (because you are not relying on a programmer's particularly potent other self to deeply understand, fix, and solve problems).
And yes, "gibbering idiot" is about how I assess the intelligence of my normal "talking" self that has to engage with other people, especially in comparison to the "other me".
haha-- Remember to thank your "other me" and you should make sure to drop little notes addressed to your future self-- beacuse it is REALLY rewarding to find a note you left addressing your future self like "Hey, Future Self-- If you're looking for the actual module that does the communication-- it's: [location]"
And if a year later you are doing EXACTLY that-- trying to track down that thing-- and you start with something you know -- and find that note- It's hard to not exclaim- "Thanks Past Self, you just saved me some searching- hats off to you sir"
“Of what others do you speak?” the Prodigy demanded.
Master Foo said: “All your future selves.”
Me 6 months later: Thank god I wrote docstrings, what is this garbled mess.
To each their own, but comments are generally a positive addition to code.
This does sometimes entail a few 'what'-style comments, so I'm disappointed to regularly read of programmers that have apparently taken up arms against them.
Level 1: Garbage code with no or bad comment.
Level 2: Garbage code with good comments.
Level 3: Good code with comments
Level 4: Code good enough that it doesn't need comments, with rare exceptions.
Each level is better than the previous. You can't level up directly from 1 to 4.
Still, 4 is the best level. I know it sounds weird if you haven't seen it.
I know some people don't feel that way, because I've been dinged for it in code reviews as something that should be covered in unit tests. But I think digging through unit tests to glean the structure of an object adds a lot of overhead.
I wish I could see over time that the latter takes precedence, but I'm just happy these days that the majority most falls somewhere in in the midpoint between both extremes.
Its proof that past me was much smarter than present me.
:)
I happened to be hosting my own mail server at the time, and I had previously implemented a crude spam filter, but the important part is that all my emails were already stored in a database and (crudely) classified as spam or ham, so I had a corpus available for training the classifier.
I spent a couple of hours in 'the zone', and wrote a Bayesian email classifier plus all the database management needed in a few hundred lines of C. The program compiled the first time - a first for me - and worked correctly the first time - another first. It did help that I had been heads-down in a complex project written in C for several months at that time, so my knowledge of the language and good design- and implementation practices were at an all time high.
That same program managed my spam pretty much unaltered for several years, until I switched to a commercial email host. Every few years, I still dig up that code as an example of good design and implementation.
On the grandparent, I never much wrote a ton of C and then compiled, did more "skeleton of the app/lower level bits/stich them together" incremental stuff. So lots of compiling and testing along the way. Not quite Lispy but Lispy for C.
But Fred Brooks makes a good point with:
"""The programmer, like the poet, works only slightly removed from pure thought-stuff. He builds his castles in the air, from air, creating by exertion of the imagination. Few media of creation are so flexible, so easy to polish and rework, so readily capable of realizing grand conceptual structures....
Yet the program construct, unlike the poet's words, is real in the sense that it moves and works, producing visible outputs separate from the construct itself. […]
The magic of myth and legend has come true in our time. One types the correct incantation on a keyboard, and a display screen comes to life, showing things that never were nor could be."""
Luckily as I have gotten older I have gotten fewer and fewer of those days.
It took months to find the bug. Turns out it started leaking once the filesystem quota was reached, the log tried to roll and failed. All logging messages were just building up in a queue. It was a definite face-palm moment once found, but yeah, took months to get there.
I had a similar issue w/ a high-res timer that was causing spurious socket timeouts. Only found because...logs were saying operations were taking +200 years to complete. That was about 6 weeks of time during development.
Forging ahead thoughtfully, incrementally, and modularly balances the ratio a lo--oh hey a foreign codebase designed in an overengineered byzantine Lovecraftian fractal of thought death. 9999999:1
If someone's good at running and marketing a large business, it doesn't necessarily mean that they do good work, and may mean that they know how to maximise profits by cutting corners whenever they can. That's not always the case, but it seems to be pretty typical.
Instead, look for the small guy who may not have a website and drives a plain van. I work for my dad, and that describes him to a tee, as well as most of the other tradesmen on the jobs we do. My dad doesn't even have a company name, nor business cards. He gets all of his work either through a few regular builders, or by word of mouth from previous customers, and is definitely not a business-man. He started carpentry with his dad after he finished high school, and just slowly grew from there. For most of his life he worked alone, but as they grew older, all of my brothers at one point worked for him full-time (it's just me now, and I'm part-time).
If you do find a potential tradesman, just ask him (or her) how he does certain aspects of the job (ex. baseboard inside corners should always be coped, never mitred), and make it clear that you expect high quality work. If he asks for significant payment up-front for anything other than materials, walk away. Better yet, supply all the materials yourself, and pay a proportion of the job each day or week until it's done. One more factor to consider is price. We charge more than the typical carpenter, but not exorbitantly more. If the price seems too good to be true, it probably is.
I've also found this to be true for auto mechanics. The run-down looking shop is more trustworthy and does better work for a better price than the highly polished franchises.
Some people's way of dealing with that is to just not get too attached to their code.
I'm not saying that all code is short-lived. Most developers I know deal with at least some code that's been around since dirt. But there is also a fair amount that gets left behind rather quickly, and neither of those scenarios necessarily has anything to do with the quality of the code nor the suitableness of it to the task at hand.
Not to mention that most of us have had projects we put a lot of effort into, that fulfilled the requirements, and was done on time, only to have it rarely ever (and sometimes never) used by the people who asked for it.
I think it's possible to either care too much about your code (in the sense that you often have no control over what's done with it in the long run, and you need to be able to accept that), or to care too little about it (if you're going to bother writing it, at least try to as good a job as you can under the circumstances).
long time; // no see $ PONG=1.1.1.1; ping $PONG
$ more cowbell
$ cat dog | tee hee
And my favourite choice of empty file: $ touch me
Also I was fairly please years ago when I briefly re-aliased cd to something that could do "the right thing" (TM): $ cd ...
$ cd ..../src/
etc..`echo "Mongo only pawn in game of life"`
I am SO gonna steal that.
:-D
catch (Exception up)
{
throw up;
}
Truly genius code try
ToastTheGenius;
except
On Glass: Exception do
raise(Glass);
end; except Exception as the_roof:
raise the_roof int ofTheJedi;
I was a bit confused until I got at the bottom of that function and saw this: return ofTheJedi;
That's when I recognized a coworker's style, haha // http://photos3.meetupstatic.com/photos/event/4/b/c/2/600_436939394.jpeg
I don't know if anyone ever noticed this comment and followed the URL, but I hope they did and were amused. (The code was eventually refactored/rewritten, so the comment no longer exists in the codebase.) struct timecube {
uint16_t millisecond_of_minute;
uint16_t minute_of_month;
uint16_t month_and_year;
};For people that don't play with bits often: Unsigned 16-bit integers have their max as 65,536. Storing data often wastes most of the bits, since a field that goes from 0-1000 doesn't fit in an 8-bit integer, and C doesn't have native integers between 8 and 16 bits long. (You can mask out relevant fields, but that's annoying.)
So there are 1000 * 60 = 60,000 milliseconds in a minute, which is an impressively good use of the space available. There are also a max of 60 * 24 * 31 = 44,640 minutes in a month, which is pretty good usage of the second value as well. The final 16 bits are probably 4 bits for month and 12 bits for the year, going up to 4096. Alternatively it could be using it as something like month_of_common_era to get it out to year 65536/12 = 5461.
IIRC, month and year was a 4-bit and 12-bit bitfield just as you describe.
stop(); // hammer time return when.all(promises).yield(true); class Action(Lawsuit): ...Mine:
const makeEmptyPromise = () => Promise.resolve([]); def daterange(start,end):
while start<=end:
yield start
start +=timedelta(days=1)
Though simplistic and straightforward, I admire the solution. I am sure there may be “better” ways to achieve the same result, and posting this here may result in cowboys trashing it or pointing out a fallacy - oh well... at the time, I was pretty satisfied with it and am still to this day.Apply generator expressions, format them with map, filter out weekends, anything in itertools (dropwhile, takewhile), etc.
I wrote a datepicker to demonstrate some concepts like lazy evaluation with JavaScript generators and it was fun coming up with the test cases.
https://github.com/gumballhead/datepicker/blob/master/src/it...
dt = timedelta(days=1)
outside the loop and using it inside would make it a bit more efficient. def range(start, end):
while start < end:
yield start
start += 1
Or is it more about the beauty of the algorithm than this specific code?https://stackoverflow.com/questions/4345045/javascript-loop-...
I hate dealing with date math, but I have to admit that Python makes date math much more elegant. I've written the functional equivalent of the OP function several times, and it's just so nice to be able to loop over dates just like they were any other generic sequence.
Edit: plus you can enhance it pretty to make arbitrary increments with ease:
def daterange(start, stop, increment='days', step=1):
start = datetime.fromisoformat(start)
stop = datetime.fromisoformat(stop)
inc = {increment: step}
while start <= stop:
yield start
start += timedelta(**inc)
> list(daterange('2020-01-01', '2020-01-14'))
[datetime.datetime(2020, 1, 1, 0, 0), datetime.datetime(2020, 1, 2, 0, 0), datetime.datetime(2020, 1, 3, 0, 0), [...], datetime.datetime(2020, 1, 14, 0, 0)]
> list(daterange('2020-01-01', '2020-01-14', 'weeks', 1))
[datetime.datetime(2020, 1, 1, 0, 0), datetime.datetime(2020, 1, 8, 0, 0)]During my first tour with the company I built, among other things:
- (on a two-person team) an ASP.NET web app that allows payroll admins to extract year-end data from their AP in order to distribute tax forms (W-2s, 1099s, etc.)
- (different two-person team) a mail-room management back-end that allowed us to print/mail over 1 million forms/year for customers of the above
- (yet another two-person team) A corporate intranet product
Since returning to the company I've been on another small team (3 developers) building an independent payroll platform. As part of that effort, we've had to integrate with all the other things I ever built at the company. It's been extremely valuable for our team that I have intimate knowledge of basically all of our integration points across the company. Much of my original comments and code from ~2007-2015 are still in the source tree. Some of that makes me happy, and some of that makes me cringe :)
Described this in a recent blog post: https://tkainrad.dev/posts/managing-my-personal-knowledge-ba...
It's nice to take a moment after finishing a project, a challenging task, or whenever you feel like it and preserve snippets that you are proud of. Going through these pieces of code later brings back memories of these past projects, teams, tasks,...
cat ~/src/example-code/py/numpy-masked-array.py
save me tons of time for those hairy things that I had to eat an hour to figure out and then use infrequently
I have a bunch of open source projects from more recent years up on Github that I look at once in a while when I'm looking for a solution for something, and they tend to be less piles of shit. BTW my biggest project open source project has been taken over by a whole team after I've left it, and I can't recognize most of the code now, that's a really weird bittersweet feeling.
My first question was, "Haven't the other developers ever touched it." They said no. This core piece of technology scaled to way more users and was essential to making 100s of thousands of dollars for the company. It didn't even break once in two years. It was core to the service and they were just asking how to move it. I was so proud of previous me.
It seems so much more interesting than the web stuff I do today.
Much older code is generally neither smart neither beautiful though.
Often I look at my older code and recognize the stage of development as a coder that I was in. It's usually not cringe-worthy but it makes me pensive about how I would handle it now.
Another joy is when I find out that a module I wrote is being used extensively by other developers. Just recently I found out that a small, single-purpose function I wrote for my specific needs and deployed to our shared library, is fundamental to another team. They asked me about modifying it for requirements they have. The code itself wasn't beautiful but it filled a need and could be understood well-enough to modify by another. It made me happy all day.
And yes, other creative pursuits give me the same joy. Some practice sessions on my drums seem effortless. My ideas seem to flow regardless of the technical difficulty. Likewise, some dinners I make are chef-level tasty and get the desired "yummmm" from my wife and daughter.
Keep a memory of the times when your code makes you smile. Those memories pull you through the down times.
The quality of the code doesn’t have to reflect the quality of the solution and we should celebrate the things we nail.
I guess not being able to carry on with my life if I know that my code has the slightest issue means that I assume it is perfect and therefore I'm idolizing it.
Which (with ~1.5KB of binary data appended, total under 2KB) creates this: https://code.shishnet.org/videos/floating_point.mp4
I feel like my youthful stupidity unlocked a lot of potential - I managed to make a lot of impressive fragile hacks which only needed to work once, and worked once. These days if I tried to create an animation like the one above, I’d probably get a couple of thousand lines into writing a well-tested reusable framework, and get bored before seeing any results...
(Also, leave a blank line before your code and indent each line of it by two spaces to make it formatted like code.)
However-- sometimes (with increasing rate into my 15 year carreer) I need to modify something and had not touche the code in a long time-- only to find to my supprise I already had that feature or ability coded into it... I then have to say "Thanks Past Jon- This is Future Jon (to you) and noice forward thinking"
While in isolation due to gobal things... it's a good time to make sure Past you and Future you get along-- Present you (third state) is both past and future but leave some notes for Future [yourname] and make sure if you find notes from Past [yourname] you remember to appreciate their work.
10 years later, it's time for me to move out, and I'd left the TV as the last thing because I had forgotten how to work the mechanism to get the TV off the wall (and it would require all sorts of annoying face-against-the-wall maneuvering to see how to unscrew, etc).
I look from the floor up behind the back, and what do you know -- I'd left myself a taped note, extra bolts, and instructions on exactly where to turn the hidden lock screws (in the state where the TV already mounted) to release the unit from the wall.
I was marveling at my foresight for a self-satisfied minute (and thanking my past self).
Regardless of comments.
When that doesn't happen, I just spend the time to understand it again and add the comments. It eventually gets better.
On an aside, someone here mentioned that python 2 isn't python 3, in that the code itself gets old quick. But I don't think that really comes into it. Unless you're spaghetti-plugging holes in clients, there's a lot of joy to be had in manipulating any language or system to a desired end, especially when it's hard won, and I would think too when you return and see yourself in the result.
Not exactly a “creative pursuit” but often with legal work it takes years for any sort of feedback on a document’s effectiveness. Sometimes you’re alerted to a potential issue and your first thought is “yikes, there’s no way I drafted for that”. Much like coding it’s always a good feeling when you go back and see that you had contemplated the weird scenario and drafted accordingly.
I’ll admit it feels a bit more “magical” when it happens in my code though. I think perhaps because the stakes are lower so I can appreciate the work instead of feeling like I’ve dodged a bullet.
1. Zero dependencies
2. Lightweight abstraction
3. API enforces correctness in usage
4. API covers the problem space well enough that the API hasn't changed since a couple months after initial release (it's been 3-4 years)
5. Library does something all of the individual pieces of software using it couldn't have done individually - not easily anyway.
When I first started working on the code, I guessed (correctly, in retrospect) that for technical reasons changing the API after version 1.0 would be a struggle, so I reached out to 3 of the more prolific developers in the space who needed what I was working on and collaborated with them early to rapidly iterate on the API. I declared 1.0 a couple weeks later once it felt like we were all pretty happy with the product.
I wasn't the only person working on that specific problem. In fact IIRC my solution was the third "to market". However, by really pushing to get through multiple iteration cycles in collaboration with my intended users, the bunch of us managed to converge onto a simple and durable design which ended up becoming the de facto standard.
It's not my most elegant code, but it solved a specific in-demand problem and did a clean job of it.
Almost every time I add a significant feature to the game -- a new enemy or object type, a state machine for enemy AI, etc. I brace myself for a drawn-out process -- and am surprised to find that things come together rather well and straightforwardly, with a minimum of bugs and glitchy behavior. And I think to myself, huh. Well, I guess I'm not as dumb as I thought I was, and made some actually good choices early on that greatly eased my development burden now.
@dataclass
class Node:
id: str
children: List[Node] = field(default_factory=list)
# beautiful Python: traverse a tree depth-first, pre-order (stack based)
def __iter__(self):
stack = [self]
while stack:
node = stack.pop()
yield node
stack = node.children + stackThe "wow this was clever" feeling I'm sure exists in all kinds of creative pursuits, but for artistic creativity I doubt the "somehow it works!" feeling is the same. If it connects with an audience you probably wonder if it was just marketing and luck, and if it doesn't, you wonder if it's just your own personal taste.
I soon got tired of drawing circles and numbers and decided to write a quick Gimp plugin that does just that:
https://github.com/silasdb/mark-number-circles/blob/master/m...
I new nothing about Scheme at the time (the script is written in an imperative style) but I still think it is one of the smallest and most useful pieces of code I've ever written and from time to time I get an email from a random person from the world thanking for this small script :-)
EDIT: fix English
The code is good, but something about the simplicity of the language and the bareness of the algorithm that makes that header and source file pair so meaningful for me.
Then upon going into the code I realize the basic framework already exists to implement the feature.
One of the more pleasant experiences in our code base.
The negative experiences of "Did I write this?!?" tend to be driven by performance bottlenecks and profiling.
It is just a really dumb search for a random solution. (I don't want to get the same solution or solutions each time.) The domains (which are always pretty small) for the variables are randomly shuffled first, so the search can just iterate through the domains.
The problems mostly have a large number of solutions out of the total space, so finding a solution is fast.
The real beauty is then being able to write short declarative code, which is very easy to write, read and modify (I'm not always sure in advance exactly what the constraints should be). None of which would be the case for the code which would construct a solution, even though it might run a little faster.
More fulfilling for me however is not the code itself, but significant results. I have captured/framed a few graphs in my career that look like a "sudden jump" or a "sudden drop", which were caused by deploying a more elegant solution to a problem or pain point.
<Expr> ::= <Reference> | <NumericLiteral> | <Expr> '+' <Expr> | ...
<Reference> ::= <identifier> | <ArrayRef>
<ArrayRef> ::= <identifier> '[' <Expr> ']'
<Varname> ::= ... (The parser is parametric in the parser for <Varname>)
... without upsetting the F# typechecker.By the way, for me this happens with all forms of creative/original endeavors, not just with coding: Sometimes I read and admire passages I wrote in clear, lucid English in the past. Sometimes I look at and admire mathematical equations I wrote in the past (even if I'm no longer as well-acquainted with them as when they were fresh in my mind). Sometimes I look at and admire diagrams I sketched in the past, e.g., for a research project.
I think (for me at least) it has a lot to do with what I see what good™ programmers are doing. If it matches that, then I allow myself to consider it good. But it's so rare for me to feel that... That's probably why I prefer working among less experienced developers. That way I can see myself as comparatively better and feel good about myself.
I still love the domain parser I had there. I actively tried to avoid regex by the time, and I had a huge validator that brings tears to my eyes. I admire it because this can be written with a single regex, but I am sure I spent an hour or two working on this, carefully planning about public suffixes, IDN conversion, host headers, etc.
I tend to do a lot of ETL-like stuff, essentially tanks that roll in one direction relentlessly. If there is an uncaught exception, it gets Pokemon-caught because it is okay if that one row doesn't happen, I can examine the problem later. The tank must roll forward. Each problem encountered in the wild results in another chunk of armor.
Select techniques from different tanks are often handy.
https://miscdotgeek.com/building-direct-conversion-receiver-...
There has been some exceptions, mainly in my Haskell-code, a monad still seems to be a monad and I start to see it with a more "math-focused-lens" and then I start to find some small admiration.
I believe there is a moment of maturity in any developer's career. And it is related to critical mass of experience - when for pretty much any new task you know upfront how it should be done , at least architecturally. And in different variants: ideal, realistic or just to show something.
But I'll also comment on the opposite (which I attribute to continually trying to improve my craft). Often when I look at code I wrote >6 months ago, I find something that I'd do differently today. Sometimes it's downright distasteful!
Nobody cares either way, though; code ultimately has its own notion of quality, and human aesthetics are totally unrelated to code quality. We all must learn to think like computers and appreciate code like computers do.
1. I could use my creativity (it was not entirely defined problem which just needed to be translated to code).
2. I have enough time to make it good, not rushed.
3. Problem was a little over my current competence level, so I could learn something new.
If you only make CRUD forms day in/day out it's hard to be proud of what you do. Creating map display engine which is more performant than anything you have seen to date IS a thing to be proud of (I'm still proud of that one thing, but it's other firm's internal tool, so I can't show you). Unfortunately, for most developers being able to work on such things is very rare. I had maybe 5 such things over my 20 year career.But what regularly happens is that I stumble on my own comments and/or helper methods, which saves me a ton of time.
Turns out that having a clean code structure with clear places to have those 5-liners that you need all the time is really useful, and by now I've got so much of them that they compose quite powerfully ! And old comments are like gold nuggets when the time comes to debug.
{ eval "package " . __PACKAGE__ . '::' . (0+$class) . "; use base qw(" . join(' ', map { ref($_) || $_ } @_) . ");" }
This might help:
my $package = bless $class, __PACKAGE__ . '::' . (0+$class);
Or this:
return Devel::Pointer::unsmash_hv(substr(ref $self, 2+length(__PACKAGE__))); }
I have learned very useful tricks over time, like the ability to automate code creation to incredible levels with my own dialects of lisp that makes me hundreds of times more productive.
But when I was young I used scalable vector graphics to document everything I did, and some ideas I had are quite impressive to me today.
Other times it’s “I think I really nailed the dev UX on this.”
These days I’m prioritizing more on conveying intent and proper use by name, location, and signature. And it seems to be supporting me back over the last two years oh my current codebase.
Really annoying, really over-engineered, and of course, undocumented. To boot, it also utilizes dependency injection because... There are no unit tests, no mocking, nothing. No reason to use DI other than to obfuscate. Very frustrating. It's 10Ks worth of C# that I could do in a few hundred in Python (and have it perform better).
You could also re-write the same code in C#, and have it perform even better than the hypothetical Python version, while being around the same length.
After that, I occasionally go back through old code asking "what have you done for ME lately?" and an eye towards dragging it behind the toolshed and going "Ole Yeller" on it.
My code has to continually prove its worth to me, or else it's gone. Code is a liability.
s=>s[0]+/.*( .|z)|...s.s?|T..|M[i-t]+|[AFINOUW][^o]v?|.*/.exec(s)[0].slice(-1).toUpperCase()
It does something pretty useful, that has surely been written many times over. But unlikely ever as succinctly as this. :)Otherwise code can always be made better.
Often I'm sort of irked by my old code.
But it is telling that from time to time I find some old simple code that was easier to read / change than I expected if only because I coded it so simply and in an iterative sort of way.
There's something to be said for being simple...
Admiring an older piece of code that I've written more than last year? Rarely, unless it's just a small puzzle or self contained code.
Now at times when I have the space and time to code things the way I wanted, I step back and do the same :)
If you don't occasionally go back and become horribly embarrassed at what you've done you're probably calcifying.
If you look at your own code months or years later (some applications do need maintenance), you'll hate it or be ashamed of it. But you should know better than improving it by then.
Right now the whole file is changed but that code is still intact.
So the best bits are probably the multipage comments that precede a handful of lines of code and explain what's going on :)
So much of my code is boring, flat, procedural code, because that's what the job calls for.
For the most part my standards get higher as time goes on though. So only small things!
amountFulfilled = isFulfilledOnSite * quantity
yes, isFulfilledOnSite is a booleanC'est la vie.
Live. Learn. Adapt. Move on.