Page 1 of 1

Please Read: Comment your code well!

Posted: Mon Sep 02, 2013 8:28 pm
by Jackolantern
I just figured I would put a little notice in here reminding everyone that they should be commenting their code well! And it isn't really for us (although it can help us to solve issues). It is for you! The general idea is that software will always need to be updated and maintained (this goes double for online games), and I can guarantee you will not remember writing that code or what it was meant to do a month or two down the line. It is just a good idea. If you learned to code from Halls' tutorial series, remember that because Halls was writing that as the video was recording and while he was explaining it, comments weren't really possible. But for pretty much all code you write yourself, you should comment it!

Not that I am the best at it, but here is an event handler from my MUD. Check out the commenting:

Code: Select all

//handler for getting items
exports.handleGetItem = function(data, socket) {
    /*
        1. Get character name and reject if not logged in
        2. Get the current room of the user
        2.1 Automatically reject if no items in the room
        3. Make local copies of important memory points
        4. Iterate through the items in the room, and check each of their callable names to see if item is in the room
        5. If a -1 was returned, notify the player that the item is not in the room
        6. If -1 was not returned, but if the shortname found is not in the room, it is an instanced object
        6.1 Make sure object is not a prop
        6.2 Make sure the player is not holding their max item count
        7. If found, add the item to the player inventory
        7.1 See if the item is part of a quest
        7.2 Increment the player's currentItemCount by item slots
        8. Remove it from the room
        9. Notify the player
        10. Notify the room
     */
    
    // 1. Get character name and reject if not logged in
    socket.get('charName', function(err, name){
        if (err) {
            //some error occurred
            return console.dir("Error rRgleW2: " + err);
        }

        //make sure the user is logged in
        if (!name) {
            socket.emit('Serror', 'You are not logged in Vnek991');
            return;
        }

        // 2. Get the current room of the user
        var roomData = allRooms[allUsers[name].room];

        // 2.1 Automatically reject if no items in the room
        var itemCount = 0;
        for (var counts in roomData.itemsAtLocation) {
            itemCount++;
        }
        if (itemCount == 0) {
            socket.emit('sendMessage', {color: 'ehealthg', message: 'There are no items at your location.'});
            return;
        }

        // 3. Make local copies of important memory points
        var userData = allUsers[name];
        var currentRoom = userData.room;
        var callable = data.get;
        var itemsAtLocation = roomData.itemsAtLocation;

        // 4. Call getShortNameIfExists, and check each of their callable names to see if item is in the room

        //create an array of item short names, since items are stored as objects
        var trimmedItemsAtLocation = [];
        var temp;
        for (var item in itemsAtLocation) {
            //the .split('_') is to deal with instanced item short names, which are in the form masterShortName_###
            temp = item.split('_');
            trimmedItemsAtLocation.push(temp[0]);
        }
        var shortNameOfItem = getShortNameIfExists(callable, trimmedItemsAtLocation);

        // 5. If a -1 was returned, notify the player that the item is not in the room
        if (shortNameOfItem == -1) {
            //ran the check on both instanced and non-instanced, so if returned -1, the object isn't in the room
            socket.emit('sendMessage', {color: 'ehealthg', message: 'That item wasn\'t found at your location.'});
            return;
        }

        // 6. If -1 was not returned, but if the shortname found is not in the room, it is an instanced object

        //set a flag to determined if it is instanced
        var isInstanced = true;

        //create an untrimmed array of items at the location
        var itemsAtLocationArray = [];
        for (var item in itemsAtLocation) {
            itemsAtLocationArray.push(item);
        }

        //now iterate through the items at the location and compare with the short name found above.
        for (var x = 0; x < itemsAtLocationArray.length; x++) {
            if (itemsAtLocationArray[x] == shortNameOfItem) {
                //if the direct short name was found at the location, then it is not instanced
                isInstanced = false;
            }
        }
        //if the short name was not found above, then it is instanced. Need to get the full short name in the room if it is instanced
        var temp2;
        if (isInstanced) {
            for (var y = 0; y < itemsAtLocationArray.length; y++) {
                temp2 = itemsAtLocationArray[y].split('_');
                if (shortNameOfItem == temp2[0]) {
                    //we found it! get the full, untrimmed name out of here
                    shortNameOfItem = itemsAtLocationArray[y];
                }
            }
        }

        //shortNameOfItem should now have the short name to remove from the room and give to the player

        // 6.1 Make sure object is not a prop

        var itemInRoomEffects = itemsAtLocation[shortNameOfItem].effects;
        var brokenDownEffects = itemInRoomEffects.split(' ');
        var isProp = false;

        //iterate through the list of effects and see if 'prop' if there if there are any effects
        if (brokenDownEffects.length != 0) {
            for (var z = 0; z < brokenDownEffects.length; z++) {
                //now check to see if the current effect is 'prop'
                if (brokenDownEffects[z] == 'prop') {
                    isProp = true;
                }
            }
        }

        //now actually check to see if it was a prop and notify the user if it was
        if (isProp) {
            socket.emit('sendMessage', {color: 'ehealthg', message: 'You can\'t take that.'});
            return;
        }

        // 6.2 Make sure the player is not holding their max item count

        //get the slots used
        //first see if it is a non-instanced item
        var slotsUsedByItem = allItems[shortNameOfItem];
        if (!slotsUsedByItem) {
            //if item not found in allItems, must be instanced
            slotsUsedByItem = allInstancedItems[shortNameOfItem].slots;
        } else {
            //it was found, so get the slots off of it
            slotsUsedByItem = slotsUsedByItem.slots;
        }

        //now check to see if picking up this item will put the player over their max
        if ((userData.currentItemCount + slotsUsedByItem) >= userData.maxInventory) {
            socket.emit('sendMessage', {color: 'ehealthg', message: 'You can\'t carry anymore.'});
            return;
        }

        // 7. If found, add the item to the player inventory

        //first see if the item is already there
        var playerInventory = userData.inventory;
        if (playerInventory[shortNameOfItem]) {
            //if we reach here, the item shortname already exists in the player's inventory, so increment the counter of it
            allUsers[name].inventory[shortNameOfItem]++;
        } else {
            //the item is not in their inventory or is perhaps instanced, so in either case, add it locally and then replace inventory in memory
            playerInventory[shortNameOfItem] = 1;
            allUsers[name].inventory = playerInventory;
        }

        // 7.1 See if the item is part of a quest

        itemForQuestCheck(shortNameOfItem, name);

        // 7.2 Increment the player's currentItemCount by item slots
        allUsers[name].currentItemCount += slotsUsedByItem;

        //it is now added to the player, so continue on..

        // 8. Remove it from the room

        //first check to see if this is the only of that item in the room, or if there are more
        if (roomData.itemsAtLocation[shortNameOfItem].quantity > 1) {
            //there is more than 1, so subtract 1
            allRooms[currentRoom].itemsAtLocation[shortNameOfItem].quantity--;
        } else {
            //there is just 1, so completely remove it
            delete allRooms[currentRoom].itemsAtLocation[shortNameOfItem];
        }

        //the item is now removed, so continue

        // 9. Notify the player

        //need the display name of the item for the player
        var displayName;

        //first check if the item is in the master item list in memory, and if not, get it from instanced items
        if (allItems[shortNameOfItem]) {
            //it is in the master item list in memory
            displayName = allItems[shortNameOfItem].displayName;
        } else {
            //it wasn't in the master list, so must be instanced
            displayName = allInstancedItems[shortNameOfItem].displayName;
        }

        //now notify the player with the display name
        socket.emit('sendMessage', {color: 'comnote', message: 'You picked up a ' + displayName + '!'});

        // 10. Notify the room
        world.broadcastToAllInRoom(currentRoom, 'caction', name + ' just picked up a ' + displayName + '.', name);
        return;
    });
};
Notice that even without being familiar with the language (Javascript), platform (Node.js) or the application, it isn't that incredibly hard to figure out what is going on.

