Prairie Developer Conference – Review

Another PDC has come to an end. Too soon.

Aside from the knowledge, the number one thing I take away from conferences like PDC is a feeling of motivation. I have ideas popping into my head throughout the sessions. I’m adding project ideas to my already long list of ideas. I have a renewed passion for programming.

The second thing I take away, is what I missed. There are so many great speakers, and too little time. Every session is a choice. Do I go to the DDD talk by Belcham? Or Dave Mosher’s talk on AngularJS? And what happens when when the session finishes and you’re excited? You compare notes with a friend who went to another talk, and you BOTH wish you could also have seen the other talk…and sometimes the other two as well!

I went to a few mobile development sessions as well, and while I have always wanted to write an app, I was never motivated enough. I had some ideas, but for iOS, you need a Mac…and then there is that $99 fee. And I’d need to use Objective C…and manage memory? It’s 2013…why would I want to do that. But, tooling has come a long way. And after I click submit on this post, I’m going to start installing Xamarin and get started on my first mobile app. I’m going to write it for Android first and see how it goes. Probably then make a nice Responsive HTML5 app as well, so that iOS, BB, and Win users can still use it…and maybe then I’ll have the extra motivation to get a Mac, and write a native iOS app. And after that…who knows.

There was also a really interesting talk on Hacking Hardware by Donald Belcham…which, coincidentally, gave me a simple hardware idea that can work with the mobile app I’m about to write.

So if you went to PDC, and didn’t learn anything, I’ll be shocked. It’s hard to listen to such great speakers, talking about things they are passionate about and not get caught up in it.

…now I have some development to do.

ps. It’s finally spring in Manitoba, I’m on the back patio relaxing as I write this…I need to work outside more!

pps. Thanks to D’Arcy and his staff, and ALL the sponsors for such a great event.

AOP – Logging with Unity

I couple months ago I was tasked with adding logging to an application we are developing. Now, the typical way people handle this, is with a call to “Logger.Log” wherever they want to log that an activity took place. However, this relies on the programmers memory, and while the original team members may know and remember to keep up this practice. The new guy on the team may not. And this is where this technique really starts to break down. Logging is a cross cutting feature. We can’t keep all the code in one place, because it’s called from all over the application.

The solution, is AOP (Aspect Oriented Programming). Since we were using Unity, it’s quite simple to intercept calls based on an interface. There is more it’s capable of, but the issue I had was I couldn’t find a simple, “hello world” example. Everything felt the need to over complicate the example.

First things first, on your project, right click, Manage NuGet packages and add Unity Interception Extension.

Second: Config changes

<?xml version="1.0"?>
<configuration>
    <configSections>
        <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
    </configSections>
    <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
      <sectionExtension type="Microsoft.Practices.Unity.InterceptionExtension.Configuration.InterceptionConfigurationExtension, Microsoft.Practices.Unity.Interception.Configuration"/>
 
      <container>
        <extension type="Interception" />
 
        <register type="LoggingTest.Namespace.IInterfaceToLog, LoggingTest.Namespace.Assembly">
          <interceptor type="InterfaceInterceptor" />
          <interceptionBehavior type="LoggingTest.Namespace.Loggers.LoggerBehavior, LoggingTest.Namespace.Assembly"/>
        </register>
      </container>
    </unity>
</configuration>

