Friday, January 24, 2014

A Kindergarten Way of Looking at Code Refactoring

I've read and heard a million different definitions, explanations, rationalizations, gyrations and procastinations about "code refactoring".  The term sounds impressive.  It has a lot of cool syllables and stuff too.  Non-coders (aka "noobs", etc.) seem to light up when it's mentioned, especially in situations were alcohol is being consumed.

I thought I'd dissect this frog using a Popsicle stick and a fork.

Let's say you want to display a list of names which are always going to be the same.  We call this a "static list".  Examples can range from product names, categories, days of the week, and so on.  Let's go with the days-of-the-week example.  It's easy enough and it leads to the weekend, which is usually a pretty good end-goal.

[vbscript]

wscript.echo "Sunday"
wscript.echo "Monday"
wscript.echo "Tuesday"
wscript.echo "Wednesday"
wscript.echo "Thursday"
wscript.echo "Friday"
wscript.echo "Saturday"

[/vbscript]

Simple enough.  But let's dice this up one more time...

[vbscript]

strDaysList = "Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday"

For each d in Split(strDaysList, ",")
    wscript.echo d
Next

[/vbscript]

Let's dice it up once more.  There are two simple functions/methods in VBscript to help with Dates, Days and so on:  Weekday and WeekdayName.  Case is not important with VBscript, so you can use weekday and WEEKDAY or WeekDay, but I try to be consistent regardless.

For this example, I'm more interested in WeekdayName, so forget Weekday for the moment.  Weekday returns the integer value of a week day as 1 to 7, with 1 being Sunday and 7 being Saturday.  But this is for pulling the day out of a date.  So Weekday(Now) would return the integer for the day of the current day (right now).  I'm writing this on a Friday night (yes, I have no life whatsoever), so it would return 6.

But getting back to WeekdayName:  This function returns the string-value name of a given week day based on the integer number.  So WeekdayName(6) would return "Friday" (it returns the proper capitalization by default).

Let's turn it around and shove a range of integers through that function and have it spit out the week day names for us.

[vbscript]

For i = 1 to 7
    wscript.echo WeekdayName(i)
Next

[/vbscript]

Summary

If you can't already tell by now:  Refactoring is the process of refining your code to achieve the same (or better) results with less coding.  And now, you can graduate to first grade.  Have a good weekend!

No comments: