language agnostic - Group functions of similar functionality -


sometimes come across problem have set of functions belong same group. functions needed @ several places, , together.

to give specific example: consider filemtime, fileatime , filectime functions. provide similar functionality. if building filemanager, you'll need call them 1 after info need. moment thinking wrapper. php provides stat, suppose don't have function.

i looked @ php sourcecode find out how solved particular problem, can't find out what's going on.

obviously, if have naive implementation of such grouping function, filetimes, this:

function filetimes($file) {     return array(         'filectime' => filectime($file)         ,'fileatime' => fileatime($file)         ,'filemtime' => filemtime($file)     ); } 

this work, incurs overhead since have open file pointer each function call. (i don't know if it's necessary open file pointer, let's assume sake of example).

another approach duplicate code of filextime functions , let them share file pointer, introduces code duplication, worse overhead introduced in first example.

the third, , best, solution came add optional second parameter filextime functions supply filepointer.
filetimes functions this:

function filetimes($file) {     $fp = fopen($file, 'r');     return array(         'filectime' => filectime($file, $fp)         ,'fileatime' => fileatime($file, $fp)         ,'filemtime' => filemtime($file, $fp)     ); } 

somehow still feels 'wrong'. there's parameter used in specific conditions.

so question is: best practice in situations these?


edit:
i'm aware typical situation oop comes play. first off: not needs class. use object oriented approach, have functions in global space.
let's we're talking legacy system here (with these 'non-oop' parts) , there lots of dependencies on filextime functions.

tdammer's answer specific example gave, extend broader problem set? can solution defined such applicable other problems in domain?

i'd rewrite filextime functions accept either filename or file handle parameter. languages can overload functions (like c++, c# etc) can use feature; in php, you'd have check type of argument @ run time.

passing both filename , file handle redundant, , ambiguous calls made:

$fp = fopen('foo', 'r'); $times = file_times('bar', $fp); 

of course, if want go oop, you'd wrap them in fileinfo class, , store (lazy-loaded?) private file handle there.


Comments

Popular posts from this blog

unicode - Are email addresses allowed to contain non-alphanumeric characters? -

c++ - Convert big endian to little endian when reading from a binary file -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -