c# - Better way to write if-else block -


i have following code (sample code) works well. think if there other better way can write following code snippet more accurately less code.

if(language == "english") {     if(student_id == 0)     {         somefunction();     }     else     {         if(getmarks(student_id) > 50 || subjectcount > 1 || projectcount > 0)         {             somefunction();         }     } } 

also, please note if student_id 0, getmarks(student_id) throws error

(for more complex scenario, check out this)

what suggest case is:

  1. to write less nested if-else block

    • one way inverting conditions and
    • gives early return whenever possible
  2. to combine conditions same actions (in case being somefunction)

  3. to exploit short circuit evaluation implemented in c# (also implemented in many other programming languages - noted martheen in comment).

    if(language != "english")     return; //assuming nothing below  if(student_id == 0 || getmarks(student_id) > 50 || subjectcount > 1 || projectcount > 0)     somefunction(); //if somefunction identical, can done 

    if have other languages checked or if have done independent actions based on language == "english", however, should not return in if (language != "english") statement:

    if(language == "english") {     if(student_id == 0 || getmarks(student_id) > 50 || subjectcount > 1 || projectcount > 0)         somefunction(); //if somefunction identical, can done } //something else must done 

edit (after question edited):

for additional condition, can put right after student_id == 0 because c# evaluate left if condition first (for || short circuit evaluation).

to illustrate: case, ok:

if(student_id == 0 || getmarks(student_id) > 50){      //if student_id == 0 true, getmarks(student_id) wouldn't evaluated } 

but not ok:

if(getmarks(student_id) > 50 || student_id == 0){      //if student_id 0, getmarks(student_id) throw exception before student_id == 0 evaluated } 

Comments

Popular posts from this blog

sql - VB.NET Operand type clash: date is incompatible with int error -

SVG stroke-linecap doesn't work for circles in Firefox? -

python - TypeError: Scalar value for argument 'color' is not numeric in openCV -