Are there new arguments to use getters and setters since Java 8? - java

As the title says, there has always been quite a discussion about getters and setters in any programming language, so also Java.
The question is the following: Are there any new arguments since Java 8 got released?
An example of an already existing argument is that getters and setters encapsulate state, or that they make it possible to change the implementation without changing the API.

Yes, there are! Since Java 8 method references were introduced, and as their name says, they can only be used with methods.
Consider the following code:
class Person {
private String firstName;
private String lastName;
public Person(final String firstName, final String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Override
public String toString() {
return firstName + " " + lastName;
}
}
Assume we want to obtain a map that contains a lists of people grouped by their last name, we can only do that via method references with the following code:
List<Person> personList = new ArrayList<>();
personList.add(new Person("Shannon", "Goldstein"));
personList.add(new Person("Donnie", "Denney"));
personList.add(new Person("Mark", "Thomas"));
personList.add(new Person("Julia", "Thomas"));
Map<String, List<Person>> personMapping = personList.stream()
.collect(Collectors.groupingBy(Person::getLastName));
System.out.println("personMapping = " + personMapping);
Which prints out, formatted nicely:
personMapping = {
Thomas=[Mark Thomas, Julia Thomas],
Goldstein=[Shannon Goldstein],
Denney=[Donnie Denney]
}
This would not have worked if we were using public variables, as you cannot obtain a method reference on them, nor reference them in another way other than writing a full-fledged lambda where it is not neccessary.
(For curious people: person -> person.lastName would need to have been used)
Also, keep in mind that this answer differs from someone claiming that if an object needs to adhere to a certain interface, that then getters and setters must be used. As in this example the Person class adheres to no interface, yet benefits from having getters available.

public class Customer {
private String email;
public void setEmail(String email) { this.email = email; }
public String getEmail() { return email; }
}

Related

How to set new value into existing object in ArrayList in java

Im still quite new into Java and I'm trying to set new value to specific field into existing object in arraylist.
I've got one class:
public class Client
private String firstName;
private String lastName;
//skip setters and getters
I added objects to arraylist using
listOfClients.add
and now I'd like to update only lastName in one of existing objects. To pick one of all objects I'm using index of Arraylist but still have no idea how can I update only this one spcific value. So far i've tried
listOfClients.set
but it didn't go well.
Could anyone tell me if there is any way to update only one, specific field in my object?
You should use the list's get method.
The get method returns the element at the specified position in this
list.
Use it as follows:
listOfClients.get(clientIndex).setFirstName(newFirstName);
Since you know the index, you can try listOfClients.get(index).setLastName("value").
listOfClients.get(index) gets you the object. Then you can set any value with it's setter method.
public class Test {
public static void main(String[] args) {
List<Client> clientList=new ArrayList<Client>();
Client c1=new Client();
c1.setFirstName("First");
c1.setLastName("FirstLast");
clientList.add(c1);
System.out.println("First: "+clientList.get(0).getFirstName() +"-"+ clientList.get(0).getLastName());
//Modify by setter
clientList.get(0).setLastName("ModifyLast");
System.out.println("After"+clientList.get(0).getFirstName() +"-"+ clientList.get(0).getLastName());
}
public static class Client{
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
}
find the index of the value and set it using: list.set( index_of_the value_to change, "value_to_update" );
Here is the example for your question i am updating the cow value here:
ArrayList nums = new ArrayList<>();
nums.add("Rat");
nums.add("cow");
nums.add("rabbit");
System.out.println(nums);
nums.set(1, "updated");
System.out.println(nums);

Ebean: How to create a column for a getter without a property

I wan't to be able to store computed values from Java in my database.
For example, I might have a Person class that with a firstName and a lastName. I may want a getter that returns the the total length of the Persons name, without it being an actual property.
#Entity
public class Person extends Model {
#Id
public Long id;
public String firstName;
public String lastName;
public Int getNameLength() {
return firstName.length() + lastName.length();
}
public Person (String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
}
So if I create a new Person like so:
Person bob = new Person("Bob", "Roy");
bob.save();
Then we should end up with this in the table:
| id | first_name | last_name | name_length |
====================================================
| 1 | "Bob" | "Roy" | 6 |
Does anyone know if this is possible?
Please for the sake of Old Gods and the New Gods don't do this
Doing something like this would totally mess up your database. You will run into problems sooner or later. Looking at your profile you obtained a CS degree so you definitely had your databases course. Remember the Second normal form and the Third normal form and how you will break this if you have attributes which depend on other attributes.
What you should do is to have either a transient field (marked with #Transient) or you can use the getter and provide the information from there. Every time you need to access the name_length you will call this getter but you won't store the information in the database.
Even if you want to calculate the length outside of your application, you can still use some database function for this - like length.
Edit based on the requirement mentioned by the OP:
In JPA there are two ways how you can declare the columns - either on fields or on methods (getters/setters). It would go like this:
#Column(name = "complex_calculation") // Due to some bad requirement
public Integer getNameLength() {
return fisrtName.length() + lastName.length();
}
However you mentioned Ebean in your question and Ebean is not regarded as the reference JPA implementation. There is a good chance this is not yet supported but you can try it in your specific case.
There is another way which is proven to work. You define your model like this:
#Entity
public class Person extends Model {
#Id
private Long id;
private String firstName;
private String lastName;
private Integer nameLength;
public Long getId() {
return id;
}
// getter for first name and last name with #Column annotation
#Column(name = "complex_calculation")
public Integer getNameLength() {
return firstName.length() + lastName.length();
}
public Person (String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
updateComplexCalculation();
}
public void setFirstName(String firstName) {
this.firstName = firstName;
updateComplexCalculation();
}
public void setLastName(String lastName) {
this.lastName = lastName;
updateComplexCalculation();
}
private void updateComplexCalculation() {
this.nameLength = firstName.length() + lastName.length();
}
}
The important part is the updateComplexCalculation method. When the constructor is called and on every setter-call you invoke this method to update the complex property. Of course you should invoke it only on setter-calls which are needed for the computation.
The following code:
Person p = new Person("foo", "bar");
p.save();
Logger.debug("Complex calculation: " + p.getNameLength());
p.setFirstName("somethingElse");
p.save();
Logger.debug("Complex calculation: " + p.getNameLength());
yields then:
[debug] application - Complex calculation: 6
[debug] application - Complex calculation: 16
What's wrong about property in the model? Just make it private add the public getter but without setter, finally override save and update methods.
private Integer nameLength;
// BTW shouldn't you also count the space between first and last name?
public Integer getNameLength() {
return firstName.length() + lastName.length();
}
#Override
public void save() {
nameLength = firstName.length() + lastName.length();
super.save();
}
#Override
public void update() {
nameLength = firstName.length() + lastName.length();
super.update();
}
If you still want to avoid property in the model, you will need to use custom SQL query (probably also within the overridden save/update methods), like showed in other answer or Ebean's docs, note that will perform at least 2 SQL queries per each save or update operation.
Thanks to Anton and biesior for giving me some ideas.
Rather than override the save or update methods, we opted for a private variable that is recalculated when the variables it's dependent on are updated.
public class Person {
#Id
public Long id;
private String firstName;
private String lastName;
private Integer nameLength;
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public void setFirstName() {
this.firstName = firstName;
calculateNameLength();
}
public void setLastName(String lastName) {
this.lastName = lastName;
calculateNameLength();
}
private void calculateNameLength() {
nameLength = getFirstName().length + getLastName().length;
}
}
This has several benefits over the suggested methods of updating the value in the save or update methods.
Recalculating in the save or update method means we need to call one of those methods every time we set a field on the object. If we don't, the nameLength will get out of sync. I couldn't, for example, change the Persons firstName, and then use the nameLength to do something else without first persisting the object to the database.
Furthermore, using the save/update methods couples the objects state to the Ebean. The ORM is for persisting object state, not for setting object state.

Setter params final in Java

I have always been programming in java, and recently i started learning some c++.
In C++ it is conventional to set setter params as const, why don't we see this as much in java ?
I mean are there any disadvantages to creating a setter like so:
public void setObject(final Object o){ this.o=o; }
vs
public void setObject(Object o){ this.o=o; }
The first one should enforce for Object param o to stay constant through the whole set function, not ?
Edit:
A final param would enforce this NOT to happen :
public void setName(String name){
name="Carlos";
this.name=name;
}
The user will never be able to set the name different from "Carlos"
There's little advantage to setting a Java method parameter as final since it does not stop someone from changing the parameter reference's state within the method. All it prevents is the re-assignment of the parameter variable to something else, which does nothing to the original reference, and it allows for use of the parameter in anonymous inner classes. If you wanted true safety in this situation, you'd strive to make your parameter types immutable if possible.
Edit
You've posted:
public void setObject(Object o){
o++; // this does not compile
this.o=o;
}
Which mixes primitive numeric and reference type. It only makes sense if o is an Integer or other numeric wrapper class, and even so, making it final would not prevent someone from creating:
private void setI(final Integer i) {
this.i = 1 + i;
}
But neither your code nor this code above would affect the parameter object on the calling code side.
Edit
OK now you've posted:
public void setName(String name){
name="Carlos";
this.name=name;
}
But then someone could write
public void setName(final String name){
this.name= name + " Carlos";
}
Here's where the danger comes and where final doesn't help. Say you have a class called Name:
public class Name {
private String lastName;
private String firstName;
public Name(String lastName, String firstName) {
this.lastName = lastName;
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
}
And then a class, Foo, with a Name field and a setter. This is dangerous code:
class Foo {
private Name name;
public void setName(final Name name) {
name.setFirstName("Carlos");
this.name = name;
}
}
Because not only does it change the state of the field, it changes the state of the Name reference in the calling code, and the final modifier won't help one bit. The solution: make Name immutable.
e.g.,
import java.util.Date;
// class should be declared final
public final class BetterName {
private String lastName;
private String firstName;
private Date dateOfBirth;
public BetterName(String lastName, String firstName, Date dob) {
this.lastName = lastName;
this.firstName = firstName;
// make and store a private copy of non-immutable reference types
dateOfBirth = new Date(dob.getTime());
}
// only getters -- no setters
public String getLastName() {
return lastName;
}
public String getFirstName() {
return firstName;
}
public Date getDateOfBirth() {
// return copies of non-immutable fields
return new Date(dateOfBirth.getTime());
}
}
Okay, a final parameter/variable cannot be assigned to. As the java compiler needs to be capable to determine if a variable/parameter is actually final (for anonymous inner classes), optimization is no factor AFAIK.
It is more that C++ has a larger tool set, which java tried to reduce. Hence using C++ const string& is important, saying
The string is passed by pointer, access is automatically dereferenced.
If the actual argument is a variable, the variable itself is not changed.
Mind there might be a conversion operator for passing something else than a const string&.
Now java:
Java does not allocate objects on the stack, only keeps primitive types and object handles on the stack.
Java has not output parameters: a variable passed to a method call will never change its immediate value.
Back to your question:
As a setter in java mostly would not benefit from a final parameter.
A final will be a contract to not use the variable for a second assignment.
However:
public final void setXyz(Xz xyz) {
this.xyz = xyz;
}
is more useful: this method cannot be overriden, and hence may be safely used in a constructor. (Calling an overriden method in a constructor would be in a context of a still not initialized child instance.)

Spring java custom get-method in domain model class

Using Spring data I would like to be able to define a custom get-method inside a domain model class without affecting the model itself. For example, using this model:
#Document
public class Person
{
private String firstName;
private String lastName;
public String getFirstName()
{
return firstName;
}
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
public String getLastName()
{
return lastName;
}
public void setLastName(String lastName)
{
this.lastName = lastName;
}
}
Eveything is working fine so far: the model Person has the fields 'firstName' and 'lastName' and I can successfully save a 'person'. The resulting JSON has the fields 'firstName' and 'lastName'. Now I would like to add some additional data in the JSON without affecting the model and its save-operations, something like this:
#Document
public class Person
{
private String firstName;
private String lastName;
public String getFirstName()
{
return firstName;
}
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
public String getLastName()
{
return lastName;
}
public void setLastName(String lastName)
{
this.lastName = lastName;
}
// custom method
public String getFullName()
{
return firstName+" "+lastName;
}
}
The JSON should contain the same data as before, but this time also an additional 'fullName'-field. However, at the same time the data model assumes an additional field 'fullName' is added and filled with null-values when saving into the database.
I have already tried annotations like #Transient, but this does not work. The documentation states "by default all private fields are mapped to the document, this annotation excludes the field where it is applied from being stored in the database", so it only can be applied to private fields in the class, not to get-methods.
What is the correct way to do this in Spring? Of course I can extend the class Person and include the getFullName-method there, but I was wondering if it is possible to include everything in one class.
Edit:
I use Elasticsearch as DB engine using spring-data-elasticsearch 1.2.0.RELEASE. I have just tested MongoDB as alternative and then it is working fine, even without the #Transient annotation. I think the index-method of the ElasticsearchRepository is serializing the provided class instance when saving it to the database. In that way the JSON-output and the saved data are always identical. Any suggestions?

Possibilities of creating immutable class in Java

what are possibilities of creating immutable bean in Java. For example I have immutable class Person. What's a good way to create instance and fill private fields. Public constructor doesn't seems good to me because of a lot input parameters will occure as class will grow in rest of application. Thank you for any suggestions.
public class Person {
private String firstName;
private String lastName;
private List<Address> addresses;
private List<Phone> phones;
public List<Address> getAddresses() {
return Collections.unmodifiableList(addresses);
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public List<Phone> getPhones() {
return Collections.unmodifiableList(phones);
}
}
EDIT: Specify question more precisely.
You could use the builder pattern.
public class PersonBuilder {
private String firstName;
// and others...
public PersonBuilder() {
// no arguments necessary for the builder
}
public PersonBuilder firstName(String firstName) {
this.firstName = firstName;
return this;
}
public Person build() {
// here (or in the Person constructor) you could validate the data
return new Person(firstName, ...);
}
}
You can then use it like this:
Person p = new PersonBuilder.firstName("Foo").build();
At first sight it might look more complex than a simple constructor with tons of parameters (and it probably is), but there are a few significant advantages:
You don't need to specify values that you want to keep at the default values
You can extend the Person class and the builder without having to declare multiple constructors or needing to rewrite every code that creates a Person: simply add methods to the builder, if someone doesn't call them, it doesn't matter.
You could pass around the builder object to allow different pieces of code to set different parameters of the Person.
You can use the builder to create multiple similar Person objects, which can be useful for unit tests, for example:
PersonBuilder builder = new PersonBuilder().firstName("Foo").addAddress(new Address(...));
Person fooBar = builder.lastName("Bar").build();
Person fooBaz = builder.lastName("Baz").build();
assertFalse(fooBar.equals(fooBaz));
You should have a look at the builder pattern.
One good solution is to make your fields final, add your constructor private and make use of Builders in your code.
In our project we combined the Builder pattern with a validation framework so that once an object is created we are sure it's immutable and valid.
Here is a quick example:
public class Person {
public static class Builder {
private String firstName;
private String lastName;
private final List<String> addresses = new ArrayList<String>();
private final List<String> phones = new ArrayList<String>();
public Person create() {
return new Person(firstName, lastName, addresses, phones);
}
public Builder setFirstName(String firstName) {
this.firstName = firstName;
return this;
}
public Builder setLastName(String lastName) {
this.lastName = lastName;
return this;
}
public Builder addAddresse(String adr) {
if (adr != null) {
addresses.add(adr);
}
return this;
}
public Builder addPhone(String phone) {
if (phone != null) {
phones.add(phone);
}
return this;
}
}
// ************************ end of static declarations **********************
private final String firstName;
private final String lastName;
private final List<String> addresses;
private final List<String> phones;
private Person(String firstName, String lastName, List<String> addresses, List<String> phones) {
this.firstName = firstName;
this.lastName = lastName;
this.addresses = addresses;
this.phones = phones;
}
public List<String> getAddresses() {
return Collections.unmodifiableList(addresses);
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public List<String> getPhones() {
return Collections.unmodifiableList(phones);
}
}
In my example you can see that all the setters in the Builder return the Builder instance so that you can easily chain the setters calls. That's pretty useful.
You could take a look at the Builder pattern presented by Joshua Bloch.
As I said before, combined with a validation framework (see for ex. http://www.hibernate.org/subprojects/validator.html) this is really powerfull.
With interfaces. Do this:
public interface Person {
String getFirstName();
String getLastName();
// [...]
}
And your implementation:
// PersonImpl is package private, in the same package as the Factory
class PersonImpl {
String getFirstName();
void setFirstName(String s);
String getLastName();
void setLastName(String s);
// [...]
}
// The factory is the only authority to create PersonImpl
public class Factory {
public static Person createPerson() {
PersonImpl result = new PersonImpl();
// [ do initialisation here ]
return result;
}
}
And never expose the implementation to the places where you want Person to be immutable.
Initializing in the constructor is nevertheless the simplest and safest way to achieve immutability, as this is the only way to have final fields in your immutable class (which is the standard idiom, and has beneficial effects especially if your class is used in a multithreaded environment). If you have lots of properties in your class, it may be a sign that it is trying to do too much. Consider dividing it to smaller classes, or extracting groups of related properties into compound property classes.
Using a Builder (with a private constructor) is a possibility, however it still needs a way to set the properties of the object being built. So you fall back to the original dilemma of constructor parameters vs accessing the private members. In the latter case you can't declare the properties of the object being built as final, which IMHO is a great minus. And in the former case you still have the same long list of constructor parameters you wanted to avoid in the first place. Just now with a lot of extra boilerplate code on top of it.
You can achieve an "immutable" bean by making a read-only interface and then making the implementation into a mutable bean. Passing around the interface won't allow for mutation, but when you construct the object and have the implementation, you can do all sorts of bean-y things:
public interface Person {
String getFirstName();
String getLastName();
// ... other immutable methods ...
}
public class MutablePerson implements Person {
// ... mutable functions, state goes here ...
}
Use the factory-pattern:
let Person be an interface with only "get"-functions
create a PersonFactory with an appropriate API for building a Person-object
the PersonFactory creates an object which implements the Person-interface and returns this
Have final fields.
Make the class as "final" class by declaring as final public class Person
do not use setXXX() methods to set the value since it will change the state of a variable. however getXXX() methods are allowed.
Use a private constructor so that you can set fields using the constructor itself.
Follow the above guidelines for Immutable class.
Use final fields for all your instance variables. You can create a constructor if you like and choose to not expose setters, e.g.,
public class Person {
private final String firstName;
....
public Person(String firstName, ... ) {
this.firstName = firstName;
}
}

Categories