Advantage of encupsulation in OO programming

I think there are two advantages in encapsulation.

Separation of implementation and API interfece

Advantage of encapsulation is that if you change the implementation,
you don't need to change api interface.

For example, see the following code. This is Mojo::Path source code.

package Mojo::Path;

...

sub trailing_slash { shift->_parse(trailing_slash => @_) }

sub _parse {
  my ($self, $name) = (shift, shift);

  unless ($self->{parts}) {
    my $path = url_unescape delete($self->{path}) // '';
    my $charset = $self->charset;
    $path = decode($charset, $path) // $path if $charset;
    $self->{leading_slash}  = $path =~ s!^/!! ? 1 : undef;
    $self->{trailing_slash} = $path =~ s!/$!! ? 1 : undef;
    $self->{parts} = [split '/', $path, -1];
  }

  return $self->{$name} unless @_;
  $self->{$name} = shift;
  return $self;
}

trailing_slash means that tail of path end with slash or not. But trailing_slash method do more than setting attribute "trailing_slash".

If you access attribute directory and want to change the implementation, api interface must be changed. This will become user cost. If you separate implementation and api interface, you don't need to change api interface.

Unify interface to object

If you unify api interface by method, things become simple. User don't think about internal data structure. You only write methods in document as api interface to object. You can change internal data structure without changing api interface.

If user and author follow the rule that interface to object is restricted to method(normal method and accessor), things become simple.

Leave a comment

About Yuki Kimoto

user-pic I am Yuki Kimoto, Japanese Perl programmer. I create tutorial site in Japanese and English. I create Perl module and upload it to CPAN. I create Web application in Github.