Entity Framework: Possible Lazy Loading Solution

So been a while since I posted last, and I’m sure everyone has been worried. Turns out that I’ve been banging my head against the wall named MVC. And man I have a slew of new posts back logged for when I have more time. However, due to the new project I’ve been working one, I forced myself to tackle Lazy Loading in the Entity Framework. Turns out the solution isn’t that hard since it has everything needed to make it work.

One of the biggest waaaaahbumlance calls is the fact that Entity Framework doesn’t have lazy loading. This isn’t true. It does, you just have to do a little work, which is to be expected from a FRAMEWORK. Now I have to admit, I wish there were a slightly less odd way of doing this, but eh it’s not too bad.

Say you have a class named Topic and it has a reference to a Forum class named ParentForum. Now this is just a property on the actual class created by the E-Work to represent a many to one foriegn key relationship between the Topic table and the Forum table. Now the problem comes in when you try to use something from that property like:

    Int32 someInt = topic.ParentForum.ForumId;

If you didn’t use the Include method when you got that topic:

    context.Include("ParentForum").Select(topic => topic);

You are screwed because the ParentForum property will return a null. So this forces you to use Include every time you want to get a Topic and access it’s ParentForum property. Sucks.

So next thought is to find out how to lazy load and then plunk it into that generated property. Eh I don’t know about you, but that sounds like a bad idea to mess around with a generated file. You have no idea when the E-Work will just trash the file and rebuild.

Next thought was to create a proxy property to check the real one and then load if it’s not already loaded. Something like:

    public Forum ParentForumLazyLoaded
    {
        get
        {
           //check and return
        }
    }

Ok so that’s not horrible except two things: The name looks dumb and people can still get at the original ParentForum property.

So in comes my solution and it’s pretty simple. Rename the property name on the class to something ParentForumInner and make it private.

bat_lazyload1

Then you can create a much nicer outward facing property like:

    public Forum ParentForum
    {
      get
      {
          if (!ParentForumInnerReference.IsLoaded)
          {
              ParentForumInnerReference.Load();
          }

        return ParentForumInner;
    }
    set
    {
        ParentForumInner = value;
    }
}

Now one of the issues with this is that although outside the class only the ParentForum property can be seen, within the class they both can be seen which can lead to issues like:

    context.Topics.Where(topic => topic.ParentForum.ForumId == id);  //boom

Where you should be using:

    context.Topics.Where(topic => topic.ParentForumInner.ForumId == id);  //yay

E-Work doesn’t know how to handle that situation when evaluating that expression and the kicker is that it does just fine compile time. You won’t know this is bad until runtime.

Other issue is that you have to do a little more work then just some setting on the property which is what most people wish for. I guess that may be true, but again this is a framework. It gives you all the tools you need to makes things work, you just have to do some coding.

The plus side to this is that with minimal coding, you can completely get rid of Include which to me is huge.

Just Use the Stupid Functionality

So something I’ve come across time and time again since starting to use ORMs (about 3 or so years ago) was the infamous “hydrate a reference object just to save another.” If you haven’t had this before, you probably will anyhow, but here’s what it is. Say I have a “Manny” object and I need to assign some kind of “fertility drug type” to it. Now this “fertility drug type” is basically representative of a table that has an id and description and nothing else really. Now the question is, if I know the ID of “HCG” is 1, should I bother even getting it from the database? I mean after all:

  Drug totallyNotUsingVitamins = toolContext.Drugs.Select(drug => drug.Name == "HCG");
  manny.DrugOfChoice = totallyNotUsingVitaminS;

Looks pointless when I can do this:

  playersObject.DrugTypeReference.EntityKey =
     new EntityKey("ToolEntities.BallPlayers", "drugOfChoiceID", 1);

Which was taken from here.

So here’s the problem: Why should I have to hit the database if I know what the ID is? I mean, that’s a trip I don’t have to make right?

If you’re asking that question, then it’s possible you don’t understand how a lot of ORMs work, or in this site’s case: The Entity Framework.

What it really comes down to a couple arguments:

  • What is the cost if it hits the database?
  • Is it actually hitting the database?
  • It’s just easier to set the ID

What is the cost if it hits the database?

