NDepend

Improve your .NET code quality with NDepend

Code reuse is not a good goal.

Code Reuse is Not a Good Goal

Wait, wait, wait.  Put down the pitchforks and listen for a minute.  You’re probably thinking that I’m about to tout the “virtues” of copy/paste programming or something.  But I assure you I’m not going to do that.  Instead, I’m going to speak to a similar but subtly different topic: code reuse as a first-class goal.

If you’ve read The Pragmatic Programmer, you know about the DRY principle.  You’ll also know that the underlying evil comes from duplication of knowledge in your system.  This creates inconsistencies and maintenance headaches.  So, since you duplicate code at your peril, isn’t code reuse a good thing?  Isn’t it the opposite of code duplication?

No, not exactly.  You can write “hello world” without any duplication.  But you can also write it without reusing it or anything in it.

Code Reuse as a First-Class Goal

So what, then, do I mean when I talk about code reuse as a first-class goal?  I’m talking about a philosophy that I see frequently in my consulting, especially in the enterprise.

The idea seems to come from a deep fear of rework and waste.  If we think of the history of the corporation, the Industrial Revolution saw an explosion in manufacturing driven by global efficiency.  The world scrambled to make things cheaper and faster, and waste or rework in the process impeded that.

Today and in our line of work, we don’t manufacture widgets.  Instead, we produce software.  But we still seem to have this atavistic terror that someone, somewhere, might already have written a data access layer component that you’re about to write.  And you writing it would be a waste.

In response to this fear, organizations come up with plans that can get fairly elaborate.  They create “centers of excellence” that monitor teams for code reuse opportunities, looking to stamp out waste.  Or they create sophisticated code sharing platforms and internal app stores.  Whatever the details, they devote significant organizational resources to avoiding this waste.

And that’s actually great, in some respects.  I mean, you don’t want to waste time reinventing wheels by writing your own source control tools and logging frameworks.  But things go sideways when the goal becomes not one of avoiding reinvented wheels but instead one of seeing how much of your own code you can reuse.

Let’s take a look at some of the problems that you see when organizations really get on the “code reuse” horse.

Continue reading Code Reuse is Not a Good Goal

C# Tools to Help with Your Code Quality

C# Tools to Help with Your Code Quality

Over the years, one of the things I’ve come to love about the .NET ecosystem is the absolute abundance of tools to help you.  It’s an embarrassment of riches.  I enjoy writing code in C# because the language itself is great.  But C# tools take the experience to a whole other level.

I know, I know.  Some of you out there might argue that you get all of this goodness only by using heavyweight, resource-intensive tooling.  I’ll just go ahead and concede the point while saying that I don’t care.  I’m happy to work on a powerful development rig, outfitted with powerful tools, to write code in a highly productive language.

Today, I’d like to talk about some of these C# tools.  Or I should say I’d like to talk about some of the many C# tools you can use that are generally oriented toward the subject of code quality.

So, if you’re a C# developer, what are some tools you can use to improve the quality of your code?

Continue reading C# Tools to Help with Your Code Quality

Marker Interface Isn't a Pattern or a Good Idea

Marker Interface Isn’t a Pattern or a Good Idea

Today, I have the unique opportunity to show you the shortest, easiest code sample of all time.  I’m talking about the so-called marker interface.  Want to see it?  Here you go.

I told you it was simple.  It’s dead simple for a code sample, so that makes it mind-blowingly simple for a design pattern.  And that’s how people classify it — as a design pattern.

How Is This “Marker Interface” Even a Pattern?

As you’ve inferred from the title, I’m going to go on to make the claim that this is not, in fact, a “design pattern” (or even a good idea).  But before I do that, I should explain what this is and why anyone would do it.  After all, if you’ve never seen this before, I can forgive you for thinking it’s pretty, well, useless.  But it’s actually clever, after a fashion.

The interface itself does nothing, as advertised.  Instead, it serves as metadata for types that “implement” it.  For example, consider this class.

The customer class doesn’t implement the interface.  It has no behavior, so the idea of implementing it is nonsense.  Instead, the customer class uses the interface to signify something to the client code using it.  It marks itself as containing sensitive information, using the interface as a sort of metadata.  Users of the class and marker interface then consume it with code resembling the following:

Using this scheme, you can opt your classes into special external processing.

Marker Interface Backstory

I’m posting code examples in C#, which makes sense.  After all, NDepend is a .NET ecosystem tool.  But the marker interface actually goes back a long way.  In fact, it goes back to the earlier days of Java, which baked it in as a first class concept, kind of how C# contains a first class implementation of the iterator design pattern.

In Java, concepts like serialize and clone came via marker interfaces.  If you wanted serialization in Java, for instance, you’d tag your class by “implementing” the marker interface Serializable.  Then, third party processing code, such as ORMs, IoC containers, and others would make decisions about how to process it.  This became common enough practice that a wide ecosystem of tools and frameworks agreed on the practice by convention.

C# did not really follow suit.  But an awful lot of people have played in both sandboxes over the years, carrying this practice into the .NET world.  In C#, you’ll see two flavors of this.  First, you have the classic marker interface, wherein people use it the way that I showed above.  Secondly, you have situations where people get clever with complex interface inheritance schemes and generics in order to force certain constraints on clients.  I won’t directly address that second, more complex use case, but note that all of my forthcoming arguments apply to it as well.

Now, speaking of arguments, let’s get to why I submit that this is neither a “pattern” nor a good idea in modern OOP.  NDepend tells you to avoid this, and I wholeheartedly agree.

Continue reading Marker Interface Isn’t a Pattern or a Good Idea

Using NDepend to Get Going Quickly on C# Projects

Using NDepend To Get Going Quickly on C# Projects

Assuming you’ve had at least one job working on one or more C# projects, let me paint a familiar picture for you.  I’m talking about your onboarding time with a new group.  It’s always an exciting and awkward experience as you feel out teammates and new codebases.

On day one, you arrive.  But rarely does anyone expect you to contribute meaningfully on that day.  In fact, you probably won’t even contribute meaningfully that first week.  Instead, you hear plenty of talk about “learning curves” and how this environment is uniquely challenging.  Ironically, every shop I visit as a consultant claims to be uniquely challenging.

C# Projects: the Onboarding Phase

What, then, does onboarding usually look like?  I’ll build you a composite picture, based on my travels.  I’ll leave out the HR component, with new team member lunches and paperwork; here, we’ll consider only about the technical aspects.

On the first day, you show up and a developer on the team works with you on the basics.  You get access to the mundane necessities: network shares, the internal SharePoint, version control, etc.  If you get lucky, all of that goes smoothly, and you actually get source code on your machine.  But this could also drag out a day or two.

During this time, everyone on the team is pretty busy.  You have chunks of time left to your own devices, instructed to study the architecture and design documents and also to look around the codebase.  These documents paint impressive architectural pictures of layer cakes, distributed clusters, tiers, and CQRS paradigms.  You secretly wonder if they’re accurate.  (Spoiler: they aren’t.)

You’d get going on real work sooner, but the architect needs to walk you through the relevant design patterns.  This is necessary so you’ll know what goes where without making a serious blunder. Of course, the architect is really busy since all problems bubble up to her.  So you wait.

Continue reading Using NDepend To Get Going Quickly on C# Projects

What the Singleton Pattern Costs You

What the Singleton Pattern Costs You

Do you use the singleton pattern?  If not, I’m assuming that you either don’t know what it is or that you deliberately avoid it.  If you do use it, you’re probably sick of people judging you for it.  The pattern is something of a lightning rod in the world of object-oriented programming.

You can always use Stack Overflow as a litmus test for programming controversy.  Someone asked “what was so bad” about singletons, and voting, responding, and commenting went off the charts.  Most of those responses fell into the negative category.  Outside of Stack Overflow, people call singletons evil, pathological liars, and anti-patterns.  People really seem to hate this design pattern — at least some of them do, anyway.

NDepend takes a stance on the singleton pattern as well, both in its rules and on the blog.  Specifically, it encourages you to avoid it.

But I’m not going to take a stance today, exactly.  I understand the cathartic temptation to call something evil in the world of programming.  If some (anti) pattern, framework, or language approach has caused you monumental pain in the past, you come to view it as the tool of the devil.  I’ve experienced this and turned it into a blog post, myself.

Instead of going that route here, however, I’m going to speak instead about what it can cost you when you decide to use the singleton pattern — what it can cost the future you, that is.  I have a consulting practice assessing third-party codebases, so I’ve learned to view patterns and practices through a dispassionate lens.  Everything is just trade-offs.

Continue reading What the Singleton Pattern Costs You

Our experience with using third-party libraries

NDepend is a tool that helps .NET developers write beautiful code. The project was started in April 2004. It is now used by more than 6 000 companies worldwide.

In more than a decade, many decisions were made, each with important consequences on the code base evolution process, sometime good consequences, sometime less good. Relentlessly dog-fooding (i.e using NDepend to analyze and improve the NDepend code base) helped us a lot to obtain more maintainable code, less bugs, and to improve the tool usability and features.

When it comes to working on and maintaining a large code base for several years, some of the most important decisions made are related to relying (or not) on some third-party libraries. Choosing whether or not to rely on a library is a double-edged sword decision that can, over time, bring a lot of value or cause a lot of friction. Ultimately users won’t make a difference between your bugs and third-party libraries bugs, their problems become your problems. Consider this:

  • Sometimes the team just needs a fraction of a library and it may be more cost-effective, and more maintainable with time, to develop your own.
  • Sometimes the licensing of a free or commercial library will prevent you from achieving your goals.
  • Sometimes the library looks bright and shiny but becomes an obsolete project a few months later and precious resources will have to be spent maintaining others code, or migrating toward a trendy new library.
  • Sometimes the library code and/or authors are so fascinating that you’ll be proud to contribute and be part of it.

Of course we all hope for the last case, and we had the chance to experience this a few times for real. Here are some libraries we’ve had great success with:

Mono.Cecil (OSS)

Mono.Cecil is an open source project developed by Jean-Baptiste Evain that can read and write data nested in .NET assemblies, including compiled IL code. NDepend has relied on Cecil for almost a decade to read IL code and other data. Both the library and the support provided are outstanding. The performance of the library is near optimal and all bugs reported were fixed in a matter of days or even hours. For our usage, the library is actually close to bug free. If only all libraries had this level of excellence…

DevExpress WinForm (Commercial)

NDepend has also relied on DevExpress WinForm for almost a decade to improve the UI look and feel. NDepend is a Visual Studio extension and DevExpress WinForm makes smooth visual integration with Visual Studio. Concretely, thanks to this library we achieved the exact same Visual Studio theming and skinning, docking controls a la Visual Studio, menus, bars and special controls like BreadCrumb to explore directories. We have never been disappointed with DevExpress WinForm. The bugs we reported were fixed quickly, it supports high DPI ratio and it is rock solid in production.

Microsoft Automatic Graph Layout MSAGL (OSS)

NDepend has relied on MSAGL for several years to draw all sorts of graphs of dependencies between code elements including Call Graphs, Class Inheritance Graphs, Coupling Graphs, Path and Cycle Graphs…  This library used to be commercial but nowadays OSS.  Here also the bugs we reported were fixed quickly, it supports high DPI ratio and it is perfectly stable in production.

NRefactory (OSS)

NDepend used to have a C# Code Query LINQ editor in 2012, a few years before Roslyn became RTM. We wanted to offer users a great editing experience with code completion and documentation tooltips on mouse-hovering. At that time NRefactory was the best choice and it proved with the years to be stable in production. Nowadays Roslyn would certainly be a better choice, but since our initial investment NRefactory still does the job well, we didn’t feel the need (yet) to move to Roslyn.

 

Here are a few things we prefer to keep in-house:

Licensing

While there are libraries for licensing, these are vital, sensitive topics that require a lot of flexibility with time, and we preferred to avoid delegating it. This came at the cost of plenty of development/support and significant levels of acquired expertise. Even taking into account that these efforts could have been spent on product features, we still don’t regret our choice.

The licensing layer is a cornerstone in our relation with our users community and it cannot suffer from any compromise. As a side remark, several times I observed that the cost of developing a solid licensing layer postponed promising projects to become commercial for a while.

Persistence

As most of application, NDepend persists and restores a lot of data, especially the large amount of data in analysis results. We could have used relational or object databases, but for a UI tool embedded in VS, the worst thing would be to slow down the UI and make the user wait. We decided only optimal performance is acceptable for our users, and optimal performance in persistence means using custom streams of bytes. The consequence of this decision is less flexibility: each time our data schema evolves, we need to put in extra effort to keep ascendant compatibility.

I underline that most of the time it is not a good idea to develop a custom persistence layer because of the amount of work and expertise required. But taken account our particular needs and goals, I think we took the right decision.

Production Logs

I explained here about our production logs system. We consider it an essential component to making NDepend a super-stable product. Here also, we could have used a third-party library. We capitalize on our own logging system because, year after year, we customized it with a plethora of production information, which was required to help fix our very own problems. We kept the system lightweight and flexible, and it still helps us improve the overall stability and correctness of our products.

Dependency Matrix and Treemap UI Components

These UI components were developed years ago and are still up to date. Both then and now, I believe there is no good third-party alternative that meets all our requirements in terms of layout and performance. A few times, we received propositions to buy those components, but we are not a component provider and don’t have plans for that.

 

In this post I unveiled a few core choices we made over the years. We hope this information will be useful for other teams.

C# Version History: Exploring the Language History from Past to Present

C# Version History: Examining the Language Past and Present

I still remember my first look at C# in the early 2000s.  Microsoft had released the first major version of the language.  I recall thinking that it was Java, except that Microsoft made it, called it something else, and put it into Visual Studio.  And I wasn’t alone in this sentiment.  In an old interview, Java inventor James Gosling called it an imitation.  “It’s sort of Java with reliability, productivity, and security deleted,” he said.  Ouch.

A lot changes in 15 years or so.  I doubt anyone would offer a similar assessment today.  In that time, Java has released four major language versions, while C# has released six.  The languages have charted divergent courses, and C# has seen a great deal of innovation.  Today, I’d like to take a look back on the history of C# and highlight some of those key points.

What did the language look like in its earliest incarnations?  And how has it evolved in the years since?

Continue reading C# Version History: Examining the Language Past and Present

In Defense of Using Your Users as Software Testers

In most shops of any size, you’ll find a person that’s just a little too cynical.  I’m a little cynical myself, and we programmers tend to skew that way.  But this guy takes it one step further, often disparaging the company in ways that you think must be career-limiting.  And they probably are, but that’s his problem.

Think hard, and some man or woman you’ve worked with will come to mind.  Picture the person.  Let’s call him Cynical Chad. Now, imagine Chad saying, “Testing? That’s what our users are for!”  You’ve definitely heard someone say this at least once in your career.

This is an oh-so-clever way to imply that the company serially skimps on quality.  Maybe they’re always running behind a too-ambitious schedule.  Or perhaps they don’t like to spend the money on testing.  I’m sure Chad would be happy to regale you with tales of project manager and QA incompetence.  He’ll probably tell you about your own incompetence too, if you get a couple of beers in him.

But behind Chad’s casual maligning of your company lies a real phenomenon.  With their backs against the wall, companies will toss things into production, hope for the best, and rely on users to find defects.  If this didn’t happen with some regularity in the industry, it wouldn’t be fodder for Chad’s predictable jokes and complaints.

The Height of Unprofessionalism

Let’s now forget Chad.  He’s probably off somewhere telling everyone how clueless the VPs are, anyway.

