James Michael Hare

...hare-brained ideas from the realm of software development...
posts - 139 , comments - 1198 , trackbacks - 0

My Links

News

Welcome to my blog! I'm a Sr. Software Development Engineer who has been performing C++/C#/Java development for over 20 years, but have definitely learned that there is always more to learn!

All thoughts and opinions expressed in my blog and my comments are my own and do not represent the thoughts of my employer.

Blogs I Read

Follow BlkRabbitCoder on Twitter

Tag Cloud

Archives

Post Categories

Thursday, April 16, 2015

C#/.NET Little Wonders: Static Using Statements in C# 6

Once again, in this series of posts I look at the parts of the .NET Framework that may seem trivial, but can help improve your code by making it easier to write and maintain. The index of all my past little wonders posts can be found here.

Visual Studio 2015 is on the horizon!  In fact, some of you may already have played with the preview and seen some of the many neat new things to come – both in the IDE and in the C# language.

For those who haven’t been keeping up with the announcements, I’m taking some blog time for a few Little Wonders posts to talk about some of the neat new things that will be in C# 6. 

Note: All of the C# 6 features mentioned are current with the latest CTP of VS2015 as of the time of this writing.  The syntax and exact feature behaviors may be subject to change in the final released version.

Importing a whole namespace with “using”

Of course, we all know that you can import a namespace with using.  This gives us the ability to use a type with just the type’s name in our code.  That is, it allows us to use the type name directly without the need of fully qualifying it with it’s namespace.

For example, if we didn’t import the System namespace, we’d have to say:

public class Driver
{
    public static void Main()
    {
        // without importing a namespace, we'd have to fully qualify the type
        // Console as System.Console
        System.Console.WriteLine("Hello, World!");
    }
}

But, of course, we can import the System namespace, so that allows us to shorten the call to just:

using System;
 
public class Driver
{
    public static void Main()
    {
        Console.WriteLine("Hello, World!");
    }
}

This eliminates a lot of redundant “System.” prefixes in our code.  But this is all old stuff, why bring it up?  Mostly, I wanted to set the stage for what using does today so I can discuss what changes have been made with the new using static directive in C# 6.

Importing a static class with “using static”

Now, in C# 6, we can go one step further and import the static members of a class into our namespace.  This means we can use the static members of a class directly with no need to qualify them with their namespace or type name!

The format is “using static” followed by the type whose static methods you wish to import.  For example, our short example before now becomes:

using static System.Console;
 
public class Driver
{
    public static void Main()
    {
        // Now, the System.Console static class is imported, so we
        // can use WriteLine directly
        WriteLine("Hello, World!");
    }
}

This may seem trivial, but it can eliminate a lot of redundant or superfluous type identifiers in the code and thus help improve readability (if used appropriately). 

Note: In previous previews, the format was simply using without the static keyword, and only worked on static classes.  In the current preview, the format has changed to using static and can import static members of any type (class, struct, enum).

Think, for example, of static classes like Math where it is simply a collection of mathematical functions.  The “Math.” prefix really doesn’t add much to the readability because we know Sqrt() is a math function, so we can drop it with a using static System.Math like this:

using static System.Console;
using static System.Math;
 
public class Driver
{
    public static void Main()
    {
        // Now we can access Sqrt directly since we imported System.Math
        WriteLine("Hello, World: the square root of 4 is " + Sqrt(4));
    }
}

Or consider static classes like Enumerable that have a lot of nice static methods like Range() and Repeat().  Again the “Enumerable.” prefix doesn’t add much to the readability, so why not drop it with a static import?

using static System.Linq.Enumerable;
 
public class Driver
{
    public static void Main()
    {
        // Now, Enumerable.Range() can just become Range()
        var nums = Range(1, 10).ToArray();
 
        ...
    }
}

As you can see, this shortens the body of our code and eliminates unnecessary identifiers.  Obviously, you’ll want to use this with care.  There are probably some instances where including the type name improves readability (that is, if you can’t easily tell the original of the method without it from the context).  As such, make sure you use good judgment on when it improves readability and when it doesn’t.

Limiting Extension Method visibility with “using static”

