What is wrong with direct DBI access?

Now I am reading Effective Perl Programming (2nd Edition). I came across a piece of code that was described as poorly written, but I still do not understand what is so bad, or how it should be improved. It would be great if someone could explain this question to me.

Here is the code in question:

sub sum_values_per_key {
   my ( $class, $dsn, $user, $password, $parameters ) = @_;
   my %results;

   my $dbh = 
     DBI->connect( $dsn, $user, $password, $parameters );

   my $sth = $dbh->prepare(
     'select key, calculate(value) from my_table');
   $sth->execute();

   # ... fill %results ...

   $sth->finish();
   $dbh->disconnect();

   return \%results;
}

An example is given in the chapter on testing your code (p. 324/325). The suggestion that made me think about how to improve the code is as follows:

Since the code was poorly written and accesses the DBI directly, you need to create a fake DBI object to stand behind the real thing.

, , , , , , ​​ ... ,

+5
5

, :

() DBI. .

. , DBI , . , , , , - (, DBI).

+8

, " " , - ( , ).

, ( ) , .

, (. " SQLite DB" ). , , , , DBI -, , .

, DBI, .

, ? , ? , ? , ? , ...

.


() :

my $dbh = set_up_dbh();
my $query = qq[select key, calculate(value) from my_table];
my $data = retrieve_data($dbh, $query);
    # Now, we don't need to test setting up database connection AND data retrieval
my $calc_results = calculate_results($data);

, calculate_results (, ), DATA, , ( ); DBI, .

+5

DBI.

, . , , . , , , . , .

, , : . , DBI::connect, , , .

+4

sum_values_per_key , , .

S ( ) SOLID. http://en.wikipedia.org/wiki/Solid_%28object-oriented_design%29

, :

  • , .
  • .
+4

1) , , . . 20 DB, .

2) , DBI My:: DBI. 144 12 .

(Apache:: DBI ).

3) 3 144 . 7 ; . .

+1

All Articles