Third: Create Behavior

   public class LoggerBehavior : IInterceptionBehavior
    {
        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            var stopwatch = new Stopwatch();
 
            var logger = LogManager.GetLogger(input.MethodBase.ReflectedType);
 
            var declaringType = input.MethodBase.DeclaringType;
            var className = declaringType != null ? declaringType.Name : string.Empty;
            var methodName = input.MethodBase.Name;
            var generic = declaringType != null && declaringType.IsGenericType
                              ? string.Format("<{0}>", string.Join<Type>(", ", declaringType.GetGenericArguments()))
                              : string.Empty;
 
            var argumentWriter = new StringWriter();
            for (var i = 0; i < input.Arguments.Count; i++)
            {
                var argument = input.Arguments[i];
                var argumentInfo = input.Arguments.GetParameterInfo(i);
                argument.Dump(argumentInfo.Name, argumentWriter);
            }
            var methodCall = string.Format("{0}{1}.{2}\n{3}", className, generic, methodName, argumentWriter);
 
            logger.InfoFormat(@"Entering {0}", methodCall);
 
            stopwatch.Start();
            var returnMessage = getNext()(input, getNext);
            stopwatch.Stop();
 
            logger.InfoFormat(@"Exited {0} after {1}ms", methodName, stopwatch.ElapsedMilliseconds);
 
            return returnMessage;
        }
 
        public IEnumerable<Type> GetRequiredInterfaces()
        {
            return Type.EmptyTypes;
        }
 
        public bool WillExecute
        {
            get { return true; }
        }
    }

That’s it. One simple class that does the logging. And a config change to mark what interfaces you want logged.

        <register type="LoggingTest.Namespace.IInterfaceToLog, LoggingTest.Namespace.Assembly">
          <interceptor type="InterfaceInterceptor" />
          <interceptionBehavior type="LoggingTest.Namespace.Loggers.LoggerBehavior, LoggingTest.Namespace.Assembly"/>
        </register>

This config change will run the LoggerBehavior on the methods defined in LoggingTest.Namespace.IInterfaceToLog. If you want to log the methods on more interfaces, just add another register node to the config. While you still need to add these manually. You do it at the interface level, rather than the method level. AND you can add/change what is logged after compiling.

There is more you can do, check the Unity codeplex page.

Red, Yellow, Green

So, random thought while driving into work the other day. Why do we have three lights on traffic signals? Why not just a green countdown until the lights turn red. Yellows aren’t always the same length, and we have no clue when the green is going to change… with a timer we could reduce accidents significantly. There’s no more ambiguity about “I had a yellow” after the accident that happened because they yellow was one second, and the person who legally entered on a yellow, but had to cross eight lanes, which given the short yellow, is impossible.

20 GOTO 10

I was hooked.

10 PRINT "HELLO CAFFGEEK! "
20 GOTO 10

I don’t remember how young I was (under five), but the first time I saw that repeated over and over on the screen, with my name, and nobody repeatedly typing it, a seed was planted. I spent countless hours typing in programs from magazines, and computer books. And countless more hounding my parents to type it for me as they were faster. Games like Face Painter only watered that seed. But it was dormant for a while.

Atari 800XL
Atari 800XL

After the Atari 800XL was no longer a viable computer and had been packed away, I made do without a computer for many years. Unimaginable now. Pretty common in the 80’s. Then, when I was in junior high, fertilizer was added. My parents were able to afford a 286 computer. My dad liked to take things apart and see how they work. So learning hardware and how to upgrade them quickly followed. I built my own computer from spare parts. Shortly after a friend introduced me to Turbo Pascal.
Turbo Pascal
Turbo Pascal 5.0

I spent time writing all kinds of things, little paint programs. Terrain tile models for games that I never built. Small little games, reminiscent of those I played on the Atari as a kid. Even writing my own 3d routines to draw, rotate, and shade objects. Some of these I recently uncovered on some 3.5″ diskettes. Maybe I’ll find a drive and see if I can view my first forays into programming (scary they may be). From then on, there was little doubt about what I would eventually do for a living. And here I am today. Still playing. Still learning. Still amazed.

Where were you? What’s your story?

Secure Passwords…are they really?

Why do so many sites require me to enter a weak password? They claim to require a strong password, they also will show a handy dandy password strength meter. However, most of the time they restrict how strong my password can actually be.

They limit the number of characters to 8 – 15. I want a longer password!
They limit the special characters I can use. Why can I use an exclamation point, but not an ampersand?

http://xkcd.com/936/
correct horse battery staple

It’s a password, nothing should be off limits! If I want my password to be “clip clop coconut horse riding swallows” I should be able to use it, it’s simple to remember, and hard to guess.

