-
8 votes
-
Reflections on past lessons regarding code quality.
Preface Over the last couple of years, I've had the opportunity to learn from the mistakes of my predecessors and put those lessons into practice. Among those lessons, three have stood out to me...
Preface
Over the last couple of years, I've had the opportunity to learn from the mistakes of my predecessors and put those lessons into practice. Among those lessons, three have stood out to me in particular:
- Consistency is king.
- Try not to be too clever for your own good.
- Good code takes time.
I know that there are a lot of new and aspiring programmers here (and I'm admittedly far from being a guru myself), so I thought it would be good to touch on these three lessons, what they mean, and why they're so important.
Consistency is King
This is something that I had drilled into my head over nearly two years working on the code base at my previous job. Not by my fellow programmers (who did not exist), nor by my boss, but by the code itself.
Consistency can mean a number of things, but there are two primary points that matter:
- Syntactic consistency.
- Architectural consistency.
Syntactic consistency concerns standards in what your code looks like. For example, the choice between
snake_caseorcamelCaseorPascalCasefor naming; function parameter order; or even something as benign as what kind of indentation and how much of it you use.Architectural consistency concerns standards in how you structure your code. Making sure that you either use public class properties or getter and setter methods; using multiple booleans or using bitmasks; using or not using objects for encapsulating data to be passed around; validating data within the primary object or relegating that responsibility to a validator class; and other seemingly minor decisions about how you handle certain behavior make a big difference.
The code base I maintained had no such consistency. You could never remember whether the method you needed to call was named using
snake_caseorcamelCaseand had to perform several searches just to find it. Worse still, some methods defined to handle Ajax calls were prefixed withajaxwhile many weren't. Argument ordering seemed to be determined by a coin flip, and indentation seemed to vary between 2-space, 3-space, 4-space, and even 5-space indentation depending on what mood my predecessor was in at the time. You often could not tell where a function's body began and where it ended. Writing code was an exercise both in problem solving and in deciphering ancient religious texts.Architecturally it was no better. There was no standardization in how data was validated or sanitized, how class members were accessed or modified, how functionality was inherited, whether the functionality was encapsulated in an object method or in a function, or which objects were responsible for which behavior.
That lack of consistency makes introducing or modifying a small feature, a task which should ordinarily be a breeze, an engineering feat of its own. Often you end up implementing that feature, after dancing around the tangled mess of spaghetti, only to find that the functionality that you implemented already existed somewhere else in the code base but was hiding out in a deep, dark corner that you never even knew was there until you had to fix some other broken feature months later and happened to stumble across it.
Consistency means predictability, and predictability means discoverability and, more importantly, easier changes and higher confidence in those changes.
Cleverness is a Fallacy
In any given project, it can be tempting to do something that saves you extra lines of code, or saves on CPU cycles, or just looks awesome and does something nobody would have thought of before. As human beings and especially as craftsmen, we like to leave our mark and take pride in breaking the status quo by taking a novel and interesting approach to a problem. It can make us feel fulfilled in our work, that we've done something unique, a trademark of sorts.
The problem with that is that it directly conflicts with the aforementioned consistency and predictability. What ends up being an engineering wonder to you ends up being an engineering nightmare to someone else. While you're enjoying the houses you build with wall studs arranged in the shape of a spider's web, the home remodelers who come along later aren't even sure if they can change part of the structure without causing the entire wall to collapse, and they're not even sure which walls are load-bearing and which aren't, so they're basically playing Jenga while blindfolded.
The code base I maintained had a few such gems, with what looked like load-bearing walls but were actually made of papier-mâché and were only decorative in nature, and the occasional spider's web wall studs. One spider's web comes to mind in particular. It's been a while since I've worked on that piece of code, so I can't recall what exactly it did, but two query-constructing pieces of logic had overlapping query structure with the difference being the operators and data. Rather than being smart and allowing those two constructs to be different, however, my predecessor decided to be clever and the query construction was abstracted into a separate method so that the same general query structure could be used in other places (note: it never was, and was only ever used in those two instances). It was abstracted so that all original context was lost and no comments existed to explain any of it. On top of that, the method was being called from the most critical piece of the system which, unfortunately, was already a convoluted mess and desperately required a rewrite and thus required me to understand what the hell that method was even doing (incidentally, I fell in love with whiteboards as a result).
When you feel like you're being clever, you should always stop what you're doing and make sure that what you're doing isn't actually a really terrible idea. Cleverness doesn't exist. Knowledge and intelligence do. Write intelligent code, not clever code.
Good Code Takes Time
Bad code more often than not is the result of impatience. We don't like to plan out the solution before we get to writing code. We like to use variables like
xandtempin order to quickly achieve functional correctness of our code because stopping to think about how to name them is just additional overhead getting in the way. We don't like to scrap our bad work if we can salvage it in some way instead, because then we have to start from scratch and that's daunting. We continually work against ourselves and gradually increase our mental overhead because we try to decrease our mental overhead. As a result we find ourselves too exhausted by the end of our initial implementations to concern ourselves with fixing obvious problems. Obviously bad but functional code is preferable because we just want the task to be done and over with.The more you get exposed to bad code and the more you try to avoid pushing that hell onto yourself and your successors, the more you realize that you need to spend less time coding and more time researching and planning. Whereas you may have been spending upwards of 50% of your time coding previously, suddenly you find yourself spending as little as 10% of your time writing any code at all.
Professionals from just about any field can tell you that you can either do something right or you can do it twice. You might recognize this most easily in the age-old piece of woodworking wisdom, "measure twice, cut once". The same is true of code, and doing something right means planning how to do it right in the first place before you've even started on the job.
Putting into Practice
I've been fortunate over the last couple of months to be able to start on a brand new project and architect it in a way that I see fit. Changes which would ordinarily take days or weeks in the old code base now take me half a day at most, and a matter of minutes at best. I remember where to find a piece of code that I need because I'm consistent and predictable about where I place things; I don't struggle to tell where something begins and where it ends because I'm consistent about structure; I don't continually hate myself when I need to make changes to my code because I don't do anything wildly out of the ordinary; and most importantly, I take my time to figure out what it is that I need to do and how I want to do it before I've written a single line of code.
When I needed to add a web portal interface for uploading a media asset to associate with a database object, the initial implementation took me a week, due to the need for planning, adding the interface, and supporting and debugging the asset management. When I needed to extended that interface to allow for uploading the same kinds of assets for a completely different object type, it took me only half an hour, with most of that time being dedicated toward updating a Vue.js component to accept configuration via props rather than working for only the single hard-coded object type. If I need to add a case for any additional object type, it will take me only five minutes.
That initial week of work for the web interface provided me with cost savings that would not have been feasible otherwise, and that initial week of work would have taken as many as three weeks had I not structured the API to be as consistent as it is now. Every initial lag in implementation is offset heavily by the long-term cost savings of writing good code.
Technical Debt
Technical debt is the cost of your code over time. The messier and worse your code gets, the more it costs you to try to change, and those costs only build up. Even good code can accumulate technical debt if the needs for your software have changed and its current architecture isn't compatible with those changes.
No project is without technical debt. Even my own code, that I've been painstakingly working on for the last couple of months, has technical debt. Odds are a programmer far more experienced than I am will come along and want to scrap everything I've done, and will do a far better job rewriting it.
That's okay, though. In fact, a certain amount of technical debt is good. If we try to never write any bad code whatsoever, then we could never possibly get to writing any code at all, because there are far too many unknowns for a new project.
What's important is knowing when to pay down on that technical debt, which could mean anything from paying it up front (i.e. through planning ahead of time) to paying it down when it starts to get too expensive (e.g. refactoring a complicated section of code when changes become sufficiently difficult). That's not something you can learn through a StackOverflow post or a college lecture, and certainly not from some unknown stranger on some relatively unknown website in a long, informal blog-like post.
Final Thoughts
I'm far from being a great programmer. There's a lot that I don't know and I still have quite a bit to learn. I love programming, though, and more than that I enjoy sharing the lessons I've learned with others. Especially the ones that I wish I'd learned back in college.
Please feel free to share your own experiences, learned lessons, and (if you have it) feedback here. I'd love to read up on some other thoughts on this subject!
21 votes -
On The Sidelines Of Democracy: Exploring Why So Many Americans Don't Vote
10 votes -
What is beautiful to you?
What do you find to be beautiful? Is there anything so beautiful it can bring you to tears? Anything so beautiful that just thinking about it brings you to tears? Please share that beauty with the...
What do you find to be beautiful? Is there anything so beautiful it can bring you to tears? Anything so beautiful that just thinking about it brings you to tears?
Please share that beauty with the rest of us!
26 votes -
Collapsed comments?
I'm starting to see occasional collapsed comments when I open threads. The first time I saw one, I thought I'd accidentally collapsed the comment myself, but this one was definitely already...
I'm starting to see occasional collapsed comments when I open threads. The first time I saw one, I thought I'd accidentally collapsed the comment myself, but this one was definitely already collapsed when I opened the thread.
Is this related to the "tagging" system that Deimos discussed the other day? At the time, he said that "tags" wouldn't have any effect. Are these effects now working? What are the effects? Also, there was no actual decision about what the different tags would be, and what they would mean. As I said in that thread, I decided not to use these tags until: a) they were agreed and defined; b) they actually did something. I thought they were just placeholders for now. I'm confused.
Or is there some other feature operating here? For example, people keep talking about "whisper" comments, and I'm not sure if they're just fantasising about a feature they would like, or if it's something that's actually planned. Are these those "whisper" comments?
25 votes -
The Julia Language Challenge
4 votes -
What have you been listening to this week?
What have you been listening to this week? You don't need to do a 6000 word review if you don't want to, but please write something! Feel free to give recs or discuss anything about each others'...
What have you been listening to this week? You don't need to do a 6000 word review if you don't want to, but please write something!
Feel free to give recs or discuss anything about each others' listening habits.
You can make a chart if you use last.fm:
http://www.tapmusic.net/lastfm/
Remember that linking directly to your image will update with your future listening, make sure to reupload to somewhere like imgur if you'd like it to remain what you have at the time of posting.
15 votes -
My Review of 5/3/1's Pervertor Template
3 votes -
Inbox is signing off. Find your favorite features in the new Gmail
36 votes -
Earliest known drawing found on rock in South African cave. Researchers believe the pattern on the fragment of rock is 73,000 years old, but are perplexed as to what it might represent
6 votes -
Why I let my daughter wear makeup to school
13 votes -
Banda Black Rio - Mr Funky Samba (1977)
4 votes -
Reddit continues its banning spree, r/GreatAwakening has been banned
This was the QAnon subreddit. I filtered it a while ago so not really sure what they’ve been up to of late, but I expect just more of the same. That subreddit genuinely terrified me honestly.
47 votes -
Munly & The Lee Lewis Harlots - Amen Corner (2004)
3 votes -
Apple event megathread: Impressions, reactions, etc
I figured a big thread might be better than smaller individual threads, so maybe we can centralise the discussion here. What are your impressions of what they've presented today?
27 votes -
Mozilla co-founder's Brave files adtech complaint against Google
15 votes -
100 years before drones, in search of better aerial photography, Dr Julius Neubronner patented a miniature pigeon camera activated by a timing mechanism and created a remarkable body of images.
11 votes -
Hurricane Florence isn't alone: Four powerful storms seen from space in one day
9 votes -
Ink cartridges are a scam
18 votes -
Feedbin goes private by default, explains design desicions to enhance user privacy
10 votes -
Exterminate Mosquitoes for the Sake of Humanity
12 votes -
Early alterations of social brain networks in young children with autism
5 votes -
GSM Phone on a Conference Badge - Computerphile
4 votes -
Natasha Aponte, woman who tricked thousands of men on Tinder, explains purpose behind dating competition
12 votes -
Jacob deGrom breaks century-old record in Mets loss (twenty-sixconsecutive starts allowing three runs or less)
8 votes -
Writing a simple SQL interpreter in Julia
7 votes -
Nearly 600 Russia-linked accounts tweeted about the health law
9 votes -
Americans want to believe jobs are the solution to poverty. They’re not.
12 votes -
England take Test series against India 4-1
5 votes -
Skripal poisoning: Vladimir Putin says suspects 'civilians, not criminals'
6 votes -
Controversial Copyright Directive approved by EU Parliament
27 votes -
Microsoft intercepting Firefox and Chrome installation on Windows 10
66 votes -
The secret drug pricing system middlemen use to rake in millions
5 votes -
I'm new to Tildes. What must I know ?
I come from reddit and I'd like to know what is basically different in the way I should post and comment. Are there any private jokes or slang I should know to understand everything ? (like...
I come from reddit and I'd like to know what is basically different in the way I should post and comment.
- Are there any private jokes or slang I should know to understand everything ? (like reddit's "/s", "FBI open up" or the verb "lurk")
- Are "mods" uncompromising ?
- Every single post I saw is intelligent. Is this required ?
- There's no downvote. Do I need to make a thoughtful comment every time I disagree ?
25 votes -
~esports
Hi, I wanted to suggest the creation of an esports specific group. The taxonomy would work in a similar way to ~games, however it would home both the business and news side of our industry as well...
Hi, I wanted to suggest the creation of an esports specific group.
The taxonomy would work in a similar way to ~games, however it would home both the business and news side of our industry as well as allowing for the competitive communities of various games to have sub groups. ~esports.leagueoflegends, ~esports.dota2, ~esports.overwatch for example.
Would like to hear other people's thoughts.
4 votes -
Any boardgamers here? What games are you in love right now?
Tonight we are having our weekly game night. Recently i've been in love with Mottainai. Specially playing with my SO. Lisboa and Agricola are still my favorites. What are your favorite games right...
Tonight we are having our weekly game night.
Recently i've been in love with Mottainai. Specially playing with my SO.Lisboa and Agricola are still my favorites.
What are your favorite games right now?
19 votes -
Star Trek: Galaxy | re:View
6 votes -
Dodger - Naiad (2018)
3 votes -
Pharma chief defends 400% drug price rise as a ‘moral requirement’
8 votes -
The best performing cryptocurrency started off as a joke by an Australian
8 votes -
Do any of you have blogs?
If you do, link them in this thread! A bit of writing's always fun, (and selfishly, I've got a new RSS reader to break-in,) and Tildes is built around the transfer of ideas, so why not share?
28 votes -
It's not too late to act on climate change
5 votes -
Facebook punishes liberal news site after fact check by right-wing site
10 votes -
Oktoberfest in the West Bank: Brewers turn beer making into resistance against occupation
5 votes -
merely players
this world is so full of energy constantly amazed by the shit i see in front of me all my wishes all my demons parade in circles surrounding me it's just the vibe that i keep it's just the air...
this world is so full of energy
constantly amazed by
the shit i see in front of me
all my wishes all my demons
parade in circles surrounding me
it's just the vibe that i keep
it's just the air that i breathe
i guess it's masochistic tendencies
i don't want your positivity
if you have to force it into me
i let it hit me gracefully
got nothing against smiling.it's great, don't need to say it.
good day, when the chardonnay hits
good friends, gonna make your sides split
good laughs, gonna bust a lung with
but don't, need to make it seem like
i don't, have times when i cry
i don't, wanna force out a vibe
of hope, when it just don't feel right
Sono, l'atarassia
Voi sie-te i Pagliacci
Why act, like the world is ending
on days, when you find you're frowningthis world is so full of sappy shit
Everyone subsists off
forced happiness, false positives
bloody nails digging for
every causative, we're at odds to live
with the negative - shit's definitive
that's why 1 in 5 on anxiety medicine
sadness the civil sin,
at all costs repent against
grin through chagrin it's sheepskin
insomniac meds for sleeping
forget that though, my heart's leaping
I swear to god
every morning, open eyes
birds chirping, and i'm in awe
don't give a nod at my
curtain facade and try defraud
ridi, ridi, Pagliaccio,
e ognun,.
applaudirà
bishop
5 votes -
Conor Oberst - Desert Island Questionnaire
5 votes -
Werner's Nomenclature of Colours
4 votes -
Starting to experiment a little with using data scraped from the destination of link topics
This is very minor so far, but I think it's good to have a topic devoted to it so that people have somewhere to discuss it, instead of having it come up randomly in topics that it applies to. I've...
This is very minor so far, but I think it's good to have a topic devoted to it so that people have somewhere to discuss it, instead of having it come up randomly in topics that it applies to.
I've recently started scraping some data about the destination of link topics using Embedly's "Extract" API (Embedly was kind enough to give me a reasonable amount of free usage since Tildes is a non-profit). You can put in the url of an article/video/etc. on that page to get an idea of what sort of data I can get from it, if you'd like to see for yourself.
I've only just started tinkering with it, and so far the data is only being used in two small ways:
-
Tweets now display the entire text of the tweet on the topic listing page, similar to the "excerpt" from text topics. You can see an example here.
-
On topic listings, the date that an article was published will be shown (after the domain name) if the publication date was at least 3 days before it was submitted. There are a few examples in the recent posts in ~misc
I'll probably adjust this threshold, but I'd like it to be an amount of time where the age of the content might feel "significant". It would also be possible to just show this info all the time, but I think the topic listings are already fairly cluttered so it's probably best to hide it when it's not interesting/significant.
As I said, these are very tiny changes so far, but there are lots of other possibilities that I hope to start using before long. I've mentioned this before, but something I'd really like to do overall is try to bring in more data about the links where it's possible to be able to show things like the lengths of videos and so on.
Let me know if you have any thoughts about it or notice any issues, thanks.
57 votes -
-
Hog farmers scramble to drain waste pools ahead of Hurricane Florence
5 votes -
Polymega launch trailer
8 votes