Now the first one you could almost make an argument, after all what’s the point of hitting it if you don’t need to? This might seem silly:

  using(ToolEntities toolContext = new ToolEntities())
  {
    Drug totallyNotUsingVitamins = toolContext.Drugs.Select(drug => drug.Name == "HCG");
    manny.DrugOfChoice = totallyNotUsingVitaminS;
  }

If that is the only time you’re using this. A one off like that does seem to beg overdoing it. But really is it? This is probably the strongest argument for the straight ID set and really what is the real cost? In order to persist the object, a connection has to be created and the entity has to be persisted. So in reality, you have to create a connection any how, so the actually getting and hydrating of the reference object is just sort of tagged onto that and unless there is something wrong with the table or connection, this adds a minimal amount of time.

Is it actually hitting the database?

But what if this has to be run a million times? Then what? I have to get that item a million times and now my hits have gone from one million to two million?

  using(ToolEntities toolContext = new ToolEntities())
  {
    for(Int32 loopCounter = 0; loopCounter < someNumber; loopCounter ++)
    {
      Drug totallyNotUsingVitamins = toolContext.Drugs
                                       .Select(drug => drug.Name == "HCG")
                                       .First();
      manny.DrugOfChoice = totallyNotUsingVitaminS;
    }
  }

Ok not the best example, but the point is that within that using you will be updating a million records which you would assume that

  Drug totallyNotUsingVitamins = toolContext.Drugs.Select(drug => drug.Name == "HCG");

Would be run a possible two million times. You could make the argument that Entity Framework does make a select against the database even if the object is in the context. This is something I’ve thought rather odd myself. However, it’s just a query on an already open connection. And since creating the query is done the first time around, the acutal query being run is minimal in effort. Basically the hard work was does the first time around. The next time is nothing to really consider.

It’s just easier to set the ID

Ok so this one is hard to discredit since it is easier. It’s about one line less easier. Is one line really worth this? Is it worth the ease of understanding? From the first example, it’s pretty easy to understand what I’m setting. Select a drug type of “HCG”. Second one, not so much. All I see is an ID, so if I want to know what drug that is, I’d have to go searching for what that ID is. Also, from a spec level, it’s more clear to say:

Set DrugOfChoice to “HCG”

Then

Set DrugOfChoice to 1

Now I may be reaching on this last example, but as I said, it will be hard to prove that the second example isn’t “easier” coding wise. After all it’s one less line. However, when things like readablity comes in, I can’t see the second being a winner in that contest.

Once a person understands how an ORM like the Entity Framework works, it becomes apparent that some of the old ways of thinking need to be abandoned as in the long run they only hold overall development back. And beyond that, sometimes when we think we’re optimizing, we could actually doing more harm than needed. Losing readability for the sake of ridiculously small amounts of time just doesn’t make sense anymore.

Programmer: Hero to All or Digital Masochist?

Ok so it hit me the other day when I was asking myself why I program. Basically I’ve hit that point in my career where I am starting to re-evaluate what the s— I’m doing and why I’m doing it. Actually it was more like me lamenting over my current path and I came to the conclusion that if I didn’t program for a living, I’d still do it as a hobby. To this the woman asked, “If you like it as a hobby, why do you hate programming?” This got me to thinking, do I hate this all the time? And the answer is no. I think this overworked bin of waste I call a blog is a testament to what I do love about programming. You know, the new stuff. The discovery. And yes (And you know it) the elation and self pleasing like act of “Yeah, I figured that out. I’m f—ing smart and stuff.” I even like the building and designing of systems (Well the non UI part since I have a restraining order that doesn’t allow me to be within 50 feet of UI design). Actually I really like that stuff.

Here’s the bad. When do I actually get a chance to do that? When do most of us ever get to do that? Problem is that most programming jobs don’t entail this. How do I know this? Well in my short 8 or so year career, I’ve had a lot of programming jobs. 9 to be exact. And about eh 50+ interviews with companies. So basically like a follower of “free love”, I’ve been around. In those jobs and interviews I’ve had 1 job and 3 possible ones where I wouldn’t have just been either:

  1. Maintenance Boy
  2. Legacy Avenger

Now you might think it’s because I suck. Well that could be a reason, but that would imply that the people I’ve worked with sucked since they were stuck doing the same thing, regardless of their experience. I can’t believe everyone I’ve worked with sucked, but I have no real proof. Then again, this isn’t being submitted to Fox New– eh The New York Ti– eh some scientific journal.

So with this I’m going out on a limb here and going to guess that the people not in the top 15% of the programming world are stuck doing tasks that involve:

  1. Updating old code
  2. Fixing old code
  3. Adding to old code
  4. Creating new things but under old standards and frameworks
  5. Spending time trying to figure out a web of stored procedures so complicated it would make Brian Greene spin. (His ENTIRE body)

And people do this everyday and a lot of them bitch about it but when pressed wouldn’t want to do anything else. Why? Because we hate ourselves! It’s simple f—ing psychology. When you hate yourself, you do things to keep that feeling of hate alive. You will be drawn to people who most likely cause us grief. You will be drawn to a job that causes pain. Think about it:

  1. In most companies, IT is the lowest rung on the ladder.
  2. People have no idea what we do which leads to horrible deadlines. Read: “It won’t take that long, it’s just HTML.”
  3. We work on systems that we didn’t build and the people who came before us didn’t have a lot of concern about someone else having to work on it.
  4. The stuff we work with can be really expensive and therefore most companies are years behind on IDEs, frameworks, ect
  5. In the high school we call the workplace, we’re basically the kid taped to the goal post.

And the best part is we’re described as problem solvers, which means right off the bat our job consists of cleaning up someone else’s f— ups or we’re expected to figure out the things that some committee of tool bags couldn’t get their collective head around.

I mean what sane person does this willingly? You know what the kicker is? We get some crazy high from when we actually do pull off some crazy impossible. Tell me how is that different than getting some kind of high after running a blade down your arm? We get pleasure from pain. That is our existence. We are sick puppies.

I’m hungry.

Singleton ObjectContext: The remix

I realized that when I posted this, I didn’t actually post my way of solving the singleton context idea. Well it’s not a real singleguy anymore in the strictest sense. It is still used by pretty much all querying BUT it is used every postback. How did I do this? With a little enginuity, brilliance, and time. (Read luck and constant pounding on the keyboard)

The old idea was to have a single context that was held in a static (Therefore the context was static). Couple problems:

  • All queries and updates will be sharing this context… for every user. Hrm. I can’t see anything wrong with Sally Starshine hitting the old update button and saving Dick McGurk’s changes. Nothing wrong with that all.
  • Any changes to an object in the context will stay in the context until the various ways of “resetting” a static object are used, regardless of being persisted to the database. Basically, if you changed the user.UserName = “YouIdiot”, “YouIdiot” will now show up anywhere you use that context… which is everywhere.

So as you can see, disaster. Now, where could I have gone from here? Well insane first, then I found a solution… Page Requests. You see, when a request is made there are two events fired of importance:

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
    }

    protected void Application_EndRequest(object sender, EventArgs e)
    {
    }

Pretty snazy, right? Well these are fired with every request, so basically these are fired every postback… and then some. The next step I took was to make context creation and tear down methods. Something like on BeginRequest: If the context doesn’t exist, create and on EndRequest: If the context does exist, DESTROY. Well this worked at first… until I realized something. That cute little method BeginRequest fires on every request (Duh) meaning anytime the page requests an image. Hrm. That’s a lot of useless building right? Well it occurred to me the tear down on EndRequest was a good idea since it won’t do anything if the context doesn’t exist. No harm no foul. The problem was the BeginRequest. Fact is, the answer was stairing at me… I already had the build up method, I just had to call it when it mattered: First use. SO can you figure out what I did? I bet you can!

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Web;

    public class EntityContext
    {
        private TISQLEntities _context;
        private static String MAIN_CONTEXT_KEY = "MainContext";

        public static TISQLEntities Context
        {
            get
            {
               if (HttpContext.Current.Items[MAIN_CONTEXT_KEY] == null)
                {
                    CreateContext();
                }

              return (TISQLEntities)HttpContext.Current.Items[MAIN_CONTEXT_KEY];
            }
        }

        private static void CreateContext()
        {
           HttpContext.Current.Items[MAIN_CONTEXT_KEY] = new TISQLEntities();
        }

        public static void RemoveContext()
       {
           if (HttpContext.Current.Items[MAIN_CONTEXT_KEY] != null)
           {
             ((TISQLEntities)HttpContext.Current.Items[MAIN_CONTEXT_KEY]).Dispose();
             HttpContext.Current.Items[MAIN_CONTEXT_KEY] = null;
            }
         }
    }

Idiot simple, as it would have to be coming from me. You might have seen that I’m holding it in the current HTTPContext. This is to hold the needed context for the current request. Yippee.

Now for the use (In the Global.asax.cs file)

    protected void Application_EndRequest(object sender, EventArgs e)
    {
        EntityContext.RemoveContext();
    }

So what happens? First time I use the context:

    EntityContext.context.SiteUser.Load();

The EntityContext class creates the context and goes to town. When the request is done, the EntityContext class removes said context.

Now on a side not, you might notice that when doing unit tests, there is no HTTPContext. This is a problem and involves one more step (That I’m not completely happy with right now) that actually takes the old Static idea and applies it. Now you might thing that I’m undoing everything I just posted, but in reality when you unit test, most likely you’ll be doing it on your computer and therefore you won’t be running into anyone else’s context. (Unlike a web site)

    private static String MAIN_CONTEXT_KEY = "MainContext";
    private static TISQLEntities _context;

    public static void RemoveContext()
    {
        if (HttpContext.Current != null && HttpContext.Current.Items[MAIN_CONTEXT_KEY] != null)
        {
            ((TISQLEntities)HttpContext.Current.Items[MAIN_CONTEXT_KEY]).Dispose();
            HttpContext.Current.Items[MAIN_CONTEXT_KEY] = null;
        }

        if(_context != null)
        {
          _context = null;
        }
    }

    public static TISQLEntities Context
    {
        get
        {
            if (HttpContext.Current == null)
            {
                if(_context == null)
                {
                    _context = new TISQLEntities();
                }
                return _context;
            }

            if(HttpContext.Current.Items[MAIN_CONTEXT_KEY] == null)
            {
                HttpContext.Current.Items[MAIN_CONTEXT_KEY] = new TISQLEntities();
            }

            return (TISQLEntities)HttpContext.Current.Items[MAIN_CONTEXT_KEY];
        }
    }

I don’t like this one fully, but for now it’s good. There has to be a better way though.

Programming Techincal Interviews: Why bother?

You know what’s awesome besides me? Technical interviews. Nothing beats being asked obscure questions about things that are rarely used while on the phone. I’ve been through enough of these stupid things (20+? over a short 7 years) to have a certain feeling about them. And just in case you are wondering, I don’t think I’ve ever failed one. (Even the online ones where I’ve consistently been above 80% of the country since the first one I took 5 years ago) I’m not bragging that I’m exceptional at programming, because I’m not. Probably average. What I am getting at is that I might have a decent view on how pointless these things are in the current state.

Insert Question Here

I can’t tell you how many times I’ve been asked things like:

“What is protected internal?” (Something I’ve never seen a company use)

“Is string an object or a structure?” (It thinks it’s a structure, so who cares?)

And my personal favorite:

“Which is better StringBuilder or String Concatenation?” (Yes?)

I get tired of these questions because everyone asks the same damned ones to the point where I feel like I could pre-record my answers on a tape recorder (Or whatever the kids use these days) and play them back while doing something more fun like washing my hair. (RUN ON SENTENCE!!!!1171) It almost puts me into this weird trance like state where my mind is off getting coffee while my body just churns out answers. Or even worse, when I try to discuss certain answers (Say the inevitable StringBuilder question) I’m met with the phone’s equivalent of a blank stare. AND IT NEVER CHANGES. I’ve heard at least these three questions at probably 90% of the ones I’ve done including at least two just within the last 4 months. Seriously, enough with difference between a datareader and a f—ing dataset. I think most people know this by now or could be informed in 10 seconds of getting the job. Or better yet, use a f—ing ORM.

The Google Era

The fun part about this is these interviews can pretty much be found in 5 minutes of a little searching. I am willing to bet if you take down the 30 most popular ones found and memorized, you’d be in the door. In fact, I pretty much know this since I’ve kind of sort of done a little studying before the interview (IE read parts of a book) to look good. And it sure worked. Now I have to admit there were other factors (Like my stunning good looks) but there were loads of people who bombed out on the technical interview due to missed answers. Even better, next time you have a technical interview, look up Microsoft Programming Interview C# and find the simple questions. One by one you mark off every one that is asked like those stupid car games that you mark off every state you see on a license plate. It will at least keep you interested. Hell, share with your friends and see who marks them all first. Put money on it.

The Recruiter Issue

Another problem that adds to the eh problem is that recruiters will tell you what you’ll be asked (Or at least point you in the direction) so that you can be ready for what’s coming. Why would they do that? Well it’s their job to make money and they make money by getting people in the door, especially if you have ANY personality. (Another thing that can completely override this precious technical interview.) I would say this is bad practice and companies should be made, but like actors and tabloids, this is a symbiotic relationship. How do I know this? Because I’ve actually had recruiters give me a list of questions the company SAID THEY WOULD ASK. What the f— is the point of asking me stuff I already know is coming? Yeah good way to make sure I don’t know what I’m talking about.

I’m just a programmer.

Here’s a though, next time your company does a technical interview, get someone who isn’t in the middle of a 70 hour week. In my experience, the one giving the interview really has better things to do, which is probably why the form letter questions are so popular. Can’t say I haven’t been in the situation when someone comes to me and says, “Hey we’re interviewing someone right now, could you get some technical questions together?” At which point there are two options, get questions off of the intarweb or put your head through your monitor to get out of it. And trust me, the second choice rarely works. Product? The same technical interview you went through last week… and last year…

Out with the old, Outsource with the new

The best so far though was a company that does these “technical interviews” (Read, they are technically an interview). Really? Outsourced interviews? I guess when I found out about this I thought that maybe MAYBE since someone was getting paid to do this, it might be interesting. Yeah not so much. For a long time I thought the prerequisites were:

  • Knew some programming.
  • Would rather be doing something else.

Turns out they can completely eliminate the first and keep the second. I honestly was asked questions like, “So you program in the c#?” and “So you have been using the object oriented programming?” This is a horrible situation for two reasons. One, the person taking the notes has no idea if you’re right or wrong and therefore could easily misquote you. Two, you will have to be put on suicide watch during the interview since at some point you’ll decide chewing your heart out is the only feasible way to escape.

Sigh, I mean honestly why do companies still bother with these? I mean if there’s any constant in the programming world, it’s that tools get hired no matter what and the rest of the company has to deal with them. Why is this? Because in the end, money is what matters. Recruiting companies will keep helping these guys through because it increases the chance of getting someone to fill the spot. Companies keep hiring them because usually they are about 1-2k cheaper per year. So in one word: Brilliant.

Ajax Webmethods, Javascript, and Anonymous Types… Booyah

As witnessed in this super awesome post I showed how to use a webmethod to get server side information with client side methods. (I know, I’m pretty sweet.) And in this one I had an example of filling a drop down list with a web method and javascript, though it was more about the anonymous method used. So what do I have now? Well a little thing about why I heart anonymous types.

What’s an anonymous type? Well it’s a type that built at compile time and requires no class file to create, but you probably have already used them if you’ve used Linq:

    var anonymous = from item in list
                    select new {
                                 Name = item.Name,
                                 Address = item.Address
                                };

And now you have a whole list of a new type that is created at compile time. Anyways, you might have been wondering why you would want these beyond linq use. Well that’s what I’m here for… that and making sure I give you a low point in your day so that things can only get better.

Now in the example from before, it was basically the idea of filling a drop down list without a postback and using a WebMethod. Now I showed the javascript needed, but I didn’t show you the web method itself.
Time to start!

        [System.Web.Services.WebMethod]
        [System.Web.Script.Services.ScriptMethod]
        public static Object GetUserList()
        {
            IList <User>userList;

            userList = LinqData.DataClasses.User
                           .GetUserList("");
            return userList
                      .Select(item => new { item.UserName, item.UserID })
                      .ToList();
        }

So there you have a method that gets some users (Waring: Actual method may vary) and you are creating a list of anonymous types that have UserName and UserID.

Now you may have noticed this:

    .Select(item => new { item.UserName, item.UserID })

Now why would I want to do that? Why can’t I just send a list of users? Well there’s nothing really stopping you from doing that, after all javascript will handle whatever you throw at it. Problem is: If you send an entire user, you’re sending everything. What if the user has an image on it? (Like an avatar) Maybe the user has a collection of addresses. Point is, that’s a lot to send out when you only need the two things. (Text and value for the dropdown list) The beauty of the anonymous types is you don’t need a new class file for the smaller version of the user thus allowing you to create a specific type that is only needed for this situation.

