Formatting your code

…This post is one for all scripters, but especially for those starters…

It can’t be said too many times, and you probably already read this more then once, but also I would like to make everone aware of the need to format your code. I am going to break it down for you, however this is something one must learn himself.

Most scripters are unorganized, lazy and careless. That is a fact. Ok, it doesn’t need to aply to you, but it did aply to me. We tend to write those lines down without taking in a visual structure in our work. At the time we realize that, it is already too late, and we either start over, or search for hours (ok… maybe less) too find something in our marvalous work. Now there are some ways to make sure that does not happen. We can call it formatting our code. It consists of naming variables, commenting, indenting and more…

Content

  1. commenting
  2. naming variables and…
  3. indenting
  4. line-length and whitespace
  5. constants

Commenting
It all starts with this easy little thing with coloured/grey-ish characters in your script. It is code that does not get processed, but can really come in handy when you look back at your script a year after you wrote it. We call it comments. With comments you can start to format your code in such way that you don’t need to look for that specific block of code in your 10000-line script anymore, but can simply find it by reading your own text.

When should one comment?
Well, remember I am speaking from my OOL background, so I use terms as methods and classes, you should comment as much as is neccesairy to make someone who can script a bit more then the basics ,in the same language, understand what that piece of code will do. This means that you should comment more on short unusual operations then on long very basic blocks.

Comment classes, methods and definitions!
The things you should at least comment on are Classes, Methods and Weird Definitions. When commenting on a class, you should give a brief summary from one or two lines on what it does, and give one line of brief information on methods and definitions. However, do include the class and method name in your comment, as that makes it easier to deal with.

#===============================================================================
# ** Game_NetPlayer - Manage Other player's data
#-------------------------------------------------------------------------------
# Author    Me™
# Version   1.4.0
# Date      14-04-06 (m/d/y)
#===============================================================================

Here is an example of how I comment most of my classes. As you can see I included more then the name and a short explanation. The reason is that I released this class for other people to use. Whenever I update it, people can compare the new comment data with theirs so they know whether theirs is outdated. Also, when working on a team-project, it can be handy to write down who made what. You know who to contact when something doesn’t work, something doesn’t seem right or whenever you need to credit a person.

#--------------------------------------------------------------------------
# * Object Initialization
#     viewport  : viewport
#     character : character (Game_Character)
#--------------------------------------------------------------------------

Here is an example of how I comment my methods. The methods accessor is initialize, but I called it Object Initialization in my comment. That way I still keep part of the name in my comment, but don’t need another line for an explanation. I also stated the attributes, as a single word does not always clearly states what you are dealing with. For example, character could have been something else to like and Game_Actor or Game_Event.

# Get the current synth from the hash
data = @synths[catid][index.to_i]
# Set the positions
x = 20 + ( ( index % 6 ) * (32 + 4) )
y = @y + 12 + 20 + ( index / 6 ) * 36
# Also, set the positions in the array
@synth_positions[catid][index] = [x+138,x+32+138]
# Create a new rect and fill it with blackness
rect = Rect.new(x, y, 32, 32)
object.fill_rect(rect, Color.new(0, 0, 0))

Lastly, an example on almost one-line-code-one-line-comment code. It will be easier to see what happens by looking at the green text, then by looking at the code. It also helps you to seperate some blocks from other blocks, thus making your code clearer.

Naming variables and…
Also said so many times: It is very important to name your variables, methods and classes descriptivly.

What about variables?
Variables should be named that way that you don’t need to look more then a few lines, if possible none, to see what it is used for.

For instance, let’s say we want to retrieve some description in a string variable. Now a variable named some_var is the worst case scenario. You don’t know what it does and what it is. Naming it some_txt is better, but still not good enough. It tells us what it is, probably a string, but it does not tell us what it does or where it belongs too. We should name it description_txt or description.

However, there is a downside too. If you are saving the x-position of an objectX in room a. The method is made in the objectX’s class, therefore will aply to all instances of objectX. Now, we could name the variable xPositionObjectXRoomA, but that will only cost you bytes. A variable named x or xpos will do fine. You HAVE to relevate everything to your code. You won’t have any other x positions in that objectX class, so what point in name it xPositionObjectXRoomA?

What about classes?
Classes should be handeld a little bit different. If you are working with namespaces, just pretend that the title of this paragraph is What about namespaces? as you won’t have a big problem with classes. If you are scripting something for a community or you are using scripts from a community, you should take two things in account when naming your class.

First, you have the problem that other people don’t know yet what your class contains. The name has to be descriptive. Exemplia gratia, don’t name your class MyObject.
Second, your class name might collide with someone else’s class. That’s is why it can be handy to prefix the class name with your name or a system abbrevation.

Indenting
I think the thing that increases the readability of your script the most, is indenting. Most script languages nowadays support the use of tabs to indent the code, but watch out for reading indented textfiles as it will replace the indent with a control character like \t. I always use the folowing rules when indenting my scripts:

  • Everything between class opening and end should be indented
  • Everything between method opening and end should be indented
  • Everything in blocks like loops and block operations should be indented

Line-Length and Whitespace
Next after indenting comes line-length and whitespace. Compare the two following pieces of code:

Input::Numberkeys.keys.each do |key| if Input.triggerd?(Input::Numberkeys[key]); then @username.push(key.to_s);  end; end; Input::Letters.keys.each do |key| if  Input.triggerd?(Input::Letters[key]);  then; (if Input.pressed?(Input::Shift) ; then; @username.push(key.upcase.to_s); else; @username.push(key.downcase.to_s); end;
[...]

Input::Numberkeys.keys.each do |key|
  @username.push(key.to_s) if Input.triggerd?(Input::Numberkeys[key])
end

Input::Letters.keys.each do |key|
  if Input.triggerd?(Input::Letters[key])
    if Input.pressed?(Input::Shift)
      @username.push(key.upcase.to_s)
     else
      @username.push(key.downcase.to_s)
     end
  end
end

[...]

As you can see, the second one is much easier to understand. When I am coding, I always:

  • Make sure the viewer does not need to scroll.
  • Use a blank line in the following places:
    • Between module and class definitions
    • Between class and method definitions
    • Between methods
    • Between parts of instructions
    • If it improves the readability and is logical
  • Use a space character in the following places:
    • After operators like + – / * etc. (xy = x + y)
    • After most commas (somethinga, somethingb = 0, 1)
    • After some parenthesis
    • If it improves the readability and is logical

As you can see, the rules aren’t always as clear. This is because everyone prefers something above something. The rules I gave you are basic rules that are used by many scripters, I believe. You should use them too. Everone will eventually have his own style, but using those rules, everyone will be able to read it afterwards, including yourself!

Constants
I have been told that if you are programming assembly, using constants is vital. It can be very helpfull too when scripting in other languages, particulary when integers and strings tend to change during development. Strings and especially Numeric values (except -1, 0, 1) should be turned into constants and be used instead. Don’t forget the rules about naming your variables, as a constant is just a special type of variable. It might decrease the readability of your script by an inch, however you will really cut time on upgrading and developing your script.

Conclusion

If everyone always took all these points of formatting very serious, we wouldn’t need to contact each other as many times as we do know. There would be less support requird, and the productivity will rise. Ok maybe that is all crap, but just try to format your code, just to have at least one good habit.

Cheers

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: