Hacker News new | past | comments | ask | show | jobs | submit login
Ask HN: Do you ever go back and admire a piece of code you wrote?
257 points by grimwall on May 8, 2020 | hide | past | favorite | 259 comments
I switched careers and got into coding about five years ago and I have always wondered about this and am a little embarrassed about it.

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.




All the time.

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!


> 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.

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".


I responded without reading anyone else's comments-- I'm so happy that my Past [name], Future [name], dialogue is something other people do! You're "other me" is the same as my "Past Jon"

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"


“But even the hacker who works alone,” said Master Foo, “collaborates with others, and must constantly communicate clearly to them, lest his work become confused and lost.”

“Of what others do you speak?” the Prodigy demanded.

Master Foo said: “All your future selves.”

http://www.catb.org/esr/writings/unix-koans/prodigy.html


Me writing docstrings: God this is so much work for nothing... my code should speak for itself.

Me 6 months later: Thank god I wrote docstrings, what is this garbled mess.


100%. It's amazing how many GitHub repos have little to no comments, not even file or function overview comments. The amount of time save by potential contributors reading and having to interpret the code is way longer than it would take for the author to write the comments in the first place.

To each their own, but comments are generally a positive addition to code.


Yes, the greatest value add of comments for me is the potential time-saving, in the ideal case (re)acquainting you with a large work of code by guiding your attention from the top-down - firstly to orient you in the broad structural aspects, then to fly you smoothly down towards the minutae of reading individual lines of 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.


Are they ‘what?’ or ‘wat?’ comments? Maybe that’s the difference?


what, opposed to ‘why’ or ‘how’


No, I understand that part; but, I think of a "what" comment as "incrementing value of X"

a "wat" comment, like the meme, is more of a "this is a really weird blob of code that might be obvious when you break the whole thing apart; but, what it's doing is _this_ this is the implementation of it because we have a complicated data structure that's connecting all these pieces"


I think there are levels:

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 don't think level 4 exists. There is no code for problems of sufficient complexity that are self-explanatory. There are too many hidden assumptions and foreknowledge and tradeoffs and decisions baked into a block of code that, unless it's trivial, there's no way code itself can reflect it adequately.


I have three things to say about that:

1. I did allow for "rare exceptions". Some things do need to be explained outside of the code. Maybe we're not so different after all :)

2. There are a number of techniques to write such code. Before I learned them, I had NO IDEA. One is to take what would have been comments and use them as variable or function names. This includes (and I had real resistance before I accepted this) breaking out a variable of function only in order to give it an informative name. "Level 4" doesn't just happen. You work at it for a long time and sharpen your skills in that area.

3. To me, much of the art of writing software is to find ways to divide a complex problem into simple pieces. If my code is real complex, I look for simpler way to write it. And I look hard.


It does exist, but only for snippets, sections of code, or at best whole individual functions, especially in languages that are concise and expressive (which are most languages that are not Java ;-). But even really good code still needs comments about how things fit together, what to find where, etc., because those things are generally not expressible in programming languages, although a good module system can help a lot with that.


I still think a file should have at least some small comment at the top to help orient the reader and set expectations.


I find it's not useful to have comments in code that you are actively working on since they quickly get out of date. They are best added when one finishes work on a block of code.


I’ll do comments first and then code. It’s a lot faster for me to keep a flow and pseudocode and then write the code in between. If the comments are two pedestrian afterwards (increment i), I will erase the comments.

I started this technique early in my career back in the late 90s after reading “Code Complete”.

It also helps me to pick back up faster if I get interrupted.


I’ve heard that styled as “do project the document, don’t document the project” but I don’t know a source to attribute this to.

The idea is to write a rough draft that covers what the project is, what it does, the API structure, and how to use the project, then write the code, “projecting the document”, and finally sort out the documentation - comments in the source, everything else in a manual page, article, or research paper.


This sounds a lot like TDD, but with comments instead of tests. It's an interesting technique I never heard of.

Do you ever get back to code you wrote and find a lot of misleading comments that you simply forgot to delete/update? Or are you always updating the comments before you try a new approach if the first one didn't work out?


The pseudocode comments are way too detailed and too much noise to keep in the code. I’m not going to keep a comment in the code like.

   //increment i 
But also if the comment is something like:

  //Call the API to get a list of customers. 
I’m going to replace it with

  List<Customer> customers= GetCustomers(); 

Use the IDE to create a valid stub function and delete the comments. The method names become self documenting. At any point I have code that compiles.


At a previous job, when I transitioned off a few projects that I had solely worked on for 7 years, I warned the dev taking over from me: I don't usually comment my code, but when I do, you'd better pay attention.

I think in one of them, only a single source file (C++) had comments, and there were more comments than code. I was explaining an intricate locking pattern around a data cache.

Like you suggested, I added the comments after I'd done the work because it was a work in progress. I added the comments because it was a very fragile piece of code and sensitive to changes (e.g. really easy to cause a deadlock or race condition if changed).


I get the feeling, but I rarely think "I'm completely done now, time to comment!" Better to admit that and document a bit earlier than when it's "finished".


More accurate comments that way, isn't it. Nothing sadder than the optimistic comment from before implementation, which took the regular twisty path towards correctness in the corner cases. More of a risk for the higher level methods than the little "DRY" functions that do something relatively functional.


I frequently think just before committing/pushing, "Time to add some comments!" That doesn't mean the code is fully finished, but it does provide a clear point in time to add them (when needed).


I think this is a matter of coding style.

When I'm writing something I'm generally "top down", breaking the problem into sub-tasks. In this mindset I'll often start a sub-task with a comment describing what it needs to do, and then set out to do it. If it turns out I was wrong about what I needed to do then I update the comment, but that's not that common.


While working on it my comment explains what the block should be doing. Extra points for lists of harebrained ideas that will likely never happen.


Especially when it comes to data structures. It's so helpful to see a comment with an example of the structure of a variable, especially because you won't have the same context when you come back to it in a few months.

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.


On a bit of a tangent here, but good commit messages are another thing I really appreciate 6 months later.


I love good commit messages as well, but it can be hard to convince people to write them. I always hear "Why? i don't use them" which is self propelling. You don't have good messages, so you don't read them when you want to know something, so you don't write good commit messages.


I don't really do comments all that often (generally, only for "Chesterton's fence-esque" things) but I do really rely on good commit messages. They are really helpful when going back in history and trying to get a general idea why something changed.


Another thing I like to put in commit messages is the ticket# (of what ever bug tracker you're using) of the feature/bug task that drove the change.


I always advise juniors to document their code because they never know, next maintenance programmer to touch it might be themselves. I can't remember why I wrote code a week ago, let alone 6 months.


I once wrote a stored procedure that did something that has now been built into most databases. I didn't write the original code, I just modified the code to use the information schema. It took me two days to understand the original code and two days to make my changes. For a few years after I wrote that code I got emails from random people asking me questions about it and I sadly could not help them.


I have lived to see both ends of the spectrum from "who wrote this, it's awful" and "wow, who wrote this it's beautiful"

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.


I am never impressed by my own style, but I do forget very quickly all the corner cases that the code had to deal with, so I am always impressed that “that guy” thought about those details that are completely outside of my radar!


I have several pieces of code from 5+ years ago that I have zero idea how they work or how I came up with that approach.

Its proof that past me was much smarter than present me.


Of course, when there's a subtle bug in that wonderful, beautiful code, it's a real bear to understand and catch…


"Wow, that just like I would have written it!"

:)


Way back, when Paul Graham first wrote "A plan for Spam", I was so intrigued upon first reading the article, that I jumped straight into coding.

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.


This sounds awesome. C is my preferred language and I use it whenever I can and when it makes sense. I'd love to see this code. Is there a public repo for it?


Try go :) it's got the speed and "here's how the machine works" of C plus a) batteries included for all the modern things, and b) excellent multi-core scheduler.

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.


I have, and I do use it for projects (and plan on using it for more). But I also need C for things that require certain performance I'm unable to get out of Go.


Use Rust, then. Rust is like Go, except its binaries are small and fast (except string formatting, which is very runtime, horribly bloated and merely "fast-ish"). Anything C can do, Rust can do better (the string formatting excepted).


What is it with people insisting on using something other than C? You don't know what I'm working on, yet you're insisting I operate completely differently?

It's so weird to me.


