Becoming a Better Programmer: A Handbook for People Who Care About Code

Views: 2265
Ratings: (0)

If you’re passionate about programming and want to get better at it, you’ve come to the right source. Code Craft author Pete Goodliffe presents a collection of useful techniques and approaches to the art and craft of programming that will help boost your career and your well-being.

Goodliffe presents sound advice that he’s learned in 15 years of professional programming. The book’s standalone chapters span the range of a software developer’s life—dealing with code, learning the trade, and improving performance—with no language or industry bias. Whether you’re a seasoned developer, a neophyte professional, or a hobbyist, you’ll find valuable tips in five independent categories:

  • Code-level techniques for crafting lines of code, testing, debugging, and coping with complexity
  • Practices, approaches, and attitudes: keep it simple, collaborate well, reuse, and create malleable code
  • Tactics for learning effectively, behaving ethically, finding challenges, and avoiding stagnation
  • Practical ways to complete things: use the right tools, know what “done” looks like, and seek help from colleagues
  • Habits for working well with others, and pursuing development as a social activity

List price: $33.99

Your Price: $27.19

You Save: 20%

 

38 Slices

Format Buy Remix

1. Care About the Code

ePub

From caring comes courage.

— Lao Tzu

It doesn’t take Sherlock Holmes to work out that good programmers write good code. Bad programmers… don’t. They produce elephantine monstrosities that the rest of us have to clean up. You want to write the good stuff, right? You want to be a good programmer.

Good code doesn’t pop out of thin air. It isn’t something that happens by luck when the planets align. To get good code you have to work at it. Hard. And you’ll only get good code if you actually care about good code.

To write good code, you have to care about it. To become a better programmer you must invest time and effort.

Good programming is not born from mere technical competence. I’ve seen highly intellectual programmers who can produce intense and impressive algorithms, who know their language standard by heart, but who write the most awful code. It’s painful to read, painful to use, and painful to modify. I’ve seen more humble programmers who stick to very simple code, but who write elegant and expressive programs that are a joy to work with.

 

2. Keeping Up Appearances

ePub

Appearances are deceptive.

— Aesop

No one likes working with messy code. No one wants to wallow in a mire of jagged, inconsistent formatting, or battle with gibberish names. It’s not fun. It’s not productive. It’s the programmer’s purgatory.

We care about good code. And so we naturally care about code aesthetics; it is the most immediate determinant of how easy a section of code will be to work with. Practically every book about programming has a chapter on presentation. Oh look, this one does, too. Go figure.

Sadly, programmers care so much about code presentation that they end up bickering about it. This is the stuff that holy wars are made of. That, and which editor is best.[1] Tabs versus spaces. Brace positioning. Columns per line. Capitalisation. I’ve got my preferences. You have yours.

Godwin’s law states that as any discussion on the Internet grows longer, the probability of a comparison to the Nazis or Hitler approaches one. Goodliffe’s law (unveiled here) states that as any discussion about code layout grows, the probability of it descending into a fruitless argument approaches one.

 

3. Write Less Code!

ePub

A well-used minimum suffices for everything.

— Jules Verne Around the World in Eighty Days

It’s sad, but it’s true: in our modern world there’s just too much code.

I can cope with the fact that my car engine is controlled by a computer. There’s obviously software cooking the food in my microwave. And it wouldn’t surprise me if my genetically modified cucumbers had an embedded microcontroller in them. That’s all fine; it’s not what I’m obsessing about. I’m worried about all of the unnecessary code out there.

There’s simply too much unnecessary code kicking around. Like weeds, these evil lines of code clog up our precious bytes of storage, obfuscate our revision control histories, stubbornly get in the way of our development, and use up precious code space, choking the good code around them.

Why is there so much unnecessary code?

Some people like the sound of their own voice. You’ve met them; you just can’t shut them up. They’re the kind of people you don’t want to get stuck with at parties. Yada yada yada. Other people like their own code too much. They like it so much they write reams of it: { yada->yada.yada(); }.

 

