NDepend

Improve your .NET code quality with NDepend

rewrite-or-refactor

Rewrite or Refactor?

I’ve trod this path before in various incarnations and I’ll do it again today.  After all, I can think of few topics in software development that draw as much debate as this one.  “We’ve got this app, and we want to know if we should refactor it or rewrite it.”

For what it’s worth, I answer this question for a living.  And I don’t mean that in the general sense that anyone in software must ponder the question.  I mean that CIOs, dev managers and boards of directors literally pay me to help them figure out whether to rewrite, retire, refactor, or rework an application.  I go in, gather evidence, mine the data and state my case about the recommended fate for the app.

Because of this vocation and because of my writing, people often ask my opinion on this topic.  Today, I yet again answer such a question.  “How do I know when to rewrite an app instead of just refactoring it?”  I’ll answer.  Sort of.  But, before I do, let’s briefly revisit some of my past opinions. Continue reading Rewrite or Refactor?

maintainable-code

Secrets of Maintainable Codebases

You should write maintainable code.  I assume people have told you this at some point.  The admonishment is as obligatory as it is vague.  So, I’m sure, when you heard this, you didn’t react effusively with, “oh, good idea — thanks!”

If you take to the Internet, you won’t need to venture far to find essays, lists, and stack exchange questions on the subject.  As you can see, software developers frequently offer opinions on this particular topic.  And I present no exception; I have little doubt that you could find posts about this on my own blog.

So today, I’d like to take a different tack in talking about maintainable code.  Rather than discuss the code per se, I want to discuss the codebase as a whole.  What are the secrets to maintainable codebases?  What properties do they have, and what can you do to create these properties?

In my travels as a consultant, I have seen so many codebases that it sometimes seems I’m watching a flip book show of code.  On top of that, I frequently find myself explaining concepts like the cost of code ownership, and regarding code as, for lack of a better term, inventory.  From the perspective of those paying the bills, maintainable code doesn’t mean “code developers like to work with” but rather “code that minimizes spend for future changes.”

Yes, that money includes developer labor.  But it also includes concerns like deployment effort, defect cycle time, the universality of skills required, and plenty more.  Maintainable codebases mean easy, fast, risk-free, and cheap change.  Here are some characteristics in the field that I use when assessing this property.  Some of them may seem a bit off the beaten path.

Continue reading Secrets of Maintainable Codebases

what to do when your colleague creates spaghetti code

What to do when Your Colleague Creates Spaghetti Code

I write for a number of different outfits and earn my living consulting around software and IT.  Because of the intersection of these three concerns — writing, offering advice professionally, and software — I field a lot of requests for advice on how to do the right technical thing without everyone around you shooting holes in it.  Consider an example.

“How can we get started with unit testing?”

Considered as a technical question alone, this invites a fairly obtuse response.  “First, write a unit test.  Second, run the unit test.”  Obviously, that’s not really what anyone is asking when they ask this question.

Instead, they want to know something orders of magnitude more complex.  “How can we overcome years of inertia, a nasty legacy codebase, Bill, who has been around for 40 years and hates everything new, and the fact that management doesn’t want to pay us to write ‘extra’ code… and then start unit testing?”  Oh, yeah, that.  Well, that’s complicated.

I frequently hear such apparently-innocuous-but-actually-complex questions about code quality.  “This idiot on my team is writing mountains of the most unmaintainable garbage imaginable — what should I do?”

Usually, this sort of question comes to me from people at client sites.  And, accordingly, I have to balance the answer that makes the most sense for the individual with the one that keeps the client’s best interests in mind.  The client pays my bill, and I have a charter to lower the cost of ownership and development of their code.

But when I’m in writer mode, and only the asker’s interests matter, I’l give a subtly different answer.  Today, I’d like to offer advice on what you should do in this situation.

Continue reading What to do when Your Colleague Creates Spaghetti Code

company coding standards

How to Get Company Coding Standards Right (and Wrong)

Nothing compares with the first week on a new job or team.  You experience an interesting swirl of anticipation, excitement, novelty, nervousness, and probably various other emotions I’m forgetting.  What will your new life be like?  How can you impress your teammates?  Where do you get a cup of coffee around here?

If you write code for a living, you know some specific new job peculiarities.  Do they have a machine with runnable code ready on day one?  Or do you have to go through some protracted onboarding process before you can even look at code?  And speaking of code, does theirs square with elegant use of design patterns and unit testing that they advertised during the interview process?  Or does it look like someone made a Death Star out of bailing wire and glue?

But one of the most pivotal moments (for me, anyway) comes innocuously enough.  It usually happens with an offhand comment from a senior developer or through something mentioned in your orientation packet.  You find yourself directed to the company coding standards document.  Oh, boy.

At this point, I start to wonder.  Will I find myself glancing at a one-pager that says, “follow the Microsoft guidelines whenever possible and only include one class per file?”  Or, will I find something far more sinister?  Images of a power-mad architect with a gleam in his eye and a convoluted variable name encoding scheme in his back pocket pop into my head.  Will I therefore spend the next six months waging pitched battles over the placement of underscores?

Ugh, Company Coding Standards

In this post, believe it or not, I’m going to make the case for coding standards.  But before I do so, I want to make my skepticism very clear.  Accordingly, I want to talk first about how coding standards fail.

Based on personal battle scars and my own experience, I tend to judge coding standard documents as guilty until proven innocent.  I cannot tell you how many groups I have encountered where a company coding standard was drafted, “just because.”  In fact, I’ve even written about this in the past.

Continue reading How to Get Company Coding Standards Right (and Wrong)

trend metrics

Keep Your Codebase Fit with Trend Metrics

A while back, I wrote a post about the importance of trends when discussing code metrics.  Metrics have an impact when teams are first exposed to them, but that tends to fade with time.  Context and trend monitoring create and sustain a sense of urgency.

To understand what I mean, imagine a person aware that he has put on some weight over the years.  One day, he steps on a scale and realizes that he’s much heavier than previously thought.  That induces a moment of shock and, no doubt, grand plans for gyms, diets, and lifestyle adjustments.  But, as time passes, his attitude may shift to one in which the new, heavier weight defines his self-conception.  The weight metric loses its impact.

To avoid this, he needs to continue measuring himself.  He may see himself gaining further weight, poking a hole in the illusion that he has evened out.  Or, conversely, he may see that small adjustments have helped him lose weight, and be encouraged to continue with those adjustments.  In either case, his ongoing conception of progress, more than the actual weight metric, drives and motivates behaviours.

The same holds true with codebases and keeping them clean.  All too often, I see organizations run some sort of static analysis or linting tool on their codebase, and conclude “it’s bad.”  They resolve only to do a better job in a year or two when the rewrite will start.  However good or bad any given figure might be, the trend-line, and not the figure itself, holds the most significance.

Continue reading Keep Your Codebase Fit with Trend Metrics

porting-to-dot-net-core

Considering a Port to .NET Core? Use NDepend

An American colloquialism holds, “only two things are certain: death and taxes.”  If I had to appropriate that for the software industry, I might say that the two certainties are death and legacy code.  Inevitably, you have code that you have had for a while, and you want to do things with it.

Software architects typically find themselves tasked with such considerations.  Oh, sure, sometimes they get to pick techs and frameworks for greenfield development.  Sometimes they get to draw fancy diagrams and lay out plans.  But frequently, life charges them with the more mundane task of “figuring out how to make that creaky old application run on an iPhone.”  Okay, maybe it’s not quite that silly, but you get the idea.

If you earn a living as an architect in the .NET world, you have, no doubt, contemplated the impact of .NET Core on your application portfolio.  Even if you have no active plans to migrate, this evolution of .NET should inform your strategic decisions going forward.  But if you have use for deploying the framework along with your application or if you want to run on different operating systems, you’re going to need to port that legacy code.

I am, by no means, an expert in .NET Core.  Instead, my areas of specialty lie in code analysis, developer training, and IT management and strategy consulting.  I help dev teams create solutions economically.  And because of this, I can recognize the value of NDepend to a port from what I do know about .NET core.

Continue reading Considering a Port to .NET Core? Use NDepend

plugging leaky abstractions

Plugging Leaky Abstractions

In 2002, Joel Spolsky coined something he called “The Law of Leaky Abstractions.”  In software, an “abstraction” hides complexity of an underlying system from those using the abstraction.  Examples abound, but for a quick understanding, think of an ORM hiding from you the details of database interaction.

The Law of Leaky Abstractions states that “all non-trivial abstractions, to some degree, are leaky.”  “Leaky” indicates that the abstraction fails to adequately hide its internal details.  Imagine, for instance, that while modifying the objects generated by your ORM, you suddenly needed to manage the particulars of some SQL query.  The abstraction leaked, forcing you to understand the details that it was supposed to hide.

Spolsky’s point may inspire a fatalistic feeling.  After all, if the things are doomed to leak, why bother with them in the first place?  But I like to consider it a caution against chasing perfection rather than a lament.

Abstractions in software help us the same way figurative language helps our prose.  Metaphors and analogies offer ease of understanding, but at the accepted price of lost precision.  If you press a metaphor enough, it will inevitably break down.  But that doesn’t render metaphors useless — far from it.

Thus, if you have a leaky abstraction, you can take steps to “plug” it, so to speak.  Spolsky says it himself, right in the law he coined: “all non-trivial abstractions are, to some degree, leaky.”  We have the ability to lessen that degree.

Continue reading Plugging Leaky Abstractions

measurecode

Measure Your Code to Get Back on Track

When I’m called in for strategy advice on a codebase, I never arrive to find a situation where all parties want to tell me how wonderfully things are going.  As I’ve mentioned before here, one of the main things I offer with my consulting practice is codebase assessments and subsequent strategic recommendations.

Companies pay for such a service when they have problems, and those problems drive questions.  “Should we scrap this code and start over, or can we factor toward a better state?”  “Can we move away from framework X, or are we hopelessly tied to it?”  “How can we evolve without doing a forklift upgrade?”

To answer these questions, I assess their code (often using NDepend as the centerpiece for querying the codebase) and synthesize the resultant statistics and data.  I then present a write-up with my answer to their questions.  This also generally includes a buffet of options/tactics to help them toward their goals.  And invariably, I (prominently) offer the option: “instrument your code/build with static analysis to raise the bar and prevent backslides.”

I find it surprising and a bit dismaying how frequently clients want to gloss over this option in favor of others. Continue reading Measure Your Code to Get Back on Track

ndepend-api

Managing Code Analysis Statistics with the NDepend API

If you’re familiar with NDepend, you’re probably familiar with the Visual Studio plugin, the out of the box metrics, the excellent visualization tools, and the iconic Zone of Uselessness/Zone of Pain chart.  These feel familiar to NDepend users and have likely found their way into the normal application development process. NDepend has other features as well, however, some of which I do not necessarily hear discussed as frequently.  The NDepend API has membership in that “lesser known NDepend features club.”  Yes, that’s right — if you didn’t know this, NDepend has an API that you can use.

You may be familiar, as a user, with the NDepend power tools.  These include some pretty powerful capabilities, such as duplicate code detection, so it stands to reason that you may have played with them or even that you might routinely use them.  But what you may not realize is the power tools’ source code accompanies the installation of NDepend, and it furnishes a great series of examples on how to use the NDepend API.

NDepend’s API is contained in the DLLs that support the executable and plugin, so you needn’t do anything special to obtain it.  The NDepend website also treats the API as a first class citizen, providing detailed, excellent documentation.   With your NDepend installation, you can get up and running quickly with the API.

