Hugoware

The product of a web developer with a little too much caffeine

Posts Tagged ‘Personal

Spelling It Out With Booleans

with 4 comments

Code complexity has been a big issue for me lately. I’ve been realizing that the quality of my code has degraded over the years to the point that I’m finding I cram large chunks of code into a vaguely named method like Load() or Render(). It wasn’t until I got an assistant and I likened programming to ‘painting by number’ that I realized that I wasn’t following my own instructions anymore.

It wasn’t that I was intentionally writing complex code but rather that a large complex function wasn’t hard to read anymore — my definition of complexity has changed.

The last time that I discussed code complexity I explained that writing short, clear methods was an ideal way to decrease code complexity. This post continues the discussion by looking at using booleans to improve the readability of code.

Clarity With Booleans

Maybe you’ve seen a snippet of code like this before…

if (value % 2 == 0) { 
    //do something
}
else {
    //do something else
}

Most programmers are going to immediately recognize what this code is going to do — but imagine for a second that you don’t know what that code does. How is a less seasoned programmer going to have any clue what just happened there? Try Googling ‘value % 2 == 0’? I don’t think that is going to work out so well.

This is a good example where a boolean can be used to create clarity in a program. A boolean is used to determine the flow of a program — so why not use well named booleans to further clarify your intent?

bool isEvenNumber = (value % 2 == 0);
if (isEvenNumber) { 
    //do something
}
else {
    //do something else
}

This is a simple example but it applies everywhere. What stops you from spelling it out with a boolean?

Describe Intent Without A Comment

MVC is a good example of where well named booleans can improve the readability of code. How much harder is the first snippet to read compared to the second.

Logic Performed Inline

<div class="<% if (allItems.IndexOf(entry) % 2 == 0) { %>alt-item %<% } %><% if (entry.DatePosted.Date < DateTime.Now.Date.AddDays(-7)) { %>old-post<% } %>" >
<div class="subject" ><% =entry.Subject %></div>
<% if (string.IsNullOrEmpty((entry.Location ?? string.Empty).Trim())) { %><div class="location" ><% =entry.Location %><% } %>
<% if (string.IsNullOrEmpty((entry.Description ?? string.Empty).Trim())) { %><div class="desc" ><% =entry.Description%><% } %>
</div>

Logic Performed In Advance

<%
    bool isEvenItem = (allItems.IndexOf(entry) % 2 == 0);
    bool olderEntry = (entry.DatePosted.Date < DateTime.Now.Date.AddDays(-7)); 
    bool hasLocation = (string.IsNullOrEmpty((entry.Location ?? string.Empty).Trim()));
    bool hasDescription = (string.IsNullOrEmpty((entry.Description ?? string.Empty).Trim()));
%>

<div class="<% if (isEvenItem) { %>alt-item %<% } %><% if (olderEntry) { %>old-post<% } %>" >
<div class="subject" ><% =entry.Subject %></div>
<% if (hasLocation) { %><div class="location" ><% =entry.Location %><% } %>
<% if (hasDescription) { %><div class="desc" ><% =entry.Description%><% } %>
</div>

Snippet one is much shorter than snippet two — but does that really make it better? Or less complex?

You could argue that the logic shouldn’t be inline with MVC to begin with and you’d be correct. Instead those same comparisons would be well named boolean properties attached to the the model being used — which is exactly what I’m suggesting here.

It doesn’t matter where they are but using well-named booleans can improve and clarify the flow of logic in your application.

Written by hugoware

October 19, 2009 at 8:30 pm

Programming – AKA: Paint By Number

with 7 comments

This last week has been pretty busy for me. I’ve been working on several projects at work, deadlines coming due, trying to get personal projects done, jLinq bugs fixed — it’s been a rough week.

I was excited a few weeks ago when the new developer was going to start. I was finally going to be able to spread out some of this work and get a little more time on my hands… or so I thought. As it turns out, this guy isn’t exactly what I was expecting. Despite my best efforts, I still ended up hiring someone with pretty much no background in programming. I went from already being maxed out to now spending between 20% to 30% of my time teaching the basics of programming… yeah – this is my fault.

But as bad as it sounds it really has actually helped me rediscover a programming rule that I thought I was still using but apparently had forgotten.

So, one of the first projects the guy had to do involved checking a directory for new files, creating a record of the file if it was found and then processing existing files to transform file types from one to another. Really, probably an hour long job at most but was really causing this guy some grief.

An Alternate Approach — Simplicity

Naturally, as a developer, the first thing I started trying to explain was how the code would work like checking file dates or creating an XmlSerializer to load and save files — none of which actually helped him solve his problem. After several frustrating whiteboarding sessions I came up with a new route — make it so simple it was impossible to mess it up!

