Programming style: Difference between revisions

Content deleted Content added
Dysprosia (talk | contribs)
unredir, add info
Line 1:
'''Programming style''' is a term that describes the way a programmer writes code in a certain [[programming language]].
#REDIRECT [[Programming language]]
 
Programming style is often dependent on the actual choice of programming language one is writing in. [[C (programming language)|C]] style will vary from [[BASIC]] style, and so on.
 
== Characteristics of style ==
Good style, being a subjective matter, is difficult to concretely categorize, however there are a number of general characteristics.
=== Appropriate variable names ===
Appropriate choices for variable names is seen as the keystone for good style. Code that uses poor names means that the overall functionality of the program is less easy to elucidate.
 
For example, consider the following [[pseudocode]] snippet
 
'''get''' a b c
'''if''' a < 12 '''and''' b < 60 '''and''' c < 60
'''return''' true
'''else'''
'''return''' false
 
What does this code do? Because of the choice of variable names, this is difficult to work out. However, if we change variable names:
 
'''get''' hours minutes seconds
'''if''' hours < 12 '''and''' minutes < 60 '''and''' seconds < 60
'''return''' true
'''else'''
'''return''' false
 
we could probably guess correctly it returns true if the time entered is in the AM.
 
=== Indent style ===
[[Indent style]], in programming languages that use braces or indenting to delimit logical blocks of code is also a key to good style. Using a logical and consistent indent style makes one's code more readable. Compare
 
if(hours<12 && minutes<60 && seconds<60)
{
return true;
}
else
{
return false;
}
 
with something like
if(hours<12 && minutes<60 && seconds<60){return true;}
else{return false;}
 
The first example is much easier to read in that it is spaced out and logical blocks of code are grouped and displayed together much more clearer.
 
=== Looping and control structures ===
The use of logical control structures for looping adds to good programming style as well. It helps someone reading code to understand the program's sequence of execution (in [[imperative programming]] languages). For example, in pseudocode:
count = 0
'''while''' count < 5
'''print''' count*2
count = count + 1
'''endwhile'''
 
obeys the above two style guidelines, but however the following using the "for" construct makes the code much easier to read.
'''for''' count = 0, count < 5, count=count+1
'''print''' count*2
 
=== Spacing ===
Certain programming languages ignore whitespace absolutely. Making good use of spacing in one's layout is good programming style.
 
Compare the following examples of C code.
int count;for(count=0;count<10;count++){printf("%d",count*count+count);}
with
int count;
for(count = 0; count < 10; count++)
{
printf("%d", count*count + count);
}