Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is more appropriate way of programmming

Tags:

validation

If a variable can take n values should we check for the validity of the values or assume that if all the n-i checks fail it would be the nth value.

For example if we have a variable that stores gender as M or F. Use this:

If gender = "M"
   do male_processing
else
   do female_processing
endif

Or this:

If gender = "M"
  do male_processing
else
  if gender = "F"
     do female_processing
  else
     print "Something has gone wrong Gender has a value " Gender
  endif

endif
like image 633
Raju Avatar asked Jun 02 '10 08:06

Raju


People also ask

Which is the most preferable programming language?

As per the latest statistics, Python is the main coding language for around 80% of developers. The presence of extensive libraries in Python facilitates artificial intelligence, data science, and machine learning processes. Currently, Python is trending and can be regarded as the king of programming languages.

What is the best type of programming to learn?

JavaScript and Python, two of the most popular languages in the startup industry, are in high demand. Most startups use Python-based backend frameworks such as Django (Python), Flask (Python), and NodeJS (JavaScript). These languages are also considered to be the best programming languages to learn for beginners.


3 Answers

For that example, I wouldn't use IF at all, I'd either use SWITCH for your second example

switch (gender) 
    case "M":
        do male_processing
        break
    case "F":
        do female_processing
        break
    default:
        print "Something has gone wrong Gender has a value " Gender
 endswitch

or for your first example, I'd simply treat exceptions as an error using ASSERT

assert (gender = "M" or gender = "F")
like image 60
blissapp Avatar answered Oct 16 '22 12:10

blissapp


Shortly - that depends on what type the variable is. If it's a boolean or an enumeration of some sort and there's no other value it can possible have (including null), a simple else clause will suffice.

You can even add a simple comment like so:

if male:
    do_male_stuff()
else: #obviously female
    do_female_stuff()

Having something like this just seems wrong:

bool = SOME_BOOLEAN_VALUE
if bool:
    do1()
elif not bool:
    do2()
else:
    huh() #?!?!

Bottom line: have an if/else/else if clause for each possible scenario, but no more than that, and keep it readable.

like image 34
Yuval Adam Avatar answered Oct 16 '22 11:10

Yuval Adam


...or, in OO world you could create a base class, say Gender and extend it with Male and Female classes. Instead of assigning value 'M' or 'F' to a variable, you could assign an instance of Male or Female class. Then simply call a method specified in the base class, for example doGenderSpecificStuff(). No need for if-elses there.

like image 2
fish Avatar answered Oct 16 '22 12:10

fish