codeigniter - PHP code duplication. At what point is duplicating code the right way to go? -


i using codeigniter question applies in general sense too.

i have table of transactions columns

item_name | type | date | price | document 

i want following in 2 independent cases.

1) list of transactions within date range. 2) total price of each transaction.type within date range.

the former can achieved using select statement > datetimestamp

the latter can achieved selecting sum, , grouping type whilst implementing required conditionals e.g > datetimestamp

although simple case, achieve need have 2 methods bulk of both of these methods (namely clauses) duplicated across both methods.

in terms of speed etc not matter seems pointless code reproduction.


a second example follows.

i had method get_data($id) row table based on id passed in.

as such in separate method 100 items example.. return array, loop through them , call get_data each.

this setup meant many different methods different lists different sources , still use same get_data function , loop required data.

this minimized code duplication incredibly ineffiecient meant looping through loads of data items , hundreds of db queries.

in current setup join data table in each of methods - code duplication clear improved efficiency.


a final example follows

in codeigniter can have function such following:

get_thing($id) { $this->load->database(); $this->db->where('id',$id); $this->db->get('table'); } 

but in alternate situations might want items in specific folder.. such making function more generic works better.. e.g.

get_thing($array) { $this->load->database(); $this->db->where($array); $this->db->get('table'); } 

but might want use function in 2 different contexts e.g user page , admin page whereby admins can see items, unverified ones. code becomes:

get_thing($array,$show_unverified = false) { $this->load->database(); $this->db->where($array); if($show_unverified == false) { $this->db->where('verified','yes'); } $this->db->get('table'); } 

as can see can out of hand , methods can become overly complex, confusing , full of conditionals.


my question follows - best practices minimizing code duplication, , how applied above situations? spent hours , hours trying make code more efficient yet i'm getting because cant workout should trying achieve.

cheers

my idea on code duplication in database access functions is better keep separate.

my rule here function should not return different kinds of data depending on parameter, example should not return single user , other times array of users. may return error codes (false) though.

it ok though if function implements different access levels, shared across several pages.


Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -