Creating Faults, Part 2

Let's carry on with some discussion of the FaultCode and FaultReason classes. I was planning to do these two types together but I decided to do them as separate articles and make each of them a bit more detailed.

I'll start with FaultReason as it's the simpler of the two. The fault reason is the primary way that users understand what happened when the fault occurred. You'll notice that FaultReason references a FaultReasonText type, which is so simple that I'm not going to break out a code section for it. A FaultReasonText is just an association of a text string with a cultural identifier. We'll see how that combination comes into play for localization of fault descriptions.

 public class FaultReason
{
   public FaultReason(FaultReasonText translation);
   public FaultReason(IEnumerable<FaultReasonText> translations);
   public FaultReason(string text);

   public SynchronizedReadOnlyCollection<FaultReasonText> Translations { get; }

   public FaultReasonText GetMatchingTranslation();
   public FaultReasonText GetMatchingTranslation(CultureInfo cultureInfo);
   public override string ToString();
}

A FaultReason is a concept that's independent of the actual words used to describe the fault. You can supply a number of different text strings that get picked from depending on the user's language settings. The Translations bucket holds all of the different text strings and their associated cultural identifiers (tied together by a FaultReasonText). When no culture is specified for a fault reason or a translation search, the assumed culture is the current thread culture. The translation process works like this:

1.
The first translation in the list is always the default fallback translation. If this procedure doesn't come out with a match, then the first translation is the one that gets used. This means that if you've only got one translation, then obviously it will always be picked regardless of the culture that's asked for.
2.
We'll first look for an exact match between the culture you specified and the translations. "Matches" means an equality match on the culture name string. Ties are broken by the one that appears earlier in the Translations list.
3.
If there's no exact match, then we'll take your preferred culture name and start chopping off the hyphenated sections. Every time we chop off a section, we'll look for a substring match against each of the cultures in the Translations list. The same match and tiebreaking procedure is used as before.

For example, if you want a translation to "en-UK", we'll first look for "en-UK" and then we'll look for "en". If we still can't find a match, then we'll take the first translation in the list, which could be anything.

Next time: Creating Faults, Part 3