Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[2주차] 객체 지향 코드 연습(qwejiung) #14

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions Week2/Account.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package Week2;

import java.math.BigDecimal;

public interface Account { //
String getAccountInfo();
void withdraw(BigDecimal value);
void deposit(BigDecimal value);
String getAccountNumber();
AccountType getAccountType();
BigDecimal getBalance();
void eraseStringBuilder();

// void setBalance(BigDecimal balance);
KoSeonJe marked this conversation as resolved.
Show resolved Hide resolved
}
15 changes: 15 additions & 0 deletions Week2/AccountType.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package Week2;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.RequiredArgsConstructor;

@Getter
//@RequiredArgsConstructor
@AllArgsConstructor
KoSeonJe marked this conversation as resolved.
Show resolved Hide resolved
public enum AccountType {
NORMAL_ACCOUNT("예금 계좌"),
SAVING_ACCOUNT("적금 계좌");

private final String accountName;
}
118 changes: 118 additions & 0 deletions Week2/Bank.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
package Week2;

import java.util.*;
import java.math.BigDecimal;
// 계좌생성, 출금, 입금, 송금 메서드 구현
// 내부에서 입력을 받는 액션?
// 적금 계좌는
public class Bank {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bank클래스가 두개이신데 사용하지 않으시면 삭제하는 것이 좋습니다

private ArrayList<Account> accountArray;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

자료구조를 직접 변수명으로 만드는 것은 좋지 않습니다. 아래와 같이 변경하는 것은 어떨까요?

Suggested change
private ArrayList<Account> accountArray;
private ArrayList<Account> accounts;

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
private ArrayList<Account> accountArray;
private final ArrayList<Account> accountArray = new ArrayList<>();

가독성과 코드 중복 방지를 위해 필드에서 초기화 하는 것이 좋습니다.
예를 들어 여러 개의 생성자를 만들 경우, 각 생성자 마다 초기화 해야하는 코드 중복이 발생합니다
final 키워드를 사용해 변경되지 않을 인스턴스라는 것을 명시해야 합니다.

private HashMap<AccountType, InterestCalculator> interestCalculator;

public Bank(){
this.accountArray = new ArrayList<>();
this.interestCalculator = new HashMap<>();
this.interestCalculator.put(AccountType.NORMAL_ACCOUNT, new NormalInterestCalculator());
this.interestCalculator.put(AccountType.SAVING_ACCOUNT, new SavingInterestCalculator());
}

// 계좌생성
// 한 메소드안에 NORMAL과 SAVING을 같이 넣을려했지만 매개변수 이슈로 나눔
public void createAccount(AccountType accountType, String accountNumber, String owner,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

메소드명을 더 구체적으로 작성해야 할 것 같습니다.
어떤 Account를 생성하는지 명시해줘야 합니다.

Suggested change
public void createAccount(AccountType accountType, String accountNumber, String owner,
public void createBasicAccount(AccountType accountType, String accountNumber, String owner,

BigDecimal balance, boolean isActivated ){

BasicAccount account = new BasicAccount(accountType, accountNumber, owner, balance, isActivated);
accountArray.add(account);

}
public void createAccount(AccountType accountType, String accountNumber, String owner,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
public void createAccount(AccountType accountType, String accountNumber, String owner,
public void createSavingAccount(AccountType accountType, String accountNumber, String owner,

BigDecimal balance, boolean isActivated,String targetAmount ){

SavingAccount account = new SavingAccount(accountType, accountNumber, owner, balance, isActivated, targetAmount);
accountArray.add(account);
}

// 입금
public void deposit(String accountNumber, BigDecimal money){

for (int i = 0; i < accountArray.size(); i++){
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

자바 Stream을 사용하는 것이 가독성 부분에서 훨씬 좋습니다.
Stream에 대해 공부해보시고 적용해보세요

// System.out.println(i);
if( accountArray.get(i).getAccountNumber().equals(accountNumber)) {
accountArray.get(i).deposit(money);
break;
}
if( i == accountArray.size()-1){
System.out.println(accountNumber+"계좌 없음");
}
}

}
// 출금
public void withdraw(String accountNumber, BigDecimal money){
for (int i = 0; i < accountArray.size(); i++){
if( accountArray.get(i).getAccountNumber().equals(accountNumber)) {
accountArray.get(i).withdraw(money);
break;
}
if( i == accountArray.size()-1){
System.out.println(accountNumber+"계좌 없음");
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

예외를 발생시켜 처리해주는 것이 좋습니다

}
}

}
// 송금
public void remittance(String accountNumber, String targetAccountNumber,BigDecimal money){
int Switch = 0;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
int Switch = 0;
int switch = 0;

for (int i = 0; i < accountArray.size(); i++){
if( accountArray.get(i).getAccountNumber().equals(accountNumber)) {
accountArray.get(i).withdraw(money);
}
for (int j = 0; j < accountArray.size(); j++){
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

반복문이 중첩되는 것은 수행 시간이 길어지고 곧 성능이 저하되는 것을 의미합니다.
가독성도 좋지 않기 때문에 다른 방법, 메소드 분리를 해주세요.
ex) 계좌 찾는 메소드 실행 -> 찾은 계좌 입금 및 출금

if( accountArray.get(j).getAccountNumber().equals(targetAccountNumber)) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if( accountArray.get(j).getAccountNumber().equals(targetAccountNumber)) {
if(accountArray.get(j).getAccountNumber().equals(targetAccountNumber)) {

accountArray.get(j).deposit(money);
Switch = 1;
break;
}
}
if (Switch == 1)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

코드 컨벤션을 지킴으로써 가독성을 높여야 합니다
if문 안에 한 줄의 코드라도 괄호로 감싸주는 것을 추천드립니다

break;


}
}

public void getAccountInfo(String accountNumber){

for (int i = 0; i < accountArray.size(); i++){
if( accountArray.get(i).getAccountNumber().equals(accountNumber)) {
System.out.println(accountArray.get(i).getAccountInfo());
System.out.println();
accountArray.get(i).eraseStringBuilder();
break;
}
if( i == accountArray.size()-1){
System.out.println(accountNumber+"계좌 없음");
}
}
}

// 이자금액 반환
// 계좌번호로 NORMAL인지 SAVING인지 확인
// 확인 후 Type에 맞는 Hashmap 메소드 사용
public void getInterest(String accountNumber){

for (int i = 0; i < accountArray.size(); i++){
if( accountArray.get(i).getAccountNumber().equals(accountNumber)) {
if( accountArray.get(i).getAccountType().equals(AccountType.NORMAL_ACCOUNT) ){
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

반복문과 가정문이 3번 중첩되었는데, 가독성 측면에서 매우 좋지 않습니다.
메소드를 분리해주세요.
거의 대부분의 경우 1depth(1번사용)로 해결이 가능합니다.

System.out.println("이자금액 : " + this.interestCalculator.get(AccountType.NORMAL_ACCOUNT).getInterest(accountArray.get(i).getBalance()));
} else if( accountArray.get(i).getAccountType().equals(AccountType.SAVING_ACCOUNT) ){
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

else if보다 early return 패턴을 찾아보시고 사용하는 것이 좋습니다

System.out.println("이자금액 : " + this.interestCalculator.get(AccountType.SAVING_ACCOUNT).getInterest(accountArray.get(i).getBalance()));
}
}
}

}



}
34 changes: 34 additions & 0 deletions Week2/BankingApplication.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package Week2;

import java.math.BigDecimal;

public class BankingApplication {

public static void main(String[] args) {

Bank bank = new Bank();

// AccountType accountType, String accountNumber, String owner,
// BigDecimal balance, boolean isActivated,String targetAmount
bank.createAccount(AccountType.NORMAL_ACCOUNT,"123123", "김지웅", BigDecimal.valueOf(150),true);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

사용자는 데이터를 직접 입력할 수 없는 것인가요?
사용자가 입력할 수 있도록 해야 할 것 같습니다

bank.withdraw("123123",BigDecimal.valueOf(30));
bank.deposit("123123",BigDecimal.valueOf(10));
bank.getAccountInfo("123123");


Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

한 칸만 줄바꿈 하는 것이 좋습니다

bank.createAccount(AccountType.SAVING_ACCOUNT,"321321", "김지웅", BigDecimal.valueOf(200),true, "500");
bank.withdraw("321321",BigDecimal.valueOf(30));
bank.deposit("321321",BigDecimal.valueOf(50));
bank.getAccountInfo("321321");



bank.getInterest("123123");

bank.remittance("123123","321321",BigDecimal.TEN);

bank.getAccountInfo("123123");
bank.getAccountInfo("321321");

}
}
62 changes: 62 additions & 0 deletions Week2/BasicAccount.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package Week2;

import java.math.BigDecimal;

import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;

@Getter
@Builder
@AllArgsConstructor(access = AccessLevel.PROTECTED) // 접근 지정자 변경
public class BasicAccount implements Account {

private final StringBuilder stringBuilder;

private AccountType accountType; // 계좌 종류

private String accountNumber; // 계좌번호

private String owner; // 소유자

private BigDecimal balance; // 잔액

private boolean isActivated; // 활성화 여부


public BasicAccount(AccountType accountType, String accountNumber, String owner, BigDecimal balance, boolean isActivated) {
this.stringBuilder = new StringBuilder();
this.accountType = accountType;
this.accountNumber = accountNumber;
this.owner = owner;
this.balance = balance;
this.isActivated = isActivated;
}
public String getAccountInfo() {
stringBuilder.append("[계좌 정보]").append("\n");
stringBuilder.append("계좌종류: ").append(accountType.getAccountName()).append("\n");
stringBuilder.append("계좌번호: ").append(getAccountNumber()).append("\n");
stringBuilder.append("소유자: ").append(getOwner()).append("\n");
stringBuilder.append("잔액: ").append(getBalance()).append("\n");
stringBuilder.append("활성여부: ").append(isActivated());
return stringBuilder.toString();
}
public void eraseStringBuilder(){
this.stringBuilder.setLength(0);
}
// public AccountType getAccountType() { return accountType;}
public void setBalance(BigDecimal balance) { this.balance = balance;}

public void withdraw(BigDecimal value) {
setBalance(balance.subtract((value)));
// this.balance=this.balance.subtract(value);
// System.out.println("withdraw"+getBalance());
}

public void deposit(BigDecimal value) {
this.balance=this.balance.add(value);
// System.out.println("deposit"+this.getBalance());
}

}
10 changes: 10 additions & 0 deletions Week2/InterestCalculator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package Week2;

import java.math.BigDecimal;
public interface InterestCalculator {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

인터페이스가 두 개 입니다..


BigDecimal getInterest(BigDecimal balance); // 계좌 잔액에 대한 이자금액 반환



}
23 changes: 23 additions & 0 deletions Week2/NormalInterestCalculator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package Week2;

import java.math.BigDecimal;

public class NormalInterestCalculator implements InterestCalculator{

// 1000만원이상은 이자율 50%, 500만원 이상은 7%, 100만원 이상은 4%, 1만원 이상은 2%, 그 외에는 1%
public BigDecimal getInterest(BigDecimal balance){ // 계좌 잔액에 대한 이자금액 반환

if( balance.compareTo(BigDecimal.valueOf(1000)) >= 0 )
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1000은 어떤 숫자를 의미하는 것인가요? 또한 0은??
상수를 구체적으로 설명해주는 변수 선언이 필요할 것 같습니다

return balance.multiply(BigDecimal.valueOf(0.5));
else if ( balance.compareTo(BigDecimal.valueOf(500)) >= 0)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

else if 를 반복해서 사용하는 것은 매우 좋지 않은 방법입니다.
Switch문을 사용해보세요. Enum클래스를 활용하는 방법도 있습니다!

return balance.multiply(BigDecimal.valueOf(0.07));
else if ( balance.compareTo(BigDecimal.valueOf(100)) >= 0)
return balance.multiply(BigDecimal.valueOf(0.04));
else if( balance.compareTo(BigDecimal.ONE) >= 0)
return balance.multiply(BigDecimal.valueOf(0.02));
else
return balance.multiply(BigDecimal.valueOf(0.01));

}

}
41 changes: 41 additions & 0 deletions Week2/SavingAccount.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package Week2;

// TODO: 구현
import lombok.*;
import java.math.BigDecimal;

public class SavingAccount extends BasicAccount{
private String targetAmount;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

targetAmount도 Bigdecimal로 생성하는 것이 좋지 않을까요?


public SavingAccount(AccountType accountType, String accountNumber, String owner, BigDecimal balance, boolean isActivated,String targetAmount ) {
super( accountType, accountNumber, owner, balance, isActivated);
this.targetAmount = targetAmount;
}

// public String getAccountNumber() { return accountNumber;}
@Override
public String getAccountInfo() {
return super.getAccountInfo() + "\n목표 금액: " + targetAmount + "\n" ;
}

public String getTargetAmount() {
return targetAmount;
}
public void setBalance(BigDecimal balance) { super.setBalance(balance);}

public void setTargetAmount(String targetAmount) {
this.targetAmount = targetAmount;
}

public void withdraw(BigDecimal value) {
BigDecimal target = new BigDecimal(getTargetAmount());
int temp = getBalance().compareTo(target.multiply(BigDecimal.valueOf(0.01)));
if(temp>0) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if(temp>0) {
if(temp > 0) {

setBalance(getBalance().subtract((value)));
// this.balance=this.balance.subtract(value);
// System.out.println("withdraw"+getBalance());
}
}


}
16 changes: 16 additions & 0 deletions Week2/SavingInterestCalculator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package Week2;

import java.math.BigDecimal;

public class SavingInterestCalculator implements InterestCalculator{

// 100만원 이상은 이자율 50%, 그외에는 1%
public BigDecimal getInterest(BigDecimal balance){ // 계좌 잔액에 대한 이자금액 반환

if ( balance.compareTo(BigDecimal.valueOf(100)) >= 0)
return balance.multiply(BigDecimal.valueOf(0.5));
else
return balance.multiply(BigDecimal.valueOf(0.01));
}

}