Tip Good Coding Practices

jjdickow

Member
Joined
Aug 19, 2010
Messages
8
Programming Experience
Beginner
This is information for the very beginner. These are random things that are good habits for new coders to pick up. None of these practices are mandatory but will help you and other people read your sources.
-If you have more good coding practices tell me and I will add them to this post!

1. Using a Name Prefix: When naming each of your controls it is always a good coding practice to give them a prefix and then name them according to what they do
(or a lot of the time their 'text' name). The prefix is always all lowercase letters. This helps you remember exactly what you are coding when you use your control.


Common Controls and Prefixes:
-Button = btn
-ComboBox = cbo
-CheckBox = chk
-Label = lbl
-ListBox = lst
-RadioButton = rdb
-PictureBox = pic
-TextBox = txt

Examples (if you don't get the idea):
-btnExit
-cboEmailProvider
-chkPasswordShow
-lblStatus
-lstFriends
ect

2. Using White Space and Grouping: Coders use white space to make their code easier to read and also organize it. Also, group things that have to do with eachother.

Bad:
VB.NET:
dim string1 as string = textbox1.text
dim string2 as string = textbox2.text
dim int1 as integer = numericupdown1.value
if string1.contains("blah") then
messagebox.show("blah")
else 
end if
if int1=12 then
messagebox.show("int1 = 12")
else
end if
if string2.contains("flubble") then
messagebox.show("flubble")
else
end if

Good:
VB.NET:
dim string1 as string = textbox1.text

if string1.contains("blah") then
messagebox.show("blah")
else 
end if

dim string2 as string = textbox2.text

if string2.contains("flubble") then
messagebox.show("flubble")
else
end if

dim int1 as integer = numericupdown1.value

if int1=12 then
messagebox.show("int1 = 12")
else
end if

3. Comment things that may be confusing. Put a single quotation mark to start a comment (') and it will comment everything on the same line out. Use this for adding notes to your projects!

Commented Code (these are self explanatory but always useful with complex code):

VB.NET:
'Define String1 as a string to find the length of later
dim string1 as string = textbox1.text

'Find the last 3 characters of string1 and show them in a messagebox to the user
MessageBox.Show(string1.Substring(string1.Length—3)
 
With regards to point 1, Hungarian Notation is outdated and is considered by many, including myself, to be very bad coding practice. Good coding practice would to use the name "exitButton" rather than "btnExit". I'm with you on the other two though.
 
2. Using White Space and Grouping: Coders use white space to make their code easier to read and also organize it. Also, group things that have to do with eachother. Good:
VB.NET:
dim string1 as string = textbox1.text

if string1.contains("blah") then
messagebox.show("blah")
else 
end if

dim string2 as string = textbox2.text

if string2.contains("flubble") then
messagebox.show("flubble")
else
end if

dim int1 as integer = numericupdown1.value

if int1=12 then
messagebox.show("int1 = 12")
else
end if
hmm not so good. We also use things like indentation, character casing, naming conventions and code color. The latter is something that is hard to reproduce in a forum post, but the other three not so much. Type the code in your editor and copy it, paste it to forum post in a code box.

I think putting empty lines in random places is questionable, I'd rather put comments in for the sections, and divide up the sections with empty lines. Too much space can lead to too voluminous code which work as an abstraction, making the code harder to read and follow.

With very little effort you might have gotten something more readable like this:
VB.NET:
'first name
Dim firstName As String = firstTextBox.Text
If firstName.Contains("blah") Then
    MessageBox.Show("blah")
Else
End If

'last name
Dim lastName As String = lastTextBox.Text
If lastName.Contains("flubble") Then
    MessageBox.Show("flubble")
Else
End If

'age
Dim age As Integer = CInt(ageNumericUpDown.Value)
If age = 12 Then
    MessageBox.Show("age = 12")
Else
End If
As you get more than one indentation level it gets proportionally more important, but even what you posted there made me immediately think 'awk, I don't want to read that, where does it start, where's this gonna end?'. ;)
 
you know readability is actually the main reason I prefer C like languages over VB. Not that I think VB is all bad or anything (it is the primary language we use at my job), but still sometimes I wish we wrote C# at work for our .Net stuff just for what I consider better readability.

That and I don't like how Visual Studio auto aligns all your text when in VB... as in it forces you into some weird alignment that I'm not to fond of.

example or what I mean about readability...

I'll take this stupid example SimpleRandom class I wrote a while back in AS3:

SimpleRandom.as - lodgamebox - Project Hosting on Google Code

and port it to both C# and VB.Net, not I include a stupid 'interface' implementation... just to make an example of it, I've been writing a lot of stuff for use with WCF lately, and interfaces in VB have been grating on me.

C#
VB.NET:
using System;

namespace CSharpLib
{
    public class SimpleRandom
    {
        private int _mode;
        private int _mult;
        private int _incr = 0;
        private int _seed;

        public SimpleRandom()
        {
            _mode = int.MaxValue;
            _mult = 16807;//7^5
            _incr = 0;
            _seed = DateTime.Now.Millisecond;
        }

        public SimpleRandom(int seed)
        {
            _mode = int.MaxValue;
            _mult = 16807;//7^5
            _incr = 0;

            if (seed < 0) seed = DateTime.Now.Millisecond;

            _seed = seed % _mode;
        }

        public int Increment
        {
            get { return _incr; }
            set { _incr = value; }
        }

        public int Next()
        {
            _seed = (_mult * _seed + _incr) % _mode;
            return _seed;
        }

        public void NextBytes(ref byte[] barr)
        {
            int block = this.Next();
            int len = (barr != null) ? barr.Length + 4 : 4;
            Array.Resize(ref barr, len);

            barr[len - 4] = (byte)((block >> 24) & 0xFF);
            barr[len - 3] = (byte)((block >> 16) & 0xFF);
            barr[len - 2] = (byte)((block >> 8) & 0xFF);
            barr[len - 1] = (byte)(block & 0xFF);
        }

        public double NextDouble()
        {
            return this.Next() / _mode;
        }
    }

    public interface IRand
    {
        int Increment { get; set; }
        int Next();
        double NextDouble();
        void NextBytes(ref byte[] barr);
    }
}

VB
VB.NET:
Public Class SimpleRandom : Implements IRand

    Private _mode As Integer
    Private _mult As Integer
    Private _incr As Integer
    Private _seed As Integer

    Public Sub New(Optional ByVal seed As Integer = -1)
        _mode = Integer.MaxValue
        _mult = 16807 '' 7^5
        _incr = 0

        If seed < 0 Then seed = DateTime.Now.Millisecond

        _seed = seed Mod _mode
    End Sub

    Public Property Increment() As Integer Implements IRand.Increment
        Get
            Return _incr
        End Get
        Set(ByVal value As Integer)
            _incr = value
        End Set
    End Property

    Public Function [Next]() As Integer Implements IRand.Next
        _seed = (_mult * _seed + _incr) Mod _mode
        Return _seed
    End Function

    Public Function NextDouble() As Double Implements IRand.NextDouble
        Return Me.Next() / _mode
    End Function

    Public Sub NextBytes(ByRef barr() As Byte) Implements IRand.NextBytes
        Dim block As Integer = Me.Next()
        Dim len As Integer
        If Not barr Is Nothing Then
            len = barr.Length + 4
        Else
            len = 4
        End If
        Array.Resize(barr, len)

        barr(len - 4) = (block >> 24) And &HFF
        barr(len - 3) = (block >> 16) And &HFF
        barr(len - 2) = (block >> 8) And &HFF
        barr(len - 1) = block And &HFF
    End Sub

End Class

Public Interface IRand
    Property Increment() As Integer
    Function [Next]() As Integer
    Function NextDouble() As Double
    Sub NextBytes(ByRef barr() As Byte)
End Interface



Personally I find VB to feel more cluttered.

But eh, that's my opinion.



One thing I do love about VB though... "Optional"... freaking love it! I know there's an Optional Attribute dealy in CSharp or something, but it requires an extra import and is very verbose... [Optional, DefaultParameterValue(0)]int value.... ugh. Way to go CSharp engineers, take a turse language and bloat it up with that.




side note... heh, I read IRand as Ayn Rand...
 
Last edited:
That and I don't like how Visual Studio auto aligns all your text when in VB... as in it forces you into some weird alignment that I'm not to fond of.
I can't see what could possibly called weird about the alignment the VB code editor uses. It's all perfectly logical. If you don't like it then you can turn Pretty Listing off in the IDE options and you can align your code any way you like. I'm not saying that you have to like it but there's definitely not anything weird about it.

Also, you're quite wrong about optional parameters in C#. You CAN use the OptionalParameter attribute, in which case you don't need to specify a default value. To make a parameter optional in C#, all you have to do is provide a default value, which is like VB except VB requires the Optional keyword.

Named and Optional Arguments (C# Programming Guide)
 
I can't see what could possibly called weird about the alignment the VB code editor uses. It's all perfectly logical. If you don't like it then you can turn Pretty Listing off in the IDE options and you can align your code any way you like. I'm not saying that you have to like it but there's definitely not anything weird about it.

Also, you're quite wrong about optional parameters in C#. You CAN use the OptionalParameter attribute, in which case you don't need to specify a default value. To make a parameter optional in C#, all you have to do is provide a default value, which is like VB except VB requires the Optional keyword.

Named and Optional Arguments (C# Programming Guide)

I like most of the alignment, but some of it is weird. Especially region tags and notes. I would turn off pretty listing, but then the 90% I do like would have to be done manually... even more annoying. It's not a huge gripe, just a tiny gripe.

And as for the optional params... I must have some type of compiler settings screwy because it doesn't let me do that. I get a "Default parameter specifiers are not permitted" error. Unless that is of course it's a new feature in the latest version of .Net w/ Visual Studio 2010 (I use 2008, and that link you posted is a 2010 related article), because any google will show you years of posts about people having problems with it in the past.
 
Last edited:
Back
Top