And as a side-note, I wrote this code about 2 months ago, and without the notes, I would already have no idea what it was doing, even with the descriptive variable and function names :P

Re: Please Read: Comment your code well!

Posted: Tue Sep 03, 2013 1:39 pm
by Sharlenwar
Okay, but how do you do it so well? What is the thought process that should occur in our heads as we code? Do we think about what we are looking at doing, write it down in the notes, then flesh it out?

By the way, awesome commenting!

Re: Please Read: Comment your code well!

Posted: Tue Sep 03, 2013 4:46 pm
by vitinho444
Good tip! When i went back to "revive" my first game in unity, i was like: "WTF Past Vitor, are you stupid? WHY DIDN'T U COMMENT THIS AND THAT? I CAN'T GET SH*T" and it took me a while to figure it out..

It also depends on the thing you are coding. If it is a 100% logic system, then it doesn't need comments..

Code: Select all

a = 3
if(a == 3)
{
b = 5;
}
else
{
b = 0;
}

if(!b)
{
a = 4;
}
You could read this (example) in a million years :P

BUT YEAH COMMENT PEOPLE!!

Re: Please Read: Comment your code well!

Posted: Tue Sep 03, 2013 6:15 pm
by Epiales
Great post! Thanks for the reminder!

Re: Please Read: Comment your code well!

Posted: Tue Sep 03, 2013 6:27 pm
by Xaos
Yeah, this is something I've really been working on, it's a very important thing to be able to do well. Will help alot later on in my life (college and the workforce) so I'm trying to get in the habit of "If I think this, write this!" in the code, and I kind of feel that's how you should do it. If you think something about the code/have a reasoning for the line of code, just put it down

Re: Please Read: Comment your code well!

Posted: Tue Sep 03, 2013 6:36 pm
by Ark
Wow nice commenting! :P

Re: Please Read: Comment your code well!

Posted: Tue Sep 03, 2013 6:44 pm
by OldRod
You can comment code?

:D

J/K... I usually go too far the other direction and have way too many comments. I end up with more comments that code... then I get bored of commenting, so I scrap the project and start on something else... damn Halls Disease!! :P

Re: Please Read: Comment your code well!

Posted: Tue Sep 03, 2013 9:01 pm
by Chromeozone
I literally write 1-2 paragraphs commenting on the code and what it does, I don't like to put to little, but it is easy to just close all comments in Notepad++ so its all good!

Re: Please Read: Comment your code well!

Posted: Tue Sep 03, 2013 10:12 pm
by Jackolantern
Sharlenwar wrote:Okay, but how do you do it so well? What is the thought process that should occur in our heads as we code? Do we think about what we are looking at doing, write it down in the notes, then flesh it out?

By the way, awesome commenting!
You got it! I always start with a comment "summary" of the steps to complete a function, method, class, etc., and then begin to fill them out. It really helps to organize your thoughts as well. Then I will add in demicals between the steps if things need to be added. Also, pretty much every discreet portion of code (as in, a block or several lines that do 1 thing) needs to be commented. And whenever I have to pause for a moment or longer to think of how to do something, it is complex enough to spell out in plain English (or your native tongue obviously ;) ) how it works. :cool:

Re: Please Read: Comment your code well!

Posted: Wed Sep 04, 2013 2:17 am
by Hamilton
And just to be Captain Obvious:
Remove all comments from the files that will go live.