Presentation: LINQ Basics

While I would not consider myself an expert on Microsoft’s LINQ technology, I would definitely consider myself an enthusiast. Others might call me a LINQ evangelist. Either way, I think LINQ is really cool.

The reason that computers exist is to process data. And rarely does anyone need to work with a data set with only one data point. In fact, the second thing every budding computer scientist and programmer learns (after “Hello world.”) is how to run a loop. Processing multiple pieces of similar data and doing work or creating new collections of data is something we all do. Entire languages have been written to handle this processing model, namely SQL.

Microsoft has done us a big favor in giving us LINQ, which is a query language subset integrated into the C# language. I recently gave a presentation at work on LINQ and its uses. I’m posting both the slides from the presentation, as well as a Visual Studio solution file containing code examples displaying some of the concepts covered in the slides.


Maybe you will find some use for this information.


Update 11/6/2015: I found a bug in the code files as I revisited this presentation. There were yield break; s in the example implementations. They would cause the code to exit completely rather than exit the current iteration. This has been fixed.

Season 2 of Derek Coming Soon!

If you haven’t already, be sure to check out Season 1 of Derek on Netflix. This show, staring Ricky Gervais is possibly the most moving portrayal of human interaction I have ever seen. I’m stoked that this Netflix Original got picked up for a second season, which will be available on May 30th. It doesn’t have as much glitz and intrigue as a show like House of Cards (which I also recommend), it definitely has enough heart to compete.

Make sure you watch season 1 so you’re ready on the 30th. But make sure you have a box of tissues ready. They pack a lot of emotion into 7 episodes.

Limitations In Chaining References Across Class Libraries

So I discovered something interesting today when working with class libraries and references in .Net. It isn’t necessarily a bug, but it is definitely not the behavior I would expect. Let me explain what I did, what I expected, and what actually happened.

What I Did

I was working in a large solution, let’s call it SomeBigApplication. This particular application uses a fancy schmancy object deserializer that at it’s heart allows you to map an indexed value in a delimited string to an object’s property. It works something like this: mapper.Map<T>(index, mapTo => mapTo.Property).

There are other methods that do similar things for collections and whatnot, but you get the drift. There is a particular class I found myself rewriting from application to application, so being a good little developer I wrote an abstract class that contains the common properties that I’d need to map again and again across applications.

namespace Company.Objects.General
     public abstract class ReusableClass<T, U>
          public T Qualifier { get; set; }
          public U Value { get; set; }

I was then able to inherit from this class for use in the application.

namespace Company.Objects.SomeBigApplication
     public class ApplicationSpecificClass : ReusableClass<string, int>
          public bool SomeSpecificProperty 
                    return SomeMethod(Qualifier); 

What I Expected

Class in hand, I then tried to map my delimited string resource into my new class.

mapper.Map<ApplicationSpecificClass>(index, asc => asc.Qualifier);
     // ...

But low and behold, this didn’t work. Wouldn’t even compile. ApplicationSpecificClass does not contain a definition for Qualifier . But that’s strange because SomeSpecificProperty can be found. And SomeSpecificProperty  even references Qualifier , which the compiler is telling us can’t be found! How odd. Let’s see why we’re getting this strange error.

What Happened

I included the name spaces in my code samples above for a reason. Each namespace exists in its own class library. Company.SomeBigApplication  references Company.Objects.SomeBigApplication  which in turn references Company.Objects.General. The mapper code is being executed within Company.SomeBigApplication. The compiler is, for whatever reason, only able to divine the signature to the first referenced class library. Because Qualifier  is defined in Company.Objects.General , which isn’t referenced by Company.SomeBigApplication , the compiler either can’t see or won’t expose Qualifier  and Value , even though the definitions within Company.Objects.SomeBigApplication  utilize those more generic definitions.

Luckily the fix was easy. All I had to do was reference Company.Objects.General  in Company.SomeBigApplication . This exposed the properties from the abstract class and all was well. But I think we’ve all learned an important lesson today on class library references. Well, if not important, an odd lesson.

Of Style and Substance

I had a spirited discussion today about the use of the keyword
in C#. I love conversations like that. Great things come from debates over the inane and trivial in programming, I’ve discovered. Some of the most impressive growth I’ve experienced as a software engineer has stemmed from debates and conversations about the nuances of programming languages, platforms, and computer science in general.

This particular conversation got me thinking about the style and substance of programming, especially where the two converge. We’ve all worked somewhere that has a set of coding practices and standards by which you should adhere. Sometimes we agree, sometimes we don’t. But in the end, does it really matter how we format and structure our code at such a granular level?

I would say yes and no.

No, because two solutions that are functionally equivalent both get the job done. What is a coherent and obvious framework for one developer may or may not be coherent and obvious to another.

Yes in the sense that a standardized code base is easier to maintain and develop around. Yes in that there are sometimes good reasons to follow a given convention based on the project and the coding situation you find yourself in.

For example, in my discussion concerning the use of the keyword this
, we were debating its use in instantiated classes. The opposing view was that this
is unnecessary and that class level members should be prefixed for easy recognition within subsequent calls. This is a perfectly valid coding convention.

My view is that using the this
keyword is a more clear demarcation of the scope of a class member or property and separates the member from those scoped to the current method or code block. This is also a perfectly valid coding convention.

So is there a right answer? Maybe, but probably not. One could possibly make an argument that one solution could be more easily understood or that one is harder to refactor, but such a case would be hard to make convincingly, I think. It would be especially hard to sway someone of the opposite persuasion.

But having your convention challenged is immensely helpful. It forces you to really think about why you do what you do. Debate forces you to defend your ideas. You’re given an opportunity to both learn and to teach.

We can all learn from one another in the field of computer science. We ought to take and embrace the chance to debate with our colleagues. We can and should gather, as the ancient Greeks did in times past, to engage and strengthen our minds and those of our brothers.

Maybe leave the togas at home though.

It’s Time to Rethink “Pro”

There has always and invariably been a “pro” version of whatever software I have used.  This version was always enhanced with additional features that a frequent user would really want. Finely tuned options, extended ranges, elimination of handicaps from the free version, and a miriad of other enhancements for the application. This way of selling software has been The Way Things Are Done™ for as long as I can remember.

But I think that’s going to change soon. It has to change or software developers will not be able to sell their software or SAAS anymore. There will simply be no market thanks to the growing arena of open souce software and platforms. Paid software has to adapt to the times.

Open source software is a hard to beat deal: free and functional software. This looks great to anyone with a budget; namely, everyone. Free or $100, and it does the same thing? Is this a trick?

But no, paid software has been safe, as it had things to offer that open source software did not. Paid software often had proprietary features. It was easy to use and came with support contracts; the kinds of things businesses rely on. It has also traditionally been easier to use than open source software.

Developers of open source software have been playing catch up, that’s for sure, but I think its been a little too long since paid developers have looked back to see just how close the open source community was getting. Which is funny, because it’s really the same people writing both, one on the company dime and the other in their free time.

In many areas, the software developed for fun and as a hobby has reached par with its paid counter part. Take operating systems, for example: not many people would argue that many Linux distributions aren’t at least as good as Microsoft’s Windows or Apple’s OSX. Even the casual user can sit down at a vanilla Ubuntu install and figure out what is going on and get just as much utility from the system as one of its paid counter parts.

Not only is the function catching up, so is form. Open source software is really learning how to present itself, and let me say it cleans up well. Or can.

And some companies exist solely to offer support contracts for open source software.

So where does this leave paid software? Where does this leave “pro”? In a pickel, it would seem. No longer can you just leave out the ability to do something crucial in your application because the open source alternative has that feature and it works for free.

Hope is not lost, though. We just have adjust what we think of as “pro” to be more in line with what I would argue should have always been our idea of “pro”.

Think of what a “pro” user really is. They’re someone that uses this type of software a lot. They know the line of business inside and out. They’re using your software to get stuff done. This means in order to compete with open source software one needs to not just make it possible to accomplish their task, but one needs to make it easy. You have to automate the small things. You need to understand the line of business you’re targeting to make the software do the heavy lifting for your user. Validation, workflow, and design become much more important if you want to keep your customers paying.

Like it or not, software is almost universally free now. But only functionally. There is still value in well crafted, programmed, designed, and executed software. Value that customers will pay for if it can improve their lives.

But heaven help us if the open source community ever finds user experience designers.

Code Snippet: ConvertToTypeT

I live for nifty code snippets. They make life so much easier. I also like .NET’s generics support. When I was recently writing a utility library for myself, I found myself wanting to convert command line arguments to a defined type. How would one go about converting an arbitrary argument passed as a string to an application specific typed value? Turns out it is extremely simple, if you use the wonderful world of generics!

You may be familiar with the Convert static class in .NET. To perform our trick, we’re going to use Convert.ChangeType(object, Type) to convert a generic type of T to a given type, determined by the caller of the method.

///  Converts an  to a type . 
///  Generic type parameter. 
///  The object. 
///  The given data converted to a type  
private static T ConvertToTypeT(object obj)
    where T : IConvertible
    var t = Convert.ChangeType(obj, typeof(T));

    if (t != null)
        return (T)t;

    return default(T);

Of particular interest in this code is the constraint that we put on the generic type T. We restrict T to types that implement the IConvertible. This will allow us to pass a generic object obj into our method, defining T as a specific type, and allows the Convert class to convert it to an object that boxes the typed value. All we do then is cast the value as a type T.

In the case of an invalid conversion type, we can’t return null because we need to return a generic type T. T may be a nullable type, but it may also be a non-nullable primitive type. For that reason, we need to return the default value of T by calling the .NET method default(T), which returns null for nullable types, or the default value defined for a primitive data type.

Let’s use our conversion method.

public static void DoSomething()
    string argument = Environment.GetCommandLineArgs().First();
    int intValue = ConvertToTypeT(argument); //We can convert to an integer.
    bool boolValue = ConvertToTypeT(argument); //We can convert to an boolean value.
    string stringValue = ConvertToTypeT(argument); //Remember this takes a generic object, so strings work as well.

Note: Thanks to some constructive feedback, I’ve made two updates. I updated the declaration of t so that no casting occurs. Instead, we check that Convert.Change(obj, typeof(T)) gave us something other than null, as it returns an object. If not null, we then cast t as a T, otherwise return the default value of T.

In Defense Of Beauty and the Beast

I don’t think that it is news to anyone that knows me that I am a Disney fanatic. It was my family’s go-to vacation destination growing up. I love the movies to this day, especially what I would consider (as a 90’s kid) the golden age of Disney animated films from about 1985 to 2000.

We don’t have the choice to grow up or not. And as we all did, I grew up. I did not, however, grow out of what I think of as a Disney Outlook on Life, which is a basic belief that everyone has redeeming qualities, that we should love one another, that we should strive to better ourselves and the world around us, and that we should struggle against everything that is keeping us back, even if what stands in our way is us. My parents brought me up with these values, and it helped to see stories in these movies that reinforced these ideals.

In my online travels, I have noticed a certain school of thought popping up surrounding the Disney animated films. One idea I find particularly disturbing is that Beauty and the Beast is somehow a dark  drama that encourages young girls to enter into and stay in abusive relationships. Belle, the theory goes, is abused by Beast and, as we see in abusive relationships in the real world, she decides to stay with him. I have even seen it suggested that Gaston is the real hero of the movie and that he was trying to save Belle from her abusive relationship.

I think this is poppycock. Furthermore, I think it is at best misguided and at worst disingenuous to suggest that a Disney movie made for children is advocating for women to stay in abusive relationships because that is somehow their place and they should be kept in it. This analysis strikes me as something that would come out of a freshman level pop psychology introduction course at a university rather than a serious analysis by anyone who has lived in or experienced the real world and people of other frames of reference.

I offer an alternative, and I believe to be more correct, interpretation of Disney’s Beauty and the Beast. I posit that Beast is the incarnation of a small boy. Like all children, Beast is not yet capable of empathy, and having been hurt early in his life, lashes out in anger at those around him. This is, I would think, a quite typical response by children who have not yet emotionally matured to the point of being able to act compassionately with others or see things from other perspectives. As much as we might like to think of children as miniature adults, that simply isn’t the case; children have to learn these skills that we take for granted as just a part of who we are.

Belle sees the possibility for growth in Beast. This potential is why Belle changes her mind about him. Similarly, Beast sees in Belle the type of compassion and empathy that he lacks. He views Belle as a reason to improve himself, which he tries very hard to do. By the end of the movie, Beast is willing to sacrifice himself for Belle. Beast achieves the ability to empathize and relate to others, which reveals his own nurturing and protective nature.

I would hope that all parents want for their children what Beast was able to achieve; betterment of self and self actualization. All children will have to go through a similar experience in order to emotionally mature and learn that we must care for others and learn to think about things from their perspective. Beast is a success story, and Belle is no tragic victim. She loves beast not only for the potential she saw in him, but for the man he matured into. The real tragedy would have occurred if Belle gave up on Beast at his first misgiving. Would you give up on a child that had a tantrum? Would you label them an abuser? Would you encourage all other children to ostracize them because of their outburst? No, because the more reasoned response is to handle the outburst and use it as a teaching moment.

I’m proud of Belle and Beast. I want for my children what they represent. In the case of Beast, the ability to self actuate and grow emotionally. In the case of Belle, the ability to have compassion for others and to help them through their problems rather than abandoning them at the first sign of trouble. No child is perfect, no life is perfect, and the world is certainly not perfect.

But then again, if the world were perfect, there would be no need for Disney movies.