Choosing appropriate name for methods in Java - java

I am a little bit confused about something and I would appreciated it if you all can bring some clarity to this. I have a class payment which has some methods and getter/setters.
Do I for example use the method ItemCost to return the valve of attribute itemCost or do I use a getter?
public class Payment {
private int itemCost, totalCost;
public int itemCost(int itemQuantity, int itemPrice){
itemCost = itemPrice * itemQuantity;
return itemCost;
}
public int totalCost(BigDecimal itemPrice){
totalCost = totalCost + itemCost;
return totalCost;
}
public int getBalance(int clickValue, int totalCost){
totalCost = totalCost - clickValue;
return totalCost;
}
public int getTotalcost(){
return this.totalCost;
}
public void setTotalcost(int totalCost){
this.totalCost = totalCost;
}
public int getItemcost(){
return this.itemCost;
}
public void setItemcost(int itemCost){
this.itemCost = itemCost;
}
}
ok so instead of instantiating:
int cost = payment.itemCost(quantity, itemPrice) in another class
DO: payment.itemCost(quantity, itemPrice)
payment.getItemcost
?
Edit 2: Would making all the methods return void and just use the getters be better coding?
public class Payment {
private int itemCost, totalCost;
public void calculateItemcost(int itemQuantity, int itemPrice){
itemCost = itemPrice * itemQuantity;
}
public void calculateTotalCost(BigDecimal itemPrice){
this.totalCost = totalCost + itemCost;
}
public void calculateBalance(int clickValue, int totalCost){
this.totalCost = totalCost - clickValue;
}
public int getTotalcost(){
return this.totalCost;
}
public void setTotalcost(int totalCost){
this.totalCost = totalCost;
}
public int getItemcost(){
return this.itemCost;
}
public void setItemcost(int itemCost){
this.itemCost = itemCost;
}
}

getter/setters are for the purpose of setting value to particular attribute in object and getting same from the object, this way you can define attributes as private and enforce encapsulation (One of the OO principles) .
When you are doing any calculations (or) business logic, its always better to use appropriate operation name instead get/set.
EDIT:
As neel commented, Its always suggested to leave POJO as simple beans instead of stuffing in business logic/calculations. You may have another class with business logic and use get/setter to get values from POJO while doing calculations.

At the moment you have 2 methods that can set itemCost.
public void setItemcost(int itemCost){
this.itemCost = itemCost;
}
public int itemCost(int itemQuantity, int itemPrice){
itemCost = itemPrice * itemQuantity;
return itemCost;
}
Ideally you would have one setting method but if you want the class to work like this I would suggest making both of these methods return void and use getItemCost to get the value.

Generally, it should be possible to understand what your method is supposed to do just from the name of your method.
So, you should use getters and setters only if you want to return or set the property of your class. That way your code looks more readable, and the name of the methods clearly states what it would do.
But, if your method is not returning the exact property, but a returning the result of some calculation, then you should name your method accordingly.
For E.g: - If your method returns the cost as a calculation on some property of your class, then name that method as calculateCost. It makes more sense.
PS: -
Remember, your code would me maintained for more number of time, than you took it to create. Code for others to understand, not for yourself to understand.

Related

How to test a private method when anonymous class return in TestNG

I need to test getPrice() method in StockPrice class by using TestNG. and cover the lines inside the priceCalculator() method
public class StockPrice {
public double getPrice(){
Stock stock = getStock();
return finalPrice(stock,1000,true);
}
private double finalPrice(Stock stock, int price, boolean isDiscountAvailable){
return stock.priceCalculator(price,isDiscountAvailable)-100;
}
private Stock getStock(){
return new Stock()
{
#Override
public double priceCalculator(int price, boolean isDiscountAvailable)
{
if (isDiscountAvailable){
return price-price/10;
}else {
return price;
}
}
};
}
}
interface Stock{
double priceCalculator(int price, boolean isDiscountAvailable);
}
I tried to cover the lines inside the 1 priceCalculator() method in several ways but did not succeed due to the following reasons
getStock() method is a private method so cannot access it. I tried with using reflections to access it but got java.lang.NoSuchMethodException:
getStock() returns and Annonymous object. Then cannot cover the lines priceCalculator() method
can you give me a solution to cover the lines in the priceCalculatormethod.
in summary, I need to cover the following code.
#Override
public double priceCalculator(int price, boolean isDiscountAvailable)
{
if (isDiscountAvailable){
return price-price/10;
}else {
return price;
}
}
Test it through public method.
Stock class doesn't access any external and slow resources, so you need to mock nothing.
#Test
public void getPrice_returns_expected_price() {
StockPrice stockPrice = new StockPrice();
double actual = stockPrice.getPrice();
assertEquals(800, actual);
}

