The C# Null Coalescing Operator

Introduction

A the ?? operator is a binary operator that is used to simplify checking for null values.

If the left operand is not null, it returns the left operand, otherwise it returns the right operand.

For example:

This means that:

Is equivalent to:

And is even shorter than:

The ?? operator is right-associative, which means that it is evaluated from right to left. This means that:

is evaluated as:

Rules

  • Arguments can be reference types or nullable types.
  • If both arguments are constant, the result is not considered to be a constant.
  • Both arguments must be of the same type.

Uses

Assigning a Non-Nullable Type from a Nullable Type

int result;
int a? = null;
result = a ?? 1; // Assigns 1 to result.

Lazily Instantiated Properties

Avoiding Double Evaluation
Chaining

References

Take Time to Go Fast

Imagine that you have to drive a long distance as fast as possible. Do you just jump in your car and put your foot down?

  • You won’t get there fast if you run out of fuel. You need to take time to fill up.
  • You won’t get there fast if you have an accident. You need to take time to drive safely.
  • You won’t ge there fast if you have to come back because you’ve forgotten something. You need to take time to pack properly.
  • You won’t get there fast if you pick a poor route. You need to take time to look at the map / program the SatNav.

We all know that, when driving, we need to take time to go fast.
Why don’t we understand the same thing about writing software?

HTML CSS and Real Programming Languages

It is a universal rule:
Wherever people talk about web programming languages:

  1. Someone will mention HTML and CSS
  2. Someone else will protest that HTML and CSS are not programming languages

But, does it matter?

A True Story

I once spent a few months developing a complex performance management system using a “proper” programming language. It automated the process of gathering data from various other systems, performed various manipulations on that data and then presented the results in a simple table, a kind of balanced scorecard.
Once it was live, a senior manager saw a tool written for a similar business, and asked if we could replace what I had written using their alternative. Furthermore, he was upset that I’d spent weeks developing my solution, where this new app had been written in a matter of days.
Further investigation revealed that the manager’s preferred option was all presentation with no substance: there were lots of colours and icons and graphs, but there was absolutely no logic behind them. All the data had to be gathered and manipulated manually. Despite the pretty interface, the application was essentially useless.
I’m happy to say that the manager in question was persuaded that my approach was the one that met his real business needs.

The Importance of Real Programming Languages

Now, as any CS graduate will know,  “real” programming languages are Turing Complete. As a proper sad geek, I find this sublimely fascinating. It means that, for any program written in a T-C language, a functionally equivalent program can be written in any other T-C language. Of course, this isn’t to say that all languages are the same. The each have their strengths and weaknesses that make them more or less suitable for certain tasks. However, I/O aside, this means that all programs can be written in all true programming languages.
Of course, the same isn’t true of a markup language like HTML or CSS. In fact, there are whole classes of problem that these languages simply can’t solve. Where I can program anything I want in a true programming language – including layout engines – it just isn’t possible to achieve the same things with languages that aren’t T-C.
(As an aside, some people think that the fact that HTLM and CSS are declarative rather than imperative actually nakes a difference here. But, that really isn’t the point. It is possible for a declarative language to be T-C and for an imperative language to be not T-C)

The Importance of Presentation

Unfortunately, when programmers get sniffy about HTML and its ilk not being true programming languages, there is often an implication that skills in HTML, CSS etc. are somehow inferior to skills in “real” programming languages. This is a serious mistake.
In my story, the senior manager felt that design was very important to him, to the extent that he was initially prepared to overlook function in its favour. Now, if this were an isolated incident, I might suggest that the manager was just being foolish.
But it wasn’t.
Time and again, I’ve met users who are impressed by flashy graphics and whizzy widgets, but unimpressed by raw functionality and my technical achievements. I think that there are several lessons to learn here:

  • People evaluate software on criteria that they understand. They often understand the difference between good-looking and ugly, but rarely appreciate technical nuances.
  • People are fooled by appearances. This may not be a good thing, but it is a reality that we must live with.
  • Appearances influence the way people feel about software. The way people feel about software is important to them. Indeed, people sometimes prefer software that makes them feel good over software that is functionally superior. Indeed, they might well be more productive with feel-good tools than with technically superior tools. To this extent, our users are not being fooled. They are actually making a wise and thoughtful choice.
  • As programmers, we often neglect the role of presentation as we focus on function. To some extent, this is right and proper. However, it is important to recognize that there is another dimension to our work that is important to our customers.