This is more secure and easier to remember than a password like ‘c0rnf1@k3s’. But on most sites, it would be rejected because it’s just alphabetic.

Let’s check some stats at https://www.grc.com/haystack.htm

The password “c0rnf1@k3s” would take 9.47 months at 100,000,000,000 guesses/second (One Hundred Billion).
The password “clip clop coconut horse riding swallows” which only requires I remember 6 words would take 3.74 trillion trillion trillion trillion centuries.

Now, this isn’t actually quite that strong, as I’ve effectively just replaced letters with words. So, when doing a brute force attack, the attacker would know that, they just need to combine words, instead of letters to generate passwords. That is, if everyone were to switch to this technique, and the attacker included this password scheme. And since this password is only 6 words long it’s pretty weak…right? Well, according to here, there are between 170,000 and 750,000 depending on your definition of a word. Since in the case of passwords the word dog, and dogs are completely different, we could safely say, there are 750,000 one word passwords. I’m using six in a nonsensical order. Which means if I did my math correctly there are about 750,000^6 = 1.77978515625e35 different possibly 6 word passwords. At one hundred billion guesses per second it would still take 5.63992e14 centuries to go through all the possibly combinations, that’s no 3.74 trillion trillion trillion trillion centuries, but it’s much longer than I plan to live. Maybe the attacker gets lucky and it’s the first guess…maybe it’s the last. Odds are it’s somewhere in the middle. But, I can remember it. And it’s secure.

So, if you’re limiting password length or the number of characters, please, do me a favour and stop…I want to use my longer, far more secure password.

Thanks.

No, I won’t fix your cell phone…

Maybe it’s just me, but after reading Coding Horror‘s latest blog post The PC is Over, it made me realize another trend I’ve been noticing. Typically, a few times a week I get the question “Hey, you’re a computer guy right? My computer is …” and then they outline the issue. I tend to reply that fixing computers isn’t really what I do. I manage to fix my own, but it’s not something I’m good at. And lately, it’s getting more true, I actually have an existing PC “pausing” issue that I can’t seem to fix (it randomly freezes up for a few seconds/minutes then works fine again). Anyhow, back to the point. I’ve been noticing that people aren’t asking me about their computers as often. I still get asked about the same frequency, but now the questions are about their smart phone.

I also started pondering a conundrum we could be in if more people use their phones than their computers. If enough people stop buying computers as frequently as they do, the cost of computers will start to increase. I hope I’m wrong, because to create the software running on the smart phones, we currently need computers. And it will be cost prohibitve to spend the money we need to develop the programs, given most people don’t buy apps for their phones like they will for their computer. Unless we get lucky, and the phones literally become replacements for computers, that I can plug in a screen, keyboard and mouse into (or wireless, whatever) and I can run servers, and development environments upon. That would be interesting…

I’m an Ass because I give a Shit

Developers get a bad wrap for being difficult to work with. We are often percieved as assholes. We don’t mean it, it’s not our fault, it’s how we are wired. We spend our working lives looking for flaws. It’s the only way to build good software. We weren’t always this way. When we started, we were optimistic. We thought everyone was competent. Why would anyone put letters in a field meant to show the price of a product? Why would anyone enter a negative age? We didn’t check for these things. We got burned. There is always someone who enters a value, or uses a program in a way it wasn’t meant to. So, we spent a lot of time writing code that validated input. We thought it was bullet proof. We prevented the user from entering garbage data. We underestimated people’s stupidity. Which reminds of us the “God builds a better idiot” joke. Over time, our applications and programs became more complex. And with more complex programs, came more complex problems. Not only are we having to protect against bad input, but now we have to ensure the application works if someone unplugs the network cable, or the computer crashes, etc. The initial problem is a simple solution, but keeping that solution working in all the uncertainty is the new problem.

What this translates into, is a hyper-critical outlook on EVERYTHING. We choose our words carefully. We point out flaws not just in the systems we work on, but in everything we see. I do this way to much. I’m looking at a small 4″ fan on my desk. Now, first, I find it silly it even needs a sticker on it that shows you’re not to stick your finger into the blades. However, there are two major flaws with this sticker. First, the grate has openings approx 4 millimeters wide. The only people with fingers that tiny are newborns. Now, there are two more issues with that. First, they wouldn’t understand the picture showing the warning. And second, while their fingers would be small enough, they wouldn’t reach the blade. So the picture should really be showing you not shoving something else in, not showing a finger fitting through the grate. The second, and more important flaw to this warning is that the sticker is on the fan blade. The only time you can read it is when the blade poses no risk! When the fan is on, the sticker is spinning and impossible to discern as it rotates at several thousand rpm. It doesn’t bother me that someone did this. It bothers me that several people saw this after the fact, and didn’t see the issues…they left it. So many projects and products suffer from this.

My last job frustrated me to no end. There were literally hundreds of little things that on their own were absolutely insignificant on their own. But they added up. When I decided to leave it was very difficult to explain that there was no one cause, and thus, no way they could actually keep me there. I’d be told to relax, that those things weren’t important, but they were. We wasted so much time and money on these little things, that I could see the huge potential we had wasted because of all these little things that were out of my control. I was an Ass because I gave a Shit. Had I went numb, and not cared, those things wouldn’t bother me. But I cared about what I did. I wanted to do a good job. I strive for perfection and have high standards for myself.

I don’t expect perfection from everyone, but I do expect you to want to improve. I do expect you to care about what you do. It’s not coming from a place of negativity, which it’s often misinterpreted as. It’s coming from optimism. I see the potential, and I want to push people towards it. I want to realize the potential I see. Is that to much to ask? Does that make me an Ass? If so, I’ll wear the label with prid. I’m an Ass.

Reduce your Technical Debt

Now, let me preface all this by saying it’s not a critique on the quality of the person. And I’m not writing this to rip apart anyone. The first goal of development is to write working software that provides business value. However, in providing business value, we can improve the value by improving the quality of code. It’s often cited that 80% of the cost of a system is maintaining it after it’s written. A lot of that maintenance is feature changes. Which is expected. However, the cost of those changes can be greatly reduced by improving the quality of code that is written, and increasing the maintainability of the codebase. Code is written for humans to comprehend, not computers. They do that in the blink of an eye. It takes us developers much longer to understand hundreds of thousands of lines of code.

Technical Debt is what all these bad decisions add up to. Eventually you have to pay it off, and fix it, or you’ll drown, and your application goes bankrupt. Forcing you to rewrite it (more on that later).

So, on with the examples of what not to do.

This is a new take on the normal misuse of booleans

        Select Case isBoolean
            Case True
                myValue = 10
            Case False
                myValue = 99
        End Select

Why not write it clearly in one line?

	myValue = IF(isBoolean, 10, 99)

or in c# (which I prefer)

	myValue = isBoolean ? 10 : 99;

If your code is FULL of hardcoded constants, put them in a config or the database or use enums! There should be NO MAGIC NUMBERS.

Use your database properly. There is no good reason to have a field, that contains delimited values!

Use tools that check the cyclomatic complexity of your functions. Anything over 10 is getting high. Anything over 15 is too high, and should likely be refactored and split up. If you have a complexity of 339! like a 1600 line function I will soon have the luxury of modifying you should be beaten and while in recovery forced to read a book about clean code…like say the book Clean Code: A Handbook of Agile Software Craftsmanship.

If you are copy/pasting in your app, you’re doing something wrong. If the functionality is that similar, extract the commonality and refactor your code properly. You should NEVER need to make the same change in two places. A very common violation of this rules is a switch statement. If you have the same switch statement in two places to control flow, your program is structured wrong.