I took a second pass at trying to get the guy started in the right direction. Instead, I opened a new class file for him and wrote something like this.

public class FileRecordSync {
    //snip...

    //This is a list of the files that the program has already detected
    //this is also where to add new files that are discovered
    public List<FileRecordEntry> CurrentFiles { get; private set; }

    //determine if this file should be processed or not
    public bool IsValidFileType(string path) {
        throw new NotImplementedException();
    }

    //check and see if this file exists in CurrentFiles or not
    public bool IsExistingFileEntry(string path) {
        throw new NotImplementedException();
    }

    //check to see if the modified date is greater than the logged modified date
    public bool IsFileEntryModified(FileRecordEntry entry) {
        throw new NotImplementedException();
    }

    //find the matching file in the CurrentFiles or return null if nothing was found
    public FileRecordEntry FindExistingEntry(string path) {
        throw new NotImplementedException();
    }

    //create a new FileRecordEntry from the path and add it to CurrentFiles
    public void AddNewFileRecordEntry(string path) {
        throw new NotImplementedException();
    }

    //set the file as expired to 
    public void MarkFileAsModified(FileRecordEntry entry) {
        throw new NotImplementedException();
    }

    //snip...
}

Granted, an experienced developer could place all of those functions into a single loop and it would still be readable but isn’t the code above the kind of code we should all be writing anyways? Simple, clear, straight-forward functions each with a specific purpose and nothing more?

Code like this manages complexity – he didn’t have to worry about how each of the functions were going to fit into the master plan but instead how to complete each of the functions.

You know what coding like this makes me think of – Paint by number! And when it comes to code complexity – that’s a VERY good thing.

paint-by-number

It’s hard to tell what that is a picture of looking at it now — but if you remain diligent and fill in each of the blanks with the correct color then before long you’re staring at a masterpiece (or maybe not — this picture looks like someone holding a gun in FPS view — but you get the idea :))!

When it was all said and done with, the loop that had caused so much grief was much easier to read – not just for him but easier for me to read as well!


public void ProcessFiles() {

    foreach(string file in Directory.GetFiles(folder)) {

        if (!this.IsValidFileType(file)) { continue; }

        if (this.IsExistingFileEntry(file) &&
            this.IsFileModified(file)) {
            FileEntryRecord entry= this.FindExistingFile(file);
            this.MarkFileAsModified(entry);

        }
        else {
            this.AddNewFileRecordEntry(file);

        }
    }

}

Even without comments, you can most likely figure out what this code does with only a cursory glance over it.

A Personal Reevaluation

Its hard to say when a developer abandons simplicity. I think a lot of us start out writing gigantic functions that do much more than they need to and then slowly realize how much easier our lives are if we create functions for specific jobs.

Ironically though, I think the smarter and more skilled we become, we begin to lose sight of what a “simple” function really is. Some of us can write a single lambda expression to create a ham-n-cheese sandwich with our eyes closed — a 20 to 30 line for loop can’t possibly be that difficult for us anymore!

I can’t deny that I would have pushed all that code into a single loop, used a handful of well named variables with a couple clear and useful comments and called it a day. But looking back on the final result I can say without a doubt that I’d rather go back and make changes to the new, simpler class — wouldn’t you say the same?

Written by hugoware

September 17, 2009 at 10:17 pm

Sony VAIO – Now With Less Bloatware!

leave a comment »

You may have seen my previous post where I was deciding on the laptop I was going to purchase. I ended up going with the Sony VAIO VGN-FW463J/B (I can actually type it from memory after all the work I did this weekend). I got an awesome deal from NewEgg.com at a mere $899 – no tax!

To recap – here are the specs…

  • Operating System Windows Vista Home Premium 64-bit
  • CPU Type Intel Core 2 Duo P8700 2.53 GHz
  • Screen 16.4″
  • Memory Size 4GB DDR2
  • Hard Disk 320GB
  • Optical Drive Dual Layer DVD Burner
  • Graphics Card ATI Mobility Radeon HD 4650 (1GB)
  • Dimensions 15.1″ x 10.3″ x 1.14-1.46″
  • Weight 6.9 lbs.

Overall I’m quite satisfied with my purchase but it was a tough road to get here. This last weekend was rough to say the least. Here are a few of the problems I had when I got started.

Heat! Yowza!

I was quite shocked when I felt how hot this laptop is. It isn’t unbearable but is certainly isn’t ideal either. The odd thing is that the bottom of the laptop actually seems to be cooler than the top!. For the most part it seems that the harddrive and the graphics cards are the culprits – but since I plan to switch to a SSD drive later on then that source of heat should go away – and since I use the n52te when I play any games then the graphics card should be irrelevant (even though the vent exits where my arm would be — but whatever, close enough :))

Wireless

The wireless works until it comes out of sleep mode – then it works for one or two requests and dies. You have to fiddle around with the connection before it finally restores itself. It isn’t terrible since the wireless “on/off” switch is on the front of the laptop and you can use it to “reboot” the connection. Just a slight annoyance that you can easily overcome.

BLOATWARE

I remember when I was a teenager my parents bought me a VAIO and if I remember correctly they had a bunch of custom software for everything. In fact, instead of using the typical Windows 98 Start menu, they had some custom screen for managing your applications. You could get out of it but it was also a pain since it was in your way at the start.

This VAIO is no different – they have a bunch of silly programs to do things that are already built into Vista (like one to manage your wireless connection – why?). Along with that you have some other apps pre-installed applications like a trial version of Office or Norton Anti-Virus.

The problem comes in since you can’t do a clean install because the restore disks automatically reinstall all the bloatware you didn’t want — well that is unless you intervene. 🙂

The solution is really quite simple – just end task out of the installer!

At one point you’ll see that the VAIO restore disks are trying to install the software and drivers – just press CTRL-SHIFT+ESC to pull up the task manager and then end the process! The program fails, the Vista install completes and all the drivers you need, minus the wireless driver, can all be found on the restore disks.

Everything was installed correctly after the Vista install finished so I doubt you need the restore disks for the drivers – but they are there if you need them (again – the wireless driver has to be downloaded from the Sony website though).

Summary

I’m happy with my new laptop even though it took some effort to get to this point. Now my desk looks even more nerdy!

In my defense the teddy bear is a father’s day gift and cannot be removed… ever…

sweet

Written by hugoware

August 31, 2009 at 2:36 am

Virgin Mobile – Think Twice!

with 7 comments

I try to keep the topics on this blog to strictly programming related posts but after a recent experience with Virgin Mobile, I felt this was something that I should make public.

I’ve got a company phone right now but I figured I ought to have my own phone for personal use. I didn’t really want to get a whole new contract so I figured I would go the “Pay As You Go” route. Between the phone and the minute pack (400 minutes) I spent just over $50. It wasn’t a lot of money but it certainly wasn’t pocket change either. Through the last month I used exactly 1 minute and 4 seconds of my 420 minutes I had available. As of last night — all of my minutes had vanished.

The Website Approach

Being a web guy, naturally the first step is to sign onto their website and see what the problem is. So I opened up Chrome and…

website-chrome-menu

Eh… Okay, well I guess I didn’t want to use that menu system anyways. Thats fine though, I realize it’s hard to get everything to work in every browser so I’ll just pull up FireFox. After messing around with it a bit more and finally getting past their login I get the following…

firefox-error

Okay… FINE. I’ll use Internet Explorer…

ie-error

… 😐

The Automated Service Approach

I really hate calling phone services and hate it even more when I can’t just talk to a person. While a “voice” controlled automated service is cool from a technical perspective they are a pain because you’re forced to listen to every option and try to find your way to the section you need. Coming from the age of twitchy fast-answer internet browsing the whole process is entirely too slow.

I don’t really need to go into great detail about this part since you can probably guess what happened since I’m even mentioning it. After fumbling through menus for awhile and getting stuck in areas where hanging up seemed to be the only ‘back button’ available, I gave up. I never heard an option to speak with a real person, not once.

The E-Mail Route

I headed back to the website figuring that I must be the one doing something wrong but after a few more login attempts I realized I was getting nowhere. After a little more searching I found a customer service feedback form which was exactly what I was hoping to find.

Except they wanted me to provide my PIN number, which is the same number you use when logging in — a step that despite all my efforts had failed every time. I went ahead and explained my situation, entered the rest of my information and sent it away. After I finished the step I couldn’t help but wonder, what about NON-customers? What if I wanted to ask some questions before I paid for the service? How is this form supposed to help these people? Clearly a usability issue but not something of my concern.

The E-Mail Follow Up

The next day I got an e-mail. I won’t post the entire thing but here is the part that rubbed me wrong.

Thanks for your email!

The Account PIN you provided is not matching our records.

We can certainly help resolve your question but first we must verify we have the right account. Can you please respond and provide your correct Account PIN (numeric security code)?

For real? I’m already having problems with this PIN number and now you won’t talk to me unless I give you the correct information? The letter doesn’t tell you how to get your PIN either – it suggests that you either log into the website (with your PIN mind you) or call customer service (and fiddle around with their automated service again… yay!).

