Can you omit setMethods if you have a constructor?

  • (2 Pages)
  • +
  • 1
  • 2

26 Replies - 1396 Views - Last Post: 16 August 2013 - 09:47 PM Rate Topic: -----

#1 streek405  Icon User is offline

  • D.I.C Addict

Reputation: 10
  • View blog
  • Posts: 535
  • Joined: 10-March 13

Can you omit setMethods if you have a constructor?

Posted 13 August 2013 - 05:50 PM

I just copied this program from my book and when I deleted the setMethods it still had the same, exact out come. Is this because the constructor is pretty much the setMethod in this case? If so, then can I always leave setMethods out if the contractor would be the same? Heres the code if it helps:

public class Loan{

	private double annualInterestRate;
	private int numberOfYears;
	private double loanAmount;
	private java.util.Date loanDate;
	
	//default constructor
	public Loan(){
		this(2.5, 1, 1000);
	}
	
	//another constuctor
	public Loan(double annualInterestRate, int numberOfYears, double loanAmount){
		
		this.annualInterestRate = annualInterestRate;
		this.numberOfYears = numberOfYears;
		this.loanAmount = loanAmount;
		loanDate = new java.util.Date();
	}
	
	//getMethods
	public double getAnnualInterestRate(){
		return annualInterestRate;
	}
	
	public int getNumberOfYears(){
		return numberOfYears;
	}
	
	public double getLoanAmount(){
		return loanAmount;
	}
	
	//setMethods, do I really need this????
	
	public void setAnnualInterestRate(double annualInterestRate){
		this.annualInterestRate = annualInterestRate;
	}
	
	public void setNumberOfYears(int numberOfYears){
		this.numberOfYears = numberOfYears;
	}
	
	public void setLoanAmount(double loanAmount){
		this.loanAmount = loanAmount;
	}
	
	//monthly payment
	public double getMonthlyPayment(){
		double monthlyInterestRate = annualInterestRate / 1200;
		double monthlyPayment = loanAmount * monthlyInterestRate / (1 - (Math.pow(1 / (1 + monthlyInterestRate), numberOfYears * 12)));
		
		return monthlyPayment;
	}
	
	//find total payment
	public double getTotalPayment(){
		double totalPayment = getMonthlyPayment() * numberOfYears * 12;
		
		return totalPayment;
	}
	
	//return loan date
	
	public java.util.Date getLoanDate(){
		return loanDate;
	}
	
	
}






and

//pg 348 class abstraction

import java.util.Scanner;

public class TestLoan{

	public static void main(String[] args){
	
		Scanner input = new Scanner(System.in);
		
		System.out.println("Enter yearly interst rate, for example 8.25: ");
		double annualInterestRate = input.nextDouble();
		
		System.out.println("Enter number of years as an integer: ");
		int numberOfYears = input.nextInt();
		
		System.out.println("Enter loan amount, for example 12000.34: ");
		double loanAmount = input.nextDouble();
		
		//create a loan object
		Loan loan = new Loan(annualInterestRate, numberOfYears, loanAmount);
		
		//display loan date, monthly payment, total payment
		System.out.printf("The loan was created on %s\n" + 
		"The monthly payment is %.2f\nThe total payment is %.2f\n",
		loan.getLoanDate().toString(), loan.getMonthlyPayment(), 
		loan.getTotalPayment());
	
	}

}



Is This A Good Question/Topic? 0
  • +

Replies To: Can you omit setMethods if you have a constructor?

#2 IvGotAPocket  Icon User is offline

  • D.I.C Head

Reputation: 22
  • View blog
  • Posts: 131
  • Joined: 12-August 13

Re: Can you omit setMethods if you have a constructor?

Posted 13 August 2013 - 06:04 PM

I would say setters and getters are important to access of that method outside the class.. In that code i dont see him using any setters so it wouldnt matter if you deleted them ..but he is using the getters. If you want to change something outside the class without changing the original data you can just use a setMethod. Like say the interest rate changes..without having to go back through you code and change the value by calling the setter.
Was This Post Helpful? 1
  • +
  • -

#3 jon.kiparsky  Icon User is offline

  • Pancakes!
  • member icon


Reputation: 7564
  • View blog
  • Posts: 12,684
  • Joined: 19-March 11

Re: Can you omit setMethods if you have a constructor?

Posted 13 August 2013 - 06:31 PM

Since this code does not call the setters, omitting them did not cause an error. If you wanted to mutate loan object after the fact, then you'd need a setter.

This raises a design question - do you want the classes that utilize the Loan class to be able to alter the terms after the Loan has been created? Possibly not - under what circumstances would this happen?

