25 September, 2007

Write Source Code for Other Developers, Not the Computer.

I’m not sure as to whom to attribute the following statistic, but i believe it was something along the lines of this;  Code is read vs. written on at a 10:1 ratio, meaning that the is far more reviewing of any specific codebase than there is writing to said code.  Furthermore, the majority of software positions involve maintaining and modifying existing code as opposed to creation of new code from the ground up.


To what does all of this allude?  The importance of writing clean code.  Knowing full well that other developers are going to have to read, understand and most likely modify your code in question at some point(s) in the future.  This is where our responsibility as software professionals (even in the case of hobbyists) comes into play.  


Several languages have tried to address this problem by intrinsic design decisions.  Most notably among those in recent times are Java and Python.  Java does so by its explicitness by design, and Python by its forced formatted a la the whitespace requirement.  Both are effective in what they do, however there are still a multitude of ways in which both can be written in a harder to read format.  Obviously choice of variable, function, class and object reference names is a very large point of readability (or not) which really cannot be enforced by a language specification.  Let us take a look at this very issue and while we’re at it, i’ll be clear that this is not a Python vs. Java issue discussion.


All too easily so many coders (I know this from having had to look at, understanding and refactor their code) overlook one of the best sources for building readable code, and that is their naming convention.  There have been several best practices and coding style specifications documents produced that one might think me as flogging a dead horse, but I assure you this is not the case.  


In the following examples we see a variation of languages and how we might commonly see the same variable name referenced (and initialised as it were):


Smalltalk:


num_of_doors = 4 ;


Python:


numberOfDoors = 4    OR    numDoors = 4    OR    number_of_doors = 4


Ruby:


numberOfDoors = 4;    OR    numDoors = 4;    OR    number_of_doors = 4;


Java, C#:


int numberOfDoors = 4;    OR    int numDoors = 4;    OR    int number_of_doors = 4;


Lisp:


number-of-doors := 4;


C, C++:


int intNumDrs = 4;    OR    int num_drs = 4;    OR    int int_drs = 4;


Perl:


my $vzoiuwriozufsd = 0x04;


The point here is that there are many varied ways in which the same variable can be referenced.  I am of the opinion that much along the lines of Guido van Rossum of Python (and to a lesser extent ABC) fame, that there really should be one and only one obvious way to do it.  This isn’t to say that I think everyone should code in the same language, and speak the same tongue, etc.  What it does mean though, is that to be understood by others (and sometimes by ourselves), we need consistency, and unless we have a set of strict guidelines set out for us as software engineers, developers, etc., we might as well code in our own made up dialects.  


I am of the opinion that a proper interpreter, compiler, virtual machine, etc., should be more than capable of quickly turning long variable, class, function and method names into concise tokens with small internal footprints.  So much to the point that there is no excuse for not being verbose.  At one point in time, every single byte of allocated memory for names of the aforementioned items was a crucial issue which required extreme concise naming conventions to be followed.  Those times are gone in this day and age, allowing us to be clearer and more expressive.  


I can see using single letter counter variable names, but never could I imagine naming a class, method or function in such a sparse manner.  I like to think that clean code reads somewhat like a choose your own adventure book, were it to have a greater variety of options available.  Functional or Object Oriented is immaterial here, as cleanly written code isn’t tied to a specific construct or paradigm.  I think most of the following rules are applicable to pretty much every language out there.  Emphasis below pertains to items that I feel are not language specific guidelines.


As can be seen, most of the above are applicable to languages other than Python.  I find myself at my current place of employment having to deal with the problems for which this list addresses.  Much of what I’m doing is updating a legacy code base that is literally plagued with dozens of individual programs and modules that are blatant attacks on decent code.  They (collectively) single-handedly break most of the above guidelines.  


First off it is almost entirely written in perl, which instantly shoots down the Readability counts factor (and no, it wasn’t done with the strict pragma, and yes it uses a bunch of requires and plenty of global variables).  

