Avoid complex nested expressions

Link to this posting

Postby Ursego » 21 Feb 2013, 11:28

Try not to 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: ***

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)))

Code: Select all
countryName = this.getCountryNameByCountryId(this.getCountryIdByCityId(this.getCityId(rowNum)));

*** GOOD code: ***

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)

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
Site Admin
Posts: 120
Joined: 19 Feb 2013, 20:33

IF you want to ((lose weight) OR (have unbelievable (brain function AND mental clarity))) THEN click:

free counters

eXTReMe Tracker