Generally speaking, most classes don't want setters or getters at all. The object should be responsible for maintaining its own data - you want methods that ask it to take an action, you don't want to have to tell it how to take that action.
Was This Post Helpful? 2
  • +
  • -

#4 salazar  Icon User is offline

  • D.I.C Addict

Reputation: 87
  • View blog
  • Posts: 539
  • Joined: 26-June 13

Re: Can you omit setMethods if you have a constructor?

Posted 13 August 2013 - 06:34 PM

Setters are necessary as it is considered good practice to keep all variables private, with a few exceptions. Without setters there will be no way to change private variables. So I would keep them in their. That's probably why the author put it in. Even though it's not used and so will not effect the program if you remove them, you'll probably use setters again.
Was This Post Helpful? 0
  • +
  • -

#5 jon.kiparsky  Icon User is offline

  • Pancakes!
  • member icon


Reputation: 7564
  • View blog
  • Posts: 12,684
  • Joined: 19-March 11

Re: Can you omit setMethods if you have a constructor?

Posted 13 August 2013 - 06:55 PM

View Postsalazar, on 13 August 2013 - 08:34 PM, said:

Setters are necessary as it is considered good practice to keep all variables private, with a few exceptions. Without setters there will be no way to change private variables.


Well, if you have setters then your variables aren't all that private, are they? And why would you want to do that, anyway? Why would you want to allow someone to change your class's data?

Java is an object-oriented language. It's about passing messages to objects and asking them to modify their state accordingly, not about reaching in and changing their state for them.

This is a common mistake, and it's one that needs to be gotten rid of. Data-oriented programming requires tight coupling - when Foo modifies Bar's state, Foo has to know far too much about the implementation of Bar, details that Bar should be handling. If Bar then changes, Foo will need to change accordingly - and now you've got one class that's split into two files for no good reason. This can easily become spaghetti code, or else it can become the God Class anti-pattern.

The beauty of object-oriented programming is that you are always building a little model of the world, in which objects communicate to each other. Program that way - it's a lot nicer.
Was This Post Helpful? 2
  • +
  • -

#6 streek405  Icon User is offline

  • D.I.C Addict

Reputation: 10
  • View blog
  • Posts: 535
  • Joined: 10-March 13

Re: Can you omit setMethods if you have a constructor?

Posted 13 August 2013 - 06:59 PM

View Postjon.kiparsky, on 13 August 2013 - 06:31 PM, said:

Since this code does not call the setters, omitting them did not cause an error. If you wanted to mutate loan object after the fact, then you'd need a setter.

This raises a design question - do you want the classes that utilize the Loan class to be able to alter the terms after the Loan has been created? Possibly not - under what circumstances would this happen?

Generally speaking, most classes don't want setters or getters at all. The object should be responsible for maintaining its own data - you want methods that ask it to take an action, you don't want to have to tell it how to take that action.

Ok thanks, I think I understand it now.
Was This Post Helpful? 0
  • +
  • -

#7 salazar  Icon User is offline

  • D.I.C Addict

Reputation: 87
  • View blog
  • Posts: 539
  • Joined: 26-June 13

Re: Can you omit setMethods if you have a constructor?

Posted 13 August 2013 - 10:37 PM

View Postjon.kiparsky, on 13 August 2013 - 06:55 PM, said:

View Postsalazar, on 13 August 2013 - 08:34 PM, said:

Setters are necessary as it is considered good practice to keep all variables private, with a few exceptions. Without setters there will be no way to change private variables.


Well, if you have setters then your variables aren't all that private, are they? And why would you want to do that, anyway? Why would you want to allow someone to change your class's data?

Java is an object-oriented language. It's about passing messages to objects and asking them to modify their state accordingly, not about reaching in and changing their state for them.

This is a common mistake, and it's one that needs to be gotten rid of. Data-oriented programming requires tight coupling - when Foo modifies Bar's state, Foo has to know far too much about the implementation of Bar, details that Bar should be handling. If Bar then changes, Foo will need to change accordingly - and now you've got one class that's split into two files for no good reason. This can easily become spaghetti code, or else it can become the God Class anti-pattern.

The beauty of object-oriented programming is that you are always building a little model of the world, in which objects communicate to each other. Program that way - it's a lot nicer.


If setters are so bad then why are they used so often? And how does an object manage its own state? Isn't that what setters do already? They send "messages" to the object. I was taught that instead of access a member datum directly, you send it a setter method to change it. I'm a little confused. Would you mine showing how this would work using the code above?

This post has been edited by salazar: 13 August 2013 - 10:38 PM

Was This Post Helpful? 0
  • +
  • -

#8 jon.kiparsky  Icon User is offline

  • Pancakes!
  • member icon


Reputation: 7564
  • View blog
  • Posts: 12,684
  • Joined: 19-March 11

Re: Can you omit setMethods if you have a constructor?

Posted 13 August 2013 - 11:31 PM

Quote

If setters are so bad then why are they used so often?


Are they? I know they're often a part of student code because they're one of the first things you learn to write, and I know that a lot of amateurs using Eclipse or NetBeans will let the IDE generate the getters and setters for them - not thinking at all about what they're doing - but I'm not sure they're really all that common in real world code.

You do come across mutator methods in container classes. Anything whose job is to hold an arbitrary value or an arbitrary object will of course have a setter - that's what those classes are for. But state data? I don't think so.

Quote

And how does an object manage its own state? Isn't that what setters do already? They send "messages" to the object. I was taught that instead of access a member datum directly, you send it a setter method to change it. I'm a little confused.


Presumably the point was that you would have some bounds checking and such like and that's why it's better to have a setter than just a bare public field. And that's true - it's better to be able to reject values that are out of bounds or to log the transaction that sets the value, or otherwise to control the transaction - but the assumption that you'd like other people to change the value needs to be reconsidered.


Quote

Would you mine showing how this would work using the code above?


Let's imagine what you want to do with a Loan object. You create it, and you register payments to it, and you occasionally ask it to tell you things - how much is owed, what will the loan look like if I pay so much per month, how much per month must I pay to get this thing cleared out in some particular time frame, and so forth. Perhaps it knows how to issue a statement (which might include some of the above information).

I honestly can't think of a realistic circumstance where you'd want to change any of the parameters after setting up the loan - that doesn't seem to be a normal thing to do. As I recall from my days in banking, you wouldn't change the terms of a loan, you'd actually close out the old loan and create a new one. This is actually a lot simpler in terms of auditing, and that's very important here.

But if you can come up with a scenario where I'd want to allow mutation of the parameters of the loan, I can tell you how I'd implement that scenario.

This post has been edited by jon.kiparsky: 13 August 2013 - 11:32 PM

Was This Post Helpful? 2
  • +
  • -

#9 salazar  Icon User is offline

  • D.I.C Addict

Reputation: 87
  • View blog
  • Posts: 539
  • Joined: 26-June 13

Re: Can you omit setMethods if you have a constructor?

Posted 14 August 2013 - 01:23 AM

View Postjon.kiparsky, on 13 August 2013 - 11:31 PM, said:

Quote

If setters are so bad then why are they used so often?


Are they? I know they're often a part of student code because they're one of the first things you learn to write, and I know that a lot of amateurs using Eclipse or NetBeans will let the IDE generate the getters and setters for them - not thinking at all about what they're doing - but I'm not sure they're really all that common in real world code.

You do come across mutator methods in container classes. Anything whose job is to hold an arbitrary value or an arbitrary object will of course have a setter - that's what those classes are for. But state data? I don't think so.

Quote

And how does an object manage its own state? Isn't that what setters do already? They send "messages" to the object. I was taught that instead of access a member datum directly, you send it a setter method to change it. I'm a little confused.


Presumably the point was that you would have some bounds checking and such like and that's why it's better to have a setter than just a bare public field. And that's true - it's better to be able to reject values that are out of bounds or to log the transaction that sets the value, or otherwise to control the transaction - but the assumption that you'd like other people to change the value needs to be reconsidered.


Quote

Would you mine showing how this would work using the code above?


Let's imagine what you want to do with a Loan object. You create it, and you register payments to it, and you occasionally ask it to tell you things - how much is owed, what will the loan look like if I pay so much per month, how much per month must I pay to get this thing cleared out in some particular time frame, and so forth. Perhaps it knows how to issue a statement (which might include some of the above information).

I honestly can't think of a realistic circumstance where you'd want to change any of the parameters after setting up the loan - that doesn't seem to be a normal thing to do. As I recall from my days in banking, you wouldn't change the terms of a loan, you'd actually close out the old loan and create a new one. This is actually a lot simpler in terms of auditing, and that's very important here.

But if you can come up with a scenario where I'd want to allow mutation of the parameters of the loan, I can tell you how I'd implement that scenario.



Okay, thanks, I understand what your're saying. It makes sense. I actually do have a scenario for you. What if you wanted to use the Loan object more than once? Wouldn't you have to instantiate another object?
Was This Post Helpful? 0
  • +
  • -

#10 cfoley  Icon User is offline

  • Cabbage
  • member icon

Reputation: 1939
  • View blog
  • Posts: 4,027
  • Joined: 11-December 07

Re: Can you omit setMethods if you have a constructor?

Posted 14 August 2013 - 01:31 AM

Quote

If setters are so bad then why are they used so often?


Because code is often poorly designed?

Let's not get carried away here. Setters are sometimes necessary and I bet even jon.kiparsky writes them from time to time. The problem is when people cannot imagine a different way to mutate state.

Why would you want to mutate a loan? It could be a pay-day-loan application with sliders that let you choose just how quickly you would like to spiral into debt. There are clearly options here. You could have setters or you could just create a new Loan object every time the slider moves or you could have a mutable LoanBuilder class that creates an immutable Loan object when the user has made his mind up.

Which you choose depends on how you anticipate the program might evolve in the future.
Was This Post Helpful? 2
  • +
  • -

#11 jon.kiparsky  Icon User is offline

  • Pancakes!
  • member icon


Reputation: 7564
  • View blog
  • Posts: 12,684
  • Joined: 19-March 11

Re: Can you omit setMethods if you have a constructor?

Posted 14 August 2013 - 01:40 AM

Well, yes, you'd instantiate a new object. Why would that be an issue?
Was This Post Helpful? 1
  • +
  • -

#12 salazar  Icon User is offline

  • D.I.C Addict

Reputation: 87
  • View blog
  • Posts: 539
  • Joined: 26-June 13

Re: Can you omit setMethods if you have a constructor?

Posted 14 August 2013 - 01:49 AM

View Postjon.kiparsky, on 14 August 2013 - 01:40 AM, said:

Well, yes, you'd instantiate a new object. Why would that be an issue?


Your right, I guess it wouldn't be an issue. I felt there might be, then I thought about what you said about a Loan. If a loan really represents a loan object. You wouldn't change it. Thanks.

This post has been edited by salazar: 14 August 2013 - 01:50 AM

Was This Post Helpful? 0
  • +
  • -

#13 jon.kiparsky  Icon User is offline

  • Pancakes!
  • member icon


Reputation: 7564
  • View blog
  • Posts: 12,684
  • Joined: 19-March 11

Re: Can you omit setMethods if you have a constructor?

Posted 14 August 2013 - 01:52 AM

View Postcfoley, on 14 August 2013 - 03:31 AM, said:

Let's not get carried away here. Setters are sometimes necessary and I bet even jon.kiparsky writes them from time to time.

Indeed. As you say, I'm taking issue with the idea that setters are essential - they're not. However, they do have their uses, and that's when you use them.

Quote

The problem is when people cannot imagine a different way to mutate state.


Exactly this. And more than this: when people don't get that you shouldn't be thinking about the other object's state. If you are, you've lost the game. You should be thinking about asking that object to do its work on your behalf.

Quote

Why would you want to mutate a loan? It could be a pay-day-loan application with sliders that let you choose just how quickly you would like to spiral into debt. There are clearly options here. You could have setters or you could just create a new Loan object every time the slider moves or you could have a mutable LoanBuilder class that creates an immutable Loan object when the user has made his mind up.



Is this a Loan, or is it a LoanApplication, or is it a LoanCalculator? I can imagine a LoanCalculator that generates a LoanApplication, which would ultimately spit out a Loan, assuming all goes well. But of course, once the Loan exists, you don't get to play with the sliders any more, do you? You just get to decide the amount of your next payment.
Was This Post Helpful? 2
  • +
  • -

#14 salazar  Icon User is offline

  • D.I.C Addict

Reputation: 87
  • View blog
  • Posts: 539
  • Joined: 26-June 13

Re: Can you omit setMethods if you have a constructor?

Posted 14 August 2013 - 01:56 AM

View Postcfoley, on 14 August 2013 - 01:31 AM, said:

Quote

If setters are so bad then why are they used so often?


Because code is often poorly designed?

Let's not get carried away here. Setters are sometimes necessary and I bet even jon.kiparsky writes them from time to time. The problem is when people cannot imagine a different way to mutate state.

Why would you want to mutate a loan? It could be a pay-day-loan application with sliders that let you choose just how quickly you would like to spiral into debt. There are clearly options here. You could have setters or you could just create a new Loan object every time the slider moves or you could have a mutable LoanBuilder class that creates an immutable Loan object when the user has made his mind up.

Which you choose depends on how you anticipate the program might evolve in the future.


Thanks, good example of a problem of not using setters even though they may be needed.

This post has been edited by salazar: 14 August 2013 - 01:58 AM

Was This Post Helpful? 0
  • +
  • -

#15 jon.kiparsky  Icon User is offline

  • Pancakes!
  • member icon


Reputation: 7564
  • View blog
  • Posts: 12,684
  • Joined: 19-March 11

Re: Can you omit setMethods if you have a constructor?

Posted 14 August 2013 - 02:02 AM

Thinking about it, wouldn't you be registering a Listener on the sliders in that case?
Was This Post Helpful? 1
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2