# Best Programming Practices Thread



## Kreij (Jun 27, 2008)

I thought I would start a thread on programming best practices.
In the years that I've been programming and maintaining code, I've seen a few things that drive me nuts and thought that maybe people would benefit from our experiences.
This thread is not language dependent so feel free to post anything you like in the language of your choice. (I will be using C#)

I would like to start out with variables.
I've seen variable use range from the most obscure to over the top, and I would like to just give you some impressions that I think make writing and maintaining code easier for both you and anyone who may have to read the code later.

*Variable names : Tell us what's in them!*
You can use almost any naming convention that you want when declaring variables, but that does not necessarily mean its good.
For instance ...

```
String[] stringArray = new String[10];
```

This is a valid string array declaration, but it does not give any indication of what the data in the string array contains. Use something more decriptive.

```
String[] CustomerNames = new String[10];
```

Another example is using loops...

```
For (int x = 0; x < 10, x++)
{
    stringArray[x] = stringArray[x] + “.”;
}
```

No one would have any idea that you are just trying to add a period the end of a customer name (in this case).


```
For (int thisCustomer = 0; thisCustomer < CustomerNames.Length; thisCustomer++)
{
    CustomerNames[thisCustomer] += “.”
}
```

Much better, no?

* Use the best variable type*
Don't put integers into floats or doubles, it just wastes space and makes it difficult to figure out what is going on, unless there is a need for it.

```
double DaysInAWeek = 7.0;
```
What a waste if memory!
In this case one should use the smallest possible variable type to contain the data.
In this case a “short” variable would have been better.

Sometimes it requires a little more typing to use these practices, but in the long run you will be much better off. Especially if you are looking at code you wrote ten years ago 

Okay, I don't want this to get too long on the initial post.
All you coders post your ideas for best practices here.


----------



## mdm-adph (Jun 27, 2008)

You haven't factored in the competing issue of job security.  Obscure variable names help keep you in a job.


----------



## Kreij (Jun 27, 2008)

If you have to use obfuscation on simple code to keep your job, you really should be looking for a new job


----------



## mdm-adph (Jun 27, 2008)

Kreij said:


> If you have to use obfuscation on simple code to keep your job, you really should be looking for a new job



On the contrary, I'd say that if obfuscation of simple code is all one needs to keep a well-paying job, then one has found the perfect job.


----------



## Kreij (Jun 27, 2008)

I disagree. If you have to write unreadable code to keep your job the place sucks.
Your performance should be based on the functionality, accessability and the fact that it has minimal problems (bugs) as opposed to the fact that you are the only one who understands what you did.
I understand that management has no clue as to what you are doing from a coding standpoint, but your software should stand or fall on its own.
There is always someone who can come in an decipher your code to replace you.

Just my 2 cents.


----------



## W1zzard (Jun 27, 2008)

never ever write variable names, function names or comments in any language other than english

re: variable type/waste of memory. smallest variable won't give you best performance. best performance is depending on architecture, typically 32-bit. use appropriate types still applies of course.

it is typically accepted that _simple_ loops use loop counters called i,j,z

dont try to "optimize" statements. the compiler is smart, usually smarter than you and will produce fast code. 
don't waste your time using assembler for performance. 
if you want to optimize, optimize your algorithms. 
before wasting your time on optimization, do exhaustive performance measurements and check if there is something to be gained that is worth the added dev time and code complexity (harder to maintain).
dont ship debug builds, dont look at them for performance issues.

if you are writing more serious projects start using some sort of versioning system. i like perforce a lot, it's free for up to 2 users.


----------



## Kreij (Jun 27, 2008)

@W1zz : Thanks, oh fearless leader. When I started this thread I had re-use and readability more in mind than performance, but please post any performance tidibits you know. It will help us all.

*Comments*
Many people like to put volumous comments in their code.
While comments are always useful, I personally find that too much commenting makes the source code difficult to wade through.
Simple commenting is sufficient.
Examples of what I personally don't like and like...

Verbose

```
// This function calculates the average and mean of various
// values for something or another and produces and output that is
// used by another function or whatever that determines to blah blah
// blah blah blah
// blah blah blah
```

Terse

```
// Calculate means and averages
```

Unless the code is unusually obscure, most coders can figure out what you are doing with terse descriptions.

I am sure that there are people who will disagree with this, but personally I like short, concise comments.


----------



## W1zzard (Jun 27, 2008)

totally agree. comment where you do magic that someone may not understand. 
dont comment i = i + 1;

don't use magic numbers, use defines
UINT32 res=ReadRegister(0x2423);

better:
#define R800_ENGINE_CLOCK 0x2423
UINT32 res=ReadRegister(R800_ENGINE_CLOCK);

put the #ifdefs at the start of your code file or wrap the accesses with #define #undefs. if you plan to copy/paste code the wrapped ifdefs come in handy


----------



## Kreij (Jun 28, 2008)

Keep your methods grouped together when similar in function.

For instance, let's say you have a form that contains menu items and buttons.
Keep the menu item events and the button events together.


```
private void menuItem1_Click() { ... }
private void menuItem2_Click() { ... }

private void button1_Click() { ... }
private void button2_Click() { ... }
```

This prevents someone (including yourself) from having to hunt endlessly through a long class trying to find where things are happening.

In the Microsoft Visual Studio IDE you can also use #region and #endregion.
These tags allow you to enclose a group of functions in a collapsable/expandable area so that you can keep the editor clear of what you are not working on at the moment.
This helps a lot when you are creating classes that do a lot or have a large number of events and properties.


```
#region Menu Item Events
private void menuItem1_Click() { ... }
private void menuItem2_Click() { ... }
#endregion

#region Button Events
private void button1_Click() { ... }
private void button2_Click() { ... }
#endregion
```

When you collapse the area you will only see one line that shows the text which you included in the #region tag.


----------



## [I.R.A]_FBi (Jun 28, 2008)

go bless you guys .. this will come in handy


----------



## Kreij (Jun 28, 2008)

Thanks Fbi, if you have any questions or suggestions feel free to post them.

Most compilers and IDEs do not care about newlines or whitespace in the code.
Use your head when writing things so as not to make it obfuscated.
You can however keep code cleaner by thinking a little.

For instance, a property in C#

```
public string GetName
{
    get
    {
        return myName;
    }
}
```

There is no real reason that you cannot simply do

```
public string GetName { get { return myName; } }
```
The above example is still clear in it intent.

HOWEVER !!  It is not fun, cute or l33t to cram a ton of stuff on a single line.

Bad example...

```
public string myFunction(){for(int x=0;x<10;x++){doSomething;doSomeMore;blah;blah;}}
```

Unless, of course, you are submitting an entry to the yearly International Obfuscated C Code Contest 
But in that case, you have to do a lot better than just cramming everything on one line.


----------



## Kreij (Jun 28, 2008)

Another things that you will see when perusing other's code is the use of type descriptors in variable names.
Letters are added to the beginning of the variable name to demonstrate the type of the variable.
For instance

```
Int32 [color="blue"]i[/color]MyInteger;
String [color="blue"]s[/color]MyString;
Double [color="blue"]d[/color]MyDouble;
```

This can make it easier at a quick glance to determine the type of the variable, but I personally feel that good variable names are more important than displaying the type.

Just my opinion on this one. Do what works best and makes life easier for you.


----------



## Disparia (Jun 28, 2008)

That's right, don't follow that Jizzler guy's bad examples 


```
bcscale(10000);

$pi = $n = 4;
for ($d = 3; $d <= 5000; $d+= 2) {
    $pi = bcadd($pi, bcdiv(($n=$n*-1), $d));
}

echo '<pre>',chunk_split($pi),'</pre>';
```

My best has a been an $a through $z function 

But at work I keep it cleaner - there's four other people on the website team that need to understand what I'm doing. Only one of them is a coder while the other three are designers.

On the compiled side I'm learning C#. Code hinting in Studio is great, so working with clear variable/function names is quick and easy.


----------



## Oliver_FF (Jun 30, 2008)

Always always always always use the parenthesis... even if you don't need to at the time!

Last week I was adding to this game i'm writing in XNA game studio, it's passed the 2100 lines of code and I was adding some functionality in when this obscure bug struck me  Took me ages to fix, but in essence I started with this:

```
...
if (blahblahblah)
    doStuff();
...
```

Then I added some giving this:

```
...
if (blahblahblah)
    doStuff();
    doMoreStuff();
...
```

And of course, despite my indenting efforts doMoreStuff() is no longer inside the If statement XD Oops...

USE PARENTHESIS ALL THE TIME!! 


```
...
if (blahblahblah)
{
    doStuff();
}
...
```


```
...
if (blahblahblah)
{
    doStuff();
    doMoreStuff();
}
...
```

It'll come back and haunt you much later if you don't


----------



## Kreij (Jun 30, 2008)

I assume you mean curly brackets or braces "{}", not parenthesis "()" 

I usually don't use them if I am testing for something that is going to cause a return.


```
private void DoSomething()
{
    if (blahblahblah != something) return;
...
}
```


----------



## Oliver_FF (Jun 30, 2008)

Kreij said:


> I assume you mean curly brackets or braces "{}", not parenthesis "()"
> 
> I usually don't use them if I am testing for something that is going to cause a return.
> 
> ...



According to the Oxford English Dictionary, [Parenthesis are] "...*usually* marked off by round or square brackets, dashes, or commas" but can in fact be any form of punctuation XD

Never start programming after dinner on a big project. You'll regret it later when it comes to sleeping  Do it the next morning


----------



## Oliver_FF (Jun 30, 2008)

Where possible, make as much use of Generics as possible! They effectively convert runtime errors into compile time errors by forcing you to specify a type of all objects that you can store in a collection.


```
//Create a standard list to hold Table objects.
Arraylist someList = new Arraylist();

//Add the first Table object.
someList.add(new Table());

//Because we're not using generics we can add these two in too :s
someList.add(new Laptop());
someList.add(new String());

//*********************************************************
//We get here and we're still good... until we try to cast a String to type
//Table and get a class cast exception AT RUNTIME - the syntax is perfect :(
//*********************************************************
Table object = (Table)someList[2];
```

Better this way:

```
//Create a standard list to hold Table objects.
Arraylist<Table> someList = new Arraylist<Table>();

//Add the first Table object.
someList.add(new Table());

//*************************************************
//Because we're using generics we get a COMPILE TIME error here!
//*************************************************
someList.add(new Laptop());
someList.add(new String());

//We're also guaranteed no class cast exception here because everything in 
//the collection MUST be/inherit from Table. Notice we also can skip the cast XD
Table object = someList[2];
```

The error will become apparent a LOT sooner than if you don't use generics, which makes things a LOT easier to fix


----------

