Design Patterns with Javascript

Design patterns makes code short, less bugs, maintainable, re-usable and scalable

위 장점에도 불구하고 주의해서 사용하지 않으면 위 장점이 전부 반대가 되어버릴 수 있다. 각 패턴에 대한 특성을 정확히 파악하고 적절한 곳에 활용 할 줄 알아야 디자인 패턴을 사용함으로 인한 장점을 극대화 할 수 있으므로 디자인 패턴만을 위한 코드를 작성하는것을 조심하자.

Keep it simple and stupid 윈칙을 상기하면서 디자인 패턴을 활용하자.

Null object pattern

Null safety 를 위한 패턴. 함수나 메소드에서 리턴하는 객체가 nullable 할 경우 null 대신 null object 를 반환하여 runtime error 을 방지하고 코드를 깔끔하게 작성하자.

Builder Pattern

Builder 클래스를 작성하거나 생성자에서 optional 파라미터는 객체로 받고, default 값을 활용하여 코드를 간결하게 만들자.

e.g)

class User {
	constructor(name, { age, address = 'seoul', email} = {}) {
		this.name = name
		this.age = age
		this.address = address
		this.email = email
	}
}

const user = new User('Sam', {age: 30, email: '[email protected]'})

console.log(user) // User {name: "Sam", age: 30, address: "seoul", email: "[email protected]"}

Facade pattern

The idea of the facade pattern is to create your own API that hides away complex or repetitive code so that you are left with a clean and easy to use API. The benefits of this is not only clean code that is easy and fun to work with, but your code is also much easier to refactor when the complex code behind your facade needs to change.

Command Pattern

The idea of the command pattern is to create an abstraction between the operations an object can do, its commands, and the actual commands themselves. This makes it really easy to combine together or chain different commands without having to change the code. The program can dynamically chain and combine these actions. The best part is since each command is its own object you can easily implement and undo function for each command and make a set of undo-able actions.

Reference

https://www.youtube.com/watch?v=BWprw8UHIzA&list=PLZlA0Gpn_vH_CthENcPCM0Dww6a5XYC7f

좋은 웹페이지 즐겨찾기