The nice thing to take from this is that you can easily create the bare minimum and really not sacrifice much. Why is that? Well you would think that the type is created for every user or maybe every time there is at least one instance running on the server. Fact is, the type itself is created at compile time so you don’t suffer that kind of pain. Beyond that, and I said this before, Javascript is more than capable of “reading” and “knowing” what the class has so you don’t have to worry about it needing some class off in some class file to send.

Now you could argue that you should have that class file and that it’s just good practice but I’m not convinced in this case. Mostly because this is a one time situation but, and yes it sounds funny to use “situation” again, situationally this is specific only to this instance… SITUATION

I suppose someone could argue that if I use other anonymous types elsewhere that use the same properties than I should make a new class file. There’s probably some truth to this, but on the other hand is it really necessary to go that far if you aren’t certain? I don’t know. But then again I’m fascinated by popcorn so you might not want to take my opinions seriously.

C#, Var, and Objec- Propert- I have no idea what the term is

So I caugh this the other day and I’m not really sure it’s useful but it got me thinking…

Say you have a string and you want to create what ReSharper calls a “implicitly typed local variable declaration”, or as most people know it as “var”, and intialize it with a created value:

  String someThing = "hi";
  var onTheFly = new { someThing };

And now you can do this:

  String somethingElse = ontTheFly.something;

What it basically did was not only take the value of the string, but the name too and made a property on the var. In fact you may have seen this already with Linq:

    var hi = from item in test
               select new {item.UserRole};

    UserRole someRole = hi.ToList()[0].UserRole;

So what does this all mean? Right now, I’m not really sure. I suppose if you have a method that you want to combine a bunch of value/objects into one var so you don’t have to keep refering to 8 different objects that might work:

    //Get the user
    User user = new User (1);
    //Get some icecream... couldn't think of any better fake class name
    IceCream iceCream = new IceCream(1);

    var stuff = new { user.UserName, user.UserRoles, user.UserLastName,
                             iceCream.Flavor, iceCream.Texture };

    //IMAGINARY CODE GOES HERE
    //MORE IMAGINARY CODE
    //??
    //PROFIT
    if(stuff.UserName.Equals("Sean", StringComparison.OrdinalIgnoreCase)
       && stuff.Flavor == IceCreamFlavor.Chocolate)
    {
       //BLAH BLAH BLAH
    }

As you can see, it could be a way to group together a bunch of things in a method, but I’m not sure that is really useful.

*WARNING THIS IS NOT TO BE TAKEN AS FACT, JUST MUSINGS OF AN IDIOT*

Now for the theory… As is, this isn’t useful but with 4.0 that might change with Duck Typing and dynamic types. Why? Well take a method like this:

    CallMe(userName, userFirstName, userLastName, userAddress,
             thisIsStupid, makeItEnd, iNeedAnAdult... endMe);

Now that’s a lot of parameters. Conventional wisdom says I should create a new class whose properties match the parameters I would be sending in and just send in that class:

    parameterClass.UserName = userName;
    parameterClass.UserFirstName = firstName;
    .....
    CallMe(parameterClass);

Now the only annoying thing is having to make the class to do this. What if dynamic types + duck typing takes that step away?

    var parameter = new { userName, userFirstName, userLastName .... };
    CallMe(parameter);

Then CallMe would take in a dynamic type and just look to see if it has the needed properties. Would be nice if this is possible but I haven’t used 4.0 yet to know, I’m only guessing from what I’ve read.

Static Abstract … should I bother?

So it came up recently that someone was bummed that you can’t create a static abstract method. Now conceptually, this is blocked by C# but I came up with this “work around”… And I have no idea if I would ever use it. This was more of a “Do it because I can” rather than “Do it because I should.”

  public abstract class Parent
  {
    public abstract String ReturnAValue(String returnThis);

    public static String ReturnAValue(String returnThis) where K : Parent
    {
        K classToCreate;

        classToCreate = Activator.CreateInstance();
        return classToCreate.ReturnAValue(returnThis);
    }
  }

So what I did here was create a parent class that causes any child to override the ReturnAValue method so that I could create a static method on the parent that basically would just instantiate the child class and call the overridden method. How’s that for a run on sentence?

  public class ChildA : Parent
  {
    public override String ReturnAValue(String returnThis)
    {
        return "ChildA " + returnThis;
    }
  }

And this in full use:

  String testReturn;
  testReturn = Parent.ReturnAValue("returned");

Can you guess what that returns? If you can, you’re special. You might wonder why I have to use generics in this. Well I mean you could do this:

    public static String ReturnAValue(Parent returnThis)
    {
        return returnThis.ReturnAValue(returnThis);
    }

But that assumes you have to instantiate the child and pass it in.

Now the main problem with this, beyond the fact that you’ll probably never use this, is Activator.CreateInstance() need a default public constructor to use. Kind of a catch.

What Is Readable Addon

Quick thought too about which to use due to readability:

var you = from factor in seansAwesomeness
          select new FactorLite
          {
             Amount = amount;
          };

or you could do:

Func<Person, FactorLite> selectFactorLite = currentFactor => new FactorLite { Amount = currentFactor.Amount };

seansAwesomeness.Select(selectFactorLite);

I guess it’s a matter of preference, but the first seems way too verbose for something too simple.

What Is Readable

So a couple of posts I read recently have been about readability of Linq, more so Linq query expressions versus the Linq methods. Don’t know what I mean?

Expression:

var result = from knowledge in Sean
             select knowledge.Linq;

As opposed to:

var result = Sean.Select(knowledge => knowledge.Linq);

Personally I would replace the lambda expression with a Func, but I can live with it right now. Anywho, the argument is that the first looks better than the second. I really don’t see this as a looks problem, but a useage problem. Fact is, they both have their uses and you should know how to read both. Why is that? Well here’s an example CAUSE I KNOW YOU WANT ONE!

One of my earlier posts had to do with solving the FizzBuzz thing with Linq where I gave you this bad ass solution:

 var result =
      listToConvert
      .Where(WhereBothDivisible(fizzNumber, buzzNumber))
      .Select(selectKeyValuePair("FizzBuzz"))
      .Concat(
            listToConvert
            .Where(WhereBuzzDivisable(fizzNumber, buzzNumber))
            .Select(selectKeyValuePair("Buzz")))
            .Concat(
                  listToConvert
                  .Where(WhereFizzDivisable(fizzNumber, buzzNumber))
                  .Select(selectKeyValuePair("Fizz")))
                  .Concat(
                         listToConvert
                        .Where(WhereNeitherDivisable(fizzNumber, buzzNumber))
                        .Select(selectKeyValuePair("Nothing")));

As you can see, I’ve used both Func fields and methods to return Funcs to clean up how this would look. I’ll even show what it would look like without this approach:

var result = listToConvert.Where(currentItem =>
             IsDivisible(currentItem, fizzNumber) && IsDivisible(currentItem, buzzNumber)
             ).Select(currentItem => new KeyValuePair(currentItem, "FizzBuzz")).Concat(...

Now I can totally admit that this second one I am showing is just ouch. So the first lesson to be learn is that Funcs and Methods that return Funcs can significantly clean up the Linq Method approach.

Now you could do the same with expressions:

 var fizzBuzz = from currentNumber in listToConvert
                where WhereBuzzDivisable(fizzNumber, buzzNumber)
                select selectKeyValuePair("FizzBuzz");

 var buzz = from currentNumber in listToConvert
            where WhereBuzzDivisable(fizzNumber, buzzNumber)
            select selectKeyValuePair("Buzz");

 var fizz = from currentNumber in listToConvert
            where WhereFizzDivisable(fizzNumber, buzzNumber)
            select selectKeyValuePair("Fizz");

var neither = from currentNumber in listToConvert
              where WhereNeitherDivisable(fizzNumber, buzzNumber)
              select selectKeyValuePair("Fizz");

Ok so nice and pretty, but now what? Concatenation. This is where is gets ugly:

  fizzBuzz.Concat(fizz.Concat(buzz.Concat(neither))));

OR

 var fizzBuzz = from currentNumber in listToConvert
                where WhereBuzzDivisable(fizzNumber, buzzNumber)
                select selectKeyValuePair("FizzBuzz")
                .Concat(
                     from currentNumber in listToConvert
                     where WhereBuzzDivisable(fizzNumber, buzzNumber)
                     select selectKeyValuePair("Buzz"))
                     .Concat(....);

See what I’m getting at? The non expression one is looking a bit better now or maybe this is a fight to see which is less fugly. Now I admit that this may not be the best FizzBuzz solution, but it gives an example or where the Linq queries can go very wrong.