Plain Old Java Object Classes [duplicate] - java

This question already has answers here:
Why use getters and setters/accessors?
(37 answers)
Closed 5 years ago.
Why do the data members of POJO classes are private and the getter/setter function are public?
Can someone please give solution for this.

Common approach: access to variables by using getters/setters:
better maintainability
accessibility to private properties only for the defining class (isolation)
used for a different data representation (you might have private data to store the birthdate, but create a getter named getAge()).

It doesn't have to be that way, it's just a pattern and it exists for a reason.
All members of a class should be private by default, so that noone can mess up things from outside or read/write values which are not important by the outside. Additionally some internal stuff can change within your class, and the outside world should not care about it.
To allow access from the 'outside world', be it reading or writing anything should be handled via getters/setters/issers to allow a governed manipulation.
Think of it like a mini API of your class - an interface to your class anyone outside can understand and rely on.

If you want to add any validation or modify any other thing before/after setting value of an object, you can use that validation in setter method. Same applies for getter.

It the basic object-oriented principle i.e only object can communicate through message which is called encapsulation.So indirectly you are not exposing your state to outside.For an example class with one attribute age is there and age can not be negative so in setter you can put a check so your object state will not in bad condition.If you access directly the variable then there is no scope for validation.

The basic principle of the oriented object programming is to encapsulate the members of a class and give access to them only via getters and setters

Related

Why instance variable in Java should be private if the Class has only getters and setters [duplicate]

This question already has answers here:
Why use getters and setters/accessors?
(37 answers)
Closed 8 years ago.
I had been asked the following question in an interview and i am curious to know the answer.
There are two classes as following,
public class EmployeeA{
public int empId;
}
public class EmployeeB{
private int empId;
public void setEmpId(int empId){this.empId = empId;}
public int getEmpId(){return empId;}
}
There are two classes where one class has a public instance field and other have a private field with getters and setters. In this case, which is better implementation and why?
[I have learned that making instance variable private is the better idea. But in both cases i can modify the value of empId attribute. ]
The one-word answer they're probably looking for is "encapsulation".
By encapsulating the private field value, you have the opportunity to change the logic on how the value is set/retrieved in the future. Say, for example, you want to validate on set and filter on retrieval (get). By encapsulating the value, your creating an API which allows for better maintenance moving forward.
Maybe a bit off-topic, although people usually talk about "encapsulation" when talking about "getter/setter", "getter/setters" are actually still far from proper encapsulation.
This famous "why getter and setter methods are evil" is something worth to read. When we say getters and setters are evil, it doesn't mean that we should expose variable directly. It is about further hiding internal data by providing meaningful behavior in class, instead of providing accessors for properties. Although there are a lot of cases we still need accessors, this is something that worth giving attention when you are designing.
Going back to your question, if it is me, I will answer: providing getters and setters provides a minimal level of encapsulation and allow us to do extra work or derives data when we are setting and getting properties. However, for a proper encapsulation, I would rather design the Employee class to provide proper behaviors, instead of simply acting as a value object which only provides bunch of getters/setters.
The accesssor (getter) and mutator (setter) are JavaBean requirement but not all classes in Java must follow this design pattern. Why not creating this class as immutable by having a constructor that take the id (or even better, a static factory). You can then provide an accessor for the the id. That is generally not a good idea to be able to change the id of an object, if the id is used in a Map as the key and you change it, good luck to retrieve you object... Make the class immutable solve this kind of problem.

Model class properties should private or public? [duplicate]

This question already has answers here:
Why Not Use Public Member Functions
(3 answers)
Closed 9 years ago.
I have question which has been going around in my mind since long.
My Model class should have properties private or public? (Below code is written in PHP but question applies in general for any language)
class Xyz extends Model {
public function __call() {
}
public $description;
public $title;
}
In above example I have public properties $description and $title. Should I make them private?
I update my model as follows
$x = new Xyz();
$x->title('Hello');
$x->description('Blah blah');
$x->save();
I can update and get them by using magic method __call. So why do we need to keep them public? I can make them private. But as I see all the frameworks around keep model properties public.
Any thoughts?
UPDATE:
In answers, everyone is saying follow encapsulation and use private methods. Good but no one has the answer why some PHP frameworks have model properties public ? There should be some reason, isn't it?
As per OOP, we need to follow encapsulation. Please make your properties private and have public accessors and mutators. but, it depends that your accessors and mutators can have other modifiers as well. But, The properties should be always private.
Class fields should always be private. Getters and setters for the fields should be public. Aside from being standard, it is also good to have it this way so that you have the control to do what ever you want to the values that the client classes wants to set to you private fields.
For example, if you want to persist an object to a database, and one column is stated to be not null, and you are not sure if your client class will really return a non-null value, you can handle the null check inside the setter so that the values that you are about to persist to the db contains no null field, as what the table of your db demands.
The fields should always be private as per OOP encapsulation principle. Now the thing is with the getter and setter accessor methods.
The getter is usually safe to make it public. The only downside of it is that you will have to maintain backward compatibility between versions, as this will be part of the public contract of the class. So if the field is something that is part of the implementation rather than interface, than maybe you want to keep it protected.
As for the setter the better question is if to create one or not. If you want to keep your class immutable (or at least some parts of it) with all the advantages and disadvantages that comes from it, then you'll not be creating a setter at all.
You have to make all properties as private in model class and if you have to encapsulate their value then you have to use appropriate getters and setters to get and set their values.

Compiling Java files

I am building an API for my application as a middle layer between model and the controller.
The model contains all data and low-level function. I have created a new class for API which uses the model but makes things easier for the user and does not let the user to access the data directly.
Now, I would like to prevent the user from accessing the model and let him to use only the functions from API.
How do I do that?
As far as I believe, this can be simply done by specifying whether the method or variable is private or public. The problem is that I have many static fields for global data. Can I restrict access to static fields so that only private functions of API can access them?
Creating a private static field in a class will ensure that ONLY functions in that class will have access to those fields. Also, if the class is re-instantiated (aka new myClass();), those fields will not be recreated; their values will remain intact and global to all instances of myClass.
In addition to the already posted answer:
It depends on what you mean by "restrict access to static fields":
If you want to prevent others from using them directly inadvertently, use the "private" modifier.
But remember that one can still access them via reflection if no other countermeasures have bin put into place.
This holds true also for the "static int foo" case if you don't seal the package since one can easily put another class into the same package which will have access again.
If you are building an API, maybe you want to read the book Practical API Design, Confessions of a Java Framework Architect.
A Method Is Better Than a Field It's better to use methods —typically getters and setters— to access fields than to expose them directly.
A Factory Is Better Than a Constructor You facilitate an API's future evolution when you expose a factory method rather than a constructor.
Make Everything Final For the sake of future evolution, it's better to disallow subclassing ... make your class final.
...

Necessity of getter methods [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why use getters and setters?
This is a newbie question. Is it very much necessary to use getmethods to access property values? Once the value has been assigned, one can get the values directory. For example, in the below code, displayName() can display firstName value without the help of any getter method. Or it is a standard coding standards that one must have getter and setter method or any other methods which gives that value?
class Test{
private String firstName;
public void setName(String fname){
firstName = fname;
}
public void displayName() {
System.out.println("Your name is " + firstName);
}
}
Tell, Don't Ask is an important principle in object-oriented design. Generally you should tell objects to do things rather than ask them questions. getters/setters every where discourage this practise because you are encouraged to reach inside an object and get to the fields (or even worse reach in and poke things about in the case of setters). This breaks encapsulation and makes your code harder to reason about.
In your particular case, I'd create an object called Name that has a constructor taking the name and single method to display it.
In Your case (to display the display name) it is not neccessary to provide Getter.
But if your want use the field in another class We need to provide the Getter method.
Getter and setters are a part of the standard interface for Java Beans and many frameworks like Hibernate expect them in place. That being said it is of course up to you to decide if and when you need them and for what purpose. They provide access to your private member variables and they can even give you the chance to do more than just plain get and set.
The point of OO software is reuse. This means that other programmers, or you years from now, can use the code for other systems.
When you have private member variables, and use get/set functions, you can change the internal implementation of the function without breaking all the other code that uses it.
Do always use Getter and Setter to access your properties!
You should take a look at this article...
Having private state, encapsulation is good, and in A LOT of cases this is the right thing. Suppose that your class is suppose to be Thread Safe, having public fields you can't ensure that.
On the other hand there are cases when this is useless! Suppose that you access your object only in one package, you are sure you will never export it, then why bother?
I do not have any links to support this, but it's what I do.
I try to avoid public fields if they are not static. So I just use protected and private fields. From within the class, you can access them without get/set, that's completely fine. From outside the class, always try to use get/set.
So your example code is completely fine to me. :)
EDIT: One exception for me is if I create a struct-like container class like this
class Point4D {
public int x1, x2, x3, x4;
}
Then I think that public fields are ok. It would be still better to make them private and name the getters public int x1() etc though. As soon as some methods are introduced to this container that change the state of the instance (like changing the values of x1/x2/x3/x4), I make them private and add get/set.

java - public access vs accessor methods [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why use getters and setters?
I'm reading the Java for Dummies 2nd edition, and it says that it's better to define accessor methods for class's variables instead of making them public. Is that true?
Yes.
Defining accessor methods allows you greater flexibility. For instance, you can make it publicly readable, but only privately writable.
Here's a Skeet answer to this particular question. He suggests always making your fields private
Yes, it's a convention.
It allow you to control how other classes will access the members (that are usually private). For example you can start with a basic get/set that return and set the value. But maybe later in the project you will want to add more control. in this case you will only have to change get/set method instead of refractoring all your project.
I'd go as far as to say it is better not to even have accessor methods either, if possible. Make the class do work on its own state rather than exposing it for another class to work with.
If you do have to expose state, accessor methods give you the opportunity to return a copy of the state rather than the actual object. This way calling classes wont be able to modify the state from outside, avoiding the issue of invariants being broken.
This is true!
In Java, it is common practice to declare class variables private, and then write public accessor and mutuator methods to control them outside of the class.
It is usually good to make accessor methods, to regulate the data any other class (and anybody) can use.
Particularly in big projects, you want other classes only to use just a few of the many variables in the class, so you only make a few getter methods.
On the second hand, it makes the code cleaner, it is easier to see what is happening. Thirdly, it is harder to create your own bugs in your program by using the wrong variable, because in other classes there are less possible variables to choose from.
I recommend reading about object oriented programming philosophy:
wikipedia:
When you define accessors you can write there some extra logic protecting the state of your objects.

Categories