c# - Is adding the logic for a event in a separated method to the one that triggers it a good practice? -


for example let's have windows form textboxes numbers , button, , when click on button want take value of of texts , math them.

would this:

private void btnsomeresult_click(object sender, eventargs e) {      dosomemath();  }  

be better practice say:

private void btnsomeresult_click(object sender, eventargs e) {      //complex math goes here.  }  

or depend on complexity of operation? example may not needed in simple multiplication, division etc.

private void btnsomeresult_click(object sender, eventargs e) {  dosomemath(); 

}

this approach better suited because of following reasons

  1. if ui changes, replacing button another button need same function, can reuse functionality written. in essence, ui independent of functionality of button control.

  2. you can test method (dosomemath) if start unit testing.

a still better way data ui elements , pass on method parameters in more specific class/type ensure data independent of ui controls

   // function reads data ui , call next method more narrow in it's parameter type (like accepting params of type int )     private void dosomemath()     {         // no error handling, demostration         string firstnumber = int.parse(txtboxfirstnumer.text);         string secondnumber = int.parse(txtboxsecond.text);          dosomemath(firstnumber, secondnumber);     }      // no relation ui it's parameter independent of ui controls      private void dosomemath(string firstnumber, string secondnumber)     {         return firstnumber + secondnumber;     }  

next, can move method dosomemath(string firstnumber, string secondnumber) different class/library can reused across different windows forms/web pages/ or other classes.


Comments

Popular posts from this blog

python - pip install -U PySide error -

arrays - C++ error: a brace-enclosed initializer is not allowed here before ‘{’ token -

cytoscape.js - How to add nodes to Dagre layout with Cytoscape -