getters and setters performing additional logic

constructor getter and setter in java example
getters and setters user input java
java getters and setters best practices
getter and setter methods for arraylist in java
java 8 getter/setter
oop getters and setters
how to apply getters and setters to a private constant (final) data
why getter and setter methods used in java

I have a Java class which represents the correlation between two elements (typical POJO):

public class Correlation {

    private final String a;
    private final String b;

    private double correlation;

    public Correlation(String a, String b) {
        this.a = a;
        this.b = b;
    }

    public double getCorrelation() {
        return correlation;
    }

    public void setCorrelation(double correlation) {
        this.correlation = correlation;
    }

}

To follow the correct correlation logic if a equals b then the correlation value should be ALWAYS 1. I could add the logic altering the getter method (ignore the fact of the possible null value for a):

public double getCorrelation() {
    if (a.equals(b)) {
        return 1D;
    } else {
        return correlation;
    }
}

What bothers me is adding this logic to a getter method, should I change the method name or documenting it should be considered enough?

Back in the early days of Java getter/setter pairs were used to identify properties of beans exactly for the purpose of making it possible to define conceptual attributes implemented through computation rather than a plain member variable.

Unfortunately with the passing of time programmers have come to rely more and more on getter/setters being just accessors/mutators for underlying attributes, trend that was sort of made official with the introduction of the term POJO to identify objects that only had getters and possibly setters as methods.

On the other hand it is a good thing to distinguish objects that perform computations from objects that just carry data around; I guess you should decide which type of class you wish to implement. In your place I probably would make correlation an additional constructor argument and check it's validity there, rather than in your getter. Your Correlation cannot be a computational object, as it doesn't have enough information to perform any computation.

How Much Logic in Getters, But getting data from a database is a whole lot more than "logic". most ORMs support lazy loading of collections, which is basically exactly what you're doing. They tell me there should be as little logic as possible in getters and setters. Getters and Setters in python are often used when: We use getters & setters to add validation logic around getting and setting a value. To avoid direct access of a class field i.e. private variables cannot be accessed directly or modified by external user. Using normal function to achieve getters and setters behaviour

Side effects in getters and setters is generally not a great idea as it is usually not expected and can lead to tricky bugs. I would suggest creating a "correlate()" method or something else that is not specifically a getter in this case.

Hope this helps.

logic inside getters and setters? DO/DON'T : javahelp, The general idea is to never put logic in a getter/setter at all. It should just get or set a … More posts from the javahelp community. 37. Posted by. u/JimLessly. Getters and setters exist in most object-oriented programming languages, including JavaScript. They are code constructs that help developers access the properties of objects in a secure way. With getters, you can access (“get”) the values of properties from external code, while setters let you change (“set”) their values.

It make more sense to enforce the value during setCorrelation(...). For example,

public void setCorrelation(double correlation) {
  if (a.equals(b)) {
    if (Math.abs(correlation - 1D) > EPSILON) {
      throw new InconsistentException(...);
    }
    this.correlation = 1D;
  } else {
    this.correlation= correlation;
  }
}

I would also consider making the correlation property a nullable, where a null indicates that a correlation has not been set yet.

Java Getter and Setter: Basics, Common Mistakes, and Best , Thus, hiding the variable number as private and then using a setter comes to the rescue. On the other hand, a getter method is the only way for� When new to C#, it may be tempting to just give all properties both getters and setters, which unless they explicitly need to be mutable, is bad practice. “Tell an object what to do, don’t ask it for information and manipulate it yourself”. With that in mind, don’t add setters and getters by default.

Given that correlation is a somehow/sometimes "derived" value from a and b (i.e. it is 1 if a equals b, but it might be calculated in some original way depending on (a,b), a good option could be calculate the correlation in the constructor and throw an IllegalArgumentException within setCorrelation if the vaule violates the inner logic of the object:

public class Correlation {

    private final String a;
    private final String b;

    private double correlation;

    public Correlation(String a, String b) {
        this.a = a;
        this.b = b;
        calculateCorrelation();
    }

    protected calculateCorrelation() { 
        // open to more complex correlation calculations depending on the input,
        // overriding by subclasses, etc.
        if (a.equals(b)) {
            this.correlation = 1D;
        } else {
            this.correlation = 0;
        }
    }

    public double getCorrelation() {
        return correlation;
    }

    public void setCorrelation(double correlation) throws IllegalArgumentException {
        if (a.equals(b) && correlation != 1D) {
            throw new IllegalArgumentException("Correlation must be 1 if a equals b");
        }

        this.correlation = correlation;
    }
}

Following this scheme you could also "generify" your Correlation class.

Why Should I Write Getters and Setters?, That's the advantage that getters and setters offer over the YAGNI train of thought. and with getters/setters, I am actually doing the same thing — making the goes wrong in the future we just add validation logic in the setter. However Getters/setters violate the open/closed principle, prevent information hiding and should be considered evil (Long version). Using getters and setters allows to decouples the business logic for setting values from the actual storage. Something that object-orientation was suppose to avoid.

I would say use something like getValue()

Avoid getters and setters whenever possible - DEV, Let's make getters and setters our last, rather than first, resort. and setters that directly expose a single private member, have the same name, and provide no other functionality. I don't remember ever doing this in all my years of software. We could add logic but it could give us a new set of troubles. Use Getters and Setters to Modify Data. To execute logic each time a public property is set, write a custom setter. If you write a setter for a public property, you must also write a getter. Annotate either the getter or the setter with @api, but not both. It’s a best practice to annotate the getter. To hold the property value inside the getter and setter, use a field.

Getter/Setter — the most hated practice in Java., One day, you think it's better to add the validation logic for the variable myVar because other people keep sending incorrect values to your system. Without a setter,� If one says getters and setters are bad *always*, one is an idiot. However, getters and setters are too verbose, while in 90% of the time they do nothing more but to set/get a value. There are frameworks that provide annotations for automatic getters/setters where no additional code is required.

Why getter and setter methods are evil, The getter/setter idiom is a commonplace feature in many Java programs. In doing so, you're in a much better position to decide whether you should use that feature or idiom. classes only when objects of one class send messages to objects of the other. strategy means that I (gasp!) put UI code into the business logic. Ah, padawan, you have touched one of the great mysteries of the Force. Why to take the long road, when the short road looks so much easier? When you instantiate an object and its constructor is called, the private variables are available to the co

Setter and Getter Methods in Java, Getters and setters - 1. But now I have to tell you an But in doing so, only valid values should be allowed. Our objects should be protected� Let me make constructors and setters clear first. Constructor : making an object out of a class. everything you pass into the constructor should be set to the attributes within the constructor block.

Comments
  • +1; this is the whole truth! It's important to distinguish between real object and dumb data transfer objects.
  • I agree except for the last sentence. I think Correlation can be a computational object since it (at least) can calculate correlation when a equals b.
  • @Jala: Correlation isn't something that's 1 when a and b are equal and undefined otherwise: one thing is to check arguments and another is to calculate a function of said arguments.
  • Even if the logic was defined on another class would you add the value constraint on the setter method?
  • On second thoughts, probably no. That logic belongs where correlation is actually calculated and this test is both very partial and likely redundant. On the other hand, if you have to have it, that's the best place to put it ;-)
  • I don't see a side effect in his second getter. One exception, the first getter might give a rounding error. But that would make the second getter preferable.
  • Agreed. In general, the best practice is to have a method do one thing only if possible and avoid side effects at all costs. Think of it as the Single Responsibility Principle applied to the method level.
  • i agree that putting logic in getters/ setters is typically not a great idea, but you may need some side effects at times - e.g. a user object may encrypt/ decrypt password in a setter/ getter
  • @aishwarya agreed good point, to clarify my answer, side-effects or operations performed in setters/getters should be paired, to use your example... if you encrypt the value on set, you would decrypt on get.
  • it is a good approach but the "a.equals(b) then 1" logic is repeated twice in the class.
  • In the end it is the 'get' part of the name which is killing me.