Avoid complex nested expressions

Share this topic:



Link to this posting

Postby Ursego » 21 Feb 2013, 11:28

Don't write more than one executable statement in one line of code.

Good developers break one long function into a number of short sub-functions - the same philosophy works for complex, super-nested expressions: we should break them down into stand-alone, simple lines:

*** BAD code: ***

PB:
Code: Select all
ls_country_name = this.uf_get_country_name_by_city_id(this.uf_get_country_id_by_city_id(this.uf_get_city_id(ll_row_num)))

C#:
Code: Select all
countryName = this.GetCountryNameByCountryId(this.GetCountryIdByCityId(this.GetCityId(rowNum)));

*** GOOD code: ***

PB:
Code: Select all
ls_city_id = this.uf_get_city_id(ll_row_num)
ls_country_id = this.uf_get_country_id_by_city_id(ls_city_id)
ls_country_name = this.uf_get_country_name_by_country_id(ls_country_id)

C#:
Code: Select all
cityId = this.GetCityId(rowNum);
countryId = this.GetCountryIdByCityId(cityId);
countryName = this.GetCountryNameByCountryId(countryId);

The last example demonstrates how this approach simplifies debugging (in addition to better readability!): if the variable countryName has not been populated as expected then you can see in the debugger (without STEP IN) which step exactly fails. In the nested version, if you want to STEP IN GetCountryNameByCountryId to debug it then you are forced firstly to STEP IN (and STEP OUT from) each one of the inner methods, beginning from the most nested GetCityId.
User avatar
Ursego
Site Admin
 
Posts: 112
Joined: 19 Feb 2013, 20:33

Return to Coding Style

Who is online

Users browsing this forum: No registered users and 1 guest


Avoid complex nested expressions

Share this topic:


If you think that this site is not too bad, please LIKE it in Facebook. Thanks!





cron
free counters

eXTReMe Tracker