Great habits II

jplindstrom on 2003-06-24T18:34:29

Things that belong together should go together

Minimize scope. Declare variables the closest they can be to the first place they are used.

  • The code is easier to understand, since you can see everything it does in one screen.
  • The piece of code is more cohesive and easy to extract to a method.
Document things near where they are implemented. Document the API next to the method. Document the design decision next to where it is implemented.
  • You are more likely to keep code and comment in sync if you see both. Out of sight, out of mind.


docs

inkdroid on 2003-06-24T19:08:43

Agreed. I'm a big fan of keeping the POD right next to the method call:
=head1 NAME

Coffee - Virtual coffee (better, faster and stronger than Java)

=head1 METHODS

=head2 new()

new() will return a Coffee object. It uses only the finest beans straight out of the sack, just in from a Brazilian coffee commune.

=cut

sub new {
     my $class = shift;
     my $self = bless { }, ref( $class ), $class;
     $self->_getBeans();
     $self->_grind();
     $self->_brew();
     return( $self );
}

Re:docs

chromatic on 2003-06-24T19:21:52

Could you comment this line?

my $self = bless { }, ref( $class ), $class;

Re:docs

inkdroid on 2003-06-24T20:20:46

## error ## my $self = bless { }, ref( $class ), $class;

my $self = bless { }, ref( $class ) || $class;

Re:docs

inkdroid on 2003-06-24T20:28:30

rather:

...

## this is an error
## my $self = bless {}, ref( $class ), $class

## this allows new() to be called as an object method ( $obj->new() )
## as well as class method ( Coffee->new() )
my $self = bless{}, ref( $class ) || $class;

...