A place to cache linked articles (think custom and personal wayback machine)
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. title: A Codebase is an Organism
  2. url: http://www.meltingasphalt.com/a-codebase-is-an-organism/
  3. hash_url: 7d25593fd8739da9608a0fdae30f5345
  4. <h3>I.</h3>
  5. <p>Here's what no one tells you when you graduate with a degree in computer science and take up a job in software engineering:</p>
  6. <blockquote><p>The computer is a <em>machine</em>, but a codebase is an <em>organism</em>.</p></blockquote>
  7. <p>This will make sense to anyone who's worked on a large or even medium-sized software project — but it's often surprising to new grads. Why? Because nothing in your education prepares you for how to deal with an organism.</p>
  8. <p>Computer science is all about how to <em>control the machine</em>: to make it do exactly what you want, during execution, on the time scale of nano- and milliseconds. But when you build real software — especially as part of a team — you have to learn how to control not only the (very obedient) machine, but also a large, sprawling, and often unruly codebase.</p>
  9. <p>This turns out to require a few 'softer' skills. Unlike a computer, which always does exactly what it's told, code can't really be bossed around. Perhaps this is because code is ultimately managed by <em>people</em>. But whatever the reason, you can't tell a codebase what to do and expect to be obeyed. Instead, the most you can do (in order to maximize your influence) is try to <em>steward</em> the codebase, <em>nurture</em> it as it grows over a period of months and years.</p>
  10. <p>When you submit a CS homework assignment, it's done. Fixed. Static. Either your algorithm is correct and efficient or it's not. But push the same algorithm into a codebase and there's a very real sense in which you're <em>releasing it into the wild</em>.</p>
  11. <p><span id="more-1836"/>Out there in the codebase, all alone, your code will have to fend for itself. It will be tossed and torn, battered and bruised, by other developers — which will include yourself, of course, at later points in time. Exposed to the elements (bug fixes, library updates, drive-by refactorings), your code will suffer all manner of degradations, "the slings and arrows of outrageous fortune... the thousand natural shocks that flesh is heir to."</p>
  12. <h3>II.</h3>
  13. <p>Whether you're a developer or otherwise, nothing will give you a better feel for code's <em>organic nature</em> than watching a <a href="http://vis.cs.ucdavis.edu/~ogawa/codeswarm/">codeswarm visualization</a> — an animation of the commit history of a codebase.</p>
  14. <p>Here's a still of the Gentoo Linux codeswarm:</p>
  15. <p><a href="http://www.meltingasphalt.com/wp-content/uploads/2014/02/gentoo_code_swarm.png"><img class="alignnone size-medium wp-image-1837" alt="gentoo_code_swarm" src="http://www.meltingasphalt.com/wp-content/uploads/2014/02/gentoo_code_swarm-600x360.png"/></a></p>
  16. <p>But a static image hardly does this any justice. The whole point is to see the <em>evolution</em> of the thing — <a href="http://www.youtube.com/watch?v=WQqm3l4MVwY">in HD</a> if you can. "Swarm" ends up being a pretty accurate description: it's like watching a flock of developers attacking a hive of text files. Well, "attacking" or "mating with" — I can't really tell which.</p>
  17. <p>(There's also a nice rendering of the <a href="http://vimeo.com/1130828">Eclipse project codeswarm</a> on Vimeo.)</p>
  18. <p>What a codeswarm makes vivid is this: that managing a codebase requires an entirely different mindset from the one needed to control a machine. It requires knowing how to deal with the unpredictable flux of a complex, wild organism.</p>
  19. <h3>III.</h3>
  20. <p>The organic nature of code manifests itself in the dual forces of <strong>growth</strong> and <strong>decay</strong>.</p>
  21. <p>Let's start with decay. Realizing that code can wither, decay, or even die leads us to the <em>nursing</em> metaphor, or <em>codebase as sick patient</em>.</p>
  22. <p>Code doesn't decay on its own, of course. Left completely untouched, it will survive as long as you care to archive it. Decay — often called <a href="https://en.wikipedia.org/wiki/Software_rot">code rot</a> or software rot — only sets in when <em>changes</em> are made, either to the code itself or to any of its dependencies. So as a rule of thumb, we can say that most code is decaying during most of its existence. It's like entropy. You never 'win' against entropy; you just try to last as long as you can.</p>
  23. <p>In a healthy piece of code, entropic decay is typically staved off by dozens of tiny interventions — bug fixes, test fixes, small refactors, migrating off a deprecated API, that sort of thing. These are the standard maintenance operations that all developers undertake on behalf of code that they care about. It's when the interventions <em>stop</em> happening, or don't happen often enough, that code rot sets in.</p>
  24. <p>We can assess a module in terms of 'risk factors' for this kind of decay. The <em>older</em> a module is, for example, the more likely it is to be suffering from code rot. More important than age, however, is the <em>time since last major refactor</em>. (Recently-refactored code is a lot like new code, for good or ill.) Also, the <em>more dependencies a module has</em>, and the more those dependencies have recently changed, the more likely the module is to have gone bad.</p>
  25. <p>But all of these risk factors pale in importance next to <em>how much execution</em> a piece of code has been getting. Execution by itself isn't quite enough, though — it has to be in a context where someone is paying attention to the results. This type of execution is also known as <em>testing</em>.</p>
  26. <p>Testing can take many forms — automated or manual, ad hoc developer testing, and even 'testing' through use in production. As long as the code is getting executed in a context where the results matter, it counts. The more regularly this happens, of course, the better.</p>
  27. <p>I find it useful to think of execution as the <em>lifeblood</em> of a piece of code — the vital flow of control? electronic pulse? — and testing as medical instrumentation, like a heart rate monitor. You never know when a piece of code, which is rotting all the time, will atrophy in a way that causes a serious bug. If your code is being tested regularly, you'll find out soon and will be able to intervene. But without testing, no one will notice that your code has flatlined. Errors will begin to pile up. After a month or two, a module can easily become so rotten that it's impossible to resuscitate.</p>
  28. <p>Thus teams are often confronting the uncomfortable choice between a risky refactoring operation and clean amputation. The best developers can be positively <em>gleeful</em> about amputating a diseased piece of code (even when it's their own baby, so to speak), recognizing that it's often the best choice for the overall health of the project. Better a single module should die than continue to bog down the rest of the project.</p>
  29. <h3>IV.</h3>
  30. <p>Now you might assume that while decay is problematic, growth is always good. But of course it's not so simple.</p>
  31. <p>Certainly it's true that a project needs to grow in order to become valuable, so the problem isn't growth per se, but rather <em>unfettered</em> or <em>opportunistic</em> growth. Haphazard growth. Growth by means of short-sighted, local optimizations. And this kind of growth seems to be the norm — perhaps because developers are often <em>themselves</em> short-sighted and opportunistic, if not outright lazy. But even the best, most conscientious developers fall pitifully short of making globally-optimal decisions all the time.</p>
  32. <p>Left to 'its' own devices, then, a codebase can quickly devolve into a tangled mess. And the more it grows, the more volume it has to maintain against the forces of entropy. In this way, a project can easily collapse under its own weight.</p>
  33. <p>For these reasons, any engineer worth her salt soon learns to be <em>paranoid</em> of code growth.</p>
  34. <p>She assumes, correctly, that whenever she ceases to be vigilant, the code will get itself into trouble. She knows, for example, that two modules will tend to grow ever more dependent on each other unless <a href="https://en.wikipedia.org/wiki/Modularity">separated</a> by hard ('physical') boundaries. She's had to do that surgery — to separate two modules that had become inappropriately entangled with each other. Afraid of such spaghetti code (rat's nests), she strives relentlessly to arrange her work (and the work of others) into small, encapsulated, decoupled modules.</p>
  35. <p>Faced with the necessity of growth but also its dangers, the seasoned engineer therefore seeks a balance between <em>nurture</em> and <em>discipline</em>. She knows she can't be too permissive; coddled code won't learn its boundaries. But she also can't be too tyrannical. Code needs some freedom to grow at the optimal rate.</p>
  36. <p>In this way, building software isn't at all like assembling a car. In terms of managing growth, it's more like <em>raising a child</em> or <em>tending a garden</em>.</p>
  37. <h3>V.</h3>
  38. <p>Once you develop an intuition for the organic nature of a codebase, a lot of the <a href="http://programmer.97things.oreilly.com/wiki/index.php/Contributions_Appearing_in_the_Book">received wisdom</a> becomes clear and easier to understand. You realize that a lot of software engineering principles are corollaries or specific applications of the same general idea — namely that:</p>
  39. <blockquote><p>Successful management of a codebase consists in <em>defending its long-term health</em> against the dangers of decay and opportunistic growth.</p></blockquote>
  40. <p>It very quickly becomes obvious, for example, that you should <strong>test the living daylights out of your code</strong>, using as much automation as possible. How else are you to prevent code rot from setting in? How else will you catch bugs as soon as they sprout?</p>
  41. <p>The organic nature of code also suggests that you should <strong>know your code smells</strong>. A <a href="https://en.wikipedia.org/wiki/Code_smell">code smell</a>, according to Wikipedia, is</p>
  42. <blockquote><p>any symptom in the source code of a program that possibly indicates a deeper problem. Code smells are <em>usually not bugs</em> [emphasis mine] — they are not technically incorrect and don't currently prevent the program from functioning. Instead, they indicate weaknesses in design that may be slowing down development or increasing the risk of bugs or failures in the future.</p></blockquote>
  43. <p>"Not a bug" means that a code smell, whatever it is, won't be causing problems during <em>execution</em>, on the machine — at least not right now. Instead, it's going to cause problems during <em>evolution</em> of the codebase. It might invite entropy to accumulate somewhere, for example, or put unnecessary constraints on growth, or allow something to grow where it shouldn't. And like a doctor trying to detect a disease in its early stages, the sooner you catch a whiff of bad code, the fewer problems you'll have down the line.</p>
  44. <p>The organic, evolutionary nature of code also highlights the importance of <strong>getting your APIs right</strong>. By virtue of their public visibility, APIs can exert a lot of influence on the future growth of the codebase. A good API acts like a trellis, coaxing the code to grow where you want it. A bad API is like a cancer, and it will metastasize all over your codebase. Some quick examples:</p>
  45. <ul>
  46. <li>If you expose a method that doesn't handle nulls properly, then you force each of your callers to branch on null before calling your API.</li>
  47. <li>If you design an asynchronous API with callbacks, you'll force all your callers to write multithreaded code. (Sometimes this is clearly the right decision, but when it's not, you're infecting the rest of the codebase with your bad decision.)</li>
  48. <li>If your API passes around a "grab bag" object, you're all but inviting fellow devs to use the "spooky <a href="https://en.wikipedia.org/wiki/Action_at_a_distance_(computer_programming)">action at a distance</a>" anti-pattern.</li>
  49. </ul>
  50. <p>Finally, here's an idea that took me many years to appreciate on a gut level (but which is completely obvious now in hindsight): <strong>the benefits of failing fast</strong>. What I should have understood is that failure (on unexpected inputs) reflects a <em>conflict of interest</em> between the computer and the codebase.</p>
  51. <p>From the perspective of the machine on which the code is executing right now, it's better <em>not</em> to fail and hope that everything will be OK — hope that some other part of the stack will handle the failure gracefully. Maybe we can recover. Maybe the user won't notice. Why crash when we could at least <em>try</em> to keep going? And everything in my CS education taught me to do what's right for the machine.</p>
  52. <p>But from the perspective of the codebase — whose success depends not on any single execution, but rather on <em>long-term</em> health — it's far better to fail fast (and loud), in order to call immediate attention to the problem so it can be fixed.</p>
  53. <p>Coddled code will fester. Spare the rod, spoil the child. These are the metaphors you need to make sense of a codebase.</p>
  54. <p>___</p>
  55. <p>Based off some remarks originally published at <a href="http://www.ribbonfarm.com/2014/01/28/technical-debt-of-the-west/">Ribbonfarm</a>.</p>