A recent example of copy/paste programming

        if (fileName.IndexOf(".zg") > 0) {
            partFileName = fileName.SubString(0, fileName.IndexOf(".zg"))
            bolExtentionRecognized = true
        }
 
        if (fileName.IndexOf(".rur") > 0) {
            partFileName = fileName.SubString(0, fileName.IndexOf(".rur"))
            bolExtentionRecognized = true
        }
 
        if (fileName.IndexOf(".dat") > 0) {
            partFileName = fileName.SubString(0, fileName.IndexOf(".dat"))
            bolExtentionRecognized = true
        }

While the intent is clear, it’s not easily maintainable, it’s much simpler if you just had to maintain the list of extensions, like this

        // acceptableExceptions loaded in a config, not inline
        // acceptableExceptions = new [] { ".zg", ".rur", ".dat" }
        foreach (var extension in acceptableExtensions) {
        	var extensionStartsAt = fileName.IndexOf(extension)
		if (extensionStartsAt > 0) {
		    partFileName = fileName.SubString(0, extensionStartsAt)
		    isExtentionRecognized = true
		}
        }

Use the right data types. Don’t store “True” and “False” or “Y” and “N” in a string when you can use a boolean variable. If it’s a number, put it in an int. Don’t store money in floating point numbers. Etc, etc.

Most importantly, know your framework. Stop reinventing the wheel. More than likely the framework has covered all the edge cases you’ll miss, and it’s been veted by thousands of programmers actively using the framework. There are methods to work with directories and files. Path.Combine is a good one to know. There are methods to parse dates, and convert strings of numbers into integers (decimals, etc). These methods can return wether it was successful (TryParse) while returning the parse result to prevent a need for exception handling. Which reminds me, exceptions should be exceptional. If you can check for it, do so first, and ensure the exception can’t happen. If you can’t check, but can’t handle it, there’s no need to catch it.

    Function returnProperTime(ByVal strDate As String) As String
        Dim strHour As String
        Dim strMinute As String
        Dim strSecond As String
 
        strHour = Mid(strDate, 1, 2)
        strMinute = Mid(strDate, 3, 2)
        strSecond = Mid(strDate, 5, 2)
 
        returnProperTime = strHour & ":" & strMinute & ":" & strSecond
    End Function

Should be using ParseExact (and should be using proper types)

    var dateTime = Date.ParseExact(strDate, "HHmmss", CulterInfo.InvariantCulter)
    var formattedTime = dateTime.ToString("HH:mm:ss")

When you see these things, fix them. You don’t have to make the app perfect all at once, but every file you open, leave it in a little better condition than you found it. Follow the boyscout rule. If everyone does that, it won’t take long and the codebase everyone dreaded to work on will become enjoyable to work on. And it didn’t require a grueling rewrite (which you should almost never do).

Change and working conditions.

It’s funny what can affect our ability to be productive. Well, actually it’s not funny. It’s serious. And it’s been studied to death. But it’s funny when you apply some of the changes and realize how drastically a simple change can affect your mood and productivity.

I, as has been mentioned before, recently changed jobs. My current employer is a consulting firm. The offices are nice. While it’s an open area, we’re rarely working at the offices. We’re typically on site. Each site has a different setup. Currently, I’m in a room, slightly smaller than it should be, but with four other devs, all working on the same things. At times it gets a little noisy, but for the most part, it’s quiet. There are no phones ringing. Rarely spontaneous meetings breaking everyones conversation. And we have a window.

That light does wonders for morale. At least for me, since I was so used to having no sunlight for 8 hours a day, and in the winter, when it’s only just starting to get light out when you walk into the building for your shift, and it’s starting to get dark when you leave, having no light during the day is an absolute energy suck. I feel so much better working in natural light.

This weekend I cleaned my home office. It was a mess. It was the room that everything was being dumped in. I should have taken a before picture. But now, after cleaning up and disposing of a lot of the clutter. As well as putting up shelves, and cleaning off the desk, I find I want to use my computer and work on projects at home again.

My last job was so negative that I didn’t even want to touch a computer when I got home. I had lost my drive to learn and try new things. It’s a great feeling when you once again love what you do, and where you work.

I have some big ideas for projects. And I can’t wait to turn them into reality.