Nourishing Creativity
24 April 07 05:39 PM | kcwalina | 0 Comments   

For those who haven’t heard about it, TED is a multidisciplinary conference for experts from technology, entertainment, and design industries. They just updated their web site and while browsing around it I found this very interesting presentation about creativity by Ken Robinson.

One of the main points Ken makes is that penalizing people for failing when they try new things is killing creativity. His talk concentrates on education systems, but I think the same mechanisms exist in the industry.

Filed under:
Online lecture on API design
29 March 07 11:31 AM | kcwalina | 30 Comments   

I gave a lecture on framework design at the Redmond’s Microsoft Research Center. They recorder and posted it on the Research Channel. You can see it here. It’s more than 3 hours long, but I think you will find it worth the time.  Let me know what you think.

Effective Presentation Skills
01 February 07 05:25 PM | kcwalina | 6 Comments   

I just watched a very interesting presentation. The content of the presentation is interesting, but not very relevant to the work software engineers do. The super interesting and relevant part is that it’s one of the best presentations I have ever seen in terms of the mechanics of presenting, and I think all who do presentations can learn a lot from it.

 

1.       The presenter wanted to communicate just one relatively simple thing that not many people pay attention to, so he had to capture the audience’s attention and he did a very good job doing it.

2.       The presentation has lots of content, but the content is just to support the main thesis; it's not a laundry list of things he wanted people to remember (that it almost never successful).

3.       The presentation shows the power of visual communication (and software). The same information presented in a static table, bullets, etc. would completely fail in communicating the main message.

Filed under:
How to Design Exception Hierarchies
30 January 07 11:47 AM | kcwalina | 12 Comments   

I still get a lot of questions on how to design exception hierarchies, despite several attempts to describe it in talks, the FDG book, and in posts on this blog. Maybe the guidance gets lots in the in the complexities of the full guidance surrounding exception handling or I am a bad communicator. Let me assume the former :-), and so here is one more attempt at describing the guidance in the most succinct way I am capable of:

·         For each error condition you reusable routine can get into, decide whether the condition is a usage error or a system error.

o   A usage error is something that can be avoided by changing the code that calls your routine. For example, if a routine gets into an error state when a null is passed as one of its arguments (error condition usually represented by an ArgumentNullException), the calling code can modified by the developer to ensure that null is never passed. In other words the developer can ensure that usage errors never occur.

o   A system error is something that cannot be avoided by simply writing code that tries to avoid the error condition.  For example, File.Open gets into an error condition when it tries to open a file that does not exist (and it throws FileNotFoundException). This error condition cannot be fully avoided. Even if you check whether the file exists before calling File.Open, the file can get deleted or corrupted between the call to File.Exists and the call to File.Open.

·         Usage errors need to be communicated to the human developer calling the routine. The exception type is not the best way to communicate errors to humans. The message string is a much better way. Therefore, for exceptions that are thrown as a result of usage errors, I would concentrate on designing a really good (that is explanatory) exception message and using one of the existing .NET Framework exception types: ArgumentNullException, ArgumentException, InvalidOperationException, NotSupportedException, etc. In other words, don’t create new exception types for usage errors because the type of the exception does not matter for usage errors. The .NET Framework already has enough types (actually too many, IMHO) to represent every usage error I can think of.

·         System errors need to be further divided into two groups:

o   Logical errors are system errors that can be handled programmatically. For example, if File.Open throws FileNotFoundException, the calling code can catch the exception and handle it by creating a new file. (Side note: this is in contrast to the usage error described above where you would never first pass a null argument, catch the NullArgumentException, and this time pass a non-null argument).

o   System failures are system errors that cannot be handled programmatically. For example, you really cannot handle out of memory exception resulting from the JIT running out of memory.

·         System failures should result in the shutdown of the process. This might sound scary at the first read, but I would say it's by-definition: a system failure is an error that can neither be handled by the developer or the program. The best way to shut down a process in such cases is to call Environment.FailFast, which logs the state of the system, and that is very useful in diagnosing the problem. The good thing is that system failures are extremely rare in reusable libraries. They are mostly caused by the execution engine.

·         Logical errors are errors that can be, and often are, handled in code. The way to handle such errors is to catch the exception and execute some “compensating” logic. Whether the catch statement executes is determined by the type of the exception the catch block claims it can handle. This means that logical errors are are condition (and actually the only conditions) where the exception type matters and when you should consider creating a new exception type.

·         If you think you are dealing with a logical error, I would validate this belief by actually writing code or describing very precisely what would the catch handler do when it catches the exception to allow the program to continue its execution. If you cannot describe it or the error can be avoided by changing the calling code, you are dealing with a usage error or a system failure.

·         Note that logical errors are still pretty rare. As a rule of thumb, I would say that error conditions in a typical reusable library fall into: <1% of system failures, 5% logical errors, and the rest ~95% are usage errors.

·         If you are convinced that your error is a logical error, you need to decide whether to reuse one of the existing exception types from the framework or create a new exception type.

o   You should use an existing Framework exception is both of the following are true

§  The exception type makes sense for your error condition. For example, you don’t want to throw FileNotFoundException if your threadpool implementation runs out of the thread quota.

§  The exception will not make an error condition ambiguous. That is, the code that wants to handle the specific error will always be able to tell whether the exception was thrown because of the error or because of some other error that happens to use the same exception. For example, you don’t want to throw (reuse) FileNotFoundException from a routine that calls Framework’s file I/O APIs that can throw the same exception, unless it does not matter to the calling code whether your code or the Framework threw the exception (BTW, it’s quite often that it does not matter).

o   If you decided not to reuse an exception type from the .NET Framework, you will have to create a new exception type. When you create a new exception type, as a rule of thumb, I would simply inherit it from System.Exception or from a single subtype of System.Exception representing custom exceptions declared in your component/framework. I would create the root only if you have more than 3 custom exceptions. There are limited cases where it’s good to create a more elaborate hierarchy, but it’s extremely rare. I would say in a typical library 99% of custom exceptions should follow this guidance. The reason is that when you catch exceptions you almost never care about the hierarchy. You almost never care about the hierarchy because you almost never want to catch more than one error at a time. You almost never want to handle more than one error at a time, because if the errors could be handled the same way, they should not be expressed using two different exception types. Now, please note that I said “almost” and “should” in several places. You your case falls into the small number of corner cases, you need to create a deeper hierarchy.

o   Lastly, keep in mind that it’s not a breaking change to change an exception your code throws to a subtype of the exception. For example, if the first version of your library throws FooException, in any future version of your library, you can start throwing a subtype for FooException without breaking code that was compiled against the previous version of your library. This means, when in doubt, I would consider not creating new exception types till you are sure you need them. At which point, you can create a new exception type by inheriting from the currently throw type. Sometimes it might result in slightly strange exception hierarchy (for example, a custom exception inheriting from InvalidOperationException), but it’s not a big deal in comparison to the cost having unnecessary exception types in your library, which makes the library more complex, adds development cost, increases working set, etc.

.NET Framework Performance Signatures
26 January 07 04:52 PM | kcwalina | 5 Comments   

I love Rico’s performance quizzes in general, but the last one has something especially interesting: a link to a file listing all members in the Framework and their estimated performance signatures (perf characteristic based on the number of allocations in the member).

Now, I only wish I had an fxcop rule warning me when I call some of the expensive members in loops, low on the callstack, on the UI thread, or in any other performance sensitive places.

System.TimeZone2 Naming ... and related design guidelines
06 October 06 05:35 PM | kcwalina | 30 Comments   

There is an interesting discussion on the BCL blog about a new BCL type called TimeZone2.  Just take a look at the comments below the System.TimeZone2 Starter Guide post. The new type supersedes an existing type called TimeZone (which is obsolete now).

Lots of people are not thrilled with the “2” suffix. I am responsible for the guidelines (excerpt below), and so I thought I would try to provide some context:

·         Some comments suggest that the BCL team just take a breaking change, i.e. remove the old type and add a new one with the same name. This is not an option for such a widely used framework. We basically have a policy against doing any intentional breaking changes. In other words, this is not negotiable :-)  

·         Some comments suggested using a new namespace, e.g. System.Globablization.TimeZone. This would cause all sorts of problems. The main one is that most source files import System namespace and this approach would mean that most source files have to fully qualify the new TimeZone (otherwise you would get type name ambiguity). I don’t like fully qualifying core types when I program and usability studies we conducted have shown that I am not alone. There are other issues related to the difficulty in searching for documentation on such duplicated types, referring to such types in books and in speech, etc.

·         Using numeric suffixes is the last resort thing. If you have a “good name” that does not include a numeric suffix, you should use it. The problem is that sometimes all reasonable names are already taken, and that’s when the guideline is applicable. It’s what we call the best out of many bad alternatives.

Having said that, I would love the BCL team to find a new “good name” for the type. If you have a great name, post it to my or the BCL blog.

And for reference, here is the excerpt from the design guidelines:

Naming New Versions of Existing APIs.

Sometimes a new feature cannot be added to an existing type even though the type’s name implies that it is the best place for the new feature. In such case a new type needs to be added, often leaving the framework designer with a difficult task of finding a good new name for the new type. Similarly, often an existing member cannot be extended or overloaded to provide additional functionality and a member with a new name needs to be added. The following guidelines describe how to choose names for new types and members that supersede or replace existing types or members.

þ Do use a name similar to the old API when creating new versions of an existing API.

This helps to highlight the relationship between the APIs.

class AppDomain {

    [Obsolete("AppDomain.SetCachePath has been deprecated. Please use  AppDomainSetup.CachePath instead.")]

    public void SetCachePath(String path) { /* … */ }

}

 

class AppDomainSetup {

    public string CachePath { get { /* … */ }; set  { /* … */ }; }

}

þ Do prefer adding a suffix rather than a prefix, in order to indicate a new version of an existing API.

This will assist discovery when browsing documentation, or using Intellisense. The old version of the API will be organized close to the new APIs as most browsers and the Intellisense show identifiers in alphabetical order.

þ Consider using a brand new, but meaningful identifier, instead of adding a suffix or a prefix.

þ Do use a numeric suffix to indicate a new version of an existing API, if the existing name of the API is the only name that makes sense (i.e. it is an industry standard), and adding any meaningful suffix (or changing the name) is not an appropriate option.

// old API

[Obsolete(“This type is obsolete. Please use the new version of the same class, X509Certificate2.”)]

public class X509Certificate { /* … */ }

// new API

public class X509Certificate2 { /* … */ }

 

 

Clearing Enum Flags
29 August 06 09:49 AM | kcwalina | 4 Comments   

UPDATE: It looks like I am confusing a lot of people with this article. I wanted to write an article about something else than the title suggests (how flags enum are built) but I did not explain it well and what’s more important I forgot to mention the most important thing: how to simply clear a flag. I apologize for the confusion and here is the simple way of just clearing a flag:

[Flags]

public enum Foos {

    A = 1,

    B = 2,

    C = 4,

    D = 8,

    AB = A | B,

    CD = C | D,

    All = AB | CD

}

 

static class Program {

    static void Main() {

        Foos value = Foos.AB;

        Console.WriteLine(ClearFlag(value,Foos.A);

    }

    public static Foos ClearFlag(Foos value, Foos flag) {

       return value & ~flag;

    }

}

… I will try to write the other article some other time :-)

Poll: Attribute Design
24 August 06 12:22 PM | kcwalina | 36 Comments   

I would like to run a quick poll. Which design do you prefer for a set of related attributes and why?

Option #1: Several Attribute Types:

public class AaaaFooAttribute: Attribute { }

public class BbbbFooAttribute: Attribute { }

public class CcccFooAttribute: Attribute { }

public class DdddFooAttribute: Attribute { }

 

Option #2: One Attribute Type and One Enum

public class FooAttribute: Attribute {

     public FooAttribute(FooType type) {}

}

public enum FooType { Aaaa, Bbbb, Cccc, Dddd }

 

Filed under:
International Phonetic Alphabet
19 July 06 07:41 PM | kcwalina | 7 Comments   

I am in Chicago at the Architecture and Design World, and today I went to a session on API design. The talk was given by Elliotte Rusty Harold, who wrote more books than I would ever guess (see his home page). The talk covered the most important do’s and don’ts of API design and was very well-delivered.

 

At the end of the talk Elliotte recommended some API design related books, including the FDG book. He said something like: A great book written by Brad Abrams and somebody whose name I cannot pronounce. J

 

… which made me think that Elliotte might not be the only person who wonders whether it’s even possible to pronounce a name with 3+ times as many consonants as vowels. J

 

So, here you go. This is my name (slightly Americanized) written in the International Phonetic Alphabet:

krYstof swalina

 

The closest English spelling would probably be something like “kristof swahleenah.”

 

BTW, I wish there was a web page where I could type in a word written in the International Phonetic Alphabet and have it converted to a sound file and played. Anybody knows anything like that?

Architecture & Design World 2006
10 July 06 02:50 PM | kcwalina | 0 Comments   

I will attending Architecture & Design World next week where  I hope to meet and chat with some fellow API designers.  Should be fun.

Choosing the Right Type of Exception to Throw
05 July 06 03:14 PM | kcwalina | 17 Comments   

My last post about the ApplicationException resulted in some questions along the lines of “so, if not ApplicationException, what should I throw instead?” The answer to this question is partially covered by my old post on Exception Throwing and partially by some additional guidelines for creating custom exceptions that did not make it to the original post, but are now included in the FDG book. For your convenience, I included both parts of the guidance below:

Choosing the Right Type of Exception to Throw

After you have decided when you need to throw exceptions, the next step is to pick the right type of exception to throw. This section provides those guidelines.

þ Consider throwing existing exceptions residing in the System namespaces instead of creating custom exception types.

See section 7.3 for detailed usage guidelines of the most common standard exception types.

þ Do create and throw custom exceptions if you have an error condition that can be programmatically handled in a different way than any other existing exception. Otherwise, throw one of the existing exceptions. See section 7.4 for details on creating custom exceptions.

ý Do not create and throw new exceptions just to have ‘your team's’ exception.

þ Do throw the most specific (the most derived) exception that makes sense.

For example, throw ArgumentNullException and not its base type ArgumentException if a null argument is passed.

Annotation (Jeffrey Richter):

Throwing System.Exception, the base class of all CLS-Compliant exceptions is always the wrong thing to do.

 

Annotation (Brent Rector):

As described in more detail later, catching System.Exception is nearly always the wrong thing to do as well.

Now that you have chosen the correct exception type, you can focus on ensuring that the error message your exception delivers says what you need it to say.

Designing Custom Exceptions

In some cases, it will not be possible to use existing exceptions. In those cases, you’ll need to define custom exceptions. The guidelines in this section provide help on doing that.

ý Avoid deep exception hierarchies. 

þ Do derive exceptions from System.Exception or one of the other common base Exceptions.

þ Do end exception class names with the ‘Exception’ suffix.

þ Do make exceptions serializable. An exception must be serializable to work correctly across application domain and remoting boundaries.

þ Do provide (at least) these common constructors on all exceptions. Make sure the names and types of the parameters are exactly as in the example below.

public class SomeException: Exception, ISerializable {

   public SomeException();

  public SomeException(string message);

  public SomeException(string message, Exception inner);

 

  // this constructor is needed for serialization.

   protected SomeException(SerializationInfo info, StreamingContext context);

}

þ Do report security sensitive information through an override of ToString only after demanding an appropriate permission.

If the permission demand fails, return a string excluding the security sensitive information.

Annotation (Rico Mariani):

Do not store the results of ToString in any generally accessible data structure unless that data structure suitably secures the string from untrusted code.  This advice applies to all strings but since exception strings frequently contain sensitive information (such a file paths) I reiterate the advice here.

þ Do store useful security sensitive information in private exception state. Ensure only trusted code can get the information.

þ Consider providing exception properties for programmatic access to extra information (besides the message string) relevant to the exception.

 

Filed under:
ApplicationException considered useless
23 June 06 02:17 PM | kcwalina | 17 Comments   

We have a guideline that bans using the ApplicationException. Here is the related excerpt from the Framework Design Guidelines:

ý Do not throw or derive from System.ApplicationException.

JEFFREY RICHTER: System.ApplicationException is a class that should not be part of the .NET Framework. The original idea was that classes derived from SystemException would indicate exceptions thrown from the CLR (or system) itself, whereas non-CLR exceptions would be derived from ApplicationException. However, a lot of exception classes didn’t follow this pattern. For example, TargetInvocationException (which is thrown by the CLR) is derived from ApplicationException. So, the ApplicationException class lost all meaning. The reason to derive from this base class is to allow some code higher up the call stack to catch the base class. It was no longer possible to catch all application exceptions..

 

Today, somebody asked me whether they should go through their code-base and remove all references to the exception.  I answered  that it’s not worth the effort. “ApplicationException is not considered harmful, just useless.” J

Synchronization at the Right Level
05 May 06 11:24 AM | kcwalina | 2 Comments   

I get a lot of questions about why the new generic collection interfaces (IList<T> for example) do not support synchronization. There are several reasons for it. One, probably the main, is that in practice synchronizing on the level of a single data structure is rarely useful. Rico explains this in a series of posts on locking. In particular see the post on putting your synchronization at the correct level.

Framewok Design Guidelines Wins Productivity Award
16 March 06 08:46 PM | kcwalina | 10 Comments   

A couple of months ago, Brad blogged about the FDG book getting into the Jolt Award finals. The winners were just announced and we have won the Productivity Award! I am shocked … that Brad did not blogged this information first! :-)

 

On that occasion, I looked up some of the past winners of the Productivity Award. These are the classics that shaped my understanding of software design:

  • Design Patterns, by Erich Gamma, et al.
  • Writing Solid Code, by Steve Maguire  
  • Object-Oriented Software Engineering: A Use-Case Driven Approach, by Ivar Jacobson

 

Framework Design Humor by Benji Smith
09 March 06 07:24 AM | kcwalina | 8 Comments   

Benji wrote a pretty funny article exposing one of the main problems with bad APIs: trying to enable every single scenario at the wrong level of abstraction.

In other words, when your APIs get too complex, think whether you are not trying to enable scenarios for which assembly level programming would be much better suited. And if that's the case, do your users a favor and leave these scenarios to the assembler.

Note: this post has been updated. I mistakenly thought Joel Spolsky wrote the original article.

Filed under:
Page view tracker