
Ask HN: Do you ever go back and admire a piece of code you wrote? - grimwall
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.<p>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!<p>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?<p>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&#x27;t feel like an exceptional programmer, feel more like an impostor, so please don&#x27;t read this as bragging.
======
redsymbol
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!

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

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

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

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

~~~
pvorb
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?

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

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

~~~
benwills
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?

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

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

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

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

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

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

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

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

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

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

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

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

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

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

~~~
frosted-flakes
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.

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

    
    
      long time; // no see

~~~
yread
I came across this gem recently:

    
    
        catch (Exception up)
        {
            throw up;
        }
    

Truly genius code

~~~
ak39

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

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

~~~
the_pwner224
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?

~~~
mywittyname
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-...](https://stackoverflow.com/questions/4345045/javascript-loop-between-
date-ranges)

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

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

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

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

~~~
twodave
Ha! Too true on both counts.

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

------
tkainrad
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...](https://tkainrad.dev/posts/managing-my-personal-
knowledge-base/#notion-snippet-database)

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

~~~
cat199
+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

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

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

~~~
sesuximo
hear! hear!

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

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

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

~~~
scared2
How big was it, and did you write it?

------
Merad
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...](https://github.com/mbcrawfo/avr-
kernel/blob/master/kernel/core/kernel_asm.s)

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

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

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

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

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

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

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

~~~
type0
Sounds like a perfect case of perfectionism.

------
Shish2k
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](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...

~~~
wizzwizz4
That's really neat. I'm guessing this is Lemonade?
[https://github.com/shish/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.)

~~~
Shish2k
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

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

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

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

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

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

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

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

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

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

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

------
roamerz
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!

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

~~~
heavenlyblue
You should really use deque for the stack

~~~
nivethan
Why?

~~~
comfydragon
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...](https://docs.python.org/3.8/library/collections.html#collections.deque)

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

------
silasdb
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...](https://github.com/silasdb/mark-number-
circles/blob/master/mark-number-circles.scm)

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

~~~
slim
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

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

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

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

------
l0b0
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](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](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.

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

~~~
e_carra
Would you mind sharing it? I am really curious.

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

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

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

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

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

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

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

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

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

~~~
mercer
I do hope you stopped doing this. Parked domains have frustrated me so often!

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

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

------
thewebcount
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!"

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

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

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

~~~
geocrasher
Oh I have plenty of those moments too!

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

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

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

------
smoyer
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!

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

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

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

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

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

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

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

------
lgas
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...](https://gist.github.com/lgastako/d4fa392cbe85cbfae7dfa5e18c14a2a4)

------
blackesthole
I remember writing this library [https://github.com/tuladhar/adns-
ruby](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.

------
floatingatoll
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__))); }

------
xamuel
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](https://github.com/semitrivial/ions)

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

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

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

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

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

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

------
rgrs
No. I really don't have that courage.

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

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

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

~~~
saagarjha
[https://codegolf.stackexchange.com/a/122957](https://codegolf.stackexchange.com/a/122957),
perhaps?

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

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

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

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

~~~
duxup
Well then I've improved A GREAT DEAL ARGH!

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

------
kunalpowar1203
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?"

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

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

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

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

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

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

------
raobit
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?

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

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

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

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

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

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

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

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

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

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

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

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

------
vmchale
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!

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

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

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

------
hknapp

      amountFulfilled = isFulfilledOnSite * quantity
    

yes, isFulfilledOnSite is a boolean

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

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

------
jeffkeen
Kinda, except the opposite.

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

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

C'est la vie.

Live. Learn. Adapt. Move on.

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

------
5cott0
I'm usually like "Who wrote this shit?"

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

------
lihaciudaniel
No, usually I never

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

------
techslave
rarely. mostly i look back in horror.

------
chukye
we call this code review

~~~
delaaxe
A code review consists of reading a piece of code written _recently_ by
_someone else_ , which is not what is asked by OP.

