Getter and Setters in Java

Is it good to do some data processing / validation in getters and setters? In wikipedia here are 2 examples:

  • The setDate method stores java.util.Date date in 3 separate private fields, such as year, month, day
  • The getAmount method combines 2 field numbers and a currency and returns something like "$ 100." And maybe the sum field does not exist at all, and getAmount is just a calculation method.

Are these good examples or is it better to avoid this? If it's better to avoid this, how can I better implement these two examples above?

UPDATE: Please do not accept date examples, etc. Seriously. This is just an example, of course, it can be stupid.

The real example that I had.

I have an external third-party system, and I need to integrate. This external system expects some data from me as a class with getters and setters. I have to pass 2 fields there, id (something like 09df723987cd7 (let’s GUID)) and formattedID something like "objecttype / 09df723987cd7". I cannot change this external system.

I want to implement it as

getId() {
  return id
}

getFormattedId() {
    return objectType + "/" + id;
}

objectType is another field in this class.

My question is: is this normal, or is there a more elegant way to implement it?

+4
source share
8 answers

The examples you cited are not suitable, at least not in the form and with the names you mentioned.

I will try some of the best examples:

Incubation

, . setDate(Date d) , , . 20 .. ( ).

, , , , , , " ".

, , getAmount(): amount, - ( ) (, ). , getAmount() :

public double getAmount() {
  return amountInCents / 100.0;
}

, getAmount() , getAmountInUSD() .

getters seters Java , ( ):

  • ( )
  • (, )
  • , .. ,
  • , Java Beans ( ).
  • / /, .. - , , ( , ) ..
  • , . , , ( dsp_user)
+2

? , - , .


Builder

( , , , , ). , ( ).

A Builder Fluent ... ...

?

. .

, , "" " " . , " " , setFrontWheel(null) ... , validateMe .

Multi-

, , -:

void setDate(int y, int m, int day) {
  int maxDaysInMonth=0;
  switch(m) {
    case 1:
    case 3:
    ...
    case 11:
       maxDaysInMonth=31;
       break;
    case 2: // that feb
       maxDaysInMonth=isLeap(y) ? 29 : 28;
       break;
    case 4:
    case 6:
    ...
       maxDaysInMonth=30;
       break;
    default: // only 12 months in the year
       throw something;
  }
  if(d>=maxDaysInMonth) {
    // you catch my drift, yeah?
  }
}

:

  • " " - , "100 " - , , "computeSomething" "toSomeForm" (, "toString" ), ... Rectangle.getCentreX

  • " " -

    protected ArrayList listeners;
    // look-but-don't-touch getter
    public List getListeners() {
      return Collections.unmodifiableList(this.listeners):
    }
  1. "void return getters" - ( ) , . , - . .
     class Rectangle {
        void getCentre(Point2D resultHere) {
          resultHere.set(minX+width/2, minY+height/2);
        }
        // and not
        // Point2D getCentre() {
        //   return new Point2D.Double(minX+width/2, minY+height/2);
        // }
        // because... performance.
     }
+1

TL; DR: . , !

, , - , .

getters seters API, , ( , , , ).

, , , , . , ( ) . , , , ,

. , , Date . , getter, promises Date, Date, , .

, , ( ).

?

, , , getter.

, , , :

public class Person {

    private String name;
    private String address;

    public Person(String firstName, String lastName) {
        setName(firstName, lastName);
    }

    /**
     * @return The first and last name as a single String
     */
    public String getName() {
        return name;
    }

    public void setName(String firstName, String lastName) {
        this.name = firstName + " " + lastName;
    }

    /**
     * @return The entire address as a single String
     */
    public String getAddress() {
        return address;
    }

    public void setAddress(String houseNumber, String streetName, String city, String state, String zip) {
        this.address = houseNumber + " "  + streetName + " " + city + " " + state + " " + zip;
    }
}

, ( - ). , .

( ), . , Person.name = "John Doe". .

, , . , . , :

public class Person {

    private String firstName;
    private String lastName;
    private String houseNumber;
    private String streetName;
    private String city;
    private String state;
    private String zip;

    public Person(String firstName, String lastName) {
        setName(firstName, lastName);
    }

    /**
     * @return The first and last name as a single String
     */
    public String getName() {
        return firstName + " " +lastName;
    }

    public void setName(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    /**
     * @return The entire address as a single String
     */
    public String getAddress() {
        return houseNumber + " " + streetName + " " + city + " " + state + " " + zip;
    }

    public void setAddress(String houseNumber, String streetName, String city, String state, String zip) {
        this.houseNumber = houseNumber;
        this.streetName = streetName;
        this.city = city;
        this.state = state;
        this.zip = zip;
    }
}

, , . .

, , . , , , - .

?

. , - , . , , - . , , .

, age Person. , setAge(int age) ( , birthDate, , age).

:

public void setAge(int age) {
    if (age < 0 || age > 120) 
        throw IllegalArgumentException("age must be between 0 and 120");

    this.age = age;
}

, - ! 0 . . , 13 18 , .

, , .

+1

. . :

class Example {
    private Integer value;
    public void setValue(Integer value) {
        this.value = value;
    }
    public void setValue(String value) {
        try {
           this.value = Integer.parseInt(value);
        } catch (NumberFormatException nfe) {
            throw new IllegalArgumentException(String.format("%s contains no valid numeric string.", value));
        }
    }
}

setValue, String, . , , . , setDate Date Date , , , .. Date Date ​​ .

0

Getter setter .

,

public class Sample
{
     private int somedata; // Encapsulated
     public int Get() {return somedata;} //Getter
     public void Set(int var) {somedata = var;} // Setter
}

.

, , , , . .

0

: ​​ , .

, . , , -.

uisng validator framework,

..
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
...

    public class xyz{


        private int id;

        @NotEmpty(message="Name is compulsary")
        @Size(min = 3, max = 100,message="Name  must be between 3 to 100 characters")
        private String personName;
        @NotEmpty(message="Person type is compulsary")
        private String personType;
        private String designation;
        private String purpos.......
0

? Yes No. :

1. setDate java.util.Date date 3 , , , .

java.util.Date, , . .

java.util.Date , . . , JVM, Date. , , . , , .

, Java dev .

2. getAmount 2 - "100 ".

, , , , , .

0

setDate java.util.Date date 3 , , ,

, . , , - , String, , .

.

, Divide:

class Divide {
private int dividend = 0;
private int diviser = 1;
private int result;
private int modulo;

public void  setDividend(int dividend) {
    this.dividend = dividend;
    this.result = this.dividend / this.diviser;
}

public void setDiviser(int diviser) {
    this.diviser = diviser;
    this.result = this.dividend / this.diviser;
}

...

, , diviser . , . :

   public void setDiviser(int diviser) {
        if (diviser == 0) throw ... // Zero divide exception
        this.diviser = diviser;
        this.result = this.dividend / this.diviser;
    }

But it is very inefficient, because you perform this check every time the divider is installed, perhaps the caller also checked, and when the operation is completed, it will be checked at another time.

So:

   // I have been told "by contract" that diviser won't be zero
   public void setDiviser(int diviser) {
        this.diviser = diviser;
        try {
            this.result = this.dividend / this.diviser;
        }
        catch (Exception e)
        {
            // do something about it
        }
    }

There are other options, such as creating a throwable method, but be very careful if you want to do an effective check. Naturally, Java does not fully implement the design by contract, but with exceptions you can keep the spirit.

0
source

Source: https://habr.com/ru/post/1655837/


All Articles