in reply to Design/Style question about writing to a file from different functions

I agree with the other posters who are suggesting more abstraction. If you disentangle the operations you need to do to perform the file manipulations from the actual things to be accomplished, I think you'll find that it makes the program as a whole decidedly simpler, and wrapping it up in an object seems like a foregone conclusion. Something like this:
sub func1 { my $file_manager = File::Manipulator->new($filename); $file_manager->write_line(...); # maybe other writes ... $file_manager->move_line($from_position, $to_position); func2($file_manager); func3($file_manager); $file_manager->move_line($from_position2, $to_position2); }
Now you have a clear separation of roles: File::Manager just diddles with the file in whatever way makes the most sense, while the functions tell File::Manager what they want done.

This means that the low-level solution in File::Manager can be swapped around to anything that makes the process work without impacting the logic of what the main program wants done. Plus, you have the advantage that you can test the two parts better: the File::Manager code can be functionally tested - I wrote a line, did it get there? I moved a line that doesn't exist, did the right thing happen? - and the mainline code can talk to a dummy version of File::Manager that just puts lines into an array so you can check if the algorithm in the main program is doing what it ought to do.

  • Comment on Re: Design/Style question about writing to a file from different functions
  • Download Code