Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Advice: Simplify your code

Status
Not open for further replies.

ndogg

Programmer
Feb 7, 2000
156
0
0
US
www.crosswinds.net
I have seen lots of code for lots of different things. Much of what I've seen has lots of redundancy and in some languages can actually slow the program down. This redundancy also has a tendancy to make code harder to read. Take for example the following two (they're not language specific, they just take attributes almost universal to any language (these &quot;//&quot; are comments):<br>
&lt;pre&gt;<br>
function DoThis(n) // creates a function called DoThis with n parameters<br>
if n = 0<br>
then print &quot;apples&quot;<br>
// print to the screen the word &quot;apples&quot;<br>
else<br>
if n = 1<br>
then print &quot;oranges&quot;<br>
// same as above except prints &quot;oranges&quot; instead<br>
if n = 2<br>
then print &quot;pears&quot;<br>
else<br>
if n = 3<br>
then print &quot;peaches&quot;<br>
end DoThis(n)<br>
&lt;/pre&gt;<br>
the same code, simplified:<br>
&lt;pre&gt;<br>
function DoThis(n) // creates a function called DoThis with n parameters<br>
array x[] = {&quot;apples&quot;,&quot;oranges&quot;,&quot;pears&quot;,&quot;peaches&quot;} // initializes the array x<br>
print array[n] // prints the value of the array<br>
end DoThis(n)<br>
&lt;/pre&gt;<br>
Now tell me which code is easier to read. <p>REH<br><a href=mailto:hawkdogg@crosswinds.net>hawkdogg@crosswinds.net</a><br><a href= by Linux</a><br>Learn Linux and Leave out the Windows :)
 
The second (with final static array).<br>
<br>
Bye, Otto.<br>

 
ndogg - <br>
<br>
I like the 2nd example for it's smallness. But in the real world I would do some bounds checking on 'n' before using it as an index into the array, since I wouldn't expect the calling routine to catch that particular exception.<br>
<br>
(I know I'm picking nits here)<br>
Chip H.<br>

 
Hi,<br>
The second version with array is probably more readable and plus easier to maintain : to add or remove an item you just have to add / remove an element of the array.<br>
Regards
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top