Throw exception at me!

I’ve been recently drawn twice into an open discussion on when to throw exception in application’s logic.
I’ve had my opinions, others have theirs but what lead me to this post is that such fundamental topic is extremely opinionated, even among same language/environment developers.
In next few paragraphs I’ll try to sum up major proposed approaches of using exceptions (both those which abuse them and those which antagonize them).
Examples will assume that you are not using models as property bags but you actually have logic in them (vide DDD). Having that in mind, we’ll skip the fact that most probably, user receives ‘first-line’ validation of inputs on the UI.

To simplify, let’s impersonate two popular approaches with two fictional developers: 💂 Cpt. Exception (throw exception carelessly) and 👑 King Status (rarely throw exception or not even at all; loves messages, statuses and enums as responses).

Let’s play around with few cases and think what might be right or wrong with each approach.

Use case: File access (and other I/O)

This is a common case when Cpt. Exception and King Status rarely disagree.
Whenever there is a problem on attempt to access file, that we do not have prior knowledge of (or its cheaper to throw), we just throw exception:

The good:
  • We mostly do not have further info with which we could work with – in most languages and libraries its rather a system exception/error that we can just handle for user and that’s all – exception as a way to go

We could’ve of course somehow translated exceptions to some status codes or responses but there is no reason of doing so in such case.

Use case: Change object property with restrictions

Let’s take a look on simple business case. We have a Product domain model (in DDD-like sense) that has a price. Price can be changed be user that is managing shop, but let’s put permissions for actions aside as they belong to application layer logic, rather than business logic.
Price of a product cannot be changed below certain level. Let’s assume it’s a level of profitability but it can be any other value that makes sense for business.
It cannot also change if product is no longer sold. It might be a policy of a company (archived products and so on) or just a simple requirement that it doesn’t make sense for users.

What would Cpt. Exception do? Probably throw exception on each case:

The good:
  • We throw exception when core business rule (price > level of profitability) is broken
  • We enforce change caller (probably application root) to react to an exception; there at least need to by some try-catch clause
The bad:
  • Exceptions are generally costly as opposed to some internal messages
  • We also throw on non-core business rule (cannot change if is no longer sold)
  • Commonly known pattern, know as try-catch-do_nothing can lead to exception being meaningless


What would King Status do? Introduce some sort of return enum or response to notify user with:

The good:
  • No overhead when compared to throwing an exception
  • Easier to deal with if you want to work with status of change somewhere else, not only deal with invalid change
  • If combined into some sort of response, can also store some sort of message what happened, similar to exception etc.
The bad:
  • Operation must always return some sort of status or response, even if everything went fine
  • Can be much more easily ommited (on purpose or by mistake) because most of languages do not enforce usage of values returned by methods, as opposed to try-catch when you throw exception
  • (minor issue) Makes validation break some languages features – for example we cannot return from C# property, therefore we need to change to plain old methods
Verdict?

I would generally mix up two approaches and throw on broken core business rule only while giving some sort of status (or even boolean return value) for non-core validations.
I like exception approach but I can see status/response pluses too.

Use case: Return entity of given identity

Let’s imagine two queries on our persistence layer, that we want to provide us with: category of given id and products from category of given id.


Cpt. Exception would do something like this I suppose:

Plain, good, old exceptions eh?
I can see at least one place when we could remove exception with no logic change at all.

Let’s take a look on status/response King Status came up with before pointing that out:

Uh, those statuses and responses all around again?
Feels quite ugly eventually, doesn’t it?
Also we need to keep in track with all those statuses that will come up, for all the flows of operation out there (or at least errors + default).

But! We can once again mix things up and try to leverage common sense with something like this:

We could also refine it further and return null (or empty array/collection) on second case if what we actually meant was “find products that have category of such id” instead of “find me category of that id and all of its products”.
A little difference but as always, it depends!

Drawing up conclusions

As I said, recently I’ve had some discussion on that topic, but I’ve made it to one more place to confront people opinions.
Together with other developers in Polish community, we came up with few ‘rules of a thumb’ that will make it easier to decide – to throw exception or not.

First things first

If you are joining ongoing project, find out what coding standards have been introduced and organizational decisions have been made.
Maybe you are not about to make a decision as it has been made already for you?
You can of course confront current state of things if you think it’s wrong and some thoughts below will help you out with that.
Keep in mind, that’s still my opinion, but maybe it will help you out making up your own.

When to throw exception:
  • If you cannot really do a thing with what happened – external services or I/O failure
  • If you have any missing operation preconditions (empty method parameters, empty ctor parameters etc.)
  • If you feel more like enforcing other developers working with your API to react on invalid operation/data (can be skipped by empty catch though)
  • If you do not expose exceptions to outside ‘world’, ie. your application root always handles exceptions before communicating them to outside
When not to throw exception:
  • If you’re about to throw a generic, base system exception, you’re actually better off not throwing them at all; only meaningful and understandable exceptions make sense. No one will parse your exceptions messages to find out what you meant before reporting to user.
  • If certain exception is often hit in certain place (no longer meaningful)
  • If operation is in application root and only possibility is that it will be thrown either to end user (web/desktop/mobile app) or to transport layer (web service endpoint)
  • If answering questions like “IsSomething”, “FindByPredicate” (no match); generally do not use exceptions as your business flow logic and decision branching tool
  • If you meant to return multiple different yet valid outcomes of certain operation (seriously, use responses or any other meaningful object instead)
Precautions on throwing exceptions:
  • Throwing an exception is costly. If performance is critical, try to avoid them (and move to lower level language perhaps?)
  • If something happens frequently, its not an exception (I’m duplicating this because it seems to be not so obvious to some)
  • Exceptions are not a way to communicate with user! They are meant to point places where application could perform invalid operation, based on conditions you do not expect, that later on could also lead to data with invalid state flying around. You are notified that you are meant to react on such occurence, that’s what they’re for.

And, finally…

“…throw exceptions at other developers, never at users.”

Unknown Twitter poster, 2016 (let me know if you know real author)

When git reset –hard doesn’t work


git


Sometimes things go wrong and we want to start from scratch. Provided you’re using Git as your version control system, it’s highly probable you’re a friend of git reset --hard.
However, I’ve found cases when git reset –hard doesn’t work. Things like clean or -f parameter doesn’t work either.
I did however found out, that sometimes on Windows machines, line endings like to live their own lives and switch randomly between CRLF and LF.
I found a solution I want to share with you. However, I do not see myself as a Git pro, so if you found out other one for such issue, let me know! 😇

First thought

First thought would be to just stop git from doing so.
Generally in either your global or repository config you have section called core. An entry called autocrlf resides there and is often responsible for behavior mentioned above.
Quick fix for this would be to just set the flag to false by calling in your repo (or adding --global after config for global scope):


If config change fails

Been here, seen that. It seems that sometimes there is an issue with line endings that is also driven by .gitattributes file, even if it is not present in repository!
A fix for this is to remove (non-exisiting) .gitattributes, then stage the change and then reset changes like you used to do:

Note: git add -A is necessary here and it can’t be changed to git add * because it won’t stage file deletion that we did with rm command.

If you do have .gitattributes included in your repository, you might want to actually tweak it with proper line endings per extension defined instead. 🔨

Visual Studio meets NDepend – use cases


NDepend


As a very long user of Visual Studio and a little less (but still long) user of Jetbrains Resharper, I’ve started to look out for a tools that would fit in my developer toolkit to cover most of the cases I encounter at work. I’ve decided to split them in general groups of my needs and then look out for tools that would help me in working things out.

One of them is decompilation of .dll, that I work with and would love to understand internally. I’ve started to use Resharper built in decompiler, but since I now own Red Gate Developer Bundle including famous Reflector, I choose it over R# in advanced scenarios.
Another one is definitely performance bottlenecks and general memory profiling. That’s were I rely on Red Gate’s product too.

But today’s post is not about those things. There was actually one tool that I really looked for few times already and failed to find. I was looking for a way to analyze my programs for code quality, meeting conventions I enforce and for general static code/program analysis.
I’ve tried few tools already, mostly free and the one that was actually closest to meet my requirements was StyleCop. It did its job, well… ok. But it was counter intuitive, lacking decent summary of analysis. Generally, UX sucked.
However, recently I’ve been contacted by Patrick Smacchia with an offer to try out his tool for general code analysis.
Let’s see then what happens when Visual Studio meets NDepend!


Review spoiler

What you probably expect here is classic functionality review, like in any other product review: we have this, and that, and that.
I chose to go the other way round and think of use cases where this tool actually fits.
My hopes are that it would make a little easier to decide, whether it fits your workflow, or not! 😉


Case I – Annual Code Quality Review


Use case

Team Leader or developer team as a whole wants to review code quality of a currently worked project to ensure it meets their criteria of ‘clean code’.

Proposed way of analysis

Depending on what we want to check, let’s scan our solution assemblies with chosen criterias and visualize everything with a heat map (called in NDepend ‘MetricTreemap’). As general Size rule I will choose # lines of code (LOC).

My proposed criterias are:

  • lines of code, per method (Level: Method | Color: # lines of code (LOC))
  • number of methods, per type (Level: Type | Color: # Methods)
  • Cyclomatic Complexity aka independent paths through source code, per type (Level: Type | Color: Cyclomatic Complexity (CC))
  • if API for external exposition percentage comment, per type (Level: Type | Color: Percentage Comment)

What do we get as a result?
As an output for every criteria we’ve chosen, we got a nice, colorful heat map representing places we need to take into consideration for refactoring. Example below of a map of lines of code, per method in a solution (gathered per assembly):

MetricTreemap


Proposed way of acting

With information we have and tools we mentioned in the beginning of the article, we now can do quite a lot to clean up our code.
Let’s take a too long method code smell that NDepend pointed us out. It will be easy to point out issues as we use a natural way of doing so – the closer to red color, the more serious problem we have.
Now, using power of Resharper to refactor the code, let’s extract a part of logic from too long method into another (possibly private) one:

  • Select part of logic you think is suited for extracting
  • Right-click -> Refactor -> Extract -> Extract Method…
  • Choose suitable name that will easily be recognizable for its responsibilities in a method we are extracting from
  • Voila!

If things get really messy, you would have to perhaps think of dividing the job to avoid technical debt. 😇
Please also note, that basic extracting mechanics are also available in Visual Studio (though not so good as in Resharper!).


Case II – Defining crucial, yet external dependencies


Use case

Throughout a lifetime of a project, team (or management, or both) can come up with an idea of switching few parts of current solution to meet new business needs (or pending deals).
Possible case could be migrating from EntityFramework to NHibernate (or other way round, or moving back to plain old SQL) or switching current JSON parsing library or perhaps moving to .NET Core?

Proposed way of analysis

Let’s think of a case when we decided to migrate from EntityFramework to other ORM. Before we even think of how complicated it would be to replace dependency, we would need to analyze how deep that dependency is. In general, first thought would be to check our data access layer and look upon its dependencies.
Let’s give it a shot then and see Dependency Graph that NDepened provides us with, when we right click on our data layer on graph and choose Keep only nodes that I use:

data-access-dependencies

Alright, we can see clearly that there is dependency to Entity Framework up here. But what if our implementation is leaky?
We should probably see if Entity Framework is not referenced by other layers of our solution.

Let’s go back to all assemblies on dependency graph by choosing first icon on the left in DependecyGraph menu: View Assemblies view-assemblies.
Now let’s find again Entity Framework and now choose Keep only nodes that use me.
We should end up with a dependency graph of what is really using our beloved (but to be migrated from) ORM framework:

using-entity-framework

We now clearly see, that there is one more direct dependency (GatewayApi in this particular case) to the ORM that we want to swap that we need to consider when making decisions on changing technology.


Proposed way of acting

Since we already defined possible points of problems – including ORM leaking out of data access layer – we need to analyze the complexity of code that we would need to rewrite. NDepend could help us here too a little, if we analyze actual complexity of dependency usage with previously used heat maps or change size of nodes in dependency graph to visualize how many calls to particular dependency we have.
This is of course where NDepend will end up being useful, as out of analysis stage we actually need to get into code and make decisions.
Great thing is that we already have an insight on the problem and can decide having broader knowledge on how many places can actually go down, when anything (or everything 😇) goes wrong.


Other use cases and verdict

While those two mentioned above were the one that immediately came up into my mind, I can think of few other (yet less probable) cases where Visual Studio toolkit and NDepend marriage would bloom.
We could for example troubleshoot performance issues (but not prematurely!) using RedGate’s performance toolkit for .NET developers and use it along with Cyclomatic Complexity, amount of memory allocated per type and number of IL calls that NDepend can visualize us with Metric Treemap.

Verdict?
Would I recommend using NDepend for analyzing and keeping in bounds projects that we’re working on? Definitely!
Can I see any points of improvement for NDepend? Yes, perhaps. Dependency graph UX needs a little more improvement. I couldn’t find ‘Search…’ option in it too, what made it a nightmare to find smaller node.
But, in the end, I guess it all goes down to the point where we need to share our feedback with Patrick (the creator) to keep the improvements coming.