NDepend

Improve your .NET code quality with NDepend

A problem with extension methods

We like extension methods. When named accordingly they can both make the caller code clearer, and isolate static methods from classes on which they operate.

But when using extension methods, breaking change can happen, and this risk is very concrete, it actually just happened to us.

Since 2012, NDepend.API proposes a generic Append() extension:

Two default rules use this extension method: Avoid namespaces dependency cycles and Avoid types initialization cycles

Last month, on Oct 17th 2017, Microsoft released .NET Framework v4.7.1 that implements .NET Standard 2.0. Around 200 .NET Standard 2.0 were missing in .NET Framewok v4.6.1, and one of those missing API is:

Within NDepend, rules, quality gates, trend metrics … basically everything, is a C# LINQ query stored as textual and compiled and executed on-the-fly. Since the compilation environment uses both namespaces NDepend.Helpers and System.Linq, when running NDepend on top of the .NET Framework v4.7.1, both Append() extension methods are visible. As a consequence, for each query calling the Append() method, the compiler fails with:

Hopefully a user notified us with this problem that we didn’t catch yet and we just released NDepend v2017.3.2 that fixes this problem Only one clean fix is possible to make it compatible with all .NET Framework versions: refactor all calls to the Append() extension method,  into a classic static method invocation, with an explanatory comment:

We expect support on this within the next weeks and months when more and more users will run the .NET Fx v4.7.1 while not changing their rules-set. There is no lesson learnt, this situation can happen and it happens rarely, this shouldn’t prevent you from declaring and calling extension methods. The more mature the frameworks you are relying on, the less likely it’ll happen.

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

Are Code Rules Meant to Be Broken?

If you’ve never seen the movie Footloose, I can’t honestly say I recommend it.  If your tastes run similarly to mine, you’ll find it somewhat over the top.

A boy from the big city moves to a quiet country town.  Once there, he finds that the town council, filled with local curmudgeons, has outlawed rock music and dancing.  So follows a predictable sequence of events as the boy tries to win his new town over and to convince them of the importance of free expression.  You can probably hear his voice saying, “come on, Mr. Uptighterton, rules are made to be broken!”

Today, I’d like to explore a bit the theme of rules and breaking them.  But I’ll move it from a boy teaching the people from American Gothic to dance and into the software development shop and to rules around a codebase.

Perhaps you’ve experienced something similarly, comically oppressive in your travels.  A power mad architect with a crazy inheritance framework.  A team lead that lectures endlessly about the finer points of Hungarian notation.  Maybe you’ve wanted to grab your fellow team members by the shirt collars, shake them, and shout, “go on, leave the trailing underscore off the class field name!”

If so, then I sympathize and empathize.  Soul crushing shops do exist, seeking to break the spirits of all working there.  In such places, rule breaking might help if only to shake people out of learned helplessness and depression.  But I’m going to examine some relatively normal situations and explore the role of rules for a software team.

Continue reading Are Code Rules Meant to Be Broken?

What Metrics Should the CIO See?

I’ve worked in the programming industry long enough to remember a less refined time.  During this time, the CIO (or CFO, since IT used to report to the CFO in many orgs) may have counted lines of code to measure the productivity of the development team.  Even then, they probably understood the folly of such an approach.  But, if they lacked better measures, they might use that one.

Today, you rarely, if ever see that happen any longer.  But don’t take that to mean reductionist measures have stopped.  Rather, they have just evolved.

Most commonly today, I see this crop up in the form of automated unit test coverage.  A CIO or high level manager becomes aware of generally quality and cadence problems with the software.  She may consult with someone or read a study and conclude that a robust, automated test suite will cure what ails her.  She then announces the initiative and rolls out.  Then, she does the logical thing and instruments her team’s process so that she can track progress and improvement with the testing initiative.

The problem with this arises from what, specifically, the group measures and improves.  She wants to improve quality and predictability, so she implements a proxy solution.  She then measures people against that proxy.  And, often, they improve… against that proxy.
Continue reading What Metrics Should the CIO See?

Alternatives to Lines of Code (LOC)

It amazes me that in 2016, I still hear the occasional story of some software team manager measuring developer productivity by committed lines of code (LOC) per day.  In fact, this reminds me of hearing about measles outbreaks.  That this still takes place shocks and creates an intense sense of anachronism.

I don’t have an original source, but Bill Gates is reputed to have offered pithy insight on this topic.  “Measuring programming progress by lines of code is like measuring aircraft building progress by weight.”  This cuts right to the point that “more and faster” does not equal “fit for purpose.”  You can write an awful lot of code without any of it proving useful.

Before heading too far down the management criticism rabbit hole, let’s pull back a bit.  Let’s take a look at why LOC represents such an attractive nuisance for management.

For many managers, years have passed since their days of slinging code (if those days ever existed in the first place).  So this puts them in the unenviable position of managing something relatively opaque to them.  And opacity runs afoul of the standard management playbook, wherein they take responsibility for evaluating performances, forecasting, and establishing metric-based incentives.

The Attraction of Lines of Code

Let’s consider a study in contrasts.  Imagine that you took a job managing a team of ditch diggers.  Each day you could stand there with your clipboard, evaluating visible progress and performance.  The diggers that moved the most dirt per hour would represent your superstars and the ones that tired easily and took many breaks would represent the laggards.  You could forecast milestones by observing yards dug per day and then extrapolating that over the course of days, weeks, and months.  Your reports up to your superiors practically write themselves.

But now let’s change the game a bit.  Imagine that all ditches were dug purely underground and that you had to remain on the surface at all times.  Suddenly accounts or progress, metrics, and performance all come indirectly.  You need to rely on anecdotes from your team about one another to understand performance.  And you only know whether or not you’ve hit a milestone on the day that water either starts draining or stays where it is.

If you found yourself in this position suddenly, wouldn’t you cling to any semblance of measurability as if it were a life preserver?  Even if you knew it was reductionist, wouldn’t you cling?  Even if you knew it might mislead you?  Such is the plight of the dev manager.

In their world of opacity, lines of code represents something concrete and tangible.  It offers the promise of making their job substantially more approachable.  And so in order to take it away, we need to offer them something else instead.

Continue reading Alternatives to Lines of Code (LOC)

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)

global coding standards abstract

How to Get Developers to Adopt Coding Standards

If you’re a manager, there’s a decent chance that the subject of coding standards makes you want to bang your head against a wall repeatedly.  If you’re a developer, you can probably understand why this is true of your manager, if you think about it.

The group coding standard has the following properties.

  • It’s extremely technical and granular.
  • Developers tend to squabble about it.
  • If it produces any business value, it does so obliquely and theoretically, from management’s perspective.

Thus, if I’m a manager, there’s this inscrutable document out there that causes my team to argue, and whose existence I must take on faith to be a good thing.  As you can see, it doesn’t start out on my good side.

Do Coding Standards Matter?

There are all manner of opinions and arguments to be found on the internet as to why coding standards matter (or don’t).  I’ve written about the subject myself from time to time (such as: Bringing Objectivity to Clean Code.).  So, without belaboring the point, I’ll make the quick business case for it.

The purpose of a coding standard, at its core, is twofold:

  1. It promotes maintainability by making all code look similar and familiar to all developers.
  2. It standardizes approaches that promote correct code (and avoid incorrect code).

Thus, on the whole, the coding standard makes the total cost of ownership of the codebase decrease by some amount ranging between 0 and “indeterminate.”  As an outside party, you simply have to take on faith that there is an ROI and that the amount of time wasted in arguments, complaining, and compliance is offset by the reduced troubleshooting and onboarding times.

And, in my experience, it generally is.  Notwithstanding pouting and bickering that happens early in the project and makes life unpleasant, it’s better to have these things than not to have them.  The key, then, becomes minimizing the cost of having the standard.  And you do this by securing compliance with the least amount of heartburn for all involved.

So how do you do that?  How do you convince the developers to buy in with a minimum of resistance and friction?

Continue reading How to Get Developers to Adopt Coding Standards

The Better Code Book – Our MVPs of 2015

We firmly believe spaghetti belongs on the dinner table and not in code. Our mission when starting NDepend was to create a tool to make best coding practices easier to maintain and improve. Writing has always been part of our message (see Patrick Smacchia’s work on CodeBetter.com) and we are proud to present our favorite pieces of writing from around the web in the last year, collected in what we are calling the Better Code Book.

We wanted to focus not only on how people use NDepend to improve their code for developers and architects, but also how to use static analysis in a broader, management sense. We are extremely grateful for our contributors in this project. Let us introduce them:

Bjørn Einar Bjartnes is a developer at the Norwegian Broadcasting Corporation. His current role is a backend developer at the API team, serving web, mobile, TV clients and more metadata about programs- and video-streams. He holds a MSc in Engineering Cybernetics and has a background from the petroleum industry, which has probably shaped his view on systems design. Also, Bjørn is active in the local F# Meetup and a proud member of the lambda club, playing with all things useless related to computers. You can also follow him on Twitter: @bjartnes

Jack Robinson is a twenty-something student in his final year of a degree in Software Engineering at Victoria University of Wellington. Currently an Intern Developer at Xero, he enjoys writing clean code, playing a board game or two with his friends, or just sitting down and watching a good film. You can read not just his musings on computer science, but also reviews on films and more at his website jackrobinson.co.nz

Prasad Narravula is a programmer, architect, consultant, and problem-solving leader.  He helps teams in agile development essentials- feedback loops to fail fast, enabling (engineering) practices, iterative and incremental design, starting at the right place, discovery, and learning. When time permits, he writes at ObjectCraftworks.com.

Erik Dietrich, founder of DaedTech LLC, is a programmer, architect, development coach, writer, Pluralsight author, and technologist. You can read his writing and find out more about him at http://www.daedtech.com/ and you can follow him on Twitter @daedtech.

Anthony Sciamanna is a software developer from Philadelphia, PA who has worked in the industry for nearly 20 years. He specializes in leading and coaching development teams, improving development practices for cross-functional teams, Test-Driven Development (TDD), unit testing, pair programming, and other Agile / eXtreme Programming (XP) practices. He can be contacted via his website: anthonysciamanna.com

Tomasz Jaskula is a software craftsman, founder and organizer of Paris user groups for F# and Domain Driven Design. He focuses on creating software delivering true business value which aligns with the business’s strategic initiatives and bears solutions with clearly identifiable competitive advantage. He is currently working for a big French bank building reactive applications in F# and C#. In his free time, he runs a startup project on applying machine learning with F# to the recruitment field, speaks at conferences and user groups, and writes blogs and articles for a French magazine for coders called “Programmez !” You can visit his site jaskula.fr

Continue reading The Better Code Book – Our MVPs of 2015

With Code Metrics, Trends are King

Here’s a scene that’s familiar to any software developer.  You sit down to work with the source code of a new team or project for the first time, pull the code from source control, build it, and then notice that there are literally thousands of compiler warnings.  You shudder a little and ask someone on the team about it, and he gives a shrug that is equal parts guilty and “whatcha gonna do?”  You shake your head and vow to get the warning situation under control.

If you’re not a software developer, what’s going on here isn’t terribly hard to understand.  The compiler is the thing that turns source code into a program, and the compiler warning is the compiler’s way of saying, “you’ve done something icky here, but not icky enough to be a show-stopping error.”  If the team’s code has thousands of compiler warnings, there’s a strong likelihood that all is not well with the code base.  But getting that figure down to zero warnings is going to be a serious effort.

As I’ve mentioned before on this blog, I consult on different kinds of software projects, many of which are legacy rescue efforts.  So sitting down to a new (to me) code base and seeing thousands of warnings is commonplace for me.  When I point the runaway warnings out to the team, the observation is generally met with apathetic resignation, and when I point it out to management, the observation is generally met with some degree of shock.  “Well, let’s get it fixed, and why is it like this?!”  (Usually, they’re not shocked by the idea that there are warts — they know that based on the software’s performance and defect counts — but by the idea that such a concrete, easily metric exists and is being ignored.)

Continue reading With Code Metrics, Trends are King

The Most Important Code Metrics You’ve Never Heard Of

Oh, how I hope you don’t measure developer productivity by lines of code. As Bill Gates once ably put it, “measuring software productivity by lines of code is like measuring progress on an airplane by how much it weighs.”  No doubt, you have other, better reasoned code metrics that you capture for visible progress and quality barometers.  Automated test coverage is popular (though be careful with that one).  Counts of or trends in defect reduction are another one.  And of course, in our modern, agile world, spring velocity is ubiquitous.

But today, I’d like to venture off the beaten path a bit and take you through some metrics that might be unfamiliar to you, particularly if you’re no longer technical (or weren’t ever).  But don’t leave if that describes you — I’ll help you understand the significance of these metrics, even if you won’t necessarily understand all of the nitty-gritty details.

Perhaps the most significant factor here is that the code metrics I’ll go through can be tied, relatively easily, to stakeholder value in projects.  In other words, I won’t just tell you the significance of the metrics in terms of what they say about the code.  I’ll also describe what they mean for people invested in the project’s outcome.

Type Rank

