RSS Feeds

Saturday, 16 February 2013

Are you a Senior Developer?

Accountability in the Software Industry

The general mentality of software industry is fundamentally flawed by arrogance, misunderstanding and lack of accountability. Making bad software is easy, anyone can do it. If you don't think you have ever done it, then you are still doing it.

Managers And Team Leaders

Sadly the same thing that makes a good manager is what makes a bad one. Ego. It makes you believe in yourself and your ideas enough to make the tough architectural decisions that need to be made. However, bad managers have some additional traits. Usually they have been been working for the same company for a number of years and have some glorified self important title like "Chief Software Architect" or some BS like that. These people will generally have some over the top coding standards that force upon developers like still insisting they use Hungarian notation despite the fact you have been using C# or Java for the last 5 years because it was they used in University. This, however, is where the personalities diverge into 2 types.

Personality 1(The Obsolete):

The easiest way to spot these people is ask them what they think about the new [insert random technology reference]. They will NEVER know what you are talking about. They are the "Chief Software Architect" they don't need to know little things like what you can and cant do with a language, details details details.

Personality 2(Loves Shiny Things):

Personality two is a bit harder to spot, it requires some digging. Generally the easiest way to spot these people is ask them what they think about a new technology that they think they know quite well and see how they have chosen to implement it. They will usually have gone the route of early optimization, not have a clear understanding WHY and WHEN to use something. A little more digging will reveal that they also don't understand basic things like unit or integration testing and they are usually fond of a multi-threaded solution.

Well both these people are responsible for not only creating bad software but the future generation of developers. These developers then leave and think that is how software development is meant to be done. Its creating a broken industry.


Senior Developers

How many industries do you know where your are considered "Senior" after 2 years. None. Its ridiculous to think that your are Senior anything after 2 years in any industry. Ego makes people want to achieve that goal as quickly as possible, and ego is what they gain from it. Arrogance and ignorance can be very dangerous. We are now in the age where writing bad software can kill people, lose millions and cause untold chaos. You know who is writing this software.... Senior Developers.

You Signed It

Making good software is hard. It requires practice discipline and EDUCATION. Just like any other industry, the software industry should have a board and a apprenticeship program that requires you to understand industry practices that should be renewed every X number of years. If a building falls down who gets blamed? The Architect. If your new car breaks down who gets blamed? The Manufacturer. If your software doesn't work who do you blame? Blame yourself you signed the EULA.

Thursday, 24 June 2010

Understanding IEquatable

Since Generics came along in C# 2.0 we have had a new interface to allow for type safe comparisons. That Interface is IEquatable which is a vast improvemnet over the previous Equals that was hung off object in the BCL.

MSDN Says:

The IEquatable interface is used by generic collection objects such as Dictionary, List, and LinkedList when testing for equality in such methods as Contains, IndexOf, LastIndexOf, and Remove. It should be implemented for any object that might be stored in a generic collection.

If you implement IEquatable, you should also override the base class implementations of Object.Equals(Object) and GetHashCode so that their behavior is consistent with that of the IEquatable.Equals method. If you do override Object.Equals(Object), your overridden implementation is also called in calls to the static Equals(System.Object, System.Object) method on your class. This ensures that all invocations of the Equals method return consistent results.

So how would I use IEquatable? I always liked using code to demonstrate.

public class IEquatableOverride
{
    private static Dictionary<Person,Person> ObjectDic = new Dictionary<Person,Person>();
    private static Dictionary<int, Person> IntDic = new Dictionary<int, Person>();


        public static void  LoadDictionary()
        {
            Person p = new Person();
            p.PersonId = 101;
            p.First = "John";
            p.Last = "Doe";
            p.Age = 30;
            p.Address = "My Address";

            ObjectDic.Add(p, p);
            IntDic.Add(p.PersonId, p);

            Console.WriteLine(" Can Find Object "+ObjectDic.ContainsKey(p));
            Console.WriteLine(" Can Find by Key " + IntDic.ContainsKey(p.PersonId));


            Person p2 = new Person();
            p2.PersonId = 101;
            p2.First = "John";
            p2.Last = "Doe";
            p2.Age = 30;
            p2.Address = "test";

            ///R1
            Console.WriteLine(" Can Find Object " + ObjectDic.ContainsKey(p2));
            Console.WriteLine(" Can Find by Key " + IntDic.ContainsKey(p2.PersonId));

        }
    }

    public class Person : IEquatable<Person>
    {
        public int PersonId { get; set; }
        public string First { get; set; }
        public string Last { get; set; }
        public int Age { get; set; }
        public string Address { get; set; }

        //Commenting this out result in #R1 being false
        public override int GetHashCode()
        {
            ///In propper use this should be immutable
            return First.GetHashCode() ^ Last.GetHashCode() ^ Age.GetHashCode();
        }

        public bool Equals(Person person)
        {
            if(person == this)
                return true;
            if(person.First == this.First && 
               person.Last == this.Last && 
               person.Age == this.Age)
                    return true;

            return false;
        } 
  }


So as you can see above if we don't override GetHash then when compareing values in a Dictionary we would get erroneous results. This seems to work but why would I override GetHash if I wasn't using the object as the key and why do I need to override Object.Equals I thought that was the whole point of having Generics?

Yes that is the point of generics but there was life before generics one example would be an ArrayList. Anybody remember those bad boys? Well if we create a new ArrayList and add p to it and then compare it to p2 like so:
arrayList.Add(p);
Console.WriteLine("Can Find in ArrayList " + arrayList.Contains(p2));

Can anybody guess what the output of the above line will be? Yep you guessed it False. It is still using the old Object.Equals if we add this to our person class everything turns peachy.


public override bool Equals(object obj)
        {
            Person person = obj as Person;
            if (person == this)
                return true;
            if (person == null)
                return false;

            if (person.First == this.First &&
               person.Last == this.Last &&
               person.Age == this.Age)
                return true;

            return false;
        }

OK but what if we just use generic lists that implement IEquatable so I don't to worry about Object.Equals and I am using a primary key for my Dictionary key. So I am not going to bother with Overridding GetHashCode either.

Nope wrong again, LinQ is also a friend to GetHashCode so even though I am currently not using LinQ functionality in my results if I ever chose to do so and used a method like Distinct or Group By I would not get the results I would expect. So in short even though we have our brand new fancy interface we need to be careful how we use it.


Further Reading:

From Jaredpar

CodeBetter

Saturday, 20 March 2010

NHibernate.ByteCode.Castle.ProxyFactoryFactory

Anyone seen this error message?

Unable to load type 'NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle'
 during configuration of proxy factory class. 
Possible causes are: 
- The NHibernate.Bytecode provider assembly was not deployed. 
- The typeName used to initialize the 'proxyfactory.factory_class' 
property of the session-factory section is not well formed.

Solution: 
Confirm that your deployment folder contains one of the following assemblies: 
NHibernate.ByteCode.LinFu.dll 
NHibernate.ByteCode.Castle.dll

Well after hours of searching I finally found that if I changed my target build from x86 to x64 the problem resolves itself. This has to go into my top 10 most annoying bugs of all time.

Sunday, 7 March 2010

Better then FizzBuzz

Anyone that has done a few interviews has come to conclusion that a lot of people that apply for programming jobs cant program. In response to this usually the first question given to new applicants is a simple programming question like fizzbuzz. FizzBuzz is an interesting problem but there is a lot of other problems out there that are just as simple and can provide much more information.

Collatz conjecture

Take any natural number n (excluding 0). If n is even, halve it (n / 2), otherwise multiply it by 3 and add 1 to obtain 3n + 1. The conjecture is that for all numbers this process converges to 1. It has been called "Half Or Triple Plus One", sometimes called HOTPO.


public static void Calculate(Int64 val)
{
    if (val > 1)
        if (val % 2 == 0)
            Calculate(val / 2);
        else
            Calculate(val*3 + 1);
}

public static void CalculateCollatz2(Int64 val)
{
   while(val != 1)
   {
       if (val % 2 == 0)
           val = val / 2;
       else
           val = val*3 + 1;
    }
}

This is one of my favourite tests, any programmer should be able to see in seconds that the very nature of this problem lends itself to a recursive solution. They should also see the obvious stackoverflow that is possible. Either solving this recursively(Calculate) or with an iterator(Calculate2) allows you to dig a little further into the candidates programming knowledge.


Reversing a String

Given a string reverse the output


public static string Reverse(string inValue)
{
    StringBuilder sb = new StringBuilder();
    foreach (char c in inValue.Reverse())
        sb.Append(c);  
    
    return sb.ToString();
}

public static string Reverse2(string inValue)
{
    int length = inValue.Length;
    char[] charArray = new char[length];
    foreach(char c in inValue)
        charArray[--length] = c;
    
    return new string(charArray);
}

public static string Reverse3(string inValue)
{
    char[] charArray = inValue.ToCharArray();
    Array.Reverse(charArray);
    
    return new string(charArray);
}

public static string Reverse4(string str)
{
     char[] charArray = str.ToCharArray();
     int len = str.Length - 1;
            
     for (int i = 0; i < len; i++, len--)
     {
         charArray[i] ^= charArray[len];
         charArray[len] ^= charArray[i];
         charArray[i] ^= charArray[len];
     }
     return new string(charArray);
}

This question is very open ended and leading. It is open enough to see if you can entice the candidate to ask some questions about the functions possible use. The result is equally as useful. Some will use the C# library(Reverse, Reverse3) to help themselevs out. Others, usually with a C++ background, will code it with a simple for loop like in Reverse2. If they are really creative they will do some XOR Bit Shifting(Reverse4) (as I found demonstrated). Equally, the question can be used to lead to such things as Big O notation or memory footprints etc. It is possible to mix it up a little as well asking them to check if the string is a palindrome etc.

Two lists Problem

Given two lists remove all the values from the first list that are present in the second list.

public static IEnumerable<int> ConvertList(List<int> inMain, List<int> inExclude)
{
   return inMain.Except(inExclude);
}

public static List<int> ConvertList2(List<int> inMain, List<int> inExclude)
{
    foreach (var i in inExclude)
        inMain.Remove(i) ;

    return inMain;
}

public static List<int> ConvertList3(List<int> inMain, List<int> inExclude)
{
    bool found;
    List<int> newList = new List<int>();
    foreach (var im in inMain)
    {
        found = false;
        foreach (var ie in inExclude)
        {
            if (im == ie)
                found = true;
            
        }
        if(!found)
            newList.Add(im);

    }
    return newList;
}

This is not my favourite question but a lot of candidates either wont be able to answer it or will come up with an implementation like shown in example 3 which is generally a bad sign.

Bonus
Given an Integer how would you store multiple boolean values.

[Flags]
public enum Permissions
{
    Read = 1,
    Write = 2,
    Update = 4,
    RunScripts = 8,
    All = Read | Write | Update | RunScripts,
}

I really don't consider this a very good opening question but it could be asked at some point during the interview process to get an idea of overall knowledge.

I think the idea behind FizzBuzz is a great one, however, if you are truly interested in not wasting time then it isn't enough to just find out if they can code a simple problem. You need to use that simple problem to extract as much information as possible in the shortest amount of time.

Saturday, 23 January 2010

Reshaper and F# Remapping the Shortcuts

I installed F# the other day and when I went to fire up the interactive window I thought wait this seems really familiar... I am sure I use this command for something else, sure enough I was correct, it is a Resharper shortcut for quick edit.

Fortunately, as of version 1.9.9, they have made the shortcut super easy to find by calling it
EditorContextMenus.CodeWindow.SendToInteractive
In version 1.9.4 it WAS called
Microsoft.Fsharp.Compiler.VSFSI.Connecdt.ML.SendSelection
but I guess having the words FSharp in the name made it too easy to identify. If you too need to remap it go to Tools --> Options --> Environment --> Keyboard and type "SendTo" or "SendLine" to remap your F# interactive shortcut!

Monday, 11 January 2010

When to use a Window Services

Why does everything need to be a service? Almost every company I have worked for has requested some kind of automated process. Anything from a nightly ftp upload to cleaning up some DB records. Sure enough someone always suggests a windows service.

Windows says a service is:
A program, routine, or process that performs a specific system function to support other programs, particularly at a low (close to the hardware) level. When services are provided over a network, they can be published in Active Directory, facilitating service-centric administration and usage. Some examples of services are the Security Accounts Manager service, File Replication service, and Routing and Remote Access service.



Console App and the Windows Scheduler
Windows has a built in scheduler that is perfect for TIMED jobs, that in combination with the a simple console app is perfect for these types of requests. Simple to build, simple to debug, simple to deploy and simple to maintain. What asset does it bring to the business to create a Service? Most of the time the person doing the recommending either doesn't really know what a service is for or they are just attempting to challenge themselves? Console apps are so much better in most cases. You can kick off a console app whenever you want, you can change it and work with it on the fly, rerun it whenever you want, and generally speaking you are going have a harder time accidental bringing down a server with a console app

99% of the time a console app is going to be less intense on the server then a service especially if that service is poorly written, like the person that suggests we build a service with a timer to kick off processes, probably should not be your first choice of someone to take advice from.

Windows Services
Windows Services can be very useful and necessary but like everything it needs to be used when the business needs actually justify it. If you need to monitor a directory, use a service. If something on the server needs to up and running at all times, use a service. Services do have some built in advantages over a console app such as failure recovery. Such as "do nothing", "restart the service", "run a different app" or "restart the computer". I personally love the restart the computer option.

Both Windows Services and console/windows scheduler have their place just be sure you have a think about what you really need and how much business value the service your itching to build really brings.

Sunday, 28 June 2009

Caching in .NET

As applications grow it is quite normal to leverage caching as a way to gain scalability and keep consistent server response times. Caching works by storing data in memory to drastically decrease access times. To get started I would look at ASP.NET caching.

There are 3 types of general Caching techniques in ASP.NET web apps:

Page Output Caching(Page Level)
Page Partial-Page Output(Specific Elements of the page)
Programmatic or Data Caching

Output Caching

Page level output caching caches the html of a page so that each time ASP.NET page requested it checks the output cache first. You can vary these requests by input parameters(VaryByParam) so the the page will only be cached for users where ID=1 if a requests come in where ID=2 asp.net cache is smart enough to know it needs to re-render the page.

Partial-Page Caching

a lot of times it wont make sense to cache the entire page in these circumstances you can use partial Page caching. This is usually used with user controls and is set the same way as page level only adding the OutputCache declarative inside the usercontrol.

Data Caching

You can store objects or values that are commonly used throughout the application. It can be as easy to as:

Cache["myobject"] = person;
Enterprise Level Caching

It is worth mention that there are many Enterprise level caching architectures that have come about to leverage the effectiveness caching. Memcache for .net and Velocity are a couple.

In General

You can't really make blanket statements on what you should and shouldn't cache because every application is different. However, you can make a few generalizations that hold true MOST of time. Static elements like images and content are OK to cache. Even a dynamic page that is getting hammered is worth caching for 5-10 seconds, it will make a world of difference to your web server.

Caching overview