Here’s one very big reason I’m excited about using static: I love extension methods.  I do not love abusing them, but I do love well designed extension methods and think they can really improve your code if used judiciously.  The problem with extension methods is that even the well-written ones can pollute your namespace (and IntelliSense) if you have a lot of them extending some of the more common types (like string or object).

One way to limit this impact would be to put your extension methods into very compartmentalized namespaces and only import the namespace you want.

For example, let’s say I have a namespace called Utilities.Extensions and under it I have extensions for:

  • Preconditions – extensions to allow me to create test preconditions much like Google Guava in Java
  • Strings – extensions to allow me to check strings for certain formats
  • Typeextensions for querying properties of types
  • etc.

If all of these static classes with their extensions were in the same namespace, and I did an import such as:

// imports the whole namespace including all extension methods
using Utilities.Extensions;

Then all of the extension methods becomes implicitly visible whether I want them or not.  It would be nice to isolate them.  So I could put each of the static classes in their own namespace, but then I’d have namespaces for Utilities.Extensions.Preconditions just to hold a Preconditions static class, which seems a bit redundant.

Instead, I can now take advantage of using static and just include the extension methods from the class that I want, which will only make those extension methods visible without an explicit reference:

// only Preconditions and it's extension methods will be visible
using static Utilities.Extensions.Preconditions;

Now, only the extension methods in Preconditions will be visible without an explicit reference, and all the other extension methods in Utilities.Extensions will not be imported.

Importing enum constants with “using static”

As I alluded to before, in the current preview you can also import the static members of any type, not just static classes.  This means you can import the constants of an enum (static by definition) so you do not need to explicitly qualify them.

Consider if you wanted to do a lot of console output with multiple colors.  You’d make use of the System.Console class and the System.ConsoleColor enum.  This would mean that you’d have to use a lot of code like:

Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("This is my output in red");
 
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("This is my output in white");
 
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine("This is my output in blue");

Now, we know we can eliminate the “Console.” with a using static System.Console, but we can also eliminate the need to qualify the constants of the enum by performing a using static System.ConsoleColor as well, this would shorten it to:

ForegroundColor = Red;
WriteLine("This is my output in red");
 
ForegroundColor = White;
WriteLine("This is my output in white");
 
ForegroundColor = Blue;
WriteLine("This is my output in blue");

This eliminates a lot of very redundant qualifiers that don’t really improve the quality of the code.

Summary

The new using static directive allows us to import the static members of a type without needing to qualify them with their type name.  This can help improve readability and maintainability in your code.  Of course, as with any syntactical sugar, you should be careful not to abuse this power.  If the addition of the qualifying type name actually improves the readability of the code, then by all means keep it.  But for cases where the qualifying type name becomes redundant or superfluous, feel free to utilize the new using static to eliminate the need to explicitly state it.

Thanks for reading and stay tuned for more features of C# 6!

Posted On Thursday, April 16, 2015 8:14 PM | Comments (7) | Filed Under [ My Blog C# Software .NET Little Wonders vNext ]

Monday, April 13, 2015

Solution to Little Puzzlers–Largest Puddle on a Bar Chart

This is the way I went about the “Largest Puddle on a Bar Chart” problem. However, keep in mind there are multiple ways to solve this, so don't worry if your solution has variations and it’s entirely possible there are more efficient ways.

Feel free to suggest your solution in the comments here or in the original post, but please be respectful of others efforts.

My Approach

Of course, the most straight-forward approach could be performed by taking each bar, and finding the pool starting at that bar to each of the bars that follow in turn and taking the max.  Then move on to the next bar as the starting point and repeat.

This would be a quadratic – O(n^2) – solution, so we’re pretty sure we can do something better. 

My approach was to consider the nature of the problem and how the water “flows”.  For example, looking at the example graph:

GraphPool

We can see that bars that increase on the left (moving right) will generate no new pool, only bars that decrease from the left.  Similarly, bars that decrease from the right (moving left) will end pools, not bars that increase from the right.

Knowing this, we can start a left and right position on each side of the graph and move in.  Obviously, they can’t move in sync because there’s no guarantee the pool will have symmetrical beginning and ending points.  But we can bring in the left and right sides until we find a pool.

So, we know that water will “flow over” the smaller of two sides.  For example, on the graph above, the smaller pool is bounded by the left bar because it’s smaller and additional water will “flow over” it.  This means that we only need to keep going until we find a bar bigger than it.

How does all of this flow into the solution?  Simply put, we will start a left position at 0 and a right position at bars.Length – 1 and move whichever bar is shorter towards the bar that is taller.  As long as we find something smaller than the shorter bar, we accumulate area.  The moment we find something larger or equal to the shorter bar, we close off the area, compare to our max area, and begin the cycle again with that new bar being the new left (or right, depending on which we chose) bar.

We can stop the moment left and right cross and the end result should be the max puddle area of the whole chart.  This solution is linear – O(n) – in time and constant in space requirements, which is fairly optimal. 

My Code

Here is the code for my solution.

public static int FindLargestPuddle(int[] bars)
{
    int maxArea = 0;
    int leftSide = 0;
    int rightSide = bars.Length - 1;
 
    // keep going till we cross
    while (leftSide < rightSide)
    {
        // move from smallest to largest
        int currentArea = 0;
        if (bars[leftSide] < bars[rightSide])
        {
            int puddleStart = leftSide;
 
            // go until we find equal bar or cross right side
            while (bars[puddleStart] > bars[++leftSide] && leftSide < rightSide)
            {
                currentArea += bars[puddleStart] - bars[leftSide];
            }
        }
        else
        {
            int puddleStart = rightSide;
 
            // go until we find equal bar or cross left side
            while (bars[puddleStart] > bars[--rightSide] && leftSide < rightSide)
            {
                currentArea += bars[puddleStart] - bars[rightSide];
            }
        }
 
        // if puddle is > max, it's the new max
        if (currentArea > maxArea)
        {
            maxArea = currentArea;
        }
    }
 
    return maxArea;
}

Summary

Hope you had fun with this one!  Of course, I’m sure many out there can tweak the answer for performance in various ways – but you get the point.

Have a solution that worked for you but was totally different?  I’d love to hear about it!

Stay tuned next week for the next Little Puzzler.

Posted On Monday, April 13, 2015 8:56 PM | Comments (2) | Filed Under [ My Blog C# Software .NET ]

Thursday, April 9, 2015

C#/.NET Little Wonders: Exception Filtering in C# 6

Once again, in this series of posts I look at the parts of the .NET Framework that may seem trivial, but can help improve your code by making it easier to write and maintain. The index of all my past little wonders posts can be found here.

Visual Studio 2015 is on the horizon!  In fact, some of you may already have played with the preview and seen some of the many neat new things to come – both in the IDE and in the C# language.

For those who haven’t been keeping up with the announcements, I’m taking some blog time for a few Little Wonders posts to talk about some of the neat new things that will be in C# 6. 

Exception Filtering

C# (like its ancestors Java and C++ before it) has long been able to filter exceptions by type.  For example, if you wanted to be able to perform a different action based on the type of exception caught, you could simply have separate catch blocks to handle those:

try
{
    // some code to check  ...
}
catch (InvalidOperationException ex)
{
    // do your handling for invalid operation ...
}
catch (IOException ex)
{
    // do your handling for IO error ...
}

However, there comes a time when we’re writing code that we need to make a decision on whether or not to handle an exception based on not only the type of exception, but also on whether a given condition is satisfied.

For example, let’s say you are writing code to perform some operation against a dependency, and that dependency will throw an exception with a bool property that tells you whether the operation IsRetryable

Such an exception may look something like this:

public class SomeDependencyException : Exception
{
    public bool IsRetryable { get; private set; }
 
    public SomeDependencyException(string message, Exception cause, bool isRetryable = false) 
        : base(message, cause)
    {
        IsRetryable = isRetryable;
    }
}

Now, let’s say that as we’re calling this dependency, we want to be able to retry any error that has IsRetryable == true up to three times, then abandon if it throws a fourth time.  However, if the exception has IsRetryable == false, we do not want to catch the exception at all, but rather let it bubble up to the caller.

Before C# 6, we’d probably write something like this:

while (tries++ < MaxAllowedTries)
{
    try
    {
        dependency.DoSomethingBig();
    }
    catch (SomeDependencyException ex) 
    {
        if (!ex.IsRetryable)
        {
            throw;
        }
 
        Console.WriteLine($"Dependency failure on try {tries}.");
    }
}

Note: The $”…{…}…” syntax is C# 6’s string interpolation feature, for more information click here for my recent post.

Taking a look at this code, a few things stick out.  First of all, our catch block now has extra conditional logic in it, which makes the flow of the program a bit less intuitive and harder to read.  It would be much clearer if we could just tell our catch block we’re only interested in exceptions that meet a certain criteria.

Second, we end up catching and re-throwing an exception we never wanted to catch in the first place.  This is not terribly efficient, it would be much better if we could avoid the cost of the catch & re-throw rather than just not catch the original throw.

Exception Filtering in C# 6

Filtering exceptions by type is still, of course, available in C# 6 and 99% of the time this will get you what you need in your exception handling.  C# 6, however, adds the ability to do that very thing we wanted in our last example: only catch an exception if a certain condition is met.

The magic is in the when keyword.  This keyword is specified as part of the catch statement and lists the condition that must be satisfied for the exception to be caught by that block (provided, of course, that it meets the type filter as well).

catch (SomeException ex) when (someConditionIsMet)
{
    // Your handler logic
}

This means that if the exception throw was of type SomeException and someConditionIsMet is true, then the exception will be caught and handled in that catch block.  If not, the exception will not be caught by that catch

Note: In previous versions of the Visual Studio 2015 CTP, the if keyword was used instead of when.

Note that it does not catch-and-rethrow behind the scenes, it is simply not caught by that catch block at all which means that you won’t incur the cost of catching and re-throwing the exception if it is not one that you care about.

So how would our example look using this feature?

while (tries++ < MaxAllowedTries)
{
    try
    {
        dependency.DoSomethingBig();
    }
    catch (SomeDependencyException ex) when (ex.IsRetryable)
    {
        Console.WriteLine($"Dependency failure on try {tries}.");
    }
}

Notice how much more clear and concise this now is.  We are now stating directly in the catch…when clause what we are catching and when.  If the type or condition do not match, the exception is not caught and will pass through.

Of course, this loop would end up absorbing this exception after the max pass.  That may not be our intention, what if instead we want to try up to three times and if, on the third try, a retryable exception was still thrown we want to let it bubble out?

We can easily do this since the condition in the catch…when clause does not necessarily have to involve the reference to the exception at all.  That is, we could examine if we have any tries left and determine whether to catch or not like this:

catch (SomeDependencyException ex) when (ex.IsRetryable && tries < MaxAllowedTries)
{
    Console.WriteLine($"Dependency failure on try {tries}.");
}

So you may be wondering now, if you can have a condition with a catch…when clause, can I have more than one and have two different catch blocks for when two different conditions are true?  Absolutely!

You can have multiple catch…when filters for a given type, or a catch…when followed by a plain catch for an exception type:

catch (SomeDependencyException ex) when (ex.IsRetryable && tries < MaxAllowedTries)
{
    Console.WriteLine($"Dependency failure on try {tries}, will retry.");
}
catch (SomeDependencyException ex) when (ex.IsRetryable)
{
    Console.WriteLine($"Dependency failure aborted after {tries} tries.");
}
catch (SomeDependencyException ex) 
{
    Console.WriteLine("Dependency failure was non-retryable, aborting.");
}

In this case, the exception filters will be checked in order to see which catch will get the SomeDependencyException.  So if we get a retryable exception on the first few throws, the first catch…when will get the exception.  If, however, we get to the point where tries == MaxAllowedTries and we’re still retryable, the second catch…when will catch us.  Or, if we ever get an exception that is not retryable, the plain catch will catch us.

Of course, keep in mind it would make no sense to put the plain catch before the catch…when for a given exception type since it would get the exception no matter what:

catch (SomeDependencyException ex)
{
    // Compiler error, this would catch all instances of SomeDependencyException
}
catch (SomeDependencyException ex) when (ex.IsRetryable && tries < MaxAllowedTries)
{
    // Impossible
}
catch (SomeDependencyException ex) when (ex.IsRetryable)
{
    // Impossible
}

Summary

The catch…when exception filtering in C# 6 gives you a lot of power to clean up complex catch blocks that have to make different handling decisions based on logical conditions in the catch.  By moving those decisions up into the catch…when declaration, we are able to write cleaner exception handling logic that is easier to read and maintain.

Stay tuned for more Little Wonders of C# 6!

Posted On Thursday, April 9, 2015 6:36 PM | Comments (3) | Filed Under [ My Blog C# Software .NET ]

Tuesday, April 7, 2015

Little Puzzlers–Largest Puddle on a Bar Chart

I like to keep my brain sharp by working on programming puzzlers. On off weeks I'm going to start posting programming puzzlers I've collected over the years. Hopefully you'll find them as entertaining as I do.

This is perhaps one of the more fun problems I’ve had to solve in an evaluation situation before.  I’m not claiming I have the optimal answer, so I’ll be curious to see what you all come up with as well!

The Problem:

Given an array of int that represents the height of bars in a bar chart, calculate the size of the largest puddle that would form if water were poured over the top of the graph. 

You may assume the following:

  • All bars have a width of 1
  • There is no extra space between adjacent bars.
  • There are no negative bars
  • The edges of the bar chart are an implicit “zero” height.

Example:

Assume you had the following array:

var bars = new [] { 10, 20, 80, 70, 60, 90, 40, 30, 40, 70 };

We would have the following bar chart with the indicated puddles forming on top:

GraphPool

Note that no water pools on the left side because there isn’t a left “wall” to hold it in.

So in this example, two pools would form: one from the 80-90 bars that hold 30 units of water, and one from the 90 bar to the 70 bar that holds 100 units of water.  Thus the largest pool size would have an area of 100.

Spoiler Alert!

Fair Warning: there may be discussion of the problem and potential solutions posted in the comments below.

Posted On Tuesday, April 7, 2015 1:28 PM | Comments (23) | Filed Under [ My Blog C# Software .NET ]

Thursday, April 2, 2015

C#/.NET Little Wonders: Getting the Name of an Identifier

Once again, in this series of posts I look at the parts of the .NET Framework that may seem trivial, but can help improve your code by making it easier to write and maintain. The index of all my past little wonders posts can be found here.

Visual Studio 2015 is on the horizon!  In fact, some of you may already have played with the preview and seen some of the many neat new things to come – both in the IDE and in the C# language.

For those who haven’t been keeping up with the announcements, allow me to take some blog time for the next few Little Wonders posts to talk about some of the neat new things that will be part of C# 6. 

Then, once it’s available for you to consume, you can hit the ground running with an arsenal of new little ways to make your code cleaner and more maintainable.

Why do we care about getting the name of a identifier?

Sometimes, we need to know the name of a variable, member, or type.  This may seem trivial, but there are many times where we end up needing this very thing, and thus we end up typing the name of a variable, member, or type as a string literal.

Take, for example, parameter validation.  When validating parameters, we will often check for their range, nullity, etc. and throw one of the various argument exceptions if the value isn’t what we expected.  In these exceptions, you’re expected to pass in the name of the identifier for the argument to let the caller know which argument was the problem.

For example, let’s say hypothetically that we don’t like the look of the expression !x.Contains(y) so we want to create a new extension method to make it read clearer, such as x.DoesNotContain(y). 

We could write an extension method such as:

// helper method to make not contain more visible than !Contains()
public static bool DoesNotContain<T>(this IEnumerable<T> collection, T value)
{
    if (collection == null)
    {
        // first agument is the name of the argument
        throw new ArgumentNullException("collection");
    }
 
    return !collection.Contains(value);
}

This works quite well, but notice that “collection” is just a string and has no real tie to the actual argument name.  What happens if we refactor our code and change the variable name?  For example, most of the System.Linq extension methods use the parameter name source to represent the sequence being operated on, so let’s make our parameter name the same for consistency.

If we just renamed the variable, we might end up with this:

public static bool DoesNotContain<T>(this IEnumerable<T> source, T value)
{
    if (source == null)
    {
        // uh oh, this didn't get renamed with the variable!
        throw new ArgumentNullException("collection");
    }
 
    return !source.Contains(value);
}

I just used the IDE’s rename command to rename the parameter and all it’s usage.  Unfortunately, it didn’t realize that the string “collection” is also describing that parameter and so now, we have an exception that refers to a parameter that no longer exists which can cause confusion when the caller is told the parameter “collection” – which doesn’t exist – cannot be null.

The new nameof() operator

So how do we alleviate this pain?  Fortunately, C# 6 adds a new operator called nameof() operator whose job is to create a string representation of the name of a variable, member, or type at compile time.

Using this operator, the code now looks like this:

public static bool DoesNotContain<T>(this IEnumerable<T> source, T value)
{
    if (source == null)
    {
        // now, whenever source is renamed, we'll have the correct name
        throw new ArgumentNullException(nameof(source));
    }
 
    return !source.Contains(value);
}

Easy!

And, as I said, this happens at compile time – there is no runtime overhead or reflection involved.  Essentially, the code here boils down to the same thing as if we typed in the string literal – in fact that’s what it will actually compile into.  The difference is, the compiler now maintains that relationship and makes sure the string matches the name of the expression for us every time we build.

This isn’t only useful in exception handling, consider getting the function name for output:

// loads the dictionary from a file
private IEnumerable<string> LoadDictionary(string filename)
{
    // will output "Started LoadDictionary at ..."
    Console.WriteLine("Started " + nameof(LoadDictionary) + " at " + DateTime.Now);
 
    ...

Again, if the function name changes, your output will change accordingly. 

As another example, consider implementing INotifyPropertyChanged to notify observers when a property value changes.  Again, this requires you to give the name of the property as a string:

public int Total 
{
    get { return _total; }
    set 
    { 
        _total = value; 
 
        // determine the name of the Total property instead of hard-coded string
        PropertyChanged(this, new PropertyChangedEventArgs(nameof(Total)); 
    }
}

Or consider the times in frameworks like MVC where you often times hard-code strings to indicate certain identifiers in the code.

// this way, if the LogIn changes it's name, we will automatically change the link as well
<%= Html.ActionLink("Log in", @typeof(SignOnController), @nameof(SignOnController.LogIn))%>

These are just a few of the many examples where nameof() can be utilized to reduce the brittleness of your code in spots where it relies on a string being in sync with the name of an identifier. 

And, as stated before, it’s all compile-time magic so you get it essentially for free!

What nameof() does not do

The nameof() operator is very handy, but there’s a few things it won’t do.  For the most part, these are non-issues because having a name for some of these things wouldn’t make sense.  That said, it’s good to be aware of its limitations.

First of all, it only works on a subset of expressions that point to an identifier (i.e. a variable, member, or type name).  It will not work on other expressions that don’t evaluate to one of those things.

For instance, nameof(2 + 4) does not resolve to an identifier and thus is a compiler error.  Likewise, keywords such as if, while, for, etc. are not identifiers and thus nameof() any of these things is a compiler error as well.

Note that type aliases like int are actually considered keyword aliases to a type (e.g. int refers to System.Int32).  Thus, nameof(int) is a compiler error, but nameof(System.Int32) is not.

Compile-time pitfall

Like all things that are performed at compile time, you should take care to note that if your nameof() expression is evaluating a type or member identifier from another compilation unit (such as another assembly) it could become stale if the dependent library is updated by the referencing library is not rebuilt.  In reality, this is also a problem for other compile-time constants such as const values, enums, default parameter values, etc. 

Visual Studio is smart enough to compile the referencing assembly automatically when the dependency assembly changes, so this will not be an issue most of the time.  The only time you should run into this is if you manually copy just the dependency assembly without updating the referencing assembly.

Summary

The nameof() operator is a small addition to C# that adds up to real gains in maintainability.  Whenever you find yourself needing to create a string literal that matches an identifier in your code, consider using nameof() instead and let the compiler keep it in sync for you. 

Stay tuned for more Little Wonders of C# 6!

Posted On Thursday, April 2, 2015 8:33 PM | Comments (2) | Filed Under [ My Blog C# Software .NET ]

Powered by: