Save and load objects without breaking encapsulation - java

I want to save and load objects to a database without using a ORM (like Hibernate).
Lets say i have the following class:
public class Person {
private int age;
public void birthday(){
age++;
}
}
This class doesn't provide a get-method, so the internal state (age) is encapsulated.
If i want to save the object i need a getter method to do the following:
insert into TABLE_PERSON (id, age) vales (1, person.getAge());
The otherway round i need a setter-method to load the object:
int age = "Select age FROM Person";
person.setAge(age);
But i dont want to break the encapsulation (by implementating additional setter- and getter-methods) just to save and load objects.
Is there any possibility to do this? Maybe some kind of pattern (memento?) or best practise?
Thank you in advance!

You mentioned Memento. There's a variant called Snapshot documented by Grand. Here's the UML class diagram:
Person would be the Originator in the pattern.
You could dump the Memento instance to a binary object in the database.
Note that Memento is an inner class of Originator. The createMemento/setMemento are a kind of single get/set which might be breaking encapsulation if you're a purist. However, the packet of information (the Memento) used on the call is an interface with no methods, so encapsulation of Originator's state is guaranteed. This might even work with an ORM if you map it properly.
Of course, this seems a lot of work just to avoid a get/set. Your Person/age example is not quite realistic (not a great model of a Person). It's quite normal to expose a person's age or date of birth, and exposing that property to persist the object would be OK. Encapsulation doesn't mean don't reveal anything. It means don't expose too much detail.
For example, let's not use age but rather Person.birthday. That could be stored internally as a String in YYYY-MM-DD format or using a Date object. Such detail would not be exposed (it would be encapsulated). This is also done so that you can change it and not affect clients of your class. Anything you hide can be changed without negatively affecting clients.
By exposing a person's birthday, you say "I'm taking the risk that Person will always have a birthday." That part is exposed and thus will be hard to change without breaking clients.
Edit after comments
Public methods (e.g., save and load) in Person can take care of the save/load database operation. They will have access to private fields (age) and can get the job done. You said you're not using an ORM, so then you just do it yourself.

Allen Holub wrote a few articles on exactly that subject. He proposes a Builder and something he calls Reverse Builder pattern.
The way it would work in your case a Person would be responsible for generating a representation of itself. That is to say you define an PersonImporter and PersonExporter interfaces to move data into and out of the Person object. These classes are basically part of the Person design. So:
interface PersonImporter {
public int getAge();
public String getId();
}
interface PersonExporter {
public void setDetails(String id, int age);
}
class Person {
private int age;
private String id;
public Person(PersonImporter importer) {
age = importer.getAge();
id = importer.getId();
}
public void export(PersonExporter exporter) {
exporter.setDetails(id, age);
}
}
This doesn't eliminate getters and setters completely it is controlling it using interfaces.
Holub's Article

This is what I think, may not be perfect.
Encapsulation is done for data hiding. Perhaps, you just don't want someone to set a wrong value to the age attribute.
Maybe you can introduces a wrapper class, which is used by external code and only that class is allowed to use your Person class.
If you create a file with public wrapper class lets say PersonWrapper, that provides getter and setter for age. But these getter and setter can have your desired logic of validations such as what values can be set for age, who can etc. Within the same file, Person class may be defined as private but with plain getter and setters for age param. Your PersonWrapper should only use Person class getter and setter on some predefined conditions.
In this way you may be able to have a better encapsulation.

one way here is the use of mapper classes. Create a PersonMAP that map the class to table and and encapsulate all database operations in that class.

I really don't see how using getters/setters is breaking encapsulation. Getters and setters respect encapsulation. In fact, they're a means to achieving it.

Related

Will it cause real issue if I use public field instead of getter/setter in Java? [duplicate]

This question already has answers here:
Are getters and setters poor design? Contradictory advice seen [duplicate]
(16 answers)
Closed 9 years ago.
I have been going through clean code book which states that the class should not expose the internal state of its data and only should be exposing the behavior. In case of a very simpl and dumb java bean exposing the internal state which getter's and setters, is it not worth just removing them and make the private members public? Or just treat the class as a data structure?
I don't think so. It depends of the lifetime of your Object and its "exposure" (external modification).
If you're only using it as a data structure, exposing fields in secure way (final) sounds enough:
public class Person {
public final String firstName;
public final String lastName;
public Person(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
}
The term POJO was intended to distinguish classes from JavaBeans or any other convention. As such a POJO is by definition NOT required to do anything.
I have been going through clean code book which states that the class should not expose the internal state of its data and only should be exposing the behavior.
This is called encapsulation and a good principle.
In case of a very simpl and dumb java bean exposing the internal state which getter's and setters, is it not worth just removing them and make the private members public?
That is an alternative approach. Some projects may forbid this approach while others may encourage it. Personally, I would favour this approach for classes which are encapsulated in some way already e.g. they are package local.
There is a view that some day in some way your class might have additional requirements and changing the "API" will be impossible. This goes against the YAGNI principle and very rarely proves to be the case and when it does has a much lower cost than adding lots of methods which don't do anything.
However, this is not always the case and if you don't use accessor methods you should consider what the impact will be on the project if you have to change it later. Using accessor methods every where means you never need to worry about this.
In summary, if you are pretty sure accessor methods are pointless and it won't be a problem to add them later, I would say you should use your judgement. However if you are not sure if it could be a problem in the future or you don't want to have to worry about it, use accessor methods.
The definition of POJO doesn't mandate getter/setter.
Experimentally, I am not using getter and setter in my current project.
The approach I am taking is this one:
unless necessary, don't provide getter/setter.
So far, I didn't find a case where I really needed get/set.
Some friend told me: "having get/set is helpful if in the future you need xyz"; my reply has been: when -in the future- I need to do so, I will provide the getter and setter; I don't want to anticipate anything.
The objection about incapsulation, that some may raise, is not really a valid one: providing getter and setter breaks incapsulation in the same manner, plus you have additional lines of (useless) code. Bugs may also lay in getter and setters.
This is an example of one of a non-trivial domain class:
public class SSHKey implements IsSerializable {
public Long id;
public Long userId;
public String type;
public String bits;
public String fingerprint;
public String comment;
#SuppressWarnings("unused")
private SSHKey() { // required by gwt-rpc
}
public SSHKey(String text) throws InvalidSSHKeyException {
Ensure.that(text != null, new InvalidSSHKeyException("Invalid Key"));
text = text.trim();
String[] parts = text.split(" ", 3);
Ensure.that(parts.length >= 2,
new InvalidSSHKeyException("Invalid Key"));
type = getType(parts);
Ensure.that(type.equals("ssh-rsa") || type.equals("ssh-dss"),
new InvalidSSHKeyException(
"Key must start with 'ssh-rsa' or 'ssh-dss'"));
bits = getBits(parts);
comment = getComment(parts);
}
private String getBits(String[] parts) {
return parts[1];
}
private String getComment(String[] parts) {
if (parts.length == 3)
return parts[2];
return type + " " + bits.substring(0, min(15, bits.length())) + "...";
}
private String getType(String[] parts) {
return parts[0];
}
}
The constructor takes the responsibility to validate and prepare the data to be manageable. Thus this logic doesn't need to be in a setter/getter.
If I was shown object with public members some years ago, I would probably not like them; maybe I am doing something wrong now, but I am experimenting and so far it is ok.
Also, you need to consider if your class is designed to be extended or not (so, foresee the future is part of the requirements), and if you want your object to be immutable. Those things you can only do with get/set.
If your object must be immutable, and you can avoid the empty constructor, you can just add 'final' to the member instances, btw.
Unfortunately I had to add IsSerializable (similar to java.io.Serializable) and an empty constructor since this is required by gwt. So, you could tell me then "you see? you need the getter an setter"; well not so sure.
There are some jdbc frameworks which promote the use of public fields btw, like http://iciql.com
This doesn't imply that this project is correct, but that some people are thinking about it.
I suppose that the need of getter/setter is mostly cultural.
The issue with making the members accessible is that you no longer control them from inside the class.
Let's say that you make Car.speed accessible. Now, everywhere in you program there can be some reference to it. Now, if you want to make sure that speed is never set a negative value (or to make the change synchronized because you need to make it thread safe), you have to either:
in all the points where speed is accessible, rewrite the program to add the control. And hope that everybody that changes the program in the future remembers to do so.
make the member private again, create the getter and setter methods, and rewrite the program to use them.
Better get used to write getter and setter from the beginning. Nowadays, most IDEs do it automatically for you, anyway.
The canonical answer to this is: You don't know whether your simple data structure will stay so simple in the future. It might evolve more than you expect now. It might be also possible, that anytime soon you want some "value changed" observer in that bean. With getter and setter methods you can do this very simply later without changing you existing codebase.
Another pro point for getter/setter is: If in Rome, do like the Romans... Which means in this case: Many generic frameworks expect getter/setter. If you don't want to rule all these usefulls frameworks out right from the start then do you and your colleagues a favour and simply implement standard getter/and setters.
Only if you expose a class in a library that's used beyond your control.
If you do release such a library, the Uniform Access Principle dictates that you should use getters and setters in order to be able to change the underlying implementation later without requiring clients to change their code. Java doesn't give you other mechanisms to do this.
If you use this class in your own system, there's no need: your IDE can easily encapsulate a public field and update all its usages in one safe step. In this case, brevity wins, and you lose nothing for the time where you need encapsulation.
I think it's a good idea to use getters and setters, unless you have very specific speed/memory/efficiency requirements or very simple objects.
A good example is a Point, where it is probably both nicer and more efficient to expose it's .x and .y variables.
That said, it will actually not be a big effort to change the visibility of a few member variables and introduce getters and setters even for a large codebase, if you suddenly require some logic in a setter.
JavaBeans require getters and setters. POJOs do not, anyway this has its benefits
The objetive of the getters and setters is to achieve encapsulation, which manages the internal state of object. This allows you to add or change business rules in your application after the application has been implemented only change the getter or setter code, example, if you have a text field that only allows for more than 3 characters can check before assigning it to an attribute and throw an exception, other reason for not doing this is if it's possible you'll want to change the implementation or change variable names or something like. This cannot be enforced if the field is publicly accessible and modifyable
anyway you can use your IDE to generate setters and getters.
If you are developing a simple application can be recommended, if your application is complex and must give maintenance is not recommend.
for the data-type objects, like POJO / PODS / JavaBean, at python you have only public members
you can set those and get those easily, without generating boilerplate setter and getter code(in java these boilerplate code usually(98%) exposes the inner private tag as noted in the question)
and at python in the case you would need to interact with a getter, then you just define extra code only for that purpose
clean and effective at the language level
at java they chose the IDE development instead of changing base java, see JavaBean e.g. how old that is and java 1.0.2 is how old...
JDK 1.0 (January 23, 1996)
The EJB specification was originally developed in 1997 by IBM and later adopted by Sun Microsystems (EJB 1.0 and 1.1) in 1999
so just live with it, use the setter getter because those are enforced by java surroundings
That's the true what #Peter Lawrey explains about encapsulation.
Only one note: it's more important, when you are working with complex objects (for example in the domain model in a ORM project), when you have attributes that aren't simple Java types. For example:
public class Father {
private List childs = new ArrayList();
public Father() {
// ...
}
private List getChilds() {
return this.childs;
}
public void setChilds(List newChilds) {
this.childs = newChilds;
}
}
public class Child {
private String name;
// ...
private String getName() {
return this.name;
}
public void setName(String newName) {
this.name = newName;
}
}
If you expose one attribute (like the childs attribute in the Father class) as a public, you won't be able to identify what part of your code are setting or changing one property of your exposed attribute (in the case, for example, adding new Child to a Father or even changing the name of a existing Child). In the example, only a Father object can retrieve the childs content and all the rest of the classes can change it, using its setter.

Is it better to use getters or to access private members directly?

Which of the following is better? Is it even opinion-based or are there any relevant differences? Can one or the other be favored in some scenarios?
public class MyClass {
private Integer myField;
public void setMyField(Integer myField) {
this.myField = myField;
}
public Integer getMyField() {
return myField;
}
}
I need a method to check wether something is allowed or not. Please, let's not talk about the sense of this code example. It's just a minimal example.
Implementation 1
public boolean isAllowed() {
MyEnum.ALLOWED.getInt().equals(getMyField());
}
Implementation 2
public boolean isAllowed() {
MyEnum.ALLOWED.getInt().equals(myField);
}
Edit:
This post does not have an answer in the linked question (see comments to the initial post)
Which of the following is better? Is it even opinion-based or are
there any relevant differences? Can one or the other be favored in
some scenarios?
It is question of good practice I think. The difference is in the readability of the code.
As a general rule, you should avoid indirection if not required.
The current instance of MyClass has the information in one of these fields to implement the operation. It doesn't need to hide its internal state to itself. So in internal, MyClass has no valuable reason to favor the use of the getMyField() over the direct use of the myField field.
The getMyField() accessor is more suitable to be used by clients of the class.
So I think that it is better in any case in your example code :
public boolean isAllowed() {
MyEnum.ALLOWED.getInt().equals(myField);
}
Edit :
Beyond the readability, here is an example why you have no interest to couple the internal state to a public getter.
Suppose during the development phase you remove from the class the public getMyField() method because not need or not needed any longer for clients of the class, if isAllowed() relies on getMyField() in its implementation, it will be broken and you should replace it by myField.
My answer won't be the most informative however it will come from direct experience of dealing with this pattern. When designing an object it is often tempting to directly access member fields rather than rely on accessors. The desire stems from wanting to simplify the object and avoid adding clutter from methods that simple return a value. Taking your example a step further to add context & meaning:
public class MyClassmate {
private Integer age;
public MyClassmate(Integer age) {
this.age = age;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
return age;
}
}
Here age is a simple number and it appears unnecessary to add getters/setters around it. If we add the following method you would be tempted to directly access the field since there is no change in behavior:
public Integer calculateScore() {
if(age > 21) return 100 - getNumberOfIncorrectAnswers();
//Add 10% before for younger students
else return (100 - getNumberOfIncorrectAnswers()) + 10;
}
Your object may then grow new features with methods relying on the age field where you continue to use it directly. Later, you might alter the way age is originated and pull the value from across a network. You might not want to incorporate the networking logic in the constructor because it is an expensive operation which should only be triggered as needed. The calculateScore() method could make the network connection and discover the age but then too would all of the other methods that rely on age. But what if calculateScore looked as follows?:
public Integer calculateScore() {
if(getAge() > 21) return 100 - getNumberOfIncorrectAnswers();
//Add 10% before for younger students
else return (100 - getNumberOfIncorrectAnswers()) + 10;
}
You could then enhance the object changing the way it derives age without touching the calculateScore() method. This means your method follows Open Closed Principle (OCP). It is open for enhancement but closed to change, or you didn't have to change the method source in order to change where it gets the age.
Depending on the complexity of your app and object model there may still be times when encapsulated access is overkill but even in these scenarios it is good to understand the tradeoffs of direct field access and these more simplistic scenarios are mostly rare.
In general you should understand that the need for encapsulation is almost never immediate. It appears over time as the object grows and if the object is not setup with encapsulation from its onset it is more expensive to phase it in. That's what makes this approach so difficult to appreciate. It takes experience (i.e. making the typical oversimplification and suffering several times over several years) to feel why encapsulation is necessary. It is not something you can eyeball and detect.
That said, this used to be a much bigger problem than it is today when IDEs were not as full featured. Today you can use the built in encapsulate fields refactoring in certain IDEs like IntelliJ to introduce the pattern as you need it. Even with modern IDEs it is still favorable to practice encapsulation from the onset.
I would recommend using the getter because in certain scenarios, it can have some additional logic (like formatting, checking for nulls and so on). So you may be losing some logic when using the field itself.
To keep a good encapsulation, the first think you need to think is which methods are you going to expose outside your class, if here, for example you are going to use only the is allowed method, I would make public only that method, and define the field in the constructor, if the field is suitable to change then you will need getter/setters but always depends on what do you want to offer from your class. And keep as much encapsulated as you can.
public class MyClass {
private Integer myField;
MyClass(Integer myField){
this.myField = myField;
}
//Only this method is offered nobody need to know you use myField to say true/false
public boolean isAllowed() {
MyEnum.ALLOWED.equals(myField);
}
}
In my Software Engineering courses I was told to realize the "principle of secret". Thus, you should always use getter- and setter-routines. This way you can be sure that nobody accesses the member variable by accident.
Strange functions or objects may never see or even change member variables except you explicitly tell them to do so by setter and getters.
Due to your attribute being private, you can only securely access it within other class using getter or setter methods. So I would say that the best implementation is the one following the encapsulating principle, i.e., the one using the getter instead of accessing directly.
This will prevent data leaks as well.
https://www.tutorialspoint.com/java/java_encapsulation.htm

Get and Set Method and the MVC Design Pattern [duplicate]

This question already has answers here:
Get and Set methods in Java. How do they work?
(5 answers)
Closed 7 years ago.
Can somebody tell me or show me something that would make me understand the get and set methods completely? I know some of it already but it still confuses me.
I am trying to learn the MVC Design Pattern but I find it hard because I haven't completely understand this. I thought it was easy but it's not really that easy. Well, at least for me.
Your own example would be appreciated. Thank you in advance guys :)
The Model, View, Controller design pattern is a useful way of decoupling the various components of an GUI driven application. It improves cohesion, which essentially emphasises the responsibility of discrete elements of your software and helps avoid unnecessary overlapping of functionality.
The Model stores what is referred to as 'business logic'. This means it houses all of the data which is core to your application.
The View is what handles the graphical interface. Everything responsible for managing how your graphics are rendered is defined here.
Finally, the Controller handles events. This includes asynchronous events such as whenever a key has been pressed, or the mouse has been moved, or the user has touched their screen. It receives these events and decides what to do with them.
So, how they come together is as follows; the Model defines what needs to be drawn. Any graphics the View needs to render is therefore housed in the Model. This means that any modifications to the Model's data will in turn effect what is drawn on the screen; however, the Model is only really defining what elements need to be drawn, it has no clue how to draw them; just how to manage them and manipulate them. It's the View which can take these elements and in turn use them within a graphical context. The controller on the other hand, handles events and in turn manipulates the contents of the Model. It does this by using a defined set of rules on how each input event will affect certain parts of the Model.
So, in this regard, the Model, View, Controller can be looked at like this:
final Model m = new Model();
final View v = new View(m);
final Controller c = new Controller(m);
Both the Controller and View need access to the Model in order to manage and render the application respectively, but the Model doesn't care about either of them. This is because the Model defines the core data dependencies of your application, which should be transferrable, and work independently of whether it's a component of a GUI or not.
In terms of getter and setter methods, all these do are provide access to a member variable sitting inside a class. So if we were to look inside the View, we would see something like this:
public final class View {
/* Member Variables. */
private final Model mModel;
public View(final Model pModel) {
/* Initialize Member Variables. */
this.mModel = pModel;
}
public final Model getModel() {
return this.mModel;
}
}
The method getModel() is referred to as a getter method; it's sole responsibility is to return a variable; in this case it returns the View's mModel variable. What's useful about getter and setter methods is that you can control access to that variable; the method can be declared public, protected and private for example, which all change just who else inside your application can get access to the Model. The same goes for a setter method, whose only responsibility should be to change the value of a specific variable belonging to the owning Object.
I know this should be a comment, but I currently don't have the reputation required to post a comment.
First of all, could you please provide more information about what specifically you'd like to know? Are you confused about how getters and setters work in general? Are you confused about how the work in an MVC pattern? (getters and setters work the same way in MVC as they do in other design patterns).
If the link posted in the comment above doesn't solve your answer, then hopefully I can help. Getters and setters (getVarName and setVarName) are used to provide additional functionality (like ensuring that a value fits a desired range, etc) and also to provide encapsulation of your code. Besides the additional functionality (like validation), encapsulation also helps avoid errors like accidentally changing the value of a class's variable when you don't mean to. Take a Customer class for example:
public class Customer {
private int empNo;
private int deptNo;
//additional class variables
public Customer() {
//default constructor }
public Customer (int emp, int dept) {
empNo = emp;
deptNo = dept;
}
public int getEmpNo() {
return empNo;
}
public void setEmpNo(int emp) {
empNo = emp;
}
//other methods
}
Let's say that all employee numbers must be 5 digits long and not start with a 0. If we don't use a setter, then there's no way to check if the number given is a valid number (or that it was even given). For that, we could write a simple validation requirement in our setEmpNo method.
public void setEmpNo(int emp) {
if(emp >= 10000 && emp <= 99999) {
empNo = emp;
}
//code to handle invalid numbers
}
Encapsulation also helps us avoid certain errors, like changing the value of empNo when we mean to just check the value in a condition, etc. For instance, if we don't use getters and setters and just have a public empNo, the following typo would change the value of the employee's employee number:
if(employee1.empNo = 12345) { //checking if this is employee 12345 would use ==
//perform action for specified employee
}
However, if we use getters and setters, we'd still run into a problem because we're not checking if the desired employee's employee number is 12345, but that employee's number would NOT be permanently changed to 12345 and would still retain his/her correct employee number. Does this make sense?
It looks like someone already posted a pretty good answer about MVC, so I won't repeat any info on that. One thing I will point out is that MVC is usually (if not always) used for server-based apps. If you have an app that contains a website that users interact with and a database, then there's a good chance you'll use some variant of the MVC pattern. However, you're not going to use MVC for something like a Hello World app.
I hope my answer isn't too basic. It's hard to judge a user's knowledge level without getting additional info. If you'd like me to clarify or give further explanation on anything I've posted, let me know.
Best of luck going forward.
Getter and setter methods used when we define instance variables private so from outside class we can't access private instance variables directly which is useful for encapsulation(hiding data from outside world). So for accessing private variables we required some methods which is basically getter and setter.
public class Employee
{
private int empNum;
public Employee(int empNum) {
this.empNum = empNum;
}
public int getEmpNum() {
return empNum;
}
public void setEmpNum(int empNum) {
this.empNum = empNum;
}
}
for more reasons why we use getter/setter read this answer
There is no direct relation between MVC and getter/setter methods.
MVC is basically design patter for software development where we divide task between different modules(model, view and controller)
model -> Data layer
view -> Representational layer
controller -> Controller layer between model and view
So when you create model class in mvc you define multiple instance variables(attributes) for model but from controller you don't want to access that variables directly so in that case you should use getter setter methods.
Actually getter/setter concept in not limited to just mvc it is use as a codding standard and for abstraction purposes.

Correct way to expose instance variables to other classes

Can someone help me understand this:
"For example, an object's instance variables (member fields that aren't constants), should always be private. Period. No exceptions. Ever. I mean it. (You can occasionally use protected methods effectively, but protected instance variables are an abomination.) You should never use get/set functions for the same reason—they're just overly complicated ways to make a field public (though access functions that return full-blown objects rather than a basic-type value are reasonable in situations where the returned object's class is a key abstraction in the design)." - http://www.javaworld.com/article/2073649/core-java/why-extends-is-evil.html
I don't understand what he means by, "You should never use get/set functions for the same reason—they're just overly complicated ways to make a field public." Let's say I have a simple Person class with Name and Age instance variables. How should I make these available to other classes? Does he mean that I should create a Data Transfer Object? Would this be a correct implementation? Is this really preferable to having the getters and setters in the Person class?
public class Person {
private PersonData personData;
public Person (String name, int age){
this.personData =
new PersonData(name, age);
}
// get personData
// person methods...
}
// data transfer object
class PersonData {
private String name;
private int age;
public PersonData(String name, int age){
this.setName(name);
this.setAge(age);
}
// getters and setters ...
}
More of a comment that an answer...
The article is dedicated to stablishing the need/advantages of loose coupling, and techniques to get it.
One of the points is avoiding relying in the internal data structure of an object, and only use its operators. In that point, automatically making your state accessible is bad, since objects using your classes may rely in these properties instead of using the more "refined" operations given to them.
From my understanding of the article, a possible example could be the following:
Imagine a Person class/interface with two operations, say, isOldEnoughToBuyBeer and isOldEnoughToDriveCars.
if you create in Person a setter/getter for dateOfBirth, then you are tying the implementations of Person to have such a property, and to implement the operations as "check current date agains dateOfBirth property and return true based in the number of years".
Of course, the statement "You should never use get/set functions for the same reason—they're just overly complicated ways to make a field public" may be too restrictive; while it is making a good point that even access through getters/setters has its consequences, it is hard to imagine that attributes are used only internally to the class that holds them.
You should definitely have getters for all the properties of the object you wish to expose to other objects. And if your object is mutable, you'll probably want setter methods for all the properties that can be modified.
set/get methods are not overly complicated ways to make a field public. They allow you to control the access and modification of your members.
For example, if your class is immutable, a get method that returns some object would return a clone of that object, to prevent the caller from modifing it.
For another example, if your class is mutable, a setter can contain validation of the new value you are trying to set.
The author argues that you should never have public instance variables. (Because they break encapsulation, but I believe you are not quiestioning this - if needed, though, we can get to it.)
When he says "You should never use get/set functions for the same reason" he's saying that, in practice, having public get and set methods for an instance variable is roughly* the same as having the varible itself public.
The only difference (and the reason why he writes "they're just overly complicated ways to make a field public"), is that instead of the modifier public in the instance variable, you created two additional methods.
(Data) Transfer Objects are a complete different animal, they aren't related to the discussed context.
* "Roughly" because we are talking about the (usual) hipothesis of the getter and setter just reading and writing to the instance variable, not doing any additional processing.
Correct way to expose instance variables to other classes
You should provide as low access to instance field as possible. The preferred way to provide access is to have three items
A private field
An public accessor method
An public mutator method
This Approach has following benefits
First benefit: This approach increases abstraction.
Suppose the getter(or accessor) method for Name is defined as follows
String getName() {
return name;
}
Now for some reason you want to change implementation of name as
String firstName;
String lastName;
In this case you can change getName() as
String getName() {
return firstName + " " + lastName;
}
Using this approach does not break your existing code which otherwise would be difficult(if not impossible) to obtain.
Second benefit: You can perform error checking all at once.
Consider a situation when the age entered by user is negative or practically impossible (like 99999999). In that case you can check such input in mutator method. This avoid manual checking and repetition of error check at different places
In addition it is advised that you should not write accessor method that return references to mutable object. This will break encapsulation. Use .clone() method of object class to return an object.

Java setter and getter?

Everyone knows that Java supports data hiding.
I went for an interview. Then interviewer asked me that if Java supports data hiding by using private as datatype.
He said if we use setters and getters in that class then by using those setters and getters we can get that private data easily.
So how this is supporting data hiding here?
It may be possible that he was trying me catch me in trap. But I could not reply this.
What should I reply for this?
He was arguing that if "Data Hiding" is an OOP principle then aren't we breaking it by exposing via getters and setters. I think he wanted you to spell out the difference in principle between being able to access a data member directly vs. doing it via a getter or setter. In the former case a client of the class can mishandle the data, assign it a value that the class designer has not designed the class to handle (for example set the age of a student as 500).
In the latter (using a setter) the class designer has imposed certain restrictions on what values can be assigned to the data. In the age example the setter might be something like:
void setAge(int age) {
if(age<3 || age>100)
return;
this.age=age;
}
assuming that students of age below 3 and over 100 aren't allowed. So you are still hiding your data but allowing means to manipulate it in a way consistent with the logic of your module.
Very simple Example:
Version 1 of class could have getter like this.
public int getTotal() {
return total_;
}
Version 2 could do this
public int getTotal() {
return a + b;
}
We've changed how the class is implemented, but clients of the class don't need to change as well, because the data is hidden behind a getter.
Data hiding is bad term, better say data encapsulation. In java access to private members is done through accessors and mutators ( getter and setter), it is all about hiding and controlling access to your members so you can control how inner state of instance will be modified.
I think if you mention something about java reflection / metadata -> you will get bonus points
The class fields are hidden, if we declare them private. No doubt (we ignore nasty reflection tricks). If we want to make the values accessible, we provide access methods (getter/setter for example).
But there is no requirement to provide getters and setters for all fields or to name them according to fields (in general).
The class internals (the fields) are perfectly hidden.
protected String name;
public void setName(String newName){
if(newName.length() > 5) this.name = newName
}
public String getName(){
return this.name;
}
In this simple case the name attribute can be accessed by its name in this class and in all its children. If you want to set the value of name from an unrelated class than you will have to use the setName() method where you can apply some validation for example.
Here you can find any information you need about this special methods.
Be aware that any property of a class can be accessed if the mutators and accessors are public. This is one of the key points of the Java Bean concept and almost all java frameworks relate to this concept at one point or another.
What you are talking about seems to be Encapsulation. Basically the getters and setters allow you to expose class variables as you like and hide any others. Getters and Setters also allow you to perform any other necessary steps such as validation.
Getters and Setters can have different access modifiers themselves, so you can expose data to certain classes but not others by using different access modifiers.
I bet he was waiting that you will refer to "immutable" types also.
PD. private is no type, it is an access modifier.
The support for "data hiding" can be explained by the fact that the getter and setter methods are like gateways to the data.
It is only by convention - the JavaBeans convention to be exact - that it is expected from them to operate on the member they are named after. They could do anything else and it would still be perfectly compilable and legal java.
Maybe, he mean Encapsulation as information hiding.
If you make the setter & getter public/protected/default, then you could access the private members on different levels .. if you make setter&getter private then the data is really hidden. This last way to go makes no sense at all though
You may think about implement set/get methods in many different ways.
As some answers already pointed out, set/get don't have to actually set or return actual members.
For example, let's say you have a Coordinate class with set/get for (x, y). The inner implementation might be based on polar coordinates:
private double radius;
private double angle;
and the get/set for (x, y) do some coordinate transformation with sin and cos.
You could change the implementation of the class to any other system of coordinate at will and still just keep the set/get for (x, y) as public methods.
So, to sum up, my answer to the question would be: the public interface of a class might provide set/get, but the actual implementation can (and should) be hidden by making all members private (or protected). So we could say that having public set/get on private data is "implementation hiding" rather than data hiding.
Data Hiding and Encapsulation are frequently mistaken for security by first time oops learners. Its important to understand that data hiding and encapsulation have nothing to do with security.
These concepts exist to ensure that inheritance of a class A, from class B (class B extends A) does not inherit the "encapsulated" members.
I hope this kinda clarifies your confusion, and also motivates you to read and study more. Your question is very basic to the OOPS concepts. And the interviewer is not trying to corner, you but ask you very basic questions on OOPS. Study hard!!!

Categories

Resources