Probably the easiest way to introduce yourself is to open the source code for the power tools project and to add a power tool, or generally to modify that assembly.  If you want to create your own assembly to use the power tools, you can do that as well, though it is a bit more involved.  The purpose of this post is not to do a walk-through of setting up with the power tools, since that can be found here.  I will mention two things, however, that are worth bearing in mind as you get started.

  1. If you want to use the API outside of the installed project directory, there is additional setup overhead.  Because it leverages proprietary parts of NDepend under the covers, setup is more involved than just adding a DLL by reference.
  2. Because of point (1), if you want to create your own assembly outside of the NDepend project structure, be sure to follow the setup instructions exactly.

A Use Case

I’ve spoken so far in generalities about the API.  If you haven’t already used it, you might be wondering what kinds of applications it has, besides simply being interesting to play with.  Fair enough.

One interesting use case that I’ve experienced personally is getting information out of NDepend in a customized format.  For example, let’s say I’m analyzing a client’s codebase and want to cite statistical information about types and methods in the code.  Out of the box, what I do is open Visual Studio and then open NDepend’s query/rules editor.  This gives me the ability to create ad-hoc CQLinq queries that will have the information I need.

But from there, I have to transcribe the results into a format that I want, such as a spreadsheet.  That’s fine for small projects or sample sizes, but it becomes unwieldy if I want to plot statistics in large codebases.  To address this, I have enlisted the NDepend API.

Continue reading Managing Code Analysis Statistics with the NDepend API

deliverprojectsontime

How to Deliver Software Projects on Time

Someone asked me recently, almost in passing, about the keys to delivering software projects on time.  In this particular instance, it was actually a question of how to deliver .NET projects on time, but I see nothing particularly unique to any one tech stack or ecosystem.  In any case, the question piqued my interest, since I’m more frequently called in as a consultant to address issues of quality and capability than slipped deadlines.

To understand how to deliver projects on time (or, conversely, the mechanics of failing to deliver on time) requires a quick bit of term deconstruction.  The concept of “on time” consists of two concerns of software parlance: scope and delivery date.  Specifically, for something to be “on time” there has to be an expectation of what will be delivered and when it will be delivered.

How We Get This Wrong

Given that timeliness of delivery is such an apparently simple concept, we sure do find a lot of ways to get it wrong.  I’m sure that no one reading has to think long and hard to recall a software project that failed to deliver on time.  Slipped deadlines abound in our line of work.

The so-called “waterfall” approach to software delivery has increasingly fallen out of favor of late.  This is a methodology that attempts simultaneously to solve all unknowns through extensive up-front planning and estimation.  “The project will be delivered in exactly 19 months, for 9.4 million dollars, with all of the scope outlined in the requirements documents, and with a minimum standard of quality set forth in the contract.”  This approach runs afoul of a concept sometimes called “the iron triangle of software development,” which holds that the more you fix one concern (scope, cost, delivery date), the more the others will wind up varying — kind of a Heisenburg’s Uncertainty Principle of software.  The waterfall approach of just planning harder and harder until you get all of them right thus becomes something of a fool’s errand.

Let’s consider the concept of “on time” then, in a vacuum.  This features only two concerns: scope and delivery date.  Cost (and quality, if we add that to the mix as a possible variant and have an “iron rectangle”) fails to enter into the discussion.  This tends to lead organizations with deep pockets to respond to lateness in a predictable way — by throwing resources at it.  This approach runs afoul of yet another aphorism in software known as “Brooks’ Law:” adding manpower to a late software project makes it later.

If we accept both Brooks’ Law and the Iron Triangle as established wisdom, our prospects for hitting long-range dates with any reliability start to seem fairly bleak.  We must do one of two things, with neither one being particularly attractive.  Either we have to plan to dramatically over-spend from day 1 (instead of when the project is already late) or we must pad our delivery date estimate to such an extent that we can realistically hit it (really, just surreptitiously altering delivery instead of cost, but without seeming to).

Continue reading How to Deliver Software Projects on Time