So, presentation-oriented languages (HTML, CSS) are important. The value added by tose who can use these tools effectively should not be underestimated.

What is the Difference, Really?

The interesting thing is that, to most people, none of this T-C business matters. The important difference between a programming language and HTLM / CSS is this:

HTML and CSS describe presentation, whereas programming languages describe function.

And both of these things matter.

Why are Programmers Pedantic About it All?

So, why do programmers spend so much passion on defending their position that HTML and CSS are not programming languages? There are lots of reasons.

  1. Because there really is a real and fundamental difference, as outlined above.
  2. Programmers spend a great deal of time, effort and money developing their skills. People naturally value the things in which they invest (“your heart is where your money is”).
  3. Programmers often feel the need to justify the amount of time it takes to produce results compared to the rapid results achieved by UI designers. In order to do this, they need to draw a distinction between what the two groups actually do.
  4. Employers need to apply the right people to the right jobs. Unless we clarify the (often technical) differences, managers easily make the wrong calls.

Is it Always Appropriate to be Pedantic?

Let’s face it, as programmers we’re a naturally pedantic lot. It goes with the territory. It doesn’t help that many of us have been burned when non-programmers have failed to understand what we do.
Nevertheless (and to be honest, this goes against my natural instincts), I don’t think we need to call people out whenever they slip over every little distinction.

The important things here are context and perspective.

I’m told that, to a biologist, a tomato is a fruit. But when I buy them in the supermarket, I look for them amongst the veg. Why? Because the technical distinction doesn’t matter in that particular context. Moreover, the distinction would actually get in the way if I daft enough to include tomatoes in a fruit salad.
It is the same with computer languages. There are times when the difference between programming languages and other languages really does matter. Quite often, however, we can all communicate perfectly effectively when just lump them all in together. In the case when people are asking what programming languages they need to lear to do web development, it really didn’t matter what languages were true programming languages and which were not. Pointing out the distinction won’t advance the discussion in any way. Indeed, in many cases, pedantry can stir up negative feelings and damages relationships… as my wife will gladly testify!

When to Make a Stand?

A preacher friend of mine once delivered a sermon entitled:

Is this a hill worth dying to be on?

He was referring to generals who make a strategic assessment over which battles are which fighting: are the gains worth the costs?

  • Is it really worth interrupting the flow of the discussion to make this distinction?
  • Does my pedantry stem from a sense of arrogance or from past hurt?
  • Do my comments value the skills of others as well a my own?

Of course, there are times when distinctions need to be made. My aim is that, when I make a contribution, it will add value to our collective endeavours.
That is, after all, the job of a every real programmer.
(This article is based on my answer to a question on Programmers)

Because there really is a real and fundamental difference, as outlined above.

BizTalk: Problem with Business Rules not Working

The Problem

If you’re having trouble getting Business Rules to work, remember that you can test your rules in the Business Rules Composer. Microsoft provides details on how to do so on MSDN.
However, I recently found that the business rules that I was testing were known to be correct (they worked on another machine) but were not being invoked on my PC.

The Solution

The reason that they were not working was because my PC was not configured correctly. I needed to add a new DWORD registry key:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\BusinessRules\3.0\StaticSupport = 1
Richard Seroter’s blog gives more details on the purpose of this key.

Practice: Don't Repeat Yourself (DRY)

Description

To eliminate information repetition of all kinds.

Every piece of knowledge must have a single, unambiguous, authoritative representation within a system. Andrew Hunt and David Thomas (2000) The Pragmatic Programmer

This does not only apply to code:

  • Copy-paste (surface features of the code are the same)
  • Logical / Functional (the same logical process, but surface features vary)
  • Data (the same information in two different places)

But also to:

  • Documentation (requirements, for users etc.)
  • Software architecture
  • The software development process

To help you remember this practice, write out 100 times, “I will not repeat myself”.

Solutions

  • Repetition in process calls for automation
  • Repetition in logic calls for abstraction

Alternative Names

  • Single Source of Truth (SSOT)
  • Single Point of Truth (SPOT)

Forces Against

  • Ignorance of parts of the system (I didn’t know it was already there!)
  • Reliance on surface information rather then deep understanding. Assumption that is different because it looks different.
  • Reuse of existing information from several non-colsolidated sources.

Problem Overcome

  • Duplication requires that all copies must be maintained
  • Leads to larger code / data base, making finding defects more difficult

Contraindications

  • Automated derivation (eg. caches, generated code / documentation) where the original source is well know.
  • Certain optimisation techniques

Part of Development Lifecycle

  • All

Related Practices

  • YAGNI

Examples

  • Code reuse: Classes, subroutines, code libraries
  • Data Normalisation
  • Design Patterns

References

  • N/A

 

Some Comments on Comments

Code is communication, and comments can make a world of difference when it comes to making code clear and readable. Every seasoned developer has seen code that could have been made clearer with a few well-placed comments. At the same time, it isn’t unusual to find code that is littered with comments that are stale, unclear, unhelpful or just downright irritating.

Nothing can be quite so helpful as a well-placed comment Robert C Martin

Knowing when to comment and how to make a comment is an art, and one that clearly separates good programmers from poor ones. It is worth taking time, then, to review our practice in comment-writing. This is particularly true for those of us who have been around for a while. Coding practices and technologies have changed, and some of our old habits are inappropriate in modern programming environments.
The rest of this article outlines my current thinking on code comments, based on my research and experience as a programmer.

The Purpose of Comments

The purpose of comments is to help to make code readable.
For this reason, comments should be:

  • Terse
  • Readable
  • Helpful
  • Correct
  • Unambiguous
  • Maintainable
  • Placed as near as possible to the code that they’re commenting on

Unhelpful Comments

Comments that should be code

As far as possible, code should be self-describing. This implies that comments should explain why, because code already explains how.

Comments do not make up for bad code Robert C. Martin

  • Comments should not repeat what the code already says, for example:

  • Where possible, refactor code to eliminate comments
    • Better function / variable names can eliminate the need for comments
    • A simpler architecture or structure requires less commentary
    • Shorter methods eliminate the need for closing brace comments, like this:

    • Split functions / classes into smaller units to eliminate comments that act as section headers or division markers

Comments that should be part of source control

…and if you aren’t using source control then you already have a bigger problem than bad comments!

  • Attributions (developer’s names)
  • Code version numbers
  • Journal comments (who did what and when)
  • Commented-out code
  • History of changes, like this:

Misleading comments

One of the biggest problems with comments is that they rot over time. The comment you write today may not match the code you write tomorrow.

  • Ambiguous or unclear statements
  • Outdated information
  • Comments that don’t apply to the present context
  • Information that applies only to specific cases
  • Comments that are just plain wrong

Comments that create unnecessary work for the author / maintainer

If comments take up too much time to maintain then they are less likely to be maintained.

  • Non-trivial formatting. Insisting, for example, that all comments are in neat boxes made of asterisks
  • Mandated comments – that your boss / process / toolset tells you should be there but which add no real value, for example:

  • Markup in comments (except when it is required by tools that generate documentation)

Comments that create unneccesary work fort the reader

  • Noisy comments
    • Comments that contain much information / irrelevant information
    • Chatty comments. Blah, blah, blah.
  • Poor spelling / punctuation in comments
  • Non-local information (such as information how callers will use a value returned from a function – that’s the caller’s business)

Unprofessional comments

  • Anything offensive, derogatory or insulting
  • Jokes / cultural references should be included sparingly, sensitively and kept short and/or clearly delimited as such

The practice of inserting jokes or cultural references in comments is a matter of some debate. Some people think they are invariably unprofessional, as they convey a lack of seriousness and waste time for both their authors and readers. Others (myself included) feel that they are conducive to a good working atmosphere. However, they should be easy to skip over for readers of the code, and should never risk your professional reputation nor that of your employer/customer.

Beneficial Comments

File headers

  • Copyright and other legal notices (everything else can be omitted)

Explanations and clarification

  • When you can’t explain something in code (by using a function name, for example)
  • Explanation of the intent of code
  • Clarifying the reason for a decison
  • Clarification of code you can’t alter, like library call results

To draw attention

  • Warnings of consequences
  • Drawing attention to important things that appear inconsequential

Comments parsed by development tools

  • TODOs
  • Documentation markup

Comments that save the reader time

Some of this last set may be a little controversial, but I find them beneficial:

  • Brief explanations of concepts, algorithms etc. so save the reader referring to external documentation
  • Comments that help interpret the solution in terms of the problem domain
  • Comments that signpost external documentation (such as urls)

Further Reading

  • “Clean Code” by Robert C. Martin

Best Practices: Why aren't they followed?

We all know it is a good idea to follow best practices, but we also know that we don’t always follow it. I find that interesting.
Now, when I want to change something, I find it helpful to understand why things are the way they are. It is worth asking, then, why don’t we follow best practice? And what can I do about it?

Ignorance

Simply not knowing what constitutes best practice appears to be a reasonable excuse for not following best practice. For someone new to the discipline, this is fair. But what about those of us who have been in the profession for some time? Is it enough to argue that nobody has shown us the way? That nobody has made the information we need available to us? Well, I do sympathize with people who face these issues. But only to some extent.
The truth is, my career is my responsibility. I have a professional responsibility to develop our skills in our chosen craft, and we live in an age where this information is more readily available than it might have been in the past. I can choose to learn if I want to.

Pressure to Deliver

My client needs a solution delivered yesterday, and my family needs me at home in the evening. When am I supposed to learn, let alone implement, best practices?
Actually, the problem for the company is not lack of time. It is lack of understanding. The reason I say this is that best practices, by definition, deliver more value for less cost. If they didn’t, they wouldn’t be best practices. The way to deal with this, issue, then, is to find ways to communicate the benefits of best practice to the people around us – having firmly established what best practice actually is as it applies to our situation. We need to persuade managers that a small investment now – a delayed delivery – will reap long-term benefits.

Take time to go fast.

Part of the solution is to recognize  that developing my skills isn’t my responsibility alone. My employer has a responsibility to support my personal development – to give me time and resource to grow so that I can add more value to the company. Sometimes, however, organizational leaders need to be reminded of this. I may have to persuade my managers that allowing me resource to grow will benefit them in the long term.

Other Developers

I am led to believe that, sometimes, other professionals actually foster ignorance of best practice. They may feel threatened by having to learn new skills or by their own practice being challenged. They may feel that they already know best, that their methods are tried and tested. They may have worked hard to develop their own practice, and as a result have formed a strong emotional attachment to the way things are done at the moment. I imagine that it takes strong leadership skills to overcome such challenges. If you face this problem (and you’re sure that the practices you propose actually are the best ones) you may want to take a course in influencing people along with your studies in professional practice. As for me, I’m fortunate that I work with like-minded people. Assuming my colleagues don’t think that I’m one of those…

Conclusion

First, I see that there are two directions from which my behavior is influenced:

  • From within – by my own assumptions and feelings and understanding
  • By my external environment – the systems and relationships that surround me

I recognize that I need to deal with both of these areas.
Second,  it seems that professional quality is not a technical problem but a people problem. To develop it, I need to develop myself and my relationships with the people around me. Which is interesting in itself. The reason I got into technology because I didn’t really see myself as a people-person. It seems I was mistaken: I’m do a technical job, so I must be a people-person after all.