Now after going over the PIN information that I already had I realized I had been entering in the wrong number. Now I readily admit that is my fault — but where was the error messages on the site? Where is the validation that says “Hey man, you entered something that doesn’t look like a PIN. The PIN number should look like…”. Anything would have been better than nothing!!

In any case, I sent back the correct PIN number and finally got the answer to my question.

I would like to inform that minute packs are good for 30 days only and if you do not purchase another Minutes Pack within 30 days from the day you purchased your first Minutes Pack, you will loose all unused minutes.

That is the reason, you have lost the unused minutes on your account as you have not purchased another minute pack.

Customer Hostile Business Model

I have another “Pay As You Go” phone that I purchased for my 8 year old daughter. I’d like for my kid to have the option to call me in case of an emergency but know that if the phone is lost then I only lose about $30 which is a lot better than someone racking up a bunch of long distance calls on a subscription.

With her phone, when I buy minutes they come with service days. Not just a couple days but something like 90 days which is excellent. Whats more, is that those days stack on top of each other along with any unused minutes. Even if I some how run out of service days I can simply buy some more and all my minutes stay intact. It is a great system that is both clear and fair to the customer in how it works.

But take Virgin Mobile – 30 days after you buy minutes, unless you give them more cash, they wipe them out – all of them. Sounds like they got their business model directly from the Dark Side if you ask me.

So to be clear, right after you buy some minutes the 30 day timer starts at the end of which your minutes are erased no matter how many you have. What if you have 5 minutes? gone. Have 500 minutes? gone. Or the maximum 5000 minutes? gone. If you want to keep your phone working then you need to spend at least $20 a month — sounds a lot like a subscription to me.

Just to backup my claim, here is part of an e-mail that I got from their customer service. To be fair, in this e-mail they offered to restore my minutes if I purchased a new minutes pack — but it was a one time exception.

To answer your question: yes, you are absolutely correct in understanding that expired minutes will be lost and cannot be restored. However, if you purchase a minute pack and reply to this email, given you are a valued Virgin Mobile customer we will credit the expired minutes to your account balance.

Summary (read the small print every single time)

Don’t get me wrong, I messed up when I didn’t read the fine print. I appreciate the gesture they displayed at the end of this ordeal but I’d rather not have the threat of a complete wipe of my minutes looming over my head. If there are other, more consumer friendly options, then they need to be the default for the account.

In any event I think this experience helped me and $50 is a cheap price for a valuable “life lesson” — even if it was an obvious one.

In summary, I doubt Virgin Mobile is an evil company but they certainly aren’t looking out for the customer. Always remember to read the fine print in detail.

Written by hugoware

August 26, 2009 at 2:14 am

Posted in General Update

Tagged with , , ,

Do You Have A Pet Project

with 2 comments

I’ve noticed that there has been some debate about the value of a programmer based on what they do with their free time. Strangely enough, it seems that a lot of value is placed on a person who leaves a 8 to 10 hour shift of programming just to return to their home and continue into the night hacking out lines of code.

I agree with the side that says when you get home you need to turn it off. You need to clear your mind for a few hours before you go back into work the next day and do it all over again…

Well, I agree with it in principle, but that’s about it… 🙂

Having A Pet Project

You may have noticed the project I was working on called jLinq, the Javascript Query Language. I’m still working on that project, trying to improve it and make it better. Better argument handling, performance tweaks, new extension libraries — etc. As much fun as writing a query language can be, there are more entertaining projects a person could be working on.

Since I was a kid, I was always into art and stuff – Never quite good enough to go professional, but good enough to get a decent job being a designer/programmer. I actually got into programming so I could make a video game (no surprise there, huh?)

I can say attempts A through G failed miserably — but the funny thing is that along the way I got a lot better at programming to the point I’ve got a career doing it.

Recently, I thought I’d give the game idea another shot.

//TODO: Come up with a game title

I’ve only been on this project about two weeks now, but here are some screenshots of the current game. It’s built in Flash, using ASP.NET MVC for the server side programming.

screenshot 1

screenshot 2

screenshot 3

screenshot 4

It’s funny, programming a game is so much easier with 8 years of software development under your belt!

Do You Have A Pet Project?… Well, Do Ya?

I really do agree you should clear your mind of programming once you get home — but I wouldn’t have gotten into my career if I followed that rule. Tinkering around with a small pet project can open doors for you that you never even knew were there!

Do you have a pet project — because if you do it may just lead you into your next career!

Written by hugoware

June 23, 2009 at 3:31 am