Search code examples
javadatabaseencapsulation

Data encapsulation for db access: Do I always have to write public + private methods?


A colleague of my says that this is data encapsulation and it has to be done when using database access:

public String foo(final int x) {
  return fooHidden(x);
}

private String fooHidden(final int x) {
  return db.lookFor(x);
}

I simplified the code to be more readable, but it's still the same structure. So in my opinion this is not data encapsulation, it doesn't hide anything, because the return value and the transfer parameter are equal. So for me, it would make no difference to write:

public String fooHidden(final int x) {
  return db.lookFor(x);
}

The upper solution would make sense for me if we overlay the method or have other parameters for the private method which use class internal attributes, but this is not the case.

Can you tell me who is right? How would you accomplish real data encapsulation for this case?


Solution

  • The two methods implementations are quite the same, i.e. in your case it makes no difference, but semantically speaking, it would make more sense to have:

    public String foo(final int x) {
      return db.lookFor(x);
    }
    

    Note the name foo and not fooHidden to make reference to publicly provided method (hidden would otherwise imply you are exposing a supposed-to-be-private method).

    Meanwhile, both implementation still hide the db field, which should be hidden from class callers and private to the wrapping class, hence encapsulated. So encapsulation is about the field state and not the method implementations.

    This implies that the class structure should be as follows in a whole:

    public class MyClass {
    
      private db; // must be private, otherwise you'll be violating the encapsulation rule
    
      public String foo(final int x) {
        return db.lookFor(x);
      }
    
    }
    

    Going back to the OP question:

    Do I always have to write public methods + private methods?

    The question should instead be: Do I always have to write public + private fields?

    And I would state that in major cases, you should do it yes. Meanwhile, there may be design requirements that need to have the rule broken.

    Encapsulation, in Java, is about Access Modifiers; meaning what fields / methods you make public thus accessible for the outside world.

    Here is what what Martin Fowler states about Access Modifiers:

    Object-oriented languages divide a program into modules called classes. Each class contains features, which consist of data (fields) and methods. (Not all languages use these terms, but they'll do for this.) Languages have various rules about what other classes can access the features of a class, these are often based on access modifiers that apply to a class.