How do you return the total value of two methods that each take in a value?

My teacher wanted us to create program to compute the bills of our home. In java we were just going over objects and classes so I made
class Bills{
Bills... etc
The problem I am having is I dont know how to get a total of two methods that take in a value.
public double getWifepay(double x){
return x;
}
public double getHusbandpay(double y){
return y;
}
public double getTotalmoney(){
???
}
Your methods should probably just return some value that is stored within the object. So you would have something like:
public double getWifePay(){
return wifePay;
}
public double getHusbandPay(){
return husbandPay;
}
And
public double getTotalmoney(){
return getWifePay() + getHusbandPay();
}
and then you probably would want to write some setter methods like:
public void setWifePay(double wifePay) {
this.wifePay = wifePay;
}
public void setHusbandPay(double husbandPay) {
this.husbandPay = husbandPay;
}
And in your class definition you should have declared these fields:
public class Bills {
double wifePay;
double husbandPay;
// And then the methods from above
}
Create the previous two method (getwifepay, gethusbandpay) as static and call them in getTotalmoney function with class name. suppose class name is A so call as A.getwifePay(value)
Not sure I understand your model classes, but as you mention, for the "getTotalMoney" method to return the sum, the elements (the numbers in this case) should be given as parameters.
On the other hand, your "getWifepay" and "getHusbandpay" methods don't make much sense, as they are returning the same parameter which is given.
With all of this, you would need to have the method "getTotalmoney" call the other two and then make the sum, like this:
public double getWifepay(){
return x;
}
public double getHusbandpay(){
return y;
}
public double getTotalmoney(){
getWifepay() + getHusbandpay();
}
Finally, I suppose that these methods are within a given class (you mentioned Bill), making it maybe something like this:
class Bill {
private double x;
private double y;
private double getWifepay(){
return x;
}
private double getHusbandpay(){
return y;
}
public double getTotalmoney(){
getWifepay() + getHusbandpay();
}
}
Hope that solves your problem.

How do i perform a calculation within a setter method in java?

I have two classes within a java project, one is the Employee1 class and the other is the info class. Within the Employee 1 class I have this code:
public class Employee1 {
String employeeName;
int hoursWorked;
double rateOfPay;
double wages;
public Employee1(String name, int hours, double pay) {
employeeName=name;
hoursWorked=hours;
rateOfPay=pay;
}
public String getName() {
return employeeName;
}
public void setName(String xName) {
employeeName = xName;
}
public double getHours() {
return hoursWorked;
}
public void setHours(int xHours) {
hoursWorked = xHours;
}
public double getPay() {
return rateOfPay;
}
public void setPay(double xPay) {
rateOfPay = xPay;
}
public double calculateWages () {
wages= hoursWorked * rateOfPay;
return wages;
}
public void print() {
System.out.println("name:"+ employeeName);
System.out.println("hours " + hoursWorked);
System.out.println("Wages Earned"+ wages);
}
}
Within my info class I have this code:
public class Info {
public static void main(String[] args) {
Employee1 x= new Employee1("Sarah",40,7.25);
Employee1 y=new Employee1("Bob",30,8.00);
Employee1 z= new Employee1("Todd",26, 8.25);
x.print();
}
}
My problem right now is that I am attempting to create a calculation for wages within my Employee1 class as you can see with my calculateWages method. However, whenever I call my print method for my existing employee x the wages always come out to be 0.0 and I am unsure why this is happening. I have preexisting variables for each of my Employee1 objects and I am still getting a 0.0 value for all of their wages but the rest of their information is printed correctly. Can anyone help me with this issue? Thank you!
In the code you provide there is not a setter method, instead there is a getter one. And yes, you can made calculation in both, getter and setter.
public void setAmount(int amount){
this.amount = quantity * price;
}
public void getAmount(){
return this.amount + otherProperty;
}
Lets start with this:
I'm new to programming but I know that this type of method is known as a setter.
No it isn't.
In OO, the code (mostly) consists of classes which consist of state (fields) and methods that (typically) operate on that state.
By convention ...
A setter is a method that sets a field to a new value provided as a method argument.
A getter is a method that returns the value of a field.
Your method is neither a setter or a (pure) getter:
It is not a setter because it doesn't set wages to a supplied value. (It is doing the calculation based on previously supplied values.)
You could view it as a getter for the wages field, but it is "impure" in that it updates the field as well as returning its value.
Every time I go to print out the "wages" variable it just gives me a zero and nothing else, I have the other variables hoursWorked & rateOfPay defined in the main
We cannot explain this without seeing the rest of your code. However, I suspect that the problem is one of the following:
Either of hoursWorked or rateOfPay is zero ... because they are not being correctly set / initialized to non-zero values.
The calculateWages method is not being called.
You have multiple instances of the class that defined this method ... and your code is looking at the wrong one.
Possibly ... some of the variables involved have been incorrectly declared as static.s
UPDATE - Now that I see your code, the reason that wages is zero is that your code doesn't call calculateWages.
You can pass those values to the calculateWages () method.
Try this
public double calculateWages (int hoursWorked, double rateOfPay) {
return hoursWorked * rateOfPay;
}
In the best practice of OOP your method should have two arguments:
e.g.
public class Answer1 {
public static double calculateWages (int hoursWorked, double rateOfPay){
return hoursWorked * rateOfPay;
}
public static void main(String[] args) {
System.out.println(calculateWages(6, 5.24));
}
}
You may want to simplify this by creating a class, outside of the main class with the main method, that does this ONE specific job of calculating a wage. We call this "isolation" in programming, and we want to isolate one class from another and make sure each class only does one particular job. Here is an example of a class that will get the total wage:
public class WagesCalc {
public static double calculateWages(int hoursWorked, double hourlyWage) {
double wage = (double)hoursWorked * hourlyWage;
return wage;
}
}
In the code above we can create a class that calculates the wages called WagesCalc. Within it, we can create a method called calculate wages. You can add hours worked, and the hourly wage as the arguments for the class. We then add a variable, and then return an the wage. We make this method static so that we can return it without an instance of the class being created. Here is the code in the main method:
public class App {
public static void main( String[] args )throws IOException{
double wages = WagesCalc.calculateWages(23, 23.50);
System.out.println("My total wage is $" + wages);
}
}
And here is the output:
My total wage is $540.5

Applying two different sets of interest rates to two objects of the same class

How can I make two objects of the same class use different interest rates?
I need to make it so that savingAccount2 and savingAccount3 use different interest rates.
savingAccount1UI savingAccount2 = new savingAccount1UI();
savingAccount1UI savingAccount3 = new savingAccount1UI();
These objects both inherit from a class called Account.java. This superclass contains all the methods that include how to calculate the interest.
Here is the current method in the superclass that calculates the 1 year interest account.java:
//add interest
public void interest(double interest){
if(balance<target){
interest = balance*lowRate;
balance = balance + interest;
updatebalance();
} else{
interest=balance*highRate;
balance = balance + interest;
}
updatebalance();
}
Here is the button that triggers this method:
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
interest(Float.parseFloat(balanceLabel.getText().substring(1)));
Currently I am using variables with double values assigned to them, but of course this means that both objects(savingAccount2 and savingAccount3) use the same numbers. Note that these variables are stored in the Account.java superclass Like so:
public double lowRate = 0.019;
public double highRate = 0.025;
I think I may need to use a constructor for each object, with pre-set values to solve my issue but I don't understand how to implement that idea. Any suggestions?
You can write method in class Account to set the values of lowRate and highRate like:
public void setRates(double lr, double hr){
lowRate=lr;
highRate=hr;
}
Now when you create an object of class SavingsAccount, you can do:
SavingsAccount sa=new SavingsAccount();
sa.setRates(0.019,0.025);
Just do it:
savingAccount1UI savingAccount2 = new savingAccount1UI(0.019,0.025);
in class definition:
savingAccount1UI(float lowRate,float highRate) {
this.lowRate = lowRate;
this.highRate = highRate;
}
when computing pass also the class to the method and access the inners value.
public void interest(double interest,savingAccount1UI account){
if(balance<target){
interest = balance*account.lowRate;
balance = balance + interest;
updatebalance();
} else{
interest=balance*account.highRate;
balance = balance + interest;
}
updatebalance();
}
It seems you are looking for this:
public class Account {
private double lowRate;
private double highRate;
//other fields
public Acount(double lowRate, double highRate) {
this.lowRate = lowRate;
this.highRate = highRate;
}
// your interest() method
// getters & setters
}
public class SavingAccount1UI extends Account {
public SavingAccount1UI(double lowRate, double highRate) {
super(lowRate, highRate);
}
// rest of your stuff
}
This way you are only able to create an object passing the values you need, like:
SavingAccount1UI savingAccount = new SavingAccount1UI(0.019, 0.025);
Now every time you call your interest() method, it will take into consideration the values passed.

Price value not being passed using an interface Java Observer Pattern

On my course I am learning the different development patterns and the problem i am stuck with is an implementation of the Observer Pattern [1]: http://www.oodesign.com/observer-pattern.html, and them problem i am having is passing a value from the subject, that has been set using a JUnit test, to the observer to it can buy/sell a number of shares. My main question is: What's the problem i am not seeing? and a secondary question: Would my buying/selling of shares code work? if doesn't work, please don't post a solution to the 2nd as i would like to fix atleast one bit myself.
Interface:
public interface ShareWatcher {
public void updatePrice(double price);}
Subject:
public class Share{
public double price = 1.00;
ArrayList<ShareWatcher> list = new ArrayList<ShareWatcher>();
public double getPrice() {
return price;
}
public boolean addShareWatcher(StockBroker stockBroker) {
boolean result;
if(!list.contains(stockBroker)){
list.add(stockBroker);
result = true;
}else{
result = false;
}
return result;
}
public boolean removeShareWatcher(StockBroker stockBroker) {
boolean result;
if(list.contains(stockBroker)){
list.remove(stockBroker);
result = true;
}else{
result = false;
}
return result;
}
}
Observer:
public class StockBroker implements ShareWatcher{
Share share = new Share();
public int portfolio ;
double price;
double buy, sell;
public int increment;
public StockBroker(double SB_BUY, double SB_SELL, int SB_INCREMENT) {
this.buy = SB_BUY;
this.sell = SB_SELL;
this.increment = SB_INCREMENT;
System.out.println(buy + "" + sell + "" + increment);
}
#Override
public void updatePrice(double price) {
this.price = share.getPrice();
}
public int getPortfolio() {
while (price > 2 && price < 2){
if(price < buy){
portfolio = portfolio + increment;
System.out.println("SB2 " + portfolio);
}else if(price > sell){
portfolio = portfolio - increment;
}
}
return portfolio;
}
}
and not sure if this would be needed on here, if not feel free to edit out, but the JUnit Test:
public void testChangePrice1() {
final Share share = new Share();
final StockBroker stockBroker = new StockBroker(SB_BUY, SB_SELL, SB_INCREMENT);
assertTrue(share.addShareWatcher(stockBroker));
share.setPrice(PRICE5);
final int expectedValue2 = 500;
assertEquals(expectedValue2, stockBroker.getPortfolio());
}
To me it seems that you are not understanding that the observer pattern is basically about a CALLBACK after a certain event.
Meaning: the observers can register themselves somewhere; in your terms, they would be using the addShareWatcher() method of Subject.
Then, when for some reason the price is changed, Subject should iterate its list of ShareWatchers ... and invoke "updatePrice()" on each of the objects.
Side note: of course this is just example code; but keep in mind that you should not use ordinary "double" values that represent currency (see http://www.javapractices.com/topic/TopicAction.do?Id=13 on alternatives).

Categories