Design Architecture/Refactoring

Decompose Conditional

lipnus 2022. 4. 20. 10:41
반응형

조건문 분해하기

 

if조건문이 주절주절이면 의미를 확인하기 어려우므로, 매소드로 빼내는 것.

이건 원래 하던거네..

 

before

import java.time.LocalDate;


public class DecomposeConditional_before {

	static class Stadium {
		//...
		public double summerRate;
		public double winterRate;
		public double winterServiceCharge;

		public Stadium(double summerRate, double winterRate, double winterServiceCharge) {
			super();
			this.summerRate = summerRate;
			this.winterRate = winterRate;
			this.winterServiceCharge = winterServiceCharge;
		}

		
		private LocalDate SUMMER_START = LocalDate.of(2021, 7, 1);
		private LocalDate SUMMER_END = LocalDate.of(2021, 8, 31);
		
		public double getTicketPrice(LocalDate date, int quantity) {
			double charge;
			if(date.isBefore(SUMMER_START) || date.isAfter(SUMMER_END) ) {
				charge = quantity * winterRate + winterServiceCharge;
			} else {
				charge = quantity * summerRate;
			}
			return charge;
		}
	}
	
	public static void main(String[] args) {
		Stadium stadium = new Stadium(75000, 90000, 12000);
		LocalDate today = LocalDate.parse("2021-09-15");

		System.out.println("Ticket price : " + stadium.getTicketPrice(today, 5));
	}

}

 

 

after

import java.time.LocalDate;


public class DecomposeConditional_before {

	static class Stadium {
		//...
		public double summerRate;
		public double winterRate;
		public double winterServiceCharge;

		public Stadium(double summerRate, double winterRate, double winterServiceCharge) {
			super();
			this.summerRate = summerRate;
			this.winterRate = winterRate;
			this.winterServiceCharge = winterServiceCharge;
		}

		
		private LocalDate SUMMER_START = LocalDate.of(2021, 7, 1);
		private LocalDate SUMMER_END = LocalDate.of(2021, 8, 31);
		
		public double getTicketPrice(LocalDate date, int quantity) {
			double charge;
			if( isSummer(date) ) {
				charge = quantity * winterRate + winterServiceCharge;
			} else {
				charge = quantity * summerRate;
			}
			return charge;
		}

		private boolean isSummer(LocalDate date) {
			if(date.isBefore(SUMMER_START) || date.isAfter(SUMMER_END)) return true;
			return false;
		}
	}
	
	public static void main(String[] args) {
		Stadium stadium = new Stadium(75000, 90000, 12000);
		LocalDate today = LocalDate.parse("2021-09-15");

		System.out.println("Ticket price : " + stadium.getTicketPrice(today, 5));
	}

}
반응형

'Design Architecture > Refactoring' 카테고리의 다른 글

Separate Query From Modifier  (0) 2022.04.20
Replace Nested Conditional With Guard Clauses  (0) 2022.04.20
Replace Type Code with Subclass  (0) 2022.04.20
Replace type Code with Class  (0) 2022.04.20
Encapsulate Collection  (0) 2022.04.20