Secondly, errors don’t pass silently because there is no built-in exception handling in perl.  Evals of code blocks does not equate to a proper exception system, nor does an add-in module.  Exceptions are something which need to be a core part of the design of the language, and perl falls far short of the bottom of the heap on this issue alone.  


Thirdly, when one is expected to maintain code in an environment wherein the expectation is to follow the existing coding schema as it were, with global variables, no exception handling, etc., it truly becomes a daunting task because one must force his/herself to think ‘wrong’.  The logical and/or proper solution that is naturally though of as a solution would only lead to reprimand, simply because trying to think in such a manner will produce mistakes, primarily because trained seasoned professionals don’t think in the same manner as the less experienced coder(s) responsible for the legacy code int eh first place.


Finally, (I’ll leave it to three to be nice to those few perl hackers who’ve read this far), after ten plus years of coding in perl, I’ve come to learn that the TIMTOWDI (There Is More Than One Way to Do It) mantra of perl is one of the biggest problems that arise from the language.  It is this careless and dare I say reckless mindset which has led to so many atrocities in the professional coding world.  


My point is simple enough to follow.  Write readable code, as it is a defining factor as to how far you’ve matured in the field of software development.  It doesn’t necessarily mean you are even that good at what you do, but what it does do is show how you understand a rudimentary problem that so many others have failed to realise.  Readability Counts, and without it, we are truly lost.  

Labels: , , , , , , , , , ,

07 July, 2007

Java Redux. Redux.

I was perusing the internet last evening to pass the time before getting into a vicious round of Champions of Norrath : Return to Arms with my lovely wife.  I had Java on my mind for a bit of the commute home and as such decided to do a bit of googling.  For whatever reason, I decided to lookup “Java for Python Programmers" much along the lines of a great "Perl to Python Migration" book I'd acquired years back.  To my utter shock, results were actually returned.  


This whole 'ordeal' with Java has been going on with me for something over 7 years.  I started teaching myself Java way back when, but found it to be utterly too verbose for productivity, opting for perl in its place.  Then perl very quickly proved to be lacking when it came to large projects, and code cleanliness (by design mind you, I have written production code which after 7 years upon seeing it again, was very easy to follow in spite of its 7,000+ line codebase), and utter hackishness about it, regardless of the raw power.  I moved to Python both personally and then shortly thereafter, professionally where I enjoy myself most.  


However, there are certain things I've come to realise over the past many years, more so over the past few specifically.  One is that I should force myself to code in one of the behemoth languages to the point of solid fluency regardless of how dreadfully painful it can be.  Two is that most jobs are hybrid these days and require a wider set of disciplines in terms of technologies, languages and toolsets than in the past, and whilst I don't have any need for Java in my current work endeavours, it doesn't negate said need in the future.  Three is that Java makes the most sense being that C/C++ are for all purposes outside of hardware tied code (such as operating systems, device drivers, compilers), dead for application creation, period.


And so it is that I venture forth again into the wonderful realm of re-re-learning the evil behemoth formerly known as oak.  May she not be as cruel a mistress as in the past as my understandings of her workings have been greatly enhanced thanks to python sharing so many of those conceptual designs and paradigms coupled with my adoration for the latter language.  


Wish me luck.

Labels: , , , , , ,

28 June, 2006

Rethinking Real-World Object Models in Simulations

    Over the past quarter century I have routinely pondered back to the time of my childhood and early experiences with interactive fiction text-based adventure games.  Chances are that if you were involved with computers  at any point prior to the mid-eighties, you have experienced what I speak of.  If not, maybe you experienced multi-user dungeons (MUDs) in your college or bulletin board (BBS) years.


    In many cases these ‘games’ were written in the low level language du jour, such as ‘C’, or in a custom language like ‘Inform’ (in the case of Infocom games) which was also written in ‘C’.   There were languages which would’ve been better suited for these games/simulations, object oriented programming (OOP) languages such as Smalltalk, or Objective-C, but they were generally not utilised as such.  


    Recently in my workplace I have been developing full time (for the past couple of years) in Python, a wonderful high level language written by Guido van Rossum which is a proper OOP language.  As such, the idea of writing a simulation (not a ‘game’ per se) which would allow me to focus on not only how one would model the real world (to a certain depth), but as an exercise in python objects.  


    While the code is still an ongoing side work of mine, I am posting the parent class (SimObject) and it’s associated child classes (Place, Person and ExitObject) for review by those who are interested.  Please note that due to certain conflicts with word press, proper pythonic indentation (required for execution) is not established as such.  



#####################################################

#                            S  I  M  O  B  J  E  C  T       C   L   A   S   S                          #

#####################################################


class SimObject:

    object_master_list=[]

    def __init__(self,

                object_id = 0,

                object_sku = 0,

                short_description = 'Short Description',

                long_description = 'Long Description',

                name = 'Name',

                weight = 1.0,

                height = 1.0,

                width  = 1.0,

                depth  = 1.0,

                visible  = True,

                closed   = False,

                contents = [],

                stack    = []):

        self._object_id         = object_id

        self._object_sku        = object_sku

        self._short_description = short_description

        self._long_description  = long_description

        self._name              = name

        self._weight            = weight

        self._height            = height

        self._width             = width

        self._depth             = depth

        self._visible           = visible

        self._closed            = closed

        self._contents          = []

        self._stack             = []

        self.object_master_list.append(self)

        


    def getObjectById(self,object_id):

        for sim_objects in self.object_master_list:

            if sim_objects.getObjectId() == object_id:

                return sim_objects

                

    def addContents(self,item):

        try:

            self._contents.append(item)

            return True

        except:

            return False


    def addToStack(self,item):

        try:

            self._stack.append(item)

            return True

        except:

            return False

            

    def isVisible(self):

        return self._visible

        

    def getContents(self):

        return self._contents       


    def getShortDescription(self):

        return self._short_description


    def getLongDescription(self):

        return self._long_description


    def getSize(self):

        return "Object Details ... Weight: %.2f, Height: %.2f, Width: %.2f, Depth: %.2f" % (self._weight, self._height, self._width, self._depth)


    def getHeight(self):

        return self._height


    def getWeight(self):

        return self._weight


    def getName(self):

        return self._name


    def getObjectId(self):

        return self._object_id


    def getDescription(self):

        output = ''

        vowels = ['a','e','i','o','u']

        if isinstance(self,Place):

            short_desc = self.getShortDescription()

            output += short_desc + "\n"

            underline = ''

            for i in str(short_desc):

                underline += '-'

            output += underline + "\n"

            output += self.getLongDescription() + '\n'

            for thing in self.getContents():

                if isinstance(thing,ExitObject):

                    if thing.isVisible():

                        output += "There is "

                        if thing.getName()[0].lower() in vowels:

                            output += 'an '

                        else:

                            output += 'a '

                        output += thing.getName() + ' '

                        output += 'here.\n'

                    else:

                        ### Don't short exits if they are just cardinal directions (_visible=False)

                        pass


            itemlist = []

            peoplelist = []

            for thing in self.getContents():

                if isinstance(thing,SimObject) and not isinstance(thing,ExitObject) and not isinstance(thing,Person):

                    itemlist.append(thing.getName()) 

                elif isinstance(thing,Person):

                    peoplelist.append(thing.getName())

            if len(itemlist) == 1:

                output += "There is "

                if itemlist[0][0].lower() in vowels:

                    output += 'an '

                else:

                    output += 'a '

                output += itemlist[0] + ' '

                output += 'here.\n'

            if len(itemlist) >= 2:                                    

                total_items = len(itemlist)

                item_counter = 1

                output += "There are "

                for items in itemlist:

                    if items[0].lower() in vowels:

                        output += 'an '

                    else:

                        output += 'a '  

                    if item_counter <= total_items-2:

                        output += str(items)+', '

                    elif item_counter == total_items-1:

                        output += str(items)+' and '

                    else:

                        output += items + " "

                    item_counter += 1

                output += "here.\n"

                output += "\n"

            if len(peoplelist) == 1:

                output += str(peoplelist[0]) + " is here.\n" 

            elif len(peoplelist) > 1:

                item_counter = 1

                total_items = len(peoplelist)

                for items in peoplelist:

                    if item_counter <= total_items-2:

                        output += str(items) + ', '

                    elif item_counter == total_items-1:

                        output += str(items) + ' and '

                    else:

                        output += str(items)

                    item_counter += 1

                output += "are here.\n"  

        elif isinstance(self,Person):

            output += self.getName()

            output += "is standing before you!\n"

        elif isinstance(self,ExitObject):

            if self.isVisible():

                output += str(self.getShortDescription()) + '\n'

            else:

                output += "You see nothing out of the ordinary here.\n"

        else:

            output += "unsure of type!\n"

        output += "\n"

        return output

        

#####################################################

#                              P   L   A   C   E        C   L   A   S   S                                  #

#####################################################


class Place(SimObject):

    def __init__(self,

                object_id = 0,

                object_sku = 0,

                short_description = 'Short Description',

                long_description = 'Long Description',

                name = 'Name',

                weight = 1.0,

                height = 1.0,

                width  = 1.0,

                depth  = 1.0,

                visible = True,

                contents = []):

        SimObject.__init__(self,

                            object_id=object_id,

                            short_description = short_description,

                            long_description  = long_description,

                            name              = name,

                            weight            = weight,

                            height            = height,

                            width             = width,

                            depth             = depth,

                            visible           = visible,

                            object_sku        = object_sku,

                            contents          = [])



#####################################################

#                          P   E   R   S   O   N          C   L   A   S   S                              #

#####################################################


class Person(SimObject):

    def __init__(self,name="",object_id=0,object_sku=0):

        SimObject.__init__(self,name=name,object_id=object_id,object_sku=object_sku)

        self._hp   = 100

    def isAlive(self):

        if self._hp > 0:

            return True

        else:

            return False

    def getStats(self):

        print "%s has %i hit points remaining!" % (self._name,self._hp)

    def receiveHit(self,damage="0"):

        self._hp = self._hp - damage

        if self._hp <>

            self._hp = 0

    def attack(self,enemy):

        if type(enemy) == type(self):

            attempt_roll = randint(1,10)

            if attempt_roll > 5:

                enemy.receiveHit(attempt_roll)         

            else:

                print "Missed %s!" % str(enemy._name)

        else:

            print "Cannot attack %s" % str(enemy)

    def getSize(self):

        return "Person Details ... Weight: %.1f, Height: %.1f, Width: %.1f, Depth: %.1f" % (self._weight, self._height, self._width, self._depth)

    def move(self,destination):

        #### add test against dimensions.  person WxD must be greater than Exit HxW, and the smallest Person dimension much be

        #### smaller than the smallest Exit dimension

        destination_room = self.getObjectById(destination)

        destination_room.addContents(self)


#####################################################

#                                  E   X   I   T        C   L   A   S   S                                    #

#####################################################


class ExitObject(SimObject):

    def __init__(self,visible=False,name="ExitName",short_description='Exit',

long_description='an Exit',aliases=(), destination=0,object_id=0,object_sku=0, weight=1.0,width=1.0,height=1.0,depth=1.0,closed=False):

        """Aliases are lists of names by which this exit can be referenced"""

        SimObject.__init__(self,visible=visible,name=name,short_description= 

short_description, long_description=long_description,object_id=object_id,

object_sku=object_sku, weight=weight,width=width,height=height,depth=depth,

closed=closed)

        self._aliases = aliases

        self._destination = destination

    def getDestination(self):

        return self._destination

    def getAliases(self):

        return self._aliases

Labels: , , , , , , , , ,