It’s possible that you’ve heard of the concept of Page Rank.  If you haven’t, page rank was, for a long time, the method by which Google determined which sites on the internet were most important.  This should make intuitive sense on some level.  Amazon has a high page rank — if it went down, millions of lives would be disrupted, stocks would plummet, and all sorts of chaos would ensure.  The blog you created that one time and totally meant to add to over the years has a low page rank — no one, yourself included, would notice if it stopped working.

It turns out that you can actually reason about pieces of code in a very similar way.  Some bits of code in the code base are extremely important to the system, with inbound and outbound dependencies.  Others exist at the very periphery or are even completely useless (see the section below on dead code).  Not all code is created equally.  This scheme for ranking code by importance is called “Type Rank” (at least at the level of type granularity — methods can also be ranked).

You can use Type Rank to create a release riskiness score.  All you’d really need to do is have a build that tabulated which types had been modified and what their type rank was, and this would create a composite index of release riskiness.  Each time you were gearing up for deployment, you could look at the score.  If it were higher than normal, you’d want to budget extra time and money for additional testing efforts and issue remediation strategies.

Cohesion

Cohesion of modules in a code base can loosely be described as “how well is the code base organized?”  To put it a bit more concretely, cohesion is the idea that things with common interest are grouped together while unrelated things are not.  A cohesive house would have specialized rooms for certain purposes: food preparation, food consumption, family time, sleeping, etc.  A non-cohesive house would have elements of all of those things strewn about all over the house, resulting in a scenario where a broken refrigerator fan might mean you couldn’t sleep or work at your desk due to noise.

Keeping track of the aggregate cohesiveness score of a codebase will give you insight into how likely your team is to look ridiculous in the face of an issue.  Code bases with low cohesion are ones in which unrelated functionality is bolted together inappropriately, and this sort of thing results in really, really odd looking bugs that can erode your credibility.

Imagine speaking on your team’s behalf and explaining a bug that resulted in a significant amount of client data being clobbered.  When pressed for the root cause, you had to look the person asking directly in the eye and say, “well, that happened because we changed the font of the labels on the login page.”

You would sound ridiculous.  You’d know it.  The person you were talking to would know it.  And you’d find your credibility quickly evaporating.  Keeping track of cohesion lets you keep track of the likelihood of something like that.

Dependency Cycles

So far, I’ve talked about managing risk as it pertains to defects: the risk of encountering them on release, and the risk of encountering weird or embarrassing ones.  I’m going to switch gears, now, and talk about the risk of being caught flat-footed, unable to respond to a changing environment or a critical business need.

Dependency cycles in your code base represent a form of inappropriate coupling.  These are situations where two or more things are mutually dependent in an architectural world where it is far better for dependencies to flow one way.  As a silly but memorable example, consider the situation of charging your phone, where your phone depends on your house’s electrical system to be charged.  Would you hire an electrician to come in and create a situation where your house’s electricity depended on the presence of your charging phone?

All too often, we do this in code, and it creates situations as ludicrous as the phone-electrical example would.  When the business asks, “how hard would it be to use a different logging framework,” you don’t want the answer to be, “we’d basically have to rewrite everything from scratch.”  That makes as much sense as not being able to take your phone with you anywhere because your appliances would stop working.

So, keep an eye out for dependency cycles.  These are the early warning light indicators that you’re heading for something like this.

Dead Code

One last thing to keep an eye out for is dead code.  Dead code is code that can never possibly be called during the running application’s lifecycle.  It just sits in your codebase taking up space to no good end.

That may sound benign, but every line of code in your code base carries a small, cognitive maintenance weight.  The more code there is, the more results come back in text searches of the code base, the more files there are to lose and confuse developers, and the more general friction is encountered when working with the system.  This has a very real cost in the labor required to maintain the code.

Use Code Metrics Wisely

These are metrics about which fewer people know, so the industry isn’t rife with stories about people gaming them, the way it is with something like unit test coverage.  But that doesn’t mean they can’t be gamed.  For instance, it’s possible to have a nightmarish code base without any actual dead code — perversely, dead code could be eliminated by finding everything useless in the code base and implementing calls to it.

The code metrics I’ve outlined today, if you make them big and visible to all, should serve as a conversation starter.  Why did we introduce a dependency cycle?  Should we be concerned about the lack of cohesion in modules?  Use them in this fashion, and your group can save real money and produce better output.  Use them in the wrong fashion, and they’ll be just another ineffective management bludgeon straight out of a Dilbert comic.