0

I recently read about not using getters and setters in Java (e.g. When are getters and setters justified).

I do not know if this is actually the best way to do object oriented programming. Anyway, supposing that I do not use getters in my code, how can I store data on a relational db? When I started using Java two years ago I used to do something like the following:

public void createTitle(Title title) {

    // ... some code here ...

    String sql = "INSERT INTO titles (title_id, name) "
            + "VALUES (TITLES_SEQ.NEXTVAL,?)";
    preparedStatement = connection.prepareStatement(sql);
    preparedStatement.setString(1, title.getName()); // Here is the getter
    preparedStatement.executeUpdate();

    // ... other code here ...
}

How can I save the title with its properties (name, in this case) in my relational database if I do not have the title.getName() getter? This is just an example, but I hope it makes sense.

Some related discussions:

Community
  • 1
  • 1
Kurt Bourbaki
  • 11,984
  • 6
  • 35
  • 53

2 Answers2

0

I don't why... But how you have to make the property name of title public and access it via the dot notation e.G title.name

fibuszene
  • 41
  • 6
  • 1
    From what I am reading about OO and encapsulation, using public fields is quite discouraged. Actually, it is often referred as being an "evil" practice. – Kurt Bourbaki Nov 10 '15 at 17:58
0

To avoid using getters/setters one would only have to make the variables public (or protected, as the case may be) for the dot-accessors to work in their place.

title.name instead of title.getName()

There's two sides of the coin:

One says that public fields are bad and expose too much, and the other says simple objects should stay simple and not require getters/setters to accomplish the same things.

If you have a strong need to disallow setting a variable (read-only), then privatizing it and making a getter is the way to go. There's a similar process for write-only variables but with only setters and no getters.

From my personal experience, if I can expose a variable without exposing dangerous side-effects to the end user, then I go ahead and make the field public. Otherwise I close up the field's access as much as possible.

John Starich
  • 619
  • 11
  • 15