Is there a right way or wrong way to Code? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Is there a right way or wrong way to Code?

Hi! I am just learning how to code. I am confused if there is a right way or wrong way to code. For eg: for my first code project, I used if-elseif-else to create a message per day program. But later on I changed and used Switch-Case. The end user result is the same, but from a coder's perspective, you can see, I used two different ways to get the same result. So how do you know which way is the right way? For ref: https://code.sololearn.com/wDXv92qsPo5f/#php https://code.sololearn.com/w9134M3TU415/#php Thanx for reading.

10th May 2018, 5:34 AM
Nft
6 Answers
+ 1
There isn't any right or wrong way, in the same way that there is no right or wrong way to paint. However, depending on the way PHP is implemented, switch statements may be faster, and thus better.
10th May 2018, 7:10 AM
Vlad Serbu
Vlad Serbu - avatar
0
- > The right way comes with errors and test-case fails. and solve the problem at hand with divide and conquer. - > The wrong way is coping and pasting someone else's code without having a understanding of what the code is doing. There is my two cents.
10th May 2018, 6:14 AM
Anthony Perez
0
@Mcqueen. I understand. Trial and error is a good way to learn. Thank you for replying.
10th May 2018, 10:50 AM
Nft
0
@Vlad. Are there other reasons besides speed, why you would choose one method over another? Not particularly for PHP. The if-switch codes above were just examples. What I am trying to learn is what would make you choose one method over another in any language. Like in Javascript. Alert is better than document.write if I want to say "You need to sign in before you can ENTER".
10th May 2018, 10:55 AM
Nft
0
Nft Aside from speed the only difference is syntax consider the following (I'm going to use C++ since I'm not familiar with PHP, but the same thing should apply) switch (operating_system) { case LINUX: case BSD: case UNIX: case MAC_OS: //do something ... Is just more readable then: if (operating_system == LINUX || operating_system == BSD || operating_system == UNIX || operating system == MAC_OS) //do something Also, automatic overflowing. case 'a': //do something if a case 'b': //do something for both a and b. break; Which would be even uglier using an if-else-if-else syntax. So, if you want to compare a value to a list of possible values, best practice is using a switch statement.
10th May 2018, 11:45 AM
Vlad Serbu
Vlad Serbu - avatar
0
@Vlad. Thank you so much for your reply. You have cleared a major confusion I was having. It isn't so much the right or wrong way. More like what makes it easy to write, read and understand. I guess, as I start writing more codes, I will be able to judge how to make my codes more easier to write. Or as you put it... more readable. Thank you again. :)
10th May 2018, 12:51 PM
Nft