4. Improve Code by Removing It

ePub

We ascribe beauty to that which is simple; which has no superfluous parts; which exactly answers its end...

— Ralph Waldo Emerson

Less is more. It’s a trite maxim, but sometimes it really is true.

Some of the most exciting improvements I remember making to code involved removing vast chunks of it. Let me tell you, it’s a good feeling.

As an Agile software development team, we’d been following the hallowed eXtreme Programming tenets, including YAGNI. That is, You Aren’t Gonna Need It: a caution to not write unnecessary code—even code you think is going to be needed in future versions. Don’t write it now if you don’t need it now. Wait until you do have a genuine need.

This sounds like eminently sensible advice. And we’d all bought in to it.

But human nature being what it is, we fell short in a few places. At one point, I observed that the product was taking too long to execute certain tasks—simple tasks that should have been near instantaneous. This was because they had been over-implemented, festooned with extra bells and whistles that were not required, and littered with hooks for later extension. None of these things were being used, but at the time they each had seemed sensible additions.

 

5. The Ghost of a Codebase Past

ePub

I will live in the Past, the Present, and the Future. The Spirits of all Three shall strive within me. I will not shut out the lessons that they teach!

— Charles Dickens A Christmas Carol

Nostalgia isn’t what it used to be. And neither is your old code. Who knows what functional gremlins and typographical demons lurk in your ancient handiwork? You thought it was perfect when you wrote it—but cast a critical eye over your old code and you’ll inevitably bring to light all manner of code gotchas.

Programmers, as a breed, strive to move onwards. We love to learn new and exciting techniques, to face fresh challenges, and to solve more interesting problems. It’s natural. Considering the rapid turnover in the job market, and the average duration of programming contracts, it’s hardly surprising that very few software developers stick with the same codebase for a prolonged period of time.

But what does this do to the code we produce? What kind of attitude does it foster in our work? I maintain that exceptional programmers are determined more by their attitude to the code they write and the way they write it, than by the actual code itself.

 

6. Navigating a Route

ePub

...the Investigation of difficult Things by the Method of Analysis, ought ever to precede the Method of Composition.

— Sir Isaac Newton

A new recruit joined my development team. Our project, whilst not vast, was relatively large and contained a number of different areas. There was a lot to learn before he could become effective. How could he plot a route into the code? From a standing start, how could he rapidly become productive?

It’s a common situation; one which we all face from time to time. If you don’t, then you need to see more code and move on to new projects more often. (It’s important not to get stale from working on one codebase with one team forever.)

Coming into any large existing codebase is hard. You have to rapidly:

You need to learn this quickly, as you don’t want your first changes to be too embarrassing, accidentally duplicate existing work, or break something elsewhere.

My new colleague had a wonderful head start in this learning process. He joined an office with people who already knew the code, who could answer innumerable small questions about it, and point out where existing functionality could be found.  This kind of help is simply invaluable. 

 

7. Wallowing in Filth

ePub

As a dog returns to its vomit, so fools repeat their folly.

— Psalms 26:11

We’ve all encountered it: quicksand code. You wade into it unawares, and pretty soon you get that sinking feeling. The code is dense, not malleable, and resists any effort made to move it. The more effort you put in, the deeper you get sucked in. It’s the man-trap of the digital age.

How does the effective programmer approach code that is, to be polite, not so great? What are our strategies for coping with crap?

Don’t panic, don your sand-proof trousers, and we’ll wade in…

Some code is great, like fine art, or well-crafted poetry. It has discernible structure, recognisable cadences, well-paced meter, and a coherence and beauty that make it enjoyable to read and a pleasure to work with.

But, sadly, that is not always the case.

Some code is messy and unstructured: a slalom of gotos that hide any semblance of algorithm. Some is hard to read: with poor layout and shabby naming. Some code is cursed with an unnecessarily rigid structure: nasty coupling and poor cohesion. Some code has poor factoring: entwining UI code with low-level logic. Some code is riddled with duplication: making the project larger and more complex than it need be, whilst harbouring the exact same bug many times over. Some code commits “OO abuse”: inheriting, for all the wrong reasons, tightly associating parts of code that have no real need to be bound. Some code sits like a pernicious cuckoo in the nest: C# written in the style of JavaScript.

 

8. Don’t Ignore That Error!

ePub

All you need is ignorance and confidence and the success is sure.

— Mark Twain

Settle yourself down for an apocryphal bedtime story. A programmer’s parable, if you will….

I was walking down the street one evening to meet some friends in a bar. We hadn’t shared a beer in some time and I was looking forward to seeing them again. In my haste, I wasn’t looking where I was going. I tripped over the edge of a curb and ended up flat on my face. Well, it serves me right for not paying attention, I guess.

It hurt my leg, but I was in a hurry to meet my friends. So I pulled myself up and carried on. As I walked further the pain was getting worse. Although I’d initially dismissed it as shock, I rapidly realised there was something wrong.

But, I hurried on to the bar regardless. I was in agony by the time I arrived. I didn’t have a great night out, because I was terribly distracted. In the morning I went to the doctor and found out I’d fractured my shinbone. Had I stopped when I felt the pain, I’d’ve prevented a lot of extra damage that I caused by walking on it. Probably the worst morning-after of my life…

 

9. Expect the Unexpected

ePub

Be Prepared…the meaning of the motto is that a scout must prepare himself by previous thinking out and practicing how to act on any accident or emergency so that he is never taken by surprise.

— Robert Baden-Powell

They say that some people see the glass half full, some see it half empty. But most programmers don’t see the glass at all; they write code that simply does not consider unusual situations. They are neither optimists nor pessimists. They are not even realists. They’re ignore-ists.

When writing your code, don’t consider only the thread of execution that you expect to happen. At every step, consider all of the unusual things that might occur, no matter how unlikely you think they’ll be.

Any function you call may not work as you expect.

Always consider errors that you can recover from, and write appropriate recovery code. Consider also the errors that you cannot recover from. Write your code to do the best thing possible—don’t just ignore it.

 

10. Bug Hunting

ePub

If debugging is the process of removing software bugs, then programming must be the process of putting them in.

— Edsger Dijkstra

It’s open season; a season that lasts all year round. There are no permits required, no restrictions levied. Grab yourself a shotgun and head out into the open software fields to root out those pesky varmints, the elusive bugs, and squash them, dead.

OK, reality is not as saccharin as that. But sometimes you end up working on code in which you swear the bugs are multiplying and ganging up on you. A shotgun is the only response.

The story is an old one, and it goes like this: Programmers write code. Programmers aren’t perfect. The programmer’s code isn’t perfect. It therefore doesn’t work perfectly the first time. So we have bugs.

If we bred better programmers we’d clearly breed better bugs. 

Some bugs are simple mistakes that are obvious to spot and easy to fix. When we encounter these, we are lucky.

The majority of bugs—the ones we invest hours of effort tracking down, losing our follicles and/or hair pigment in the search—are the nasty, subtle issues. These are the odd, surprising interactions; the unexpected consequences of our algorithms; the seemingly non-deterministic behaviour of software that looked so very simple. It can only have been infected by gremlins. 

 

11. Testing Times

ePub

Quality is free, but only to those who are willing to pay heavily for it.

— Tom DeMarco and Timothy Lister Peopleware: Productive Projects and Teams

Test-driven development (TDD): to some it’s a religion. To some, it’s the only sane way to develop code. To some, it’s a nice idea that they can’t quite make work. And to others, it’s a pure waste of effort.

What is it, really?

TDD is an important technique for building better software, although there is still confusion over what it means to be test driven, and over what a unit test really is. Let’s break through this and discover a healthy approach to developer testing, so we can write better code.

It’s a no-brainer: we have to test our code.

Of course you run your new program to see whether it works. Few programmers are confident enough, or arrogant enough, to write code and release it without trying it out somehow. When you do see corners cut, the code rarely works the first time: problems are found, either by QA, or—worse—when a customer uses it.

 

12. Coping with Complexity

ePub

Simplicity is a great virtue but it requires hard work to achieve it and education to appreciate it. And to make matters worse: complexity sells better.

— Edsger Dijkstra

Code is complex. Complexity is a battle that we all have to fight daily.

Of course, your code is great, isn’t it? It’s other people’s code that is complex.

Well, no. Not always. Admit it. It’s all too easy to write something complicated. It happens when you’re not paying attention. It happens when you don’t plan ahead sufficiently. It happens when you start working on a “simple” problem, but soon you’ve discovered so many corner cases that your simple algorithm has grown to reflect a labyrinth, ready to entrap an unwary programmer.

My observation is that software complexity stems from three main sources. Blobs. And lines.

And what you get when you combine them: people.

In this chapter, we’ll take a look at each of these and see what we can learn about writing better software.

 

13. A Tale of Two Systems

ePub

Architecture is the art of how to waste space.

— Philip Johnson

A software system is like a city—an intricate network of highways and hostelries, of backroads and buildings. There’s a lot going on in a busy city; flows of control are continually being born, weaving their life through it, and dying. A wealth of data is amassed, stored, and destroyed. There are a range of buildings: some tall and beautiful, some squat and functional, others dilapidated, falling into disrepair. As data flows around them, there are traffic jams and tailbacks, rush hours, and road works. The quality of your software city is directly related to how much town planning went into it.

Some software systems are lucky; they have had thoughtful design from experienced architects. They are structured with a sense of elegance and balance. They are well-mapped and easy to navigate. Others are not so lucky—a software settlement that grew up around the accidental gathering of some code. The transport infrastructure is inadequate and the buildings are drab and uninspiring. Placed in the middle of it, you’d get completely lost trying to find a route out.

 

14. Software Development Is…

ePub

And this, our life, exempt from public haunt, finds tongues in trees, books in the running brooks, sermons in stones, and good in everything.

— William Shakespeare As You Like It

It’s a sad fact that I won’t be able to rely on my sharply honed intellect forever. Some time in the future my wits will fade, and I’ll no longer be the sharp, erudite, humble genius I am now. So I need a pension plan, a way to make my millions so that I can live in luxury in my old age.

My original plan for world domination seemed so simple it couldn’t fail: fizzy milk! However, before I got a chance to work out the finer details of the recipe, I received devastating news: fizzy milk had already been invented. Gutted, and with the patent rights slipping through my fingers, I went back to the drawing board to come up with a new pension plan. And this time it was a good one.

This piece of genius goes back to the classic foods of my youth: custard and Alphabetti Spaghetti. I’m sure you can see where I’m going: Alphabetti custard! My initial experiments have proved promising. And almost palatable: it’s a bit like rice pudding, but wheatier. Admittedly, it’s an acquired taste, but I think it could catch on.

 

15. Playing by the Rules

ePub

If I’d observed all the rules, I’d never have got anywhere.

— Marilyn Monroe

We live our lives by many rules. This could be a dystopian Orwellian nightmare, but it’s not. Some rules are imposed on us. But some we set ourselves. These rules oil the cogs of our lives.

Rules facilitate our play, describing how a game works: saying who has won and how. They make our sports fair and enjoyable, and provide plenty of opportunity for (mis)interpretation (see soccer’s off-side rule).

They impinge on our travel, where security rules dictate you can only carry so much liquid, and no sharp objects, on airplanes. They describe traffic speed limits, and how to safely navigate a path on the road. Such rules ensure the safety of all.

Rules bound our social norms, stating that it’s not appropriate to lick a stranger’s ear when you first meet them, no matter how tasty it looks.

Yes, we live our lives continually observing a set of rules. We’re so used to this that we often don’t think about them.

 

16. Keep It Simple

ePub

Simplicity is the ultimate sophistication.

— Leonardo da Vinci

You’ve heard the advice before: “KISS.” Keep it simple, stupid. Exactly how stupid do you have to be to get that wrong? Simplicity is an undoubtedly excellent objective; you should certainly strive for it in your code. No programmer yearns to work with overly complex code. Simple code is transparent; its structure is clear, it does not hide bugs, it is easy to learn, and easy to work with.

So why isn’t all code like that?

In the developer world, there are two kinds of simplicity: the wrong sort and the right sort. The “simplicity” we are looking for specifically does not mean: write your code the easiest way you can, cut corners, ignore all the nasty complicated stuff (brush it all under the rug and hope it goes away), and generally be a programming simpleton.

Oh, if only it were that easy. Too many programmers in the real world do write “simple” code like this. Their brain does not engage. Some of them don’t even realise that they’re doing anything wrong; they just don’t think enough about the code they’re writing, and fail to appreciate all of the inherent subtle complexities.

 

17. Use Your Brain

ePub

“Rabbit’s clever,” said Pooh thoughtfully.

“Yes,” said Piglet, “Rabbit’s clever.”

“And he has Brain.”

“Yes,” said Piglet, “Rabbit has Brain.”

There was a long silence. “I suppose,” said Pooh, “that that’s why he never understands anything.”

— A.A. Milne Winnie-the-Pooh

“Use your brain” is not a derogatory injunctive to slipshod colleagues. Rather, it is a core principle for the conscientious coder. It is the second of my team’s hand-picked rules for guru programming. It has a number of important applications to our daily coding regimen.

We’ve mentioned the KISS rule already: keep it simple, stupid. Here we take it one step further: don’t be stupid. It sounds like obvious advice, but we programmers need repeated reminders.

It’s incredible how dumb hyperintelligent people can be. Some utter geniuses suffer a chronic medical bypass of the common sense gland. Code that ninjas trip over because of their myopic vision; they miss the blindingly obvious right in front of them. Awesome architects walk into walls because their heads are stuck in the clouds.

 

18. Nothing Is Set in Stone

ePub

They always say time changes things, but you actually have to change them yourself.

— Andy Warhol

There is a strange fiction prevalent in programming circles: once you’ve written some code then it is sacred. It should not be changed. Ever.

That goes double for anyone else’s code. Don’t you dare touch it.

Somewhere along the development line, perhaps at the first check-in, or perhaps just after a product release, the code gets embalmed. It changes league. It is promoted. No longer riffraff, it becomes digital royalty. The once-questionable design is suddenly considered beyond reproach and becomes unchangeable. The internal code structure is no longer to be messed with. All of the interfaces to the outside world are sacred and can never be revised.

Why do programmers think like this? Fear. Fear of getting it wrong. Fear of breaking things. Fear of extra work. Fear of the cost of change.

There is a very real anxiety that comes from changing code you don’t know fully. If you don’t understand the logic from the inside out, if you’re not entirely sure what you’re doing, if you don’t understand every possible consequence of a change, then you could break the program in strange ways or alter odd corner-case behaviour and introduce very subtle bugs into the product. You don’t want to do that, do you?

 

Load more


Details

Print Book
E-Books
Slices

Format name
ePub (DRM)
Encrypted
true
Sku
2370006452997
Isbn
9781491905579
File size
3 KB
Printing
Disabled
Copying
Disabled
Read aloud
No
Format name
ePub
Encrypted
No
Printing
Allowed
Copying
Allowed
Read aloud
Allowed
Sku
In metadata
Isbn
In metadata
File size
In metadata