'Archive' 카테고리의 다른 글

Dependency Injection (의존성 주입)  (0) 2012.01.24
Enum을 사용한 State 패턴  (0) 2012.01.24
한글 띄워쓰기 쉽게 교정하는 방법  (1) 2012.01.17
Eclipse에서 Shift + Enter 기능  (0) 2012.01.15
Javadoc에 @link로 링크걸기  (0) 2012.01.15
  

Stop Over-Engineering

Posted by epicdev Archive : 2011. 10. 4. 20:54
출처: http://www.industriallogic.com/papers/StopOverEngineering.pdf

Patterns are a cornerstone of object-oriented design, while test-first programming and merciless refactoring are cornerstones of evolutionary design. To stop over- or underengineering, balance these practices and evolve only what you need.
By Joshua Kerievsky
 
The great thing about software patterns is that they convey many useful design ideas. It follows, therefore, that if you learn a bunch of these patterns, you'll be a pretty good software designer, right? I considered myself just that once I'd learned and used dozens of patterns. They helped me develop flexible frameworks and build robust and extensible software systems. After a couple of years, however, I discovered that my knowledge of patterns and the way I used them frequently led me to over-engineer my work.
 
Once my design skills had improved, I found myself using patterns in a different way: I began refactoring to patterns, instead of using them for up-front design or introducing them too early into my code. My new way of working with patterns emerged from my adoption of Extreme Programming design practices, which helped me avoid both over- and under-engineering.

Zapping Productivity
What does it mean to over-engineer? When you make your code more flexible or sophisticated than it needs to be, you overengineer it. Some do this because they believe they know their system's future requirements. They reason that it's best to make a design more flexible or sophisticated today, so it can accommodate the needs of tomorrow. That sounds reasonable, if you happen to be a psychic.
 
But if your predictions are wrong, you waste precious time and money. It's not uncommon to spend days or weeks fine-tuning an overly flexible or unnecessarily sophisticated software design—leaving you with less time to add new behavior or remove defects from a system.
 
What typically happens with code you produce in anticipation of needs that never materialize? It doesn't get removed, because it's inconvenient to do so, or because you expect that one day the code will be needed. Regardless of the reason, as overly flexible or unnecessarily sophisticated code accumulates, you and the rest of the programmers on your team, especially new members, must operate within a code base that's bigger and more complicated than it needs to be.

To compensate for this, folks decide to work in discrete areas of the system. This seems to make their jobs easier, but it has the unpleasant side effect of generating copious amounts of duplicate code, since everyone works in his or her own comfortable area of the system, rarely looking elsewhere for code that already does what he or she needs.
 
Over-engineered code affects productivity because when someone inherits an over-engineered design, they must spend time learning the nuances of that design before they can comfortably extend or maintain it.
 
Over-engineering tends to happen quietly: Many architects and programmers aren't even aware they do it. And while their organizations may discern a decline in team productivity, few know that over-engineering is playing a role in the problem.

Perhaps the main reason programmers over-engineer is that they don't want to get stuck with a bad design. A bad design can weave its way so deeply into code that improving it becomes an enormous challenge. I've been there, and that's why up-front design with patterns appealed to me so much.

The Patterns Panacea
When I first began learning patterns, they represented a flexible, sophisticated and even elegant way of doing object-oriented design that I very much wanted to master. After thoroughly studying the patterns, I used them to improve systems I'd already built and to formulate designs for systems I was about to build. Since the results of these efforts were promising, I was sure I was on the right path.
 
But over time, the power of patterns led me to lose sight of simpler ways of writing code. After learning that there were two or three different ways to do a calculation, I'd immediately race toward implementing the Strategy pattern, when, in fact, a simple conditional expression would have been a perfectly sufficient solution.
 
On one occasion, my preoccupation with patterns became quite apparent. I was pair programming, and my partner and I had written a class that implemented Java's TreeModel interface in order to display a graph of Spec objects in a tree widget. Our code worked, but the tree widget was displaying each Spec by calling its toString() method, which didn't return the Spec information we wanted. We couldn't change Spec's toString() method since other parts of the system relied on its contents. So we reflected on how to proceed. As was my habit, I considered which patterns could help. The Decorator pattern came to mind, and I suggested that we use it to wrap Spec with an object that could override the toString() method. My partner's response to this suggestion surprised me. "Using a Decorator here would be like applying a sledgehammer when a few light taps with a small hammer would do." His solution was to create a small class called NodeDisplay, whose constructor took a Spec instance, and whose one public method, toString(), obtained the correct display information from the Spec instance. NodeDisplay took no time to program, since it was less than 10 simple lines of code. My Decorator solution would have involved creating more than 50 lines of code, with many repetitive delegation calls to the Spec instance.

Experiences like this made me aware that I needed to stop thinking so much about patterns and refocus on writing small, simple, straightforward code. I was at a crossroads: I'd worked hard to learn patterns to become a better software designer, but now I needed to relax my reliance on them in order to become truly better.

Going Too Fast
Improving also meant learning to not under-engineer. Under-engineering is far more common than over-engineering. We under-engineer when we become exclusively focused on quickly adding more and more behavior to a system without regard for improving its design along the way. Many programmers work this way—I know I sure have. You get code working, move on to other tasks and never make time to improve the code you wrote. Of course, you'd love to have time to improve your code, but you either don't get around to it, or you listen to managers or customers who say we'll all be more competitive and successful if we simply don't fix what ain't broke.

That advice, unfortunately, doesn't work so well with respect to software. It leads to the "fast, slow, slower" rhythm of software development, which goes something like this:
  • You quickly deliver release 1.0 of a system, but with junky code.
  • You attempt to deliver release 2.0 of the system, but the junky code slows you down.
  • As you attempt to deliver future releases, you go slower and slower as the junky code multiplies, until people lose faith in the system, the programmers and even the process that got everyone into this position.
That kind of experience is far too common in our industry. It makes organizations less competitive than they could be. But there is a better way.

Socratic Development
Test-first programming and merciless refactoring, two of the many excellent Extreme Programming practices, dramatically improved the way I build software. I found that these two practices have helped me and the organizations I've worked for spend less time over-engineering and under-engineering, and more time designing just what we need: well-built systems, produced on time.
 
Test-first programming enables the efficient evolution of working code by turning programming into what Kent Beck once likened to a Socratic dialogue: Write test code to ask your system a question, write system code to respond to the question and keep the dialogue going until you've programmed what you need. This rhythm of programming put my head in a different place. Instead of thinking about a design that would work for every nuance of a system, test-first programming enabled me to make a primitive piece of behavior work correctly before evolving it to the next necessary level of sophistication.
 
Merciless refactoring is an integral part of this evolutionary design process. A refactoring is a "behavior-preserving transformation," or, as Martin Fowler defined it, "a change made to the internal structure of software to make it easier to understand and cheaper to modify without changing its observable behavior" (Refactoring: Improving the Design of Existing Code, Addison -Wesley, 1999).

Merciless refactoring resembles the way Socrates continually helped dialogue participants improve their answers to his questions by weeding out inessentials, clarifying ambiguities and consolidating ideas. When you mercilessly refactor, you relentlessly poke and prod your code to remove duplication, clarify and simplify.
 
The trick to merciless refactoring is to not schedule time to make small design improvements, but to make them whenever your code needs them. The resulting quality of your code will enable you to sustain a healthy pace of development. Martin Fowler documents a rich catalog of refactorings, each of which identifies a common need for an improvement and the steps for making that improvement.
 
Why Refactor to Patterns?
On various projects, I've observed what and how my colleagues and I refactor. While we use many of the refactorings described in Fowler's book, we also find places where patterns can help us improve our designs. At such times, we refactor to patterns, being careful not to produce overly flexible or unnecessarily sophisticated solutions.

When I explored the motivation for refactoring to patterns, I found that it was identical to the motivation for implementing nonpatterns-based refactorings: to reduce or remove duplication, simplify the unsimple and make our code better at communicating its intention.
 
However, the motivation for refactoring to patterns is not the primary motivation for using patterns that is documented in the patterns literature. For example, let's look at the documented Intent and Applicability of the Decorator pattern (see Design Patterns: Elements of Reusable Object -Oriented Software by Erich Gamma, et al. Addison -Wesley, 1994) and then examine Erich Gamma and Kent Beck's motivation for refactoring to Decorator in their excellent, patterns-dense testing framework, JUnit.

Decorator's Intent: Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.

Decorator's Applicability
:
  • To add responsibilities to individual objects dynamically and transparently; that is, without affecting other objects.
  • For responsibilities that can be withdrawn.
  • When extension by subclassing is impractical. Sometimes a large number of independent extensions are possible and could produce an explosion of subclasses to support every combination, or a class definition may be hidden or otherwise unavailable for subclassing.
Motivation for Refactoring to Decorator in JUnit: Gamma remembered the following reason for refactoring to Decorator: "Someone added TestSetup support as a subclass of TestSuite, and once we added RepeatedTestCase and ActiveTest Case, we saw that we could reduce code duplication by introducing the TestSetup Decorator." (Note: This was from a private e-mail.)
 
Can you see how the motivation for refactoring to Decorator (reducing code duplication) had very little connection with Decorator's Intent or Applicability (a dynamic alternative to subclassing)? I noticed similar disconnects when I looked at motivations for refactorings to other patterns. Consider the examples in the table below.

Based on these observations, I began to document a catalog of refactorings to patterns to illustrate when it makes sense to make design improvements with patterns. (To see the work-in -progress, visit http://industriallogic.com/xp/refactoring/ ). For this work, it's essential to show refactorings from real-world projects in order to accurately describe the kinds of forces that lead to justifiable transformations to a pattern.

My work on refactoring to patterns is a direct continuation of work that Martin Fowler began in his excellent catalog of
refactorings, in which he included the following refactorings to patterns:
  • Form Template Method
  • Introduce Null Object
  • Replace Constructor with Factory Method
  • Replace Type Code with State/Strategy
  • Duplicate Observed Data
Fowler also noted the natural relation between patterns and refactorings. Patterns are where you want to be; refactorings are ways to get there from somewhere else.

This idea agrees with the observation made in Design Patterns: "Our design patterns capture many of the structures that result from refactoring. … Design patterns thus provide targets for your refactorings."

Evolutionary Design
Today, after having become quite familiar with patterns, the "structures that result from refactoring," I know that understanding good reasons to refactor to a pattern are more valuable than understanding the result of a pattern or the nuances of implementing that result.

If you'd like to become a better software designer, studying the evolution of great software designs will be more valuable than studying the great designs themselves. For it is in the evolution that the real wisdom lies. The structures that result from the evolution can help you, but without knowing why they were evolved into a design, you're more likely to misapply them or over-engineer with them on your next project.

To date, our software design literature has focused more on teaching great solutions than teaching evolutions to great solutions. We need to change that. As the great poet Goethe said, "That which thy fathers have bequeathed to thee, earn it anew if thou wouldst possess it." The refactoring literature is helping us reacquire a better understanding of good design solutions by revealing sensible evolutions to those solutions.

If we want to get the most out of patterns, we must do the same thing: See patterns in the context of refactorings, not just as reusable elements existing apart from the refactoring literature. This is perhaps my primary motivation for producing a catalog of refactorings to patterns.

By learning to evolve your designs, you can become a better software designer and reduce the amount of work you over- or under-engineer. Test-first programming and merciless refactoring are the key practices of evolutionary design. Instill refactoring to patterns in your knowledge of refactorings and you'll find yourself even better equipped to evolve great designs.

Intention and Motivation in Refactoring Patterns
 Pattern Intent  Refactoring Motivations
 Builder Separate the construction of a complex object from its representation so that the same construction process can create different representations.
 Simplify code
 Remove duplication
 Reduce creation errors 
 Factory Method Define an interface for creating an object, but let the subclasses decide which class to instantiate. The Factory Method lets a class defer instantiation to subclasses.  Remove duplication
 Communicate intent 
 Template Method Define the skeleton of an algorithm in an operation, deferring some steps to client subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.  Remove duplication
 

'Archive' 카테고리의 다른 글

테스트하기 쉬운 코드  (0) 2011.10.05
/etc/passwd 파일의 포맷  (0) 2011.10.04
디자인 패턴 공부 순서  (0) 2011.10.04
프로그래머를 위한 공부론 - 김창준  (0) 2011.10.04
리팩토링  (0) 2011.10.04
  

디자인 패턴 공부 순서

Posted by epicdev Archive : 2011. 10. 4. 19:18
출처: http://www.industriallogic.com/papers/learning.html

Design Patterns Navigation

l Factory Method Session 1
Begin with Factory Method. This pattern is used by a number of patterns in the book and throughout the patterns literature.
 
u Strategy Session 2
Strategy is used frequently throughout the book, and an early knowledge of it helps in understanding other patterns.
 
n Decorator Session 3
For an early dose of elegance, nothing is better than the Decorator. The discussion of "skin" vs. "guts" is a great way to differentiate Decorator from the previous pattern, Strategy.
 
n Composite Session 4
The Composite pattern appears everywhere and is often used with Iterator, Chain of Responsibility, Interpreter, and Visitor patterns.
 
u Iterator Session 5
Reenforce the reader's understanding of Composite by studying Iterator.
 
u Template Method Session 6
The author's footnote to Iterator explains that a method called "Traverse" in the Iterator example code is an example of a Template Method. This pattern also reenforces Strategy and Factory Method.
 
l Abstract Factory Session 7
The reader now returns to the second-easiest creational pattern, the Abstract Factory. This pattern also helps reenforce Factory Method.
 
l Builder Session 8
The reader now may compare another creational pattern, the Builder, with the Abstract Factory.
 
l Singleton Session 9
Singleton is often used to model Abstract Factories, as the "Related Patterns" section of Singleton describes.
 
n Proxy Session 10
The reader now has a chance to learn how Proxy is used to control access to an object. This pattern leads directly into the next pattern, Adapter.
 
n Adapter Session 11
The Adapter pattern may be compared with what the reader understands about Decorator, Proxy, and later, Bridge.
 
n Bridge Session 12
Finally, the reader learns how the Bridge pattern differs from both the Adapter and Proxy patterns.
 
u Mediator Session 13
Now the reader learns the Mediator pattern, in preparation for understanding Observer and the Model-View-Controller design.
 
u Observer Session 14
Discover how the Mediator is used by the Observer to implement the classic Model-View-Controller design.
 
u Chain of Responsibility Session 15
After exploring how messages are passed using the Observer and Mediator patterns, the reader now may contrast how messages are handled by the Chain of Responsibility pattern.
 
u Memento Session 16
The reader now moves on to Memento. This pattern leads directly into a discussion of undo and redo, which is related to the next pattern, Command.
 
u Command Session 17
The Command pattern is used in a number of ways, one of which relates to the previous pattern, Mediator.
 
l Prototype Session 18
Perhaps the most complex creational pattern, Prototype is often used with the Command pattern.
 
u State Session 19
The reader may now study State to understand another way an object's behavior changes.
 
u Visitor Session 20
Visitor is often combined with the Composite and/or Iterator patterns.
 
n Flyweight Session 21
The Flyweight pattern is one of the more complex patterns. An examples use of this pattern is described in the next pattern, Interpreter.
 
u Interpreter Session 22
The Interpreter pattern is complex. It makes reference to and helps reenforce one's understanding of Flyweight and Visitor.
 
n Facade Session 23
The final pattern to read is Facade. Facade is relatively straightforward and follows nicely after Interpreter since the example code is similar in theme to example code in the Interpreter.

 
Opening Questions For A Study Group

l Factory Method Session 1
How does Factory Method promote loosely coupled code?
 
u Strategy Session 2
Part 1: What happens when a system has an explosion of Strategy objects? Is there some way to better manage these strategies?

Part 2: In the implementation section of this pattern, the authors describe two ways in which a strategy can get the information it needs to do its job. One way describes how a strategy object could get passed a reference to the context object, thereby giving it access to context data. But is it possible that the data required by the strategy will not be available from the context's interface? How could you remedy this potential problem?

 
n Decorator Session 3
In the Implementation section of the Decorator Pattern, the authors write: A decorator object's interface must conform to the interface of the component it decorates.

Now consider an object A, that is decorated with an object B. Since object B "decorates" object A, object B shares an interface with object A. If some client is then passed an instance of this decorated object, and that method attempts to call a method in B that is not part of A's interface, does this mean that the object is no longer a Decorator, in the strict sense of the pattern? Furthermore, why is it important that a decorator object's interface conforms to the interface of the component. it decorates?

 
n Composite Session 4
Part 1: How does the Composite pattern help to consolidate system-wide conditional logic?

Part 2: Would you use the composite pattern if you did not have a part-whole hierarchy? In other words, if only a few objects have children and almost everything else in your collection is a leaf (a leaf can have no children), would you still use the composite pattern to model these objects?

 
u Iterator Session 5
Consider a composite that contains loan objects. The loan object interface contains a method called "AmountOfLoan()", which returns the current market value of a loan. Given a requirement to extract all loans above, below or in between a certain amount, would you write or use an Iterator to do this?
 
u Template Method Session 6
The Template Method relies on inheritance. Would it be possible to get the same functionality of a Template Method, using object composition? What would some of the tradeoffs be?
 
l Abstract Factory Session 7
In the Implementation section of this pattern, the authors discuss the idea of defining extensible factories. Since an Abstract Factory is composed of Factory Methods, and each Factory Method has only one signature, does this mean that the Factory Method can only create an object in one way?

Consider the MazeFactory example. The MazeFactory contains a method called MakeRoom, which takes as a parameter one integer, representing a room number. What happens if you would also like to specify the room's color & size? Would this mean that you would need to create a new Factory Method for your MazeFactory, allowing you to pass in room number, color and size to a second MakeRoom method?

Ofcourse, nothing would prevent you from setting the color and size of the Room object after is has been instantiated, but this could also clutter your code, especially if you are creating and configuring many objects. How could you retain the MazeFactory and keep only one MakeRoom method but also accomodate different numbers of parameters used by MakeRoom to both create and configure Room objects?

 
l Builder Session 8
Like the Abstract Factory pattern, the Builder pattern requires that you define an interface, which will be used by clients to create complex objects in pieces. In the MazeBuilder example, there are BuildMaze(), BuildRoom() and BuildDoor() methods, along with a GetMaze() method. How does the Builder pattern allow one to add new methods to the Builder's interface, without having to change each and every sub-class of the Builder?
 
l Singleton Session 9
The Singleton pattern is often paired with the Abstract Factory pattern. What other creational or non-creational patterns would you use with the Singleton pattern?
 
n Proxy Session 10
If a Proxy is used to instantiate an object only when it is absolutely needed, does the Proxy simplify code?
 
n Adapter Session 11
Would you ever create an Adapter that has the same interface as the object which it adapts? Would your Adapter then be a Proxy?
 
n Bridge Session 12
How does a Bridge differ from a Strategy and a Strategy's Context?
 
u Mediator Session 13
Since a Mediator becomes a repository for logic, can the code that implements this logic begin to get overly complex, possible resembling speggheti code? How could this potential problem be solved?
 
u Observer Session 14
Part 1: The classic Model-View-Controller design is explained in Implementation note #8: Encapsulating complex update semantics. Would it ever make sense for an Observer (or View) to talk directly to the Subject (or Model)?

Part 2: What are the properties of a system that uses the Objserver pattern extensively? How would you approach the task of debugging code in such a system?

Part 3: Is it clear to you how you would handle concurrency problems with is pattern? Consider an Unregister() message being sent to a subject, just before the subject sends a Notify() message to the ChangeManager (or Controller).

 
u Chain of Responsibility Session 15
Part 1: How does the Chain of Responsibility pattern differ from the Decorator pattern or from a linked list?.

Part 2: Is it helpful to look at patterns from a structural perspective? In other words, if you see how a set of patterns are the same in terms of how they are programmed, does that help you to understand when to apply them to a design?

 
u Memento Session 16
The authors write that the "Caretaker" participant never operates on or examines the contents of a memento. Can you consider a case where a Caretaker would infact need to know the identity of a memento and thus need the ability to examine or query the contents of that memento? Would this break something in the pattern?
 
u Command Session 17
In the Motivation section of the Command pattern, an application's menu system is described. An application has a Menu, which in turn has MenuItems, which in turn execute commands when they are clicked. What happens if the command needs some information about the application in order to do its job? How would the command have access to such information such that new comamnds could easily be written that would also have access to the information they need?
 
l Prototype Session 18
Part 1: When should this creational pattern be used over the other creational patterns?

Part 2: Explain the difference between deep vs. shallow copy.

 
u State Session 19
If something has only two to three states, is it overkill to use the State pattern?
 
u Visitor Session 20
One issue with the Visitor pattern involves cyclicality. When you add a new Visitor, you must make changes to existing code. How would you work around this possible problem?
 
n Flyweight Session 21
Part 1: What is a non-GUI example of a flyweight?

Part 2: What is the minimum configuration for using flyweight? Do you need to be working with thousands of objects, hundreds, tens?

 
u Interpreter Session 22
As the note says in Known Uses, Interpreter is most often used "in compilers implemented in object-oriented languages...". What are other uses of Interpreter and how do they differ from simply reading in a stream of data and creating some structure to represent that data?
 
n Facade Session 23
Part 1: How complex must a sub-system be in order to justify using a facade?

Part 2: What are the additional uses of a facade with respect to an organization of designers and developers with varying abilities? What are the political ramifications?

 

'Archive' 카테고리의 다른 글

/etc/passwd 파일의 포맷  (0) 2011.10.04
Stop Over-Engineering  (0) 2011.10.04
프로그래머를 위한 공부론 - 김창준  (0) 2011.10.04
리팩토링  (0) 2011.10.04
동시성을 고려한 설계를 하면 좋은 이유  (0) 2011.10.04
  
코드의 결합도를 줄여라

부끄럼타는 코드를 작성하라. 즉 불필요한 어떤 것도 달느 모듈에 보여주지 않으며, 다른 모듈의 구현에 의존하지 않는 코드르 작성하라. 그리고 디미터 법칙을 따르려 노력 해 보자. 객체의 상태를 바꿀 필요가 있다면, 객체 스스로가 여러분을 위해 그러한 일을 수행하게 만들라. 이렇게 한다면 코드는 다른 코드 구현으로부터 분리 된 채로 남아있을 것이며, 계속하여 직교성을 유지 할 기회가 많아 질 것이다.

전역 데이터를 피하라

코드가 전역 데이터를 참조 할 때마다, 코드는 해당 데이터를 공유하는 다른 컴포넌트와 묶이게 된다. 읽기 전용 목적으로 전역 데이터를 사용한다 하더라도 문제가 발생 할 수 있다. 예를 들어 코드를 갑자기 멀티쓰레드로 바꿔야 한다면 어떻게 될까? 일반적으로 모듈이 필요로 하는 컨텍스트를 명시적으로 넘겨주면 코드를 이해하고 유지보수하기 쉽게 된다. 객체지향 애플리케이션에서는 컨텍스트를 객체 생성자의 매개 변수로 넘기기도 한다. 또한 컨텍스트를 포함하는 구조체를 만들어 이를 필요로 하는 모듈에 레퍼런스로 넘겨 줄 수도 있다. 싱글톤 패턴은 특정 클래스의 객체가 단 하나의 인스턴스만을 갖도록 보장 해 준다.
하지만 많은 개발자들이 싱글톤 객체를 전역 데이터의 일종으로 남용한다 (특히 자바와 같이 전역 개념을 지원하지 않는 언어의 경우에는 더욱 심하다). 싱글톤을 사용 할 때는 주의를 기울여라. 싱글톤은 불필요한 링크를 유도한다. 

유사한 함수를 피하라

종종 유사해 보이는 함수의 집합을 구현해야 할 때가 있다. 아마도 시작과 끝에서는 공통 코드를 공유하지만 중간의 알고리즘이 다를 것이다. 중복 코드는 구조적 문제의 징후다. 스트래티지 패턴을 사용하여 더 나은 구현을 할 수는 없는지 고려 해보기 바란다.


실용주의프로그래머
카테고리 컴퓨터/IT > 프로그래밍/언어
지은이 앤드류 헌트 (인사이트, 2007년)
상세보기
 

'Archive' 카테고리의 다른 글

슈뢰딩거의 고양이 이야기  (0) 2011.10.02
직교성과 테스트  (0) 2011.10.01
직교적인 설계가 되어있는지 테스트하는 방법  (0) 2011.10.01
코드의 직교성의 장점  (0) 2011.10.01
코드내의 문서화  (0) 2011.10.01
  
 «이전 1  다음»