Programming isn't unique in allowing you swing between moods of "this feels great :D" and "I'm so dumb". (I think most people feel like either at times, even hours apart).

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."""


When I started my first programming job the CEO told me that programming is 59 minutes of feeling like an idiot and 1 minute of feeling like a genius. It's really stuck with me, and has so far proven true.


What's awful are those bad days when it's actually hours and hours of feeling like an idiot, draining you away, and then when you figure it out you still feel like an idiot because first off it was so simple and second of all solving something in minutes is not going to wash away hours of feeling like an idiot.

Luckily as I have gotten older I have gotten fewer and fewer of those days.


I learn to accept when I am tired and need to take a break. Sometimes hours of needling through code can be solved in minutes on a fresh brain. I used to be stubborn and wouldn’t stop until I had made some progress and that went on making a tired day into an exercise in frustration. Took a while to have the confidence to shut down and start fresh the next day.


This hit me real hard, thank you I need to become better at this.

Just had a few frustrating days at work, lo and behold problem solved elegantly in 1 hour on a Great Prayer Day where I was supposed to be off-work.

The simple solution was just writing out a truth-table and then implementing it using the new C# switch expression to make sure I had all combinations taken into consideration.


I once had an issue where it appeared my servers were leaking less than a byte of memory per request (WTF? less than a byte?).

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.


59:1 is pretty good. Sometimes debugging gets me really down


That's when you hack and slash and debug by friction. : p

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


I find it reassuring to read these accounts. Even though I've been in the industry for years, I still have times (like this week), where I spend way too much time trying to do something that I feel shouldn't be that hard to do and imposter syndrome kicks in hard. A lot of what I see on hacker news is people at the top of their game, so it's nice to see people talking about actually struggling.


Love this comment!


What I like better is when you are bumbling through code you wrote a while ago trying to figure something out and there it is, a golden comment from past you, telling future you why you wrote shit this way. Usually it's some corner case or weirdness in an API you're calling.


I always write // XXX comments that mean there's something here I'm supposed to remember but I don't have the time to write it down right now. It's always fun going back over those and trying to reverse engineer what the hell I was thinking at the time.


Came here to say this - I almost never think much of the code I wrote. But when I see a moment in time that I took the care to do something for future me, it's almost the same as looking at an old photo of myself, and thinking, 'Hey, I didn't look half bad back then!"


I call writing these comments "being kind to my future self". It's easier to take the time to justify writing these when I think of doing my future self -- or the poor person who has to maintain my code -- a kindness.


[flagged]


Too many comments explain what is going on. That should be obvious from well-written code. But comments why it's done that way can be extremely valuable.

And sometimes there is indeed something wrong with the code. In those cases, a comment saying so can save a lot of time analyzing what's wrong with the code.


The counter-argument I've heard is that commit messages are a better tool for those kinds of annotations, especially if there are multiple points across the codebase where a change was made for the same reason.

That's exactly what commit messages are designed to do, too.

I've seen plenty of comments in code that say "handle case X because of behavior in place Y", that's tied to changes in place Y. I find it more meaningful when I see all those changes together, bundled in a commit diff, with a message on why.

In an especially good editor you can even have the title of the commit rendered into the blank space on the end of the line, which I find useful if I'm trying to figure out the past motivation behind a piece of code.


That's a false dichotomy. You can do both. The problem with relying only on commit messages, is that someone examining the code does not see it. You need to dig through the history. People don't do that nearly as often as reading the code.

But if you leave a comment with what the issue is, and add a reference to the commit message, you've got the best of both worlds.


Sometimes context should really be next to the code it applies to. If I'm adding pull-to-refresh functionality I might have a commit with ten changed files; there's no reason to put "use a dispatch_async to the main queue here so the animation gets put on the next runloop" in the commit message.


I came to write basically this exact thing FWIW. Always write the why, not the what. It's the clear difference between useful comments and excess noise.


There are particularly clever one liners that need a bit of unpacking on the what - Python is bad for this but anytime you are patting yourself on the back for the cleverness, a brief note (at least on the test) is probably warrented. I supposed one can code without cleverness but it's less fun :)


Cleverness that hurts readability is not good. Sometimes you can do a lot in a single line without hurting readability (it may even be more readable), but sometimes there's indeed so much to unpack that it's better to show the steps.


Comments should explain the "why" and not the "what".

The code _should_ explain the what just fine, but it doesn't explain the problem the code is trying to solve at all. If you struggle to explain the why with a docstring or few comments, then that's a sign you didn't decompose the problem enough.


Everyone's talking about code, but I do this with carpentry. Right now, I'm working as a trim carpenter in residential construction, and I pride myself on doing as good a job as I can. As a result, when I come back to a job to install door hardware after everything is painted, I sometimes just wander around the house and admire my work. Especially tricky details that took a bit of thinking to get right, even if no-one else will ever notice them.


The guys who installed new tile in my shower put in a custom shower niche that incorporated an interesting tile pattern, and I was glad to notice them taking pictures of it when they were done. It was neat to see their pride in creating an elegant one-of-a-kind feature (in what was otherwise a fairly routine project).


I sometimes wonder why it’s so difficult to find people like that.


Are you like that?


I wasn't expecting to be philosophically blindsided by this thread


"I am a builder," the end user replied. "Many of the houses of this town were made under my chop."

http://www.catb.org/esr/writings/unix-koans/end-user.html


How does one find a trim carpenter (or any skilled tradesman) who has this level of attention to detail? There's definitely two tiers of work, someone who cares and work good enough for a rental unit, and you have no idea what you're going to get until it's done.


I hate to say it, but mostly by word of mouth.

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.


I've noticed good trades people always take pictures of their work. I'm now wondering if it's worth asking to see images of their recent jobs.


Yeah, I take pictures too, but I've never really done anything with them. Mostly for my one satisfaction, but I suppose they could be useful to show customers.


I do this with almost everything I make. The act of creating is an act of achieving an aesthetic you developed in your mind's eye, so it seems reasonable to want to spend some time admiring that aesthetic once achieved.


The thing I can't get over, is that I know a lot of successfull, highly paid programmers who don't care about code at all. It's sad (to me) that they get rich, while not caring about their code.


I suspect that for some of these people, the reason they don't care is that they know it is fairly likely that their code won't last long, regardless of how awesome it might be. They will move on to other projects, possibly other jobs, and/or someone will decide it's time for a rewrite in a new language/framework, or whatever. Or the company will decide to flush their work and move to an outside provider, or to a different tool.

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).


I wish you'd done the trim work in my new house, then. Seems like these guys did it as quickly as they possibly could and then did their best RoadRunner impression.


It's good to know people do this outside the programming profession. Thanks for sharing.


The only thing I have ever gone back and admired is when I wrote the following snippet of code:

  long time; // no see


Hehe, well if we're going here there are various go-to shell commands / filenames / hostnames I inevitably end up using at some point just for the wry smile:

    $ 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..


"cd ..." etc. worked in 4DOS, an alternative (and extended) DOS shell: https://en.wikipedia.org/wiki/4DOS.


I think it was standard DOS, from maybe DOS 5 upwards?


I was thinking it worked in MS DOS after some point, but I was remembering more like Windows 95 era. I don't think it worked in MS DOS 6.x, because IIRC that's when I was using 4DOS. However, it doesn't work in Windows 10 CMD.EXE.


I wrote a generic bash function to spin up a mongodb instance called `mongo`. I couldn't resist adding

`echo "Mongo only pawn in game of life"`


You would get bonus points if you wrapped the mongodb process so that when it receives a SIGKILL it logs out "Mongo like candy!"


LOL - thanks for sharing this. Especially "$ more cowbell".

I am SO gonna steal that.

:-D


I came across this gem recently:

    catch (Exception up)
    {
        throw up;
    }
Truly genius code


  try
     ToastTheGenius;
  except
   On Glass: Exception do
     raise(Glass);
  end;


Or in Python:

  except Exception as the_roof:
      raise the_roof


I'm... going to have to use this. A lot.


I once came across a function that declared this:

    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


I once came across some code, written by a coworker, that consisted of deeply nested blocks. I added a comment that simply contained a URL:

  // 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.)


Well, I followed the URL and was amused. So it wasn't a complete loss (even if I never did see the code). Thanks for sharing!


Remember timecube guy? Seen on a 16-bit DSP...

    struct timecube {
        uint16_t millisecond_of_minute;
        uint16_t minute_of_month;
        uint16_t month_and_year;
    };


That's clever. I might steal that at some point. Or combine into a millisecond_of_month on a 32 bit processor.

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.


It also cooperates with leap seconds, by counting faithfully up to 61,000 on such a minute.

IIRC, month and year was a 4-bit and 12-bit bitfield just as you describe.


This gem in a Flash frame (Actionscript)

    stop(); // hammer time


was there an actual hammer involved in the game at this point? I think then it would be great, most of these cute, funny bits of code are making me feel annoyed by proxy.


I wrote the following, completely innocently:

  return when.all(promises).yield(true);


Except for the return to happen when that's true, you'd need an await. At least in JS.


Not if it's returned by an async function. In JS, async functions automatically await promises that are returned.


That's not actually right. An async function will always return a promise, so if you return a promise directly it's indeed pretty much the same as if you return a promise that waits on that promise; it's the calling function that actually awaits on the returned promise.

The main difference would be error handling: if you have a catch block that returns a different value, returning the promise directly would actually throw in the calling function, whereas if you "return await", it's going to get caught in your catch block, resolving the promise to your own custom value.

Found a detailed explanation here: https://jakearchibald.com/2017/await-vs-return-vs-return-awa...


Every time I implement an action class, I make sure to make an empty parent class to subclass it from.

    class Action(Lawsuit): ...


Code puns, yay!

Mine:

    const makeEmptyPromise = () => Promise.resolve([]);


That's worth printing on a t-shirt. :)


But was this in C?


It was in Java...but I C where you are going with this.


Well, actually, the fact that it wasn't in C kinda makes it work even better, from one point of view. :-D


Yes. Early on in my career, I needed a function that produced a range of dates, given a start and end date. After it was all said and done, it boiled out like so:

  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.


What's cool about this is now that you have a date generator, you can apply all kinds of fun things to your date ranges with Python's standard library.

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...


Not trying to trash it, but doing

  dt = timedelta(days=1)
outside the loop and using it inside would make it a bit more efficient.


I'm struggling to understand how this is special... isn't it basically just the normal 2-argument range function, but with date instead of int?

    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?


I think it's just the relative simplicity of code that handles date logic compared to other languages:

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)]


Python's date handling is meh. Some languages have dates as first class primitives and are a dream to work with.


Are you proud of using a generator to create dates as you need? Just trying to understand the logic


I've had the joy(?) of working for a company for close to 10 years, moving on to other work for about 5 years, and then returning again.

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 :)


They're lucky (or cursed) to have had the same person build so many different systems at the company.


Ha! Too true on both counts.


It's been years since I've asked a question on Stack Exchange. There comes a point when any place I get caught up nobody can help me. So there are several questions I've answered myself. Of course, working in the same space six months later, I'll have a problem, search for it, and land on the question on Stack Exchange that I've answered months earlier. It's happened a few times.


I have a Notion database of code Snippets for this purpose.

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,...


+1 for db of code snippets - things like:

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 keep a copy of some very old code, from 15ish years ago, and I've peeked into it a few times in recent years when facing similar problems to what I've solved there, only to be horrified by what a pile of garbage that was. So there's also a fun element in that - seeing how far I've come. It's a good laugh.

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.


I've always loved seeing recursive functions I wrote in the past. The amount of power and elegance that can come from a good recursive function is my favorite.


hear! hear!


For me it's the opposite, I'm truly proud of those times where the obvious recursive solution is avoided and I manage to solve it with a "while(..){}". I'd be like "LOOK I DIDN'T TOUCH THE STACK ONCE". I'm raised on microcontrollers though.


My number one favorite time is after I sold a company. Two years later, the company contacted me as the old CTO and asked me about some piece of core technology. They asked me to take them through it and show them what was going on since they wanted to migrate it into something else.

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.


Wow. You should be proud indeed. Turned out you maintained enough corner cases right there.


How big was it, and did you write it?


One I like to go back to is the micro-kernel scheduler written in assembly I did for a grad school project: https://github.com/mbcrawfo/avr-kernel/blob/master/kernel/co...

It seems so much more interesting than the web stuff I do today.


I wouldn't call it admiration. Most of my code archeology is like "this code is a mess, what fool wrote that. git blame... oh, it was me"


I generally admire the architecture and and some nice and elegant tricks on my past code, but not the code itself. I always feel like things could be cleaner, with better names, with a more consistent coding style (I am quite severe to my self on this point).

Much older code is generally neither smart neither beautiful though.


well, that's the path to coding enlightenment! hahaha, just keep climbing for a few years more


Yes! Some code reflects what the requirements demand, including error handling, and no more. The design is elegant in that it abstracts properly, is very readable and extensible. Periodically, when I'm feeling down about my abilities, I look over this code and smile.

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.


I read this after making my own post that starts the same. This sums up my thinking too so elegantly. There are so many aspects to code and how it gets written that inform the output that each needs to be viewed in the context of that. Was it time critical? Was it part of a legacy migration? Was it a complex problem?

The quality of the code doesn’t have to reflect the quality of the solution and we should celebrate the things we nail.


I don't feel proud of my code if it works but I do feel terrible about it if it doesn't work perfectly. As soon as I realize that there is any problem in any of my projects, I need to drop everything and fix it immediately or else I can't sleep or think about anything else.

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.


Sounds like a perfect case of perfectionism.


When I was ~15 I wrote this: $c=`clear`;for(`tail -c+324 $0|zcat`){if(/^p/){print@l;@l=()}elsif(/^d(.+)/){select$u,$u,$u,$1/10}elsif(/^s(.)/){$s=9;$e=-30;$m=-1;if('o'eq$1){$s=-30;$e=9;$m=1}for($i=$s;$i!=$e;$i+=$m){$j=0;for(@l){print substr($_,$i+$j++>0?($i+$j)2:0,-1)."\n"}select$u,$u,$u,.1;print$c}}elsif(/^c/){print$c;@l=()}else{push@l,$_}}__END__

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...


That's really neat. I'm guessing this is Lemonade? https://github.com/shish/lemonade

(Also, leave a blank line before your code and indent each line of it by two spaces to make it formatted like code.)


It is indeed :) Looking at the code now, I see so many opportunities for “improvement” like making it run on OSX as well as Linux; but I think that might spoil the magic :P


Sometimes-- but most of the time when I look at code I wrote and was proud of but 6months or a year later-- I'm like, what was I thinking- I would of done it differently now. I call it programmers remorse. Since we're always learning and patterns change over time based on technology I think that most programmers live in a constant state of embarassment over things they previously had done.

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.


Just to continue the analogy about carpentry / home construction. About a decade ago when I moved into my apartment it came with a wall mount for the TV that had a tricky mechanism that would not be clear to a casual user how to mount/unmount from quick looking. And it would be even more difficult to figure out with a TV in the way.

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).


No, I mostly go back and surrender to not understanding why I wrote what I wrote. Yes, I am in awe. But because it's a like a third person wrote it.

Regardless of comments.


Haha. I'm always proud of myself when I look at code that I don't understand, and I see some comment clarifying it and making obvious the reason why it couldn't be simpler and why I did something the way I did it. And then I'm like: "hey, you can trust yourself"

When that doesn't happen, I just spend the time to understand it again and add the comments. It eventually gets better.


I often return to things with reluctance, assuming massive technical debt, only to be pleasantly surprised (sometimes I am pleasantly offended!). I'll usually attempt a "haut-syntactica" refactor, only to fall back into the flow and elegance of the original work ... tho I definitely have a tendency towards over-engineering in the first instance.

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.


Best feeling I ever got was when I was starting out using list comprehensions and ternaries in Python. I sometimes got the (slightly creepy) feeling I wasn't so much writing this thing myself but using a feather duster carefully to clean away the cobwebs sort of like an archaeologist. That feeling of "discovery" is what I use to guide me. If it's not there, I know there's a better implementation. Got me thinking about Socrates and how discovery could really just be recollection. So my take is a little bit opposite what you are calling for. It's not "I wrote that!" with pride but "I was used to bring that about!".


> Are there analogous feelings in other creative pursuits you practice?

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.


There's one particular piece of code I'm especially proud of, coming from a side project. It's a non-trivial amount of code, and it's not the cleanest code, and it has bugs and missing functionality. However, as a library it hits the sweet spot of:

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.


I'm working on a mobile game using an ECS-based engine I wrote myself.

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.


I wouldn't say admire. When I stumble upon code from many years ago I (somewhat painfully) realize I've lost a lot of the ingenuity I used in my early days. I read the code and find myself thinking "how the hell did I come up with that solution". I didn't care about finding the optimal algo/ds, I would just use whatever I knew at that moment without a second thought. Now I have to care a lot more about writing code that looks smart and learning "new" frameworks.


My first ‘real’ program. Written in VB6 in 2005. It connected to a state message switch using dmpp2020 protocol. It function was to run drivers license numbers and return a photo for Police Officers. It had two components- a back end that connected to the state and a web based front end. They were connected through a sql server. The front end wrote a request to a table and the back end monitored that table. The response from the state was then returned into another table. It was used by a couple of agencies including our 911 center. This was necessary as binary objects were a new thing at the time and neither our CAD or RMS system could do anything except plain text. So the subject of this - do you ever go back and admire your code - in this case I go back and wonder how it ever managed to function lol. Seriously. In reality though my admiration was in how rock solid it was. It’s last use :( was in 2017 so it was in service for 12 years and during that time it crashed literally never. I can’t say the same for the our other interfaces to the same message switch. So thanks HN for the opportunity to remember that!


Not entirely mine but beautiful nonetheless:

    @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 + stack


You should really use deque for the stack


It's what I did in other parts of the project but I haven't noticed any performance increase. I guess standard lists are already fast enough for implementing stacks.


Why?


Probably just an efficiency argument, since deque is designed to be efficient when used as a stack/queue. https://docs.python.org/3.8/library/collections.html#collect...


> Are there analogous feelings in other creative pursuits you practice?

The "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 have some stories about old code but this is a nice one: in my old job I've needed to write technical documentation about a GUI we had developed. This consisted in making numbered labels in pictures using Gimp, embedding the pictures in a LibreOffice document (at the time, OpenOffice) and writing what each item was about.

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


I made the script-fu to generate a color hex triplet before it was part of the color dialog box. It was the first time I write scheme as well. I still love scheme even though I never got to use it


I have an old A* pathfinder I wrote in C about 13 years ago that I revisit with surprising frequency. Every now and then I'll have a glass of whisky and pull up the .h and .c files and smile.

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.


Yes! I do! But they’re never the parts I think they’ll be. Sometimes it’s the simplest of things like a nice CRUD api that’s bounded and neat. Sometimes it’s a horribly complex system with well known trade offs and intricate guarantees. I love looking back and thinking “yea I got that right” or seeing an abstraction that’s stood the test of time (my six year old report query definition and data table responses in a reporting system is one concrete example I’m proud of, but I’d rename some fields for sure). I have a few of these that I’m so proud of if I really stop and consider it. On the flip side, the majority of projects teach me something that I wouldn’t do the next time, hence the common “old code sucks” trope. I think it’s important to recognise when something worked as much as when something didn’t. It’s these successes that give me the confidence to try things a little outside the box if I think it’s for the best.


I find that some ideas gestate on the backburner "I wish I had time to implement feature X".

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.


I once had the idea for a tool which would print the next few crontab runs, to make sure they were staggered correctly. Asked on Stack Overflow how to do it (https://unix.stackexchange.com/q/36307/3645), and someone actually went and implemented it in C! Fast forward a few years, and I've reimplemented most of it in Rust with 98% code coverage (https://gitlab.com/victor-engmark/cronlist). It's very likely neither optimal nor idiomatic, but every time I implement something using TDD it's a hundred times more readable than without, even when using an unfamiliar language.


I immediately think of my very simple 17-line constraint satisfaction problem solver which has saved me so much work.


Would you mind sharing it? I am really curious.


I can't share the code.

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.


My one particular stand out accomplishment was back in the Lumatic (RIP) days. We were a small app that provided pedestrian navigation in cities that included public transit. When we expanded beyond a single city we quickly learned we had to deal with timezones. The straightforward thing was to convert the times in each GTFS feed (the file containing scheduled transit times/stops/etc) to UTC. So I started digging into to the horrors of the tzdata format and spent a solid 8 hours looking into options there, hit a wall, tabled the project for a few days after which time an idea popped into my head: change the timezone for the process serving the city to match the timezone of the city. Sure enough, changing the TZ environment variable worked like a charm and unix did the rest.


Yes, absolutely.

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.


Perl code mostly. I rarely use Perl anymore and my current code is much more straightforward and maintainable that the Perl stuff I wrote but wow was some of it elegant and clever. I enjoyed writing lots of it which isn't something I experience much anymore.


Not on purpose but sometimes I need to get back at an old project and it always takes a few minutes to get my mind around it's architecture again. Sometimes, as I re-understand why I did things a certain way, I get aha-moment and am sort-of proud I guess.


Writing parsers with parser combinator libraries (personally, I use FParsec on F# and pyparsing on Python) feels like this all the time. I am especially happy about one doubly-recursive, parametric parser I had to write to handle an expression grammar of this kind:

    <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.


Yes, but only with a fairly small share of the code I've written in the past. Most of the code I've written is nowhere near as good as it could be; some of it is embarrassing.

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.


Maybe a fun side project I did in Python a while back: a small source-to-source transpiler. I find it beautiful for the simple fact that it feels idiomatic and good python code, based on some inspiration I got from other (senior) codebases back then.

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.


One of my very first was Inna domain parking app, that it tried to "fertilize" any domain that was pointed to the server. It would obtain feeds piped via Yahoo feeds for keywords from the domain, and sell the domains later at higher price for the slightly better SEO value.

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 do hope you stopped doing this. Parked domains have frustrated me so often!


Definitely. I wrote a React application that had a large amount of flexibility requirements for a client. They would need to re-purpose this application to deploy on multiple client sites with a variety of contextual content. I built a sort of navigator wrapper that would allow arbitrary content, but meet a pretty extensive list of contextual requirements as well. It was a fun elegant solution and they were expecting new child pages to take days to add, I showed them how a decent developer could add them in minutes.


I have some big programs that serve more as touchstones for me. I am familiar with the layout and I can see the various functions that work very well.

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.


I have on one or two occasions come up with a pretty neat algorithm for some task that seemed really clever. Later I'd learn that I wasn't the first to invent it and that so-and-so had discovered that algorithm years ago. It could make me sad, but usually it makes me think, "Hey! I'm as smart as that programmer!" or at least, "Hey! I have been as smart as that programmer was when they came up with that algorithm! I'm not a complete idiot!"


I'm opposite. Never ever I felt proud of my code, I always am critical of it and thinking in the back of my head "I know how to refactor it even better". It's a never-ending story for me. And whenever happen to do maintenance of a old project of mine from years ago I cringe of the way I implemented some stuff and plenty of times I have to restrain myself to not refactor it since the client wants only a simple change while the refactoring would eat away my free time.


I don't code, but I do write. I regularly re-read my own writing to spot any problems, but sometimes just for pleasure. For example, about 18 months ago I wrote a 5 part series on how to build a direct conversion receiver for the ham radio bands from scratch. I learned tons along the way and it was really rewarding to write. Re-reading it recaptures some of that joy and reminds me that I'm a good writer, even when I think I'm just another hack.


If it captures you back then yes, your writing is so good that it doesn’t get in the way, you don’t even notice it. I am not a natural writer and have to always make an effort to make something sound the way I want to. Quite often I cringe at my old scribblings and that sometimes without a reason..


Oh I have plenty of those moments too!


I want to read that. Can you post it on here or on your profile or something please?


Never mind, I found it at miscdotgeek.


Thanks for checking it out! Here's the link for anyone else:

https://miscdotgeek.com/building-direct-conversion-receiver-...


I'm 50 now, but when I see the code I was writing in my teens and twenties, I'm convinced I am nowhere near as clever anymore. Time to get back to my roots.


Not really. If you remove the algorithm part (which can be drawn very nicely and admired on paper) you have code. And code age, and it ages fast. Python 2 is not Python 3. C++11 is not C++20. I see the changes that need to be done instead of the beauty of the work.

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.


Most of the time. But that applies to code that I wrote in last 15 years, especially in Sciter, its core was written around 2005.

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.


There have been a few times that I've really admired code that I wrote ... it happened way more often building embedded systems where I was short on processor cycles and memory.

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!


That's just how some people are. For what it's worth, I can't look at anything I make and be happy with it; I only see the flaws, omissions, and infelicities. If you can be proud of what you make, then great!

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.


It depends on what you code. For me there must be three things for me to be proud of some codebase:

  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.


I find it differently... I look at the old code and look at the lessons I learned as I wrote items on top of each other... my projects are basically layers on top of each other.


Rereading old code (and sometimes admiring it) is a way to gauge, whether you learned something in the past month. If you did not, change your course.


Rarely !

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.


Yes. I wrote some Rust code about 3 years ago. I've set it aside until the IDE situation improves, and now I look at it to remind me that I wrote that (not too shabby) code because I want to pick up Rust again at some point and if I went by the tone of the articles on HN (Rust is hard, you're constantly fighting the borrow checker, etc) it would be too discouraging.


I've never written a single line of code that I liked. I enjoy programming, but I'm a terrible programmer even after... Jesus, thirteen years. Sometimes I'm not totally unhappy with my solutions, but most people here could do a hell of a lot better. Fortunately, that doesn't keep me from getting paid and delivering acceptable work.


I resonate with the feeling of joy of having translated thoughts into a concrete result :) More often though I find all sorts of loopholes and alternative ways I could've done the same thing. Perhaps, it's because we're viewing an older thought process, and have sufficiently dissociated ourselves with it, so we're able to neutrally critique it.


I revisit my generalized monoidal FizzBuzz implementation on occasion. It's hard not to given it's elegance and beauty. :) https://gist.github.com/lgastako/d4fa392cbe85cbfae7dfa5e18c1...


I remember writing this library https://github.com/tuladhar/adns-ruby few years back. I sometimes go through the code to be in that moment again and be "man I wrote this". I cannot express that feeling, but it feels great.


Yes. But if you can figure out what it does you’re going to be really sad.

{ 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 admire this library of ordinal notations I wrote, which can be considered as a systematic meditation on the nature of strong AI and more specifically on computer programs that write computer programs:

https://github.com/semitrivial/ions


Sometimes I leave random/joking comments around my code if I've been in a rabbit hole for a long time and end up with a preposterously simple and elegant solution. I erupted with laughter a couple days ago seeing "# i fink yo freaky and i like u a lot" in the middle of some brambles I was untying.


All the time.

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.


Sometimes my old code is “why did I over engineer this, it’s so hard to trace through”

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.


I have this problem with a codebase I work on now. Basically, the program flow is: 1. Download file 2. Load file to local DB 3. Load local DB to cloud 4. Load cloud to different local DB 5. Generate file for other system.

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).


> 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.


Maybe in the first 6 months or so after writing it.

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.


No. I really don't have that courage.


I do reminisce,but do the opposite of admire, perhaps because my day job has never been primarily to write code.


I do sometimes go back and stare at this wonder I crafted once:

  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. :)


Alright, I'll bite - what does it do?



It takes the name of a state in the United States and returns its two letter abbreviation.

EDIT: I swear I didn't look at the CodeGolf link. :(


I admire my old code when I go back to that code and by reading the code, see some idiosyncratic behaviour. Then a pay slightly more attention and see my own comment in the code saying that the author knows about it and that was the assumption made in the first place.

Otherwise code can always be made better.


I wrote a GPS coordinate mapping tool for a fun project once. I wrote it on a train, and I didn't have the device that was going to use it. I sent them the link and they said it worked perfectly. I doubt the code was very good, but we just used the first version for the project.


I've only been coding for a few years now.

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...


Going back and being annoyed with your old code means you've improved.


Well then I've improved A GREAT DEAL ARGH!


I had this feeling from time to time, usually right after finishing a project. While every relevant contextual details are still fresh in my mind.

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.


It is the best way to stay motivated as a programmer. The power to model a real world scenario into code and seeing it work has been my motivation to keep coding. Make sure you also look at that stupid code once in a while and ponder "What was i thinking?"


I publish as much of my stuff as I can as MIT License, just so if I need to re-solve a problem I've seen before in three years and I'm at a different job, I can say, "Didn't I solve this three years ago?" and go back and repurpose the old code.


I used to do a fair amount of artsy stuff, and always stepped back to admire my work at multiple points in the process, as I suspect isn't uncommon among artists

Now at times when I have the space and time to code things the way I wanted, I step back and do the same :)


I've got a big text file of 6502 machine code I wrote a few years back that I pull out and marvel at from time to time. One of those things that you have to be fully in the "zone" to pull off, so it seems like magic to present-day me.


If you don't occasionally go back to appreciate what you've built, you're probably not taking enough pride in your work.

If you don't occasionally go back and become horribly embarrassed at what you've done you're probably calcifying.


It will pass :) And you're looking at the code right after you wrote it.

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.


Once or twice. I still remember a Perl routine I wrote probably 10 years ago. It's maybe 10-12 lines long, but what I remember is that I wrote the entire routine in one continuous train of thought, ran it and it worked on the first try.


What are you problem solving approach when implementing a particular feature,functionality and it is the first time you are doing or you have been stuck for days and not able to figure it our, how do you guys go about it?


I can get this feeling with non-novel code when I slot something into a larger framework (following the paradigm). I find that easier to walk away from than writing novel code, as it takes longer to feel satisfied with the latter.


There is one instance which I wrote almost a year back. It's does nothing special, hasn't increased the company's revenue but it does one thing and does it best.

Right now the whole file is changed but that code is still intact.


Less so with the code per se and more with some elegant or minimalist abstraction it implements.

So the best bits are probably the multipage comments that precede a handful of lines of code and explain what's going on :)


I'm still proud of my LTE RRC layer protocol implementation for mobile phone testing: design, implementation, its ability to work with diverse physical layer emulators... Wrote it probably 10 years ago.


Funny thing, I update one of my first iOS apps from time to time and I still see the quality and more important consistency of the code I wrote. It's a breeze to maintain.


Yes, i still like how we were able to run 72 voicemail lines on one machine under a ms-Dos environment with 5Mb coax network. Written under Pascal, still got the code.


I did it few times, most of them were cases when I took extra time to enable extending the code instead of writing ad-hock code that fit only the problem at hand.


Yes, I do this sometimes. I feel proud of most of the things that I wrote but not about stuff that was written by multiple people and where I just added some things.


When I like to reminisce, I go back and look at my recursive code.

So much of my code is boring, flat, procedural code, because that's what the job calls for.


You should always take pride in your own work regardless of what profession you're in. There's nothing wrong with that at all.


Only if I go back to a language that I haven't used for a few years where I don't remember how the solutions are implemented.


All the time. I put pride in my code. I worked in various teams and codebases and came to appreciate the quality of my code.


I'm a fan of my recursion scheme examples :p

For the most part my standards get higher as time goes on though. So only small things!


Ive been toying with Racket and found myself admirig scheeme and recursion in general. It is so simple and yet so elegant.


I not only go back and read old code, I still use some code I wrote thirty years ago on a day-to-day basis.


Yes. Sometimes I can't believe how smart I was back then and wondered what happened to me.


  amountFulfilled = isFulfilledOnSite * quantity
yes, isFulfilledOnSite is a boolean


No - I'm hard on myself and so look back and always say "this is sh!t"


actually I do this from time to time. because I tend to forget about the beauty of it. this is one of the nicest thing about being a developer, to be able to step back and enjoy the work. I take this as a motivation for clean code.


Kinda, except the opposite.


Every bloody monday I admire the naivety of the code I wrote friday.


Yes. But not as often as I cringe at something I wrote.

C'est la vie.

Live. Learn. Adapt. Move on.


Yes, I also get surprised on how I implemented the solution.


I'm usually like "Who wrote this shit?"


I wrote an very concise recursive solution to one of our interview problems. Not really 'good' code because its hard to read and reason about, but I enjoy looking at it every 6-12 months.


No, usually I never


yes I check back my previous leetcode submissions before interview and sometimes amazed how the hell did i come up with that.


rarely. mostly i look back in horror.


we call this code review


A code review consists of reading a piece of code written recently by someone else, which is not what is asked by OP.




Consider applying for YC's Spring batch! Applications are open till Feb 11.

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

Search: