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 Chriss Miller 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
US
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 :)
 
Although you are right but the better way to do is use switch case method instead of doing both the other ways. For eg. <br>
<br>
switch(n) {<br>
case 1:<br>
print(...);<br>
break;<br>
case 2:<br>
print(...);<br>
break;<br>
case 3:<br>
print(...);<br>
break;<br>
case 4:<br>
print(...);<br>
break;<br>
case 5:<br>
print(...);<br>
break;<br>
default:<br>
print(...);<br>
break;<br>
}<br>
<br>
Now if you look on the code. Here you can have a default clause also. Which says that even if the values are not 1 to 5 , you can do something. While in the array case where you initialized you have to specifically check for boundary limit of the array. <br>
i.e, What about value beyond 3 . <br>
This would check the run time error it would've caused if you pass value beyond 3 in the array.<br>
<br>
Siddhartha Singh<br>
<A HREF="mailto:ssingh@aztecsoft.com">ssingh@aztecsoft.com</A>
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top