Fail Fast

failfast

For goodness sakes don’t swallow exceptions! It’ll kill you (not really)!!!

Don’t try to hobble along. If an exception is thrown, log it, present the user with a “Sorry, but we had a problem…” message and assure them you are on top of the issue and graceful close the application or restart it.

In business programming there is no reason to try to “Save” the context. It’s a disaster waiting to happen. By swallowing an exception the application is put into an unknown state. Badness can happen when your application is an unexpected state. Anything from data corruption to your application being compromised. One of the strategies of hackers is to test edge cases, looking for an in or an error to gain more information on compromising the application.

When your application throws an exception, logged it and close the application. The context may have been lost, but the application lives on.

The Three Tenets of Object Oriented Design

apple-pie-sliced

The three principles of Object Oriented Design.

P.I.E.

Polymorphism – Is the ability of an object to have more than one form.

Inheritance – Is the ability for an object to be sub classed from a base or parent class. Typically the child classes share some common functionality with the parent class.

Encapsulation – This is simply the hiding of implementation or data. “Don’t be concerned on how it’s done…”

Am I Due a Raise When I Graduate?

Stack Of Cash

I’d like to give the company the benefit of the doubt, but in my experience they don’t deserve it. They probably hired you at lower rate to get a steal. Remember, all businesses are in the game to make a profit otherwise they die, which is bad for you. At the same time, if you leave the company, they also loose. They have hiring costs and training costs invested in you and you have part of the company mind-share. They do not want to loose their investment in you.

If I was hiring you, I would bring you in as low as possible. Let’s say at 50k. If this your first professional job, you are probably use to making 10 to 15 dollars an hour. That is roughly 30k a year. They offer you 50k a year. That seems like a lot of money to you and you accept.

You graduate with a degree, yes you are worth more, but we started you out at 50k. We’ll give you a 10 percent raise. They will give you some line of crap about how a 10 percent raise is almost unheard of in the industry and it’s tough times! You can tell them it’s not enough and explain to them the average wage is 65k for your position and that you’ll cut them a deal and accept 70k. Because that’s how good you are. Or you can do what most people do and accept the 10 percent wage and feel all warm and fuzzy inside.

Are you willing to find another job? Your bargaining chip is you leaving. I’ve seen people ask for a raise and not get it. They leave company and come back a year later taking a higher position and making double their old salary.

WordPress 3.5.1 MultiSites on Windows Azure

191935013_36f9e4569b

Out of the box the web.config included does not work with sub-directories.

The following web.config worked for me on Windows Azure:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <rewrite>
      <rules>
        <rule name="WordPress Rule 1" stopProcessing="true">
          <match url="^index.php$" ignoreCase="false" />
          <action type="None" />
        </rule>
        <rule name="WordPress Rule 2" stopProcessing="true">
          <match url="^([_0-9a-zA-Z-]+/)?files/(.+)" ignoreCase="false" />
          <action type="Rewrite" url="wp-includes/ms-files.php?file={R:2}" appendQueryString="false" />
        </rule>
        <rule name="WordPress Rule 3" stopProcessing="true">
          <match url="^([_0-9a-zA-Z-]+/)?wp-admin$" ignoreCase="false" />
          <action type="Redirect" url="{R:1}wp-admin/" redirectType="Permanent" />
        </rule>
        <rule name="WordPress Rule 4" stopProcessing="true">
          <match url="^" ignoreCase="false" />
          <conditions logicalGrouping="MatchAny">
            <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" />
          </conditions>
          <action type="None" />
        </rule>
        <rule name="WordPress Rule 5" stopProcessing="true">
          <match url="^[_0-9a-zA-Z-]+/(wp-(content|admin|includes).*)" ignoreCase="false" />
          <action type="Rewrite" url="{R:1}" />
        </rule>
        <rule name="WordPress Rule 6" stopProcessing="true">
          <match url="^([_0-9a-zA-Z-]+/)?(.*.php)$" ignoreCase="false" />
          <action type="Rewrite" url="{R:2}" />
        </rule>
        <rule name="WordPress Rule 7" stopProcessing="true">
          <match url="." ignoreCase="false" />
          <action type="Rewrite" url="index.php" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>

Comparing Enums With the Same Values

comparing_notes_popupRecently I came across some code where a switch statement was used to convert one Enum to another Enum. There were over 20 cases in the switch statement. The kicker was the values were the same. Why did they not use a single Enum? I’m still trying to figure that out.

I wrote some code that eliminated the massive switch statement:

        public TTo MapEnum(TFrom from)
            where TFrom : struct, IConvertible
            where TTo : struct, IConvertible
        {
            System.Diagnostics.Contracts.Contract.Requires(!typeof(TTo).IsEnum, "TTo must be an enumerated type");
            System.Diagnostics.Contracts.Contract.Requires(!typeof(TFrom).IsEnum, "TFrom must be an enumerated type");
          
            string fromValue = Convert.ToString(from);

            TTo toEnum;
            bool found = Enum.TryParse(fromValue, true, out toEnum);

            if (!found)
            {
                throw new Exception("Could not find value {0} for type {1} in enum {2} ");
            }

            return toEnum;
        }

Writing the SVN Reversion to a File in TeamCity

I spent hours trying to figure this one out. It turned out brain dead simple.

  1. Add a build step
  2. Select the command line runner type
  3. Set the working path to the path you’d like to save the version file too.
  4. In the Custom Script Text Field add the following text: ECHO %build.vcs.number% > version.txt

Considerations When Throwing Exceptions

iStock_000007846219_ExtraSmall

A co-worker sent an email with some code he’s struggling with. He’s trying to avoid using try/catches to drive business logic.

The problem is not the try/catches it’s simply a symptom of the problem. Can you spot the problem? You’ll have to make some assumption, but I have faith you’ll come to the same conclusion I came too.

The code is below; I changed it to protect the innocent:

private Customer GetOrCreateCustomer(long customerTelephoneNumberOrCustomerId)
        {
           Customer customer;
            try
            {
                customer = this.DoMagic(customerMasterTelephoneNumberOrCustomerId);
            }
            catch (DataException)
            {
                try
                {
                    //TODO: I know this isn't ideal. Still thinking of a better way to do this. 
                    customer = this. GetCustomer(customerMasterTelephoneNumberOrCustomerId);
                }
                catch (DataException)
                {
                    customer = this.GetCustomerFromExternal(customerMasterTelephoneNumberOrCustomerId);
                    customer.CustomerId = this.CreateCustomer(customer);
                }
            }

            return customer;
        }

There is an underlining philosophy in this system that nulls are bad. In most cases where a null can be generated an exception is thrown. At first I did not see a problem with this. I saw it as an architecture decision, an aesthetic, but as I interface with the code, it’s apparent to me it’s an architectural mistake.

You might ask, why is throwing an exception in the case of nulls bad?

Below are some guidelines when considering throwing an exception:

  1. The fact that you have to check for the null to throw the exception should be a hint that it is not needed. It an expected outcome, thus not an exception.
  2. Throwing an exception is a resource intensive operation, one of the most resource intensive operations that can be done in .Net.
  3. An exception is just that, an exception. It’s an exception to the assumptions made in the code – when these assumptions are broken, the system must terminate, it cannot move on because the system is in an unknown state (i.e. the database is no longer available) this could also be an attack vector.
  4. Throwing an exception means you have to wrap the upstream call in a try/catch block to enforce business rules. A null value is a business opportunity to control the flow of the application. The action upon the null value should be done at the point in which a business decision must take place. For example, a customer variable is null, at the UI layer a message is shown to the user stating the customer with id ‘1234’ cannot be found.

Naked WHERE Clause

iStock_000017613670_Small

In a conversation today, my coworker mentioned a ‘naked WHERE clause’. I’d never heard of the term. I posted a question on StackOverflow and an answer was posted shortly thereafter.

A naked WHERE clause would refer to something that always returns true.

WHERE 1 = 1

This is commonly used on something like a search form where the user can enter one or many values and rather than checking a counter to see if you need to add a WHERE clause you add a generic WHERE clause and build everything up in an AND clause. You can run into issues if you aren’t checking to make sure there is at least on AND clause added.

My first reaction was, why would someone do this and what is the big deal.

Then it hit me. A naked where clause is the same as a select without a where clause.

A Year as a Government Employee

capital

Truth be told, I was not actually a government employee. I was a contractor, but the agency I worked at treated me as a full-time employee.

I was hesitant in taking the job. I’d heard bad things about government positions: the red tape will drive you crazy, you cannot get anything done, government workers are only there for the paycheck, they are lazy, they sleep at their desks, they cannot be fired… the list goes on. Some of this is true, most of it is not.

To say government employees cannot be fired is a stretch of the truth. They can be fired, but it takes detailed documentation of disobedience, and even then rehabilitation must have been tried and clearly documented.

By far the most shocking experience was walking around the office the first week and seeing everyone and when I say everyone, I mean EVERYONE watching NetFlix. WTF!?! Really? It’s even talked about in the office. “Oh, I am waiting for Ed to get done. He said he’d be done in about 30 minutes. In the meantime I’ll watch some NetFlix.”

I’m a man who works best when I have a goal. In profit driven organizations the ultimate goal is simple: Be profitable. In government agency there is no such overarching goal. This makes sense. You don’t want a profit motivated fireman or police officer — Only the wealthy neighborhoods would be patrolled. The dark side of this mentality is there is no motivation to saving money. This is seen in the 10,000 dollar hammer. In my government position, I coded many projects 3 times over. I would spend weeks on a project that would be canceled, why? The vision had changed.

Would I work a government contract again? Yes. However, I would not take a full-time position as a government employee. I found it hard to be motivated when I could not see how my efforts fit into the success of the agency.

Don’t Write ETL in C#

Unless ETL is the company’s core competency there is very little reason to write and maintain ETL in C#. In the short term it’s going to be expensive, it will be slow, there will be mistakes (i.e. corrupt data), there will be edge cases, there will be duplication between ETL implementations, it will be fragile and it will be increasingly expensive in the long run. Honestly, what developer wants to spend his/her days writing and maintaining ETL in C#? I’ve done it. It’s about as far away from creative work as one can get.

Use a tool like Informatica, a company whose business is ETL. They’ve been working this problem for over 15 years. They have it solved. Their tools are drag and drop, reusability is built-in, as is performance. Most anyone (i.e. developers don’t have too) can create ETL with Informatica tooling. I’m not trying to sell Informatica, use any tool. Just don’t re-invent the wheel and write custom ETL code.

In the long run buying a tool, such as Informatica or using SSIS will save the company potentially millions. And best of all you will not have to maintain the ETL or be responsible for it when it breaks.