How to choose your getters and setters in java - java

I have the payment class with only one local private variable - totalCost, as such totalCost also has a getter and setter methods. TotalCost is the only local variable because its the only one used in more than one method in the payment class. Should this class have more getters and setters?
public class Payment {
private int totalCost;
public Payment(){
}
public int calculateItemcost(int itemQuantity, int itemPrice){
return itemPrice * itemQuantity;
public int calculateTotalcost(int itemCost){
return totalCost = totalCost + itemCost;
}
public int calculateBalance(int clickedValue, int totalCost){
return this.totalCost = totalCost - clickedValue;
public int getTotalcost(){
return this.totalCost;
}
public void setTotalcost(int totalcost) {
this.totalCost = totalcost;
}
}

You use getters for the fields that you might need to "get" in other classes,
and setters for the fields that you might need to "set" in other classes. So before writing a getter/setter, think of your requirements.

Since you only have one field, which you already have getters and setters for. There is no point. Looks fine.
Although, refactor this:
public int calculateTotalcost(int itemCost){
return totalCost = totalCost + itemCost;
}
public int calculateBalance(int clickedValue, int totalCost){
return this.totalCost = totalCost - clickedValue;
}
To call the setter. Example:
public int calculateTotalcost(int itemCost){
setTotalCost(totalCost + itemCost);
return getTotalCost();
}
This way changes to totalCost is localized to the setTotalCost method.

Do you know the law of Demeter?
It gathers some small guidelines to avoid loose coupling in your code.
Getters and setters are the elements leading to thight coupling between classes.
Why?
Because getters and setters informs you about the implementation of a class (its field especially) and its design.
Developer who ALWAYS code with creation of getters/setters systematically have misunderstood totally the notion of Object-Oriented programming.
Indeed, this leads to anemic domain model.
Thus, it forces client to implements the business logic themselves even though it isn't its role.
To put in a nutshell: In an application, 80% of getters and setters are unnecessary.
Object-Oriented programming is about messages. You want a behaviour from an object, tell it ! Don't ask for information about its state in order to make your kitchen aside cause that would be typically a procedural way of coding.
(Tell ! Don't Ask !!) and favor the non-respect of DRY (Don't repeat yourself).

Two guidelines I follow.
First, not necessarily all private data should be exposed via getters and setters, since some of them may be for internal use only.
Second, the getters and setters should provide an object view, not an implementation view.
For example, if your class has a hard-coded 10% tax rate on purchases (forgetting for now that hard-coding this is a bad idea), you could have a getter for the taxation component even though it's a calculated value rather than a private member. In addition, you may want to set the value based on the pre-tax price.
So, if the pre-tax value has 10% added on for the government vultures, something like:
public void setPreTax (int preTaxAmt) {
totalCost = preTaxAmt * 11 / 10;
}
public int getTax (void) {
return totalCost / 11;
}
I haven't bothered using floating point for the calculations since it's irrelevant to the discussion and you're already using int.
This object/implementation split is a good thing - you should design your API based on the information you want to provide to the clients of it, not based on internal details.

Related

Is this proper encapsulation for this Java code? I am confused

Does this Java code involving a Book class use proper encapsulation? I feel it can be a lot simpler if I omit some methods but we're required to every method that is in there [especially setters and getters].
Here's the first class:
public class Book
{
private String title;
private double price;
private final double SALES_TAX=0.075;
public String getTitle()
{
return title;
}
public void setTitle(String title)
{
this.title=title;
}
public double getPrice()
{
return price;
}
public void setPrice(double price)
{
this.price=price;
}
public double getSalesTax()
{
return SALES_TAX;
}
public double increasePrice(double incresePrice)
{
return incresePrice;
}
public double calculateSales(double sales)
{
return sales;
}
}
And the second class:
public class BookDriver
{
public static void main(String[] args)
{
Scanner keyboard=new Scanner(System.in);
Book bookOne=new Book();
Book bookTwo=new Book();
bookOne.setTitle("Life of Pi");
System.out.print("Enter number to buy of "+bookOne.getTitle()+": ");
bookOne.setPrice(13.50*bookOne.calculateSales(keyboard.nextDouble()));
bookOne.setPrice((bookOne.getPrice()*bookOne.getSalesTax())+bookOne.getPrice());
System.out.print("Cost for "+bookOne.getTitle()+" $");
System.out.printf("%.2f"+"\n",bookOne.getPrice());
bookTwo.setTitle("Harry Potter: The Goblet Of Fire");
System.out.print("Enter number to buy of "+bookTwo.getTitle()+": ");
bookTwo.setPrice(22.00*bookTwo.calculateSales(keyboard.nextDouble()));
bookTwo.setPrice((bookTwo.getPrice()*bookTwo.getSalesTax())+bookTwo.getPrice());
System.out.print("Cost for "+bookTwo.getTitle()+" $");
System.out.printf("%.2f"+"\n",bookTwo.getPrice());
System.out.print("Enter percent increase of "+bookOne.getTitle()+": ");
bookOne.setPrice((bookOne.getPrice()*bookOne.increasePrice(keyboard.nextDouble()))+bookOne.getPrice());
System.out.printf("Cost of "+bookOne.getTitle()+": $"+"%.2f"+"\n",bookOne.getPrice());
System.out.print("Enter percent increase of "+bookTwo.getTitle()+": ");
bookTwo.setPrice((bookTwo.getPrice()*bookTwo.increasePrice(keyboard.nextDouble()))+bookTwo.getPrice());
System.out.printf("Cost of "+bookTwo.getTitle()+": $"+"%.2f"+"\n",bookTwo.getPrice());
keyboard.close();
}
}
I know that this is a lot so I'm not really expecting much in terms of a response but anything would help. Thanks!!
Let's look at the point of encapsulation. You have a Class which consists of properties and methods. The idea behind encapsulation is, you want the methods in your class to be the only way to change the value (state) of the properties. Think of it like this: if some other code in the program wants to change the value of one of the properties, it cannot do it itself, it must ask a method on the class they reside in to do it. That way, you control access to the properties.
The way this is implemented is with getter and setter methods of which you have created a few. A getter method returns the value of the property and a setter method changes it to a new value.
1.
Your getter and setter methods up to increasePrice() are good. You are preventing access to the properties other than from the methods on your class.
2.
increasePrice() only spits out what was passed into it. It doesn't change the value of any of the properties and thus has no purpose. If you want to be able to increase the price you can change the method like so:
public void increasePrice(double amountOfPriceIncrease) {
price += amountOfPriceIncrease;
/*
price += amountOfPriceIncrease is the same as
price = price + amountOfPriceIncrease
*/
}
3.
This line is a bit troubling. For starters, increasePrice() doesn't do anything other than spit out what was put into it and secondly, there is a lot going on in the one line that makes it complicated and hard to follow.
bookTwo.setPrice((bookTwo.getPrice()*bookTwo.increasePrice(keyboard.nextDouble()))+bookTwo.getPrice());
You dont necessarily need all the setters. For example, its probably reasonable to assume that a book has a title, and it doesnt change. So you can make it final, omit the setter, and pass it into the constructor.
Also, think about how you're modelling things. Is sales tax a property of a book? I'd say not.
Because all the required variables title, price for class Book are set to private, and that access can only be used using get..(), and changing it if possible can only be used using set..(some variable) or an instance method affecting one of the fields, it demonstrates proper encapsulation, so all getting and setting are regulated.
However, I spotted several mistakes in BookDriver, namely with the improper usage of Book fields.
The price should change only through setPrice or increasePrice.
You should also implement getPriceAfterTax to determine after-tax prices for a book.
The total cost of the books you bought should not involve any setPrice.
There is a mistake with public double calculateSales(double sales). It does nothing but returns back sales. The calculateSales should calculate the total cost of the book(s) being bought, using one int variable, and you also resorted in changing the price of these books, which shouldn't happen. It is the reason why you wrote messy code, as in the excerpt
bookTwo.setPrice(22.00*bookTwo.calculateSales(keyboard.nextDouble()));
bookTwo.setPrice((bookTwo.getPrice()*bookTwo.getSalesTax())+bookTwo.getPrice());
This avoids the potential case of changing the values of that BOOK object to unexpected or unusual values and value combinations.
Additionally, SALES_TAX can be made into a public static final double instead, as it is assumed to never change, and you can simply obtain SALE_TAX without requiring getSalesTax().
The last two methods do not make much sense. You simply return what you put in. Do it this way:
public double increasePrice(double increase)
{
price *= increase;
}
public double calculateSales(double sales)
{
//return {your formula}
}

What's the point of get and set methods [duplicate]

This question already has answers here:
Set and Get Methods in java?
(16 answers)
Closed 8 years ago.
In my CS class I am just learning about classes and OOP.
So when you create a class you initialize a certain number of private variable.
I know you make them private because if they were public they would be easily changeable and could lead to a lot of bugs.
So we use get and set methods to change the variable. But that once again makes the variables very easy to change right? So whats the point of making them private in the first place?
Some benefits of using getters and setters (known as encapsulation or data-hiding):
1. The fields of a class can be made read-only (by only providing the getter) or write-only (by only providing the setter). This gives the class a total control of who gets to access/modify its fields.
Example:
class EncapsulationExample {
private int readOnly = -1; // this value can only be read, not altered
private int writeOnly = 0; // this value can only be changed, not viewed
public int getReadOnly() {
return readOnly;
}
public int setWriteOnly(int w) {
writeOnly = w;
}
}
2. The users of a class do not need to know how the class actually stores the data. This means data is separated and exists independently from the users thus allowing the code to be more easily modified and maintained. This allows the maintainers to make frequent changes like bug fixes, design and performance enhancements, all while not impacting users.
Furthermore, encapsulated resources are uniformly accessible to each user and have identical behavior independent of the user since this behavior is internally defined in the class.
Example (getting a value):
class EncapsulationExample {
private int value;
public int getValue() {
return value; // return the value
}
}
Now what if I wanted to return twice the value instead? I can just alter my getter and all the code that is using my example doesn't need to change and will get twice the value:
class EncapsulationExample {
private int value;
public int getValue() {
return value*2; // return twice the value
}
}
3. Makes the code cleaner, more readable and easier to comprehend.
Here is an example:
No encapsulation:
class Box {
int widthS; // width of the side
int widthT; // width of the top
// other stuff
}
// ...
Box b = new Box();
int w1 = b.widthS; // Hm... what is widthS again?
int w2 = b.widthT; // Don't mistake the names. I should make sure I use the proper variable here!
With encapsulation:
class Box {
private int widthS; // width of the side
private int widthT; // width of the top
public int getSideWidth() {
return widthS;
}
public int getTopWIdth() {
return widthT;
}
// other stuff
}
// ...
Box b = new Box();
int w1 = b.getSideWidth(); // Ok, this one gives me the width of the side
int w2 = b.getTopWidth(); // and this one gives me the width of the top. No confusion, whew!
Look how much more control you have on which information you are getting and how much clearer this is in the second example. Mind you, this example is trivial and in real-life the classes you would be dealing with a lot of resources being accessed by many different components. Thus, encapsulating the resources makes it clearer which ones we are accessing and in what way (getting or setting).
Here is good SO thread on this topic.
Here is good read on data encapsulation.
As the above comment states, getters and setters encapsulate (i.e. hide) inner details of your class. Thus other classes that interact with yours, do not need to know about the implementation details.
For example, in the simple case you describe, instance variables are exposed via getters and setters. But what if you wanted to change your class so that you no longer used instance variables, but rather you persisted the values to disk. You could make this change to your class without affecting the users of your class.
Keep in mind also that getters and setters need not always be provided. If you do not want your class to provide a way to set or read these properties, then don't. Simply make them private.
get is used to obtain a value for an attribute and set is used to put a value to an attribute
ex:
private int variable;
public int getVariable(){
return variable;
}
public void setVariable(int aux){
variable=aux;
}
In general, is used to encapsulate an attribute.
reference:
Set and Get Methods in java?
Encapsulation or data hiding gives u more control on what values can be set to a field. Here is an example if you don't want a class attribute to have a negative value:
class WithoutGetterSetter {
public int age;
}
class WithGetterSetter {
private int age;
public setAge(int age) {
if(age < 0)
// don't set the value
else
this.age = age;
}
}
public class testEncapslation {
public static void main(String args[]) {
WithoutGetterSetter withoutGetterSetter = new WithoutGetterSetter();
withoutGetterSetter.age = -5;
WithGetterSetter withGetterSetter = new WithGetterSetter();
withGetterSetter.setAge(-5);
}
}
Get and Set methods are preferable to "public" variables because they insulate the users of a class from internal changes.
Supposing you have a variable "StockQty" and you made it public because that seemed like the easiest thing to do.
Later on you get a user requirement to track the history of stock over time. You now need to implement a SetStockQty() method so you can save the old quantity somewhere before setting the new quantity.
Now all the users of your class have to change there code, re-document and re-test.
If you had SetStockQty() method to begin with only you would need to change and test your code.
The second reason is you can have Getters without Setters effectivly making the variable "read only".
Traditionally, they are justified in terms of encapsulation. By providing moderated access to read and write the fields of a class, we supposedly reduce coupling.
In simpler language: by controlling the ways in which other classes can read and change our data, we reduce the ways in which our class's data can change. This means that the connections between classes are reduced, which reduces complexity.
However, the same logic says that getters and setters should generally be avoided unless there's an actual need for them, and there very seldom is such a need. For the most part, a class should "tend to its own knitting" - if there's a calculation to be done on this class's data, it should do it. If a value should be changed, it should do the changing.
For example, consider an object in space. It has a location specified as (x,y,z). We could possibly allow other classes to just set those arbitrarily - this would be horrible, obviously, but it's not obvious that a setter for these would be any better. What you really want is a constructor to set an initial position, and then methods to influence that position - for example, to register an impact or an acceleration. Then you're doing OO programming.
One word, Encapsulation.setters also allow you to control how values are entered into your program. Many new programmers like myself are often confused by this concept. I strongly advice you read this SO question
Being objective: it's all about best pratices!!!
1) IF necessary, expose your attributes with get methods.
2) IF necessary, allow attribute modification (state modification) using set methods;
Have both public get and set methods without treatment is the same as have the attributes public.

Java: When to use attributes, when to use method parameters?

I tried googling and searching for this question but somehow couldn't find anything relevant about it. I'm wondering if there is a bbest-practise guide on when to use attributes in a class and when not, but rather use parameters to the single methods.
Many cases are clear to me, e.g.
public class Dog
{
private name;
public setName(...) {....}
}
But sometimes it's not clear to me what's better to use.
E.g. the following, either use:
public class calculation
XYZ bla;
public calculation(XYZ something)
{
this.bla = something;
}
public void calc1()
{
// some calculations with this.bla
}
public void calc1()
{
// some more calculations with this.bla
}
public XYZ getBla()
{
return this.bla;
}
}
or maybe do:
public class calculation
public calculation() {}
public static XYZ calc1(XYZ bla) // maybe static, if not dependant on other attributes/instance-variables etc
{
// some calculations with bla
return bla;
}
public static XYZ calc1() // maybe static, if not dependant on other attributes/instance-variables etc
{
// some more calculations with bla
return bla;
}
}
I mean you can argue for both cases. I see advantages and maybe disadvantages for both different styles, but somehow I prefer the second one as far as long as there are not too many arguments/parameters needed. Sure, if I need many many more attributes etc., then the first one will be better, simpler etc. because I dont need to pass so many parameters to the method...
Just a question of personal style?
Or how to decide for one approach?
Thanks
EDIT: A better example: I'm curently doing much image processing and the question would be wether to store the image internally in the state of the object or not. I'm currently NOT doing it because I'm using static methods, and psasing the image itself I to each method:
public class ImageProcessing
{
/**
*
*/
public static Mat cannyEdges(Mat I, int low, int high)
{
// ...
return I;
}
public static Mat cannyEdges(Mat I)
{
return ImageProcessing.cannyEdges(I, ContourDetection.CANNY_LOWTHRES, ContourDetection.CANNY_HIGHTHRES);
}
/**
*
*/
public static Mat getHoughLines(Mat Edges, ...some_conf_vars...)
{
// ...
return I;
}
}
and then I'm calling it from the outside like this e.g.:
// here: read image to I...
Mat edges = ImageProcessing.cannyEdges(I, 20, 100);
Mat lines = ImageProcessing.getHoughLines(I);
// draw lines...
question is: Does I belong to the state of the object? Would it make sense to convert to non-static and then use for example:
// here: read image to I...
ImageProcessing IP = new ImageProcessing(I);
IP.cannyEdges(20, 100); // CHANGE OF cannyEdges: Also save `edges` internally as property!?
IP.calcHoughLines(); // also save the lines internally maybe?
Mat lines = IP.getLines();
// draw lines...
is this nicer?
The question arising is then again: Should I for example store the result of getHoughLines() (i.e. the lines) internally or should I directly return it to the caller!?
I can use some examples:
public class Multiplier {
private int number;
public Multiplier(int number) {
this.number = number;
}
public int multiply(int other) {
return number * other;
}
}
This class could be instantiated like:
Multiplier multiplyByTwo = new Multiplier(2);
I could use it to multiply many elements on a list by 2.
But I could need to multiply pairs of numbers. So the following class could be what I neeed:
public class Multiplier {
public static int multiply(int number, int other) {
return number * other;
}
}
I could make it static since no state is needed.
This example could be used like this on a list:
for (int x:listOfInts) {
print(Multiplier.multiply(x * 2));
}
But probably in this specific case the 1st example was nicer.
for (int x:listOfInts) {
print(multiplyByTwo(x));
}
or even nicer used with a Java 8 ''map''
If I need to get the elements of the multiplication and the result at many points in my code i could do.
class Multiplier {
private int x;
private int y;
public int multiply() {
return x * y;
}
// getters and setters for x and y
}
In this last case I may consider not adding setters and pass x, y in the constructor.
Every structure could be used in some specific cases.
It's not entirely a question of personal style. But nevertheless, I assume that this topic might be slightly controversial (opinion-based) and thus not perfectly suited for a Q/A-site.
However, the obvious question is: Does an object of the respective class really carry a state? That is, is there any benefit in having the state represented by an instance? If the sole purpose of the instance is to be an accumulator of variables that are modified with a sequence of set... calls and a final call to an execute() method, then there is usually no real justification for such an instance - except for avoiding to have a static method with "many" parameters.
I think that the advantages of static methods outweigh most of the potential clumsiness of calling a method with "many" parameters. One of the most important ones is probably that the approach with static methods doesn't increase the state space. Every field is another dimension in the state space, and documenting state space properly can be hard. Static methods enforce a more "functional" programming style: They don't have any side-effects, and thus, are thread-safe (which is becoming increasingly important).
(Note: All this refers to static methods that are not related to any static state - that should be avoided anyhow. And of course, this refers to methods that are not involved in or aiming at anything related to polymorphism).
And after all, one can easily call any static method from anywhere - even from within an instance method, and pass in some fields as parameters. The opposite is not so easy: When you want to call a method that depends on many instance fields, it can be a hassle when you first have to create an object and set the fields appropriately (still not knowing whether it is in a valid state to call the method). I also see the default methods of Java 8 as a nice application case where static utility methods come in handy: The default method may easily delegate to the utility method, because no state is involved.
There are a few reasons I'd go with the first option, i.e. an object with state over static functions, particularly for complex calculations but also for simpler ones.
Objects work better for the command pattern.
Objects work better for the strategy pattern.
Static methods can turn unit tests into a nightmare.
Static is an anti-pattern in OOP because it breaks polymorphism, with the side-effect that related techniques will break with it, e.g. open/closed, mocking, proxies, etc.
That's my 2c at least.
The weird part of your first example is that those calcX methods don't say anything about idempotency, so it's unclear what this.bla is when it's being manipulated. For complex computations with optional settings, an alternative is to construct an immutable object using a builder pattern, and then offer calcX methods that return the result based on fixed object state and parameters. But the applicability of that really depends on the use case, so YMMV.
Update: With your new code, a more OOP approach would be to decorate Mat. Favouring delegation over inheritance, you'd get something like
public class MyMat
{
private Mat i;
public MyMat(Mat i) {
this.i = i;
}
public Mat getBackingMat() {
return this.i;
}
public MyMat cannyEdges(int low, int high)
{
// ...
return new MyMat(I); // lets you chain operations
}
public MyMat cannyEdges()
{
return new MyMat(ImageProcessing.cannyEdges(I, ContourDetection.CANNY_LOWTHRES, ContourDetection.CANNY_HIGHTHRES));
}
public MyMat getHoughLines(...some_conf_vars...)
{
// ...
}
}
MyMat myMat = new MyMat(I);
lines = myMat.cannyEdges(20, 100).calcHoughLines();
This is just a guess, cause I have no idea what those things mean. :)
When not to use static:
If the result that will be returned is dependent on other variables (state) that make up your "calculation" class then static cannot be used.
However, if you are simply doing calculations on a variable, as the example implies, static is probably the way to go as it requires less code (For example to perform calc1 and then calc2 on a variable by the first method you would have to do:
calculation calc = new calculation(x)
calc.calc1();
calc.calc2();
XYZ y = calc.getBla();
while with the second example you could do
static import ...calculation.*;
...
XYZ y = calc2(calc1(x));

Should I set up getters and setters even when I only need one of them?

I have an object in which the constructor's job is to set the fields and they aren't set up or changed after that, ever. However, I need a getter for them. Then, do I need to have setters even though I won't ever use them "just in case" or I can remove them and leave the getters only while leaving setting the values to the constructor?
According to the java bean specification, it is legal to omit a getter or setter
method. so, you can safely omit the setter if you never use them
If your constructor is setting the fields and you don't need to change them they sound like they are immutable.
I would make them final and then just have getters.
If you omit the final then you allow someone in the future to add setters. If you don't need setters then you should enforce this as part of your design and have gettets with final fields.
This will make it explicit to anyone reading the code that they are immutable by design.
There is also the issue of writing more code than us needed. If you write setters then you could introduce bugs as this code may not be fully tested as you don't consider it needed
If you want to use the object property as read-only and initialize it in the object's constructor then you don't need the setter. If you want to access this property outside of this class, then you need getter for that.
Also suggest you to read this SO Question
below is from an architect at google :
class Foo{
private int a;
private int b;
public Foo(int num1, int num2){
a= num1;
b= num2;
}
public int getA(){
return a;
}
public int getB(){
return b;
}
}
Here you dont need setter and once you construct your object. you cant change the state of it.
In the case of something that only you will see it's all personal choice since most editors can add them automatically for you.
If it is something that should never ever change and bad things can happen if it does, then that should not have a setter and should be a private variable.
If you are writing something with an eye towards re-use and sharing with others, then you do want getters and setters anywhere it is ok to do so since you won't know what other people may need to do with your API.
I think it depends on what your constructor is doing. If your constructor is merely doing raw setting of variables, then I don't think you need to include setters for them.
However, if your constructor code is doing any kind of business logic prior to setting the value of a variable, then I think this warrants creating a setter for at least the variable in question (if not all of them).
For example, if your constructor code does this, then don't include any setters:
public MyClass( String varA, String varB, int varC )
{
this.varA = varA;
this.varB = varB;
this.varC = varC;
}
But if your code does this, you should include a setter to decouple the logic and make it cleaner:
public MyClass( String varA, String varB, int varC )
{
if ( varA == null )
{
this.varA = '(empty)';
}
else
{
this.varA = varA;
}
this.varB = varB;
if ( varC < 0 )
{
callSomeMethod();
}
this.varC = varC;
}
This kind of logic warrants creating setters.

Java getter vs this

This is a very generic scenario, where I am setting a variable using setter function and using the variable only locally.
class Main {
private String str;
public Main(String value)
setStr(value);
}
private String getStr() {
return str;
}
private void setStr(String str) {
this.str = str;
}
public void display() {
//METHOD1
System.out.println(getStr());
//METHOD2
System.out.println(this.str);
}
}
What would be the better practise to follow between the two METHOD1/2 in display function, basically what would be the better way of using "str" variable.
Does it even make sense to have private getter/setter functions?
Ivard
If the getter is private, and doesn nothing more than returning a private variable, it isn't needed, IMHO (i.e. I prefer the second method of accessing it).
But if the getter was public and not final, and could thus be redefined by a subclass, then you'd have to decide if you want to get the potentially overridden value returned by the getter, or if you want the value of the private field in the display method.
Here should be at least one comment with Yes.
By providing new abstraction barrier you can separate data accessors and data presentation. For example, lets look at complex number class. Which can be implemented as
class ComplexNumber {
private final double realPart;
private final double imaginaryPart;
ComplexNumber(double realPart, double imaginaryPart) {
this.realPart = realPart;
this.imaginaryPart = imaginaryPart;
}
public double getRealPart() {
return realPart;
}
public double getImaginaryPart() {
return imaginaryPart;
}
}
or in polar expressions form
class ComplexNumber {
private final double r;
private final double angle;
ComplexNumber(double r, double angle) {
this.r = r;
this.angle = angle;
}
public double getR() {
return r;
}
public double getAngle() {
return angle;
}
}
Presume that you should implement basic operation like +-/*. What presentation model should you choose? For addition and subtraction standard model preferable, but for multiplication and division polar form preferable. So you can create getters for both form. And implement add/_sub_ like you have standard model and div/_mult_ like with polar form. This operation wouldn't depend from your actual data presentation. For change presentation you should change getters. Thats all. In Java world it's called self encapsulation.
For simple cases you'd just use this.str. For more complex cases, you might want to inherit from such a class, and have getStr() be implemented in a subclass perhaps it would lazily get the string from a file/database. Then these methods would't be private though.
For trivial cases where you just assign and fetch a private member, not really. For more complex cases where you might need to do additional logic, it'd make sense to confine that logic to one place. As with 1., it would make sense if you want sub classes to override the methods as welll.
Unless you have a side effects in your public getter which you desire I would consider always using this for consistency unless inheritance is assumed.
It doesn't make sence at all to me to employ private accessors. A routine should typically only do one thing and preferably without side effects. Creating a private getter
without side effects only creates useless redundancy.
with side effects basically proves that either the method is doing too much or is poorly named
Using this might also make refactoring easier [1].
[1] Refactoring a private variable gives less impact than refactoring a method. If you later decide to change the contract, e.g., by no longer providing a getter routine you will get less to refactor. Besides, many editors highlight all occurences of a variable when pointing the cursor to it, which is lost when hiding its use in a sub-routine.
No, it's not useful to have private getter/setter methods. If they were public or otherwise overridible by subclasses though it would be a different story. Should a subclass override your getter/setter, it could change the way the display() method functions.

Categories