Most of the groups that you’ll work with as a software pro would recoil in horror at a deliberate strategy of using your users as testers.  They work for months or years implementing the initial release and then subsequent features.  The company spends millions on their salaries and on the software.  So to toss it to the users and say “you find our mistakes” marks the height of unprofessionalism.  It’s sloppy.

Your pride and your organization’s professional reputation call for something else.  You build the software carefully, testing as you go.  You put it through the paces, not just with unit and acceptance tests, but with a whole suite of smoke tests, load tests, stress tests and endurance tests.  QA does exploratory testing.  And then, with all of that complete, you test it all again.

Only after all of this do you release it to the wild, hoping that defects will be rare.  The users receive a polished product of which you can be proud — not a rough draft to help you sort through.

Users as Testers Reconsidered

But before we simply accept that as the right answer and move on, let’s revisit the nature of these groups.  As I mentioned, the company spends millions of dollars building this software.  This involves hiring a team of experienced and proud professionals, among other things.  Significant time, money, and company stake go into this effort.

If you earn a living as a salaried software developer, your career will involve moving from one group like this to another.   In each of these situations, anything short of shipping a polished product smacks of failure.  And in each of these situations, you’ll encounter a Chad, accusing the company of just such a failure.

But what about other situations?  Should enlisting users as testers always mean a failure of due diligence?  Well, no, I would argue.  Sometimes it’s a perfectly sound business or life decision.

Continue reading In Defense of Using Your Users as Software Testers

Fixing Your Tangled Dependency Graph

I’ve written before about making use of NDepend’s dependency graph.  Well, indirectly, anyway.  In that post, I talked about the phenomenon of actual software architecture not matching the pretty diagrams people draw in Visio.  It reminds me of Helmuth von Moltke’s wisdom that no battle plan survives contact with the enemy.

Typically, architects conceive of wondrous, clean, and decoupled systems.  Then they immortalize this pristine architecture in Visio.  Naturally, print outs go up on the wall, and everyone knows what the system should look like.  But somehow, it never actually winds up looking like that. Continue reading Fixing Your Tangled Dependency Graph

Is There a Correct Way to Comment Your Code?

Given that I both consult and do a number of public things (like blogging), I field a lot of questions.  As a result, the subject of code comments comes up from time to time.  I’ll offer my take on the correct way to comment code.  But remember that I am a consultant, so I always have a knee-jerk response to say that it depends.

Before we get to my take, though, let’s go watch programmers do what we love to do on subjects like this: argue angrily.  On the subject of comments, programmers seem to fall roughly into two camps.  These include the “clean code needs no comments” camp and the “professionalism means commenting” camp.  To wit:

Chances are, if you need to comment then something needs to be refactored. If that which needs to be refactored is not under your control then the comment is warranted.

And then, on the other side:

If you’re seriously questioning the value of writing comments, then I’d have to include you in the group of “junior programmers,” too.  Comments are absolutely crucial.

Thins would probably go downhill from there fast, except that people curate Stack Overflow against overt squabbling.

Splitting the Difference on Commenting

Whenever two sides entrench on a matter, diplomats of the community seek to find common ground.  When it comes to code comments, this generally takes the form of adages about expressing the why in comments.  For example, consider this pithy rule of thumb from the Stack Overflow thread.

Good programmers comment their code.

Great programmers tell you why a particular implementation was chosen.

Master programmers tell you why other implementations were not chosen.

Jeff Atwood has addressed this subject a few different times.

When you’ve rewritten, refactored, and rearchitected your code a dozen times to make it easy for your fellow developers to read and understand — when you can’t possibly imagine any conceivable way your code could be changed to become more straightforward and obvious — then, and only then, should you feel compelled to add a comment explaining what your code does.

Junior developers rely on comments to tell the story when they should be relying on the code to tell the story.

And so, as with any middle ground compromise, both entrenched sides have something to like (and hate).  Thus, you might say that whatever consensus exists among programmers, it leans toward a “correct way” that involves commenting about why.

Continue reading Is There a Correct Way to Comment Your Code?