Design Architecture/Refactoring

Encapsulate Collection

lipnus 2022. 4. 20. 08:59
반응형

메소드가 collection을 반환할 때
• 그 메소드가 읽기전용 view를 반환하게 수정하고 add() 와 delete() 메소드를 작성한다.

 

Before

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class EncapsulateCollection_before {

	static class Course {
		String name;
		boolean isAdvanced;

		public Course(String name, boolean isAdvanced) {
			this.name = name;
			this.isAdvanced = isAdvanced;
		};

		public boolean isAdvanced() {
			return this.isAdvanced;
		};
	}

	static class Person {
		private Set<Course> courses;

		// ...
		public Set<Course> getCourses() {
			return courses;
		}

		public void setCourses(Set arg) {
			courses = arg;
		}
	}

	public static void main(String[] args) {
		Person kent = new Person();
		Set<Course> s = new HashSet<Course>();
		s.add(new Course("Smalltalk Programming", false));
		s.add(new Course("Appreciating Single Malts", true));
		kent.setCourses(s);
		
		
		Course refact = new Course("Refactoring", true);
		kent.getCourses().add(refact);
		kent.getCourses().add(new Course("Brutal Sarcasm", false));
		
		kent.getCourses().remove(refact);

		Iterator<Course> iter = kent.getCourses().iterator();
		int count = 0;
		while (iter.hasNext()) {
			Course each = (Course) iter.next();
			if (each.isAdvanced())
				count++;
		}
		
		System.out.println("Advanced courses: " + count);
	}

}

 

After


public class ReplaceTypeCodeWithClass_before {
	static public class Person {
		private BloodGroup _bloodGroup;

		public int getBloodGroupCode(){
			return _bloodGroup.getCode();
		}

		public BloodGroup getBloodGroup(){
			return _bloodGroup;
		}

		public Person(BloodGroup bloodGroup){
			_bloodGroup = bloodGroup;
		}

		public void setBloodGroup(BloodGroup arg){
			_bloodGroup = arg;
		}
	}

	public static class BloodGroup{
		public static final BloodGroup O = new BloodGroup(0);
		public static final BloodGroup A = new BloodGroup(1);
		public static final BloodGroup B = new BloodGroup(2);
		public static final BloodGroup AB = new BloodGroup(3);

		private static final BloodGroup[] _values = {O, A, B, AB};
		private final int _code;

		private BloodGroup(int code){
			_code = code;
		}
		public int getCode(){
			return _code;
		}
		public static BloodGroup code(int arg){
			return _values[arg];
		}
	}
	
	public static void main(String[] args) {

		Person thePerson = new Person(BloodGroup.A);
		System.out.println("Blood group : " + thePerson.getBloodGroup());

		thePerson.setBloodGroup(BloodGroup.AB);
		System.out.println("Blood group : " + thePerson.getBloodGroup());
	}

}
반응형

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

Replace Nested Conditional With Guard Clauses  (0) 2022.04.20
Decompose Conditional  (0) 2022.04.20
Replace Type Code with Subclass  (0) 2022.04.20
Replace type Code with Class  (0) 2022.04.20
Replace Data Value with Object  (0) 2022.04.20