블로그 이미지
Flying Mr.Cheon youGom

Recent Comment»

Recent Post»

Recent Trackback»

« 2025/12 »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31

 
 




조슈아 케이에브스키 저, 윤성준/조상민 역, 인사이트 출판


1. 접근 계기
2. 리팩토링이란?
3. 왜 이책인가.
4. 널오브젝트


외부에서 들어온 코드를 다듬을 필요가 있었다.
코드를 받았을 때, 대박이었다. 도저히 확장이 불가능한 코드였다. 마음같아선 다시 만들고 싶었지만, 일정에 대한 고민 때문에 쉽사리 결정 할 수 없었다.

그 때 기억속에 희미하게 다가온 것은 리팩토링이었다.


리팩토링이 무엇인가에 대한 이야기를 잠깐 하겠다.

리팩토링은 코드를 재생산한다는 의미로 기존코드의 생산성을 높게 만드는 일이다.
리팩토링에 대한 이해가 없는 사람이 보았을 땐, 일을 하기 위한 일로 보일 수 있다. 왜 리팩토링이 필요한지 설명하기엔 어려운 부분이 많다. 개발일정에 리팩토링이란 기간은 산출되지 않으며, 리팩토링은 개발기간에 완료되어야 한다고 생각한다.

그렇다면 어떻게 해야하는가?!

간결하게 말하면, 리팩토링을 안하면 된다. 프로젝트에 사용된 코드는 한번 사용하고 버리면 된다는 말이다.

내가 관리자라면 추천하지만, 강요하지 않는다. 이유는 간단하다. 리팩토링을 하지 않으면, 본인 스스로가 괴롭기 때문이다.

무슨말인지 직접적으로 다가오지 않는가? 대한민국 사람이라면 누구나 배운 ' 산 수 ' 로 예를 들어보겠다.
[ 1 + 2 + 3 + 4 + 5 + 6 + 10 + 20 + 30 + 40 * 3 + 2 + 1 + 3x = ] 은 무엇일까? 왜 이걸 물을까?

저 산술식이 당신이 짜 놓은 코드와 별반 다를게 없다.

[ 81 + 120 + 6 + 3x = ], -> [ 207 + 3x = ] 이렇게 간단하게 해 놓으면 얼마나 보기 좋은가?

이게 바로 리팩토링이다.

영어라서 생소할 뿐이다. 위 처럼 재생산하는 방식을 [ 덧셈 제거 패턴 ] 이라 명명했다 치자.
영어로 하면 [ Plus Remove Pattern ] 뭐 이런 이름이 되지 않을까? 아무것도 아닌데.. 괜히 영어라 부담된다.

이게 우리나라 리팩토링과 기술에 관한 일반적인 접근 오류다.

여기까지 리팩토링이 무엇인지 잠깐 이야기 해 보았다.



리팩토링에 대한 책을 본지도 오래되어 되새김을 하기 위해 책 몇권을 빌렸다. ( 아마 4권 빌린거 같다. )
그중에서 내 손에 남은 것은 단 한권, 조슈아 케리에브스키가 쓴 [ 패터을 활용한 리팩토링 ] 이다.
다른 책에 눈에 들어오지 않는 건, 이전에 코드에 집중한 리팩토링을 많이 들어왔고, 이미 익숙해져버린 탓이라 생각한다.

이책은 소프트웨어 구조 관점에서 접근 했다. 일반적 코드 스타일의 오류나 패턴을 잘못 활용하는 부분에 대한 지적도 있었다. 여기에서 내가 생각했었던 패턴 남용에 대해서도 언급되어 자신감이 붙은 부분도 있고, 내가 오류를 범하고 있음 느끼기도 해주는 좋은 가이드라 생각한다. 




나는 이 책을 볼 때, 차례로 보지 않았다.
책의 하드케이스 부분, 앞 부분은 리팩토링 목록 / 방향, 뒷 부분에는 코드 냄새 / 학습 순서가 있다.
나는 뒷 부분의 코드 냄새와 학습 순서를 기준으로 책장을 넘겼다.

절반정도 본 상태다. 현재까지 본 내용 중, 나의 뇌리에 강한 충격을 준 부분은 Null Object 패턴이었다.
Null Object를 한마디로 설명할 수 있다.
[ Null 체크 없이, 소프트웨어를 안전성을 보장한다. ]

완성도를 높이기 위해 예외처리를 많이 해본 사람이라면, 이게 얼마나 대단한 것인지 느낄 수 있을 것이다.
이 것을 제대로 이해하고 사용하려면 OOP 인터페이스에 대한 이해가 깊어야 한다는 단점이 있다.
그러나, 그 단점을 딛고 일어선다면, 남들 코드 1000줄로 구현한 내용을 약 500줄로 줄일 수 있게 된다.
코드 줄수에 대한 내용은 추측이 아니다. 패턴을 활용한 프로그래밍으로 3만줄이 나 되는 코드를 1만줄 이하로 구현한 경험이 있기 때문에 당당하게 말한다.

그러나 주의해야 할 것이 있다. 패턴 남용에 대해 잠깐 이야기 하겠다.
패턴은 추천 사항이지 필수가 아니다. 간단한 예를 들겠다.
[ if else ] 의 단 두가지의 분기문에 대해 Strategy 를 사용할 필요는 없다는 것이다.
고작 2줄에서 10줄이면 끝날 내용을 패턴 남용으로 프로그램의 복잡도를 높일 필욘 없다는 것이다.


본래의 내용으로 돌아와 Null Object의 사용법에 대한 이야기다.

우리는 일반적으로 널체크를 하고 안전하게 사용한다.
if( null == pGeneralObj )  pGeneralObj->Method();

널체크 없이 그냥 사용해도 소프트웨어의 안정성은 보장된다.
pNullObj->Method();

어떻게 이것이 가능할까?

이렇게 구현하면 된다.
class IMethod {
    public:
    void Method() = 0;
 };

class NullObj : public IMethod()
{
    public :
    void Method() {}
};

class RealObj : public IMethod()
{
    public:
    void Method() { cout << "oops! real object?"; }
};

어느 정도 힌트를 얻었을거라 생각한다.

우리는 오브젝트를 초기화할때, pObj = null; 와 같은 코드를 많이 사용한다.
만약, pObj = NullObj::GetInstace(); 를 사용하면 코드의 안정성과 개발 생산성의 가속을 얻게 된다.


한가지 주의 할 점이 있다.
Null Object도 마찬가지로 추천사항이지, 필수 사항이 아니다.
널체크 두 세번만 사용하는 부분이나 객체 수가 현저히 적은 부분에 사용할 필요는 없다.



책을 좀 더 보다가, 잼있는 내용이 있으면 더 덧붙일까 한다. ^-^ !




:

서문

번역/Patterns For Parallel Software Design | 2011. 10. 17. 21:46 | Posted by youGom
The steady increases in processor speeds associated with Moore's Law has improved software performance for decades without necessitating significant changes in software designs or practices. Over the past several  years, however, the exponential growth in CPU speed has stalled. Increases in software performance now stem largely from exploiting parallel processing to exchange data reliably and scalably across high-speed interconnects, dynamically balance workload in computation grids, and efficiently synchronize access to shared resources. Researchers and practitioners rely on parallel processing to accelerate scientific discoveries and deliver value to users in a wide range of application domains, including high-performance scientific computing, weather forecasting, financial services, animation rendering, text mining, homeland security and enterprise content management.
 

무어의 법칙대로 프로세서 속도의 지속적인 증가는, 소프트웨어 설계나 관행에 특별한 변화를 필요로 하지 고, 수 십년간 소프트웨어 성능을 개선시켜 왔습니다.
  

 Although parallel processors and interconnects continue to improve, it remains tedious and error-prone to develop complex application and infrastructure software that can meet challenging – and changing – user requirements. This situation has yielded a ‘parallel software crisis’, in which the hardware becomes ever more capable but the software remains hard to develop, debug, optimize and evolve. Much of the effort expended on parallel software is spent rediscovering core concepts such as coordination, communication, and synchronization, and reinventing common components such as active objects, dynamic load balancers, job schedulers, message brokers and notification engines. Moreover, despite advances in key technologies, such as concurrent programming languages, vectorizing and optimizing compilers, operation system clustering techniques and grid computing middleware, many software developers lack experience of how and when to best apply these technologies.
 

 Addressing the parallel software crisis therefore requires more than just adopting the latest technologies it requires learning and applying successful parallel software patterns that document recurring architectures and designs and convey proven parallel software structures, algorithms and best practices. Knowledge of patterns helps researchers and practitioners to avoid rediscovering and reinventing core concepts and common components of parallel software. Patterns can also explain how and when to best apply parallel technologies.


 Popular patterns such as Adapter, Bridge, Reactor and Strategy have captured and guided the designs of application and infrastructure software for two decades. Many of these patterns were identified initially by developers of object-oriented graphical user interface frameworks that work in contexts where quality factors like usability, extensibility and portability are paramount. In addition to these quality factors, developers of parallel software must also understand and apply patterns that work in context in which low latency and high throughput, reliability and scalability are paramount.

Over the year, isolated coverage of parallel software patterns has appeared in various conference proceedings and book. For example, those associated with the Pattern Languages of Programming ( PLoP ) conferences present patterns for scalable locking and communication. Likewise, the Pattern-Oriented Software Architecture( POSA) series of books presents patterns for pipeline parallelism, master/slave processing, distributed request brokering and dynamic resource management. Until Jorge Ortega-Arjona published this book on pattern for parallel software design, however, no single source provided such a broad and deep spectrum of architectural patterns, design patterns and common idioms for developing parallel software.

Popular patterns such as Adapter, Bridge, Reactor and Strategy have captured and guided the designs of application and infrastructure software for two decades. Many of these patterns were identified initially by developers of object-oriented graphical user interface frameworks that work in contexts where quality factors like usability, extensibility and portability are paramount. In addition to these quality factors, developers of parallel software must also understand and apply patterns that work in context in which low latency and high throughput, reliability and scalability are paramount.

 The patterns and idioms that Jorge present in this book help to resolve key parallel software challenges such as coordinating interaction between concurrently executing task, partitioning parallel algorithms and data to improve performance substantially, and minimizing synchronization overhead in local and distributed shared memory. In addition to describing the structure and functionality of essential parallel software patterns and idioms, Jorge also presents many examples from a range of applications domains, including high-performance scientific computing, image processing and animation rendering. Moreover, Jorge’s detailed case studies extend the book beyond a catalog of parallel software patterns to provide keen insights into parallel software design processes and methods that help alleviate key accidental and inherent complexities in parallel software development projects.

For parallel software development to develop from an art to an engineering discipline, successful practices and design expertise must be documented systematically and disseminated broadly. My colleagues and I have documented and applied patterns in a wide range of distributed and parallel application and infrastructure software, including the ACE, TAO and Zircomp middleware. We’ve found that studying and applying patterns helps to:

n  Facilitate reuse of architecture and design artifacts, which reduces the effort required to develop high-quality parallel software frameworks and application components. These patterns can be reused even when reuse of algorithms, implementations, interfaces or detailed design is not feasible due to heterogeneous software and hardware platforms.

n  Document ‘best practices’ of parallel software systems, which have traditionally resided in the minds of expert developers or buried within complex source code. Capturing the most useful strategies and tactics of parallel software in terms of patterns makes the learning curve for new developers more gentle, by giving them good role models for developing parallel software applications and infrastructure.

n  Preserve important design information, which is often lost over time in conventional development processes, causing increased maintenance costs and software defects. Software evolution effort can thus be reduced significantly by documenting the intent, structure and behavior of parallel software components in terms of the patterns they reify, as well as explaining how and when to best apply these components in various contexts.

n  Guide design choices for new systems, since patterns capture proven experience in a from that can be used to address new design challenges. By understanding the potential traps and pitfalls in their domains, developers can select suitable parallel software architectures, protocols and platform features without wasting time and effort implementing solutions that are known to be inefficient or error-prone.

 

 A thorough understanding of the parallel software patterns, processes and methods in Jorge’s book will help you develop better parallel software applications and infrastructure likewise. If you want a thorough coverage of the key pattern-oriented software architectures that are shaping the next-generation of parallel software, then read this book. I’ve learned much from it and I’m confident that you will too.

 
 

Douglas C. Schmidt

Nashville, Tennessee, USA

 

 


 

'번역 > Patterns For Parallel Software Design' 카테고리의 다른 글

차례  (0) 2011.10.17
앞 표지, 뒷 표지 내용  (0) 2011.10.16
도전! Patterns for parallel software design  (0) 2011.10.16
:

차례

번역/Patterns For Parallel Software Design | 2011. 10. 17. 13:25 | Posted by youGom
- 불펌 하시면 안됩니다. ^^ [ yougom.com ] -


서문

저자서문
저자에 대해
감사글
기고자 일대기

챕터 1.
소프트웨어 패턴
소프트웨어 패턴의 개념
패턴 서술, 구성, 분류
요약

챕터 2.
병렬 프로그래밍에 쉽게 접근하기
병렬 프로그래밍
병렬 프로그램 수행에 영향을 미치는 요인
병렬 프로그래밍의 장점과 단점
요약

챕터 3.
병렬 프로그래밍을 위한 아키텍쳐 패턴
병렬 파이프 & 필터
병렬 레이어
선형 요소 전달하기
매니저-워커
공용 자원
요약

챕터 4.
통신 컴포넌트의 디자인 패턴
공용 가변 파이프
복합적인 지역( Local ) 호출
메시지 전달 파이프
복합적인 원격 호출
공용 가변 채널
메시지 전달 채널
지역 랑데뷰
원격 랑데뷰
요약

챕터 5.
동기화 메커니즘의 표현식 ( Idiom )
세마포어
크리티컬 영역
모니터
메시지 전달
원격 프로시저 호출
요약

챕터 6.
두가지 사례 연구
혈관 세분화
조절 가능한 3D 그리드 기반 오일러( 기체역학의 ) 프로그램
요약

챕터 7.
병렬 소프트웨어 디자인
일반적인 병렬 소프트웨어 디자인 프로세스
패턴 기반 병렬 소프트웨어 디자인 방법
문제 분석
조직화 ( Coordination ) 설계 - 아키텍쳐 패턴
통신 ( Communication ) 설계 - 디자인 패턴
세부 설계 - 표현식 ( Idiom )
구현과 진화
요약

챕터 8.
병렬 소프트웨어 아키텍쳐
병렬 소프트웨어 아키텍쳐의 정의
병렬 소프트웨어 디자인
요약

챕터 9.
병렬 프로그래밍 패턴의 방향
소프트웨어 설계의 상황
설계 지식과 기술
병렬 소프트웨어 시스템의 실제 서술
병렬 소프트웨어 설계 측정의 필요성

용어 사전

표기법

참조 문헌

패턴 색인

색인


















------------------------------------ 원문 -----------------------------------------


Foreword


Preface
About the Author
Acknowledgements
Contributor Biography

Chapter 1
Software Patterns
The Concept of a Software Pattern
Pattern Description, Organization and Categorization
Summary

Chapter 2
A Brief Introduction to Parallel Programming
Parallel Programming
Factors that Influence the Performance of a Parallel Program
Avantages and Disavantages of Parallel Programming
Summary
Chapter 3
Architectural Patterns for Parallel Programming
Parallel Pipes and Filters
Parallel Layers
Communicating Sequential Elements
Manager-Workers
Shared Resource
Summary
Chatper 4
Design Patterns for Communication Components
Shared Variable Pipe
Multiple Local Call
Message Passing Pipe
Mulple Remote Call
Shared Variable Channel
Message Passing Channel
Local Rendezvous
Remote Rendezvous
Summary

Chapter 5
Som Idioms for Synchronization Mechanisms
Semaphore
Critical Region
Monitor
Message Passing
Remote Procedure Call
Summary

Chapter 6
Two Case Studies
Blood Vessel Segmentation
Adaptive 3D Grid-Based Eulerian ( Gasdynamic ) Program
Summary

Chapter 7
Parallel Software Design
A General Parallel Software Design Process
A Pattern-Based Parallel Software Design Method
Problem Analysis
Coordination Design - Architectural Patterns
Communication Design - Design Patterns
Detailed Design - Idioms
Implementation And Evaluation
Summary

Chapter 8
Parallel Software Architecture
A Definition of Parallel Software Architecture
Parallel Software Design
Summary

Chapter 9
Directions in Patterns for Parallel Programming
The Situation in Software Design
Design Experience and Techiques
A Tangible Description for Parallel Software Systems
The Need for Measurement in Parallel Software Design
Final Remarks


Glossary

Notations

References

Index of Patterns

Index


 

'번역 > Patterns For Parallel Software Design' 카테고리의 다른 글

서문  (0) 2011.10.17
앞 표지, 뒷 표지 내용  (0) 2011.10.16
도전! Patterns for parallel software design  (0) 2011.10.16
:
- 무단 불펌 하시면 안됩니다. ^^ [ yougom.com ] -


[ 앞표지 ]

Patterns for Parallel Software Design
병렬 소프트웨어 설계를 위한 패턴

Jorge Luis Ortega-Arjona 
저자. 조지 루이스 오르티가-아르조나 


[ 뒷표지 ]

Patterns for Parallel Software Design is essential reading for developers looking to understand patterns for parallel programming.
병렬 소프트웨어 설계 패턴은 병렬 프로그래밍 패턴들을 습득하려는 개발자들이 필수적으로 읽어야 합니다.



Written from an architectural point of view, Patterns for parallel Software Design presents a pattern-oriented software architecture approach to parallel software design providing solutions in concurrent and distributed programming, based on existing design knowledge.

저자는 아키텍쳐 관점에서, 병렬-소프트웨어-설계-패턴을 기존 설계 지식에 기반하는 동시처리와 분산처리 프로그래밍의 해결책으로 병렬-소프트웨어-설계를 패턴-지향-소프트웨어-아키텍쳐로 접근 합니다.



A pattern-oriented approach to parallel software design is not a design method in the classic sense,
but a new way of managing and utilizing existing design knowledge for designing parallel programs.
 Using this approach leads to parallel software systems that are modular, adaptable, understandable and evolvable.
Thus, this method aims to enhance not only build-time properties of parallel systems, but also their run-time properties.

패턴 지향적 병렬 소프트웨어 설계는 클래식한 설계법이 아니지만, 병렬 프로그래밍을 설계하는 기존 설계 지식을 활용하고 관리하는 새로운 방법입니다. 이를 활용해 접근한다면 모듈화되고 적응력( adaptable )있으며 이해하고 쉽고 진화적인 병렬 프로그램 설계로 이끌어 낼 수 있습니다. 이와 같은 방법들은 병렬 시스템의 빌드타임 속성뿐만 아니라, 런타임 속성 향상에 도움을 줍니다.



Key topics include :
 - Use of known solutions in concurrent and distributed programming, applied to the development of parallel programs.
 - Significant architectural patterns that describe how to divide an algorithm and/or data to find a suitable partition, and hence, link it with a programming structure that allows for such a division.
 - Delivers proven solutions to the problems faced by parallel programmers.

주요 주제는 다음과 같습니다.
 - 동시 및 분산 프로그래밍에 알려진 해결책은 병렬 프로그램 개발에 사용됩니다.
 - 어떻게 알고리즘과 데이터를 구분할 것인가, 어떻게 적절한 분할 영역을 찾을 것인가에 대해 묘사해주는 중요한 아키텍저적인 패턴 입니다. 게다가, 분할 구조로 하는 프로그래밍과 관련이 있습니다.
 - 병렬 프로그래밍에 직면한 문제들의 입증된 해결책을 제시합니다.



Coverage is aimed at developers new to parallel programming, who require a base to understand parallel software design and implementation for future parallel platforms. Patterns for Parallel Software Design is an essential must-have guide for developers and programmers who want to solve unique design problems.

이 책은 병렬 소프트웨어 설계의 기본적인 이해와 미래적 병렬 플랫폼을 위한 구현을 요구하는 개발자에게 새로운 병렬 프로그래밍을 하도록 하는 것입니다. 병렬 소프트웨어 설계 패턴은 고유의( Unique ) 설계 문제들을 풀고 싶어 하는 개발자들과 프로그래머들에게 필수로 지니고 있어야 할 안내서입니다.

 

'번역 > Patterns For Parallel Software Design' 카테고리의 다른 글

서문  (0) 2011.10.17
차례  (0) 2011.10.17
도전! Patterns for parallel software design  (0) 2011.10.16
:

이 책으로 번역 작업에 도전하려고 한다.

후배하고 같이, 책 한권 쓰려고 계획중인 것도 있다.
책을 만드는 건, 창의적인 생각에 도움이 된다.

그 것도 좋지만, 번역 작업을 하면서, 부족했던 영어 공부도 하면 좋을 것 같다는 생각이 든다.
 
번역 작업을 하는 건, 타인의 생각을 제대로 이해하고, 때로는 직역을 때로는 의역이 필요하다.
처음이라, 서투른 부분도 있을꺼라 본다. 서두르지 않아야 겠다




아직, 어느 출판사에게 연락할지 정하지 않은 상태 입니다. 좋은 출판사 있으면 소개시켜주시길 부탁 드립니다. ^^; 

'번역 > Patterns For Parallel Software Design' 카테고리의 다른 글

서문  (0) 2011.10.17
차례  (0) 2011.10.17
앞 표지, 뒷 표지 내용  (0) 2011.10.16
:

[POSA1] Broker Architecture Pattern

소프트웨어 공학/설계 | 2011. 10. 7. 17:04 | Posted by youGom
1.
여기에서 핵심 클래스는 Broker Class다.
Broker 클래스는 Client, Server에 접근하고, Client Proxy, Server Proxy에 접근한다.
Bridge 클래스를 통해 세부 구현을 숨길수도 있으며, 다른 브로커에 접근할 수 있다.

2.
Broker는 등록되어진 Client와 Server를 안전하게 연결해 준다.
Client는 본인이 사용하는 하나의 어플리케이션으로 볼수 있다.
Server는 서비스를 제공하는 하나의 매개체다.
Client/Server Proxy는 부가적인 데이터 처리를 해준다.

3.
포사에 적혀 있는 내용을 압축하면 위와 같이 정리된다.
POSA 책을 봐도 잘 이해 안가는걸 한번 더 압축하니, 첨 본 사람은 더욱 어리둥절 할 수 있다.


4.
우리 생활에 가까운 것으로 예를 들면 개념을 이해 하는데 도움이 된다.

a. 우리는 크롬을 켠다. ( ex. www.google.com )
b. 검색을 한다. ( ex. 김태희 )
c. 검색 목록이 뜬다. ( ex. 알흠다운 김태희 기사와 사진들~ *_* 므흣..! )
d. 김태희 기사를 본다.
e. 김태희 홈페이지를 들어간다. 
f. 홈페이지가 제대로 안뜨길래, 익스플로러로 김태희 홈페이지로 들어갔다.
g. 에러 없이 모든 내용을 볼 수 있다.


5.
위 내용을 가지고 Broker 패턴을 이해 할 수 있다.

a. Client 1 :    우리는 크롬을 켠다. ( ex. www.google.com )
b. Broker :      검색을 한다. ( ex. 김태희 )
c. Sever-List : 검색 목록이 뜬다. ( ex. 알흠다운 김태희 기사와 사진들~ *_* 므흣..! )
d. Server 1 : 김태희 기사를 본다.
e. Server 2 : 김태희 홈페이지를 들어간다. 
f. Client 2 :  홈페이지가 제대로 안뜨길래, 익스플로러로 김태희 홈페이지로 들어갔다.
g. Server 2 : 에러 없이 모든 내용을 볼 수 있다.


6.
추가 설명이 필요한 분들을 위해, 부가적인 설명을 덧 붙이겠다.

Client 브라우저다. 브라우저는 크롬과 익스플로러이고, 파이어폭스나 모질라도 가능하다.
Broker는 김태희 정보가 있는 서버 정보를 검색하는 역할을 한다.
Server는 본인이 원하는 서버들 중 하나를 선택해서 접근하는 것이다.
 ( 여기서 site 주소를 실제 서버 IP로 연결해주는게 DNS 인데, DNS도 브로커로 볼 수 있다. )
연결된 Server는 본인이 켜둔 Client 브라우저로 정보를 Reponse해주는 것이다.


7.
Proxy는 추가적인 데이터처리를 위해 추가 할 수 있다. 특히 Intranet을 사용할 때, Proxy Server는 필수가 된다.
일반적으로 Proxy 옵션을 따로 설정하진 않는다.


8.
가벼운 소재를 가지고, 쉽게 풀어 보았다.
혹시라도.. 설명에 부족한 부분이 있다면, 댓글을 조심히 부탁드린다.


9.
Broker 패턴에 대한 정확한 정보는 아래 주소로 가면, POSA 내용을 엿볼 수 있다.
 http://thisisliving.tistory.com/category/Studying/Pattern-Oriented%20Software%20Architecture


 

'소프트웨어 공학 > 설계' 카테고리의 다른 글

[수강후기] CBD, Component Based SW Design  (0) 2012.09.02
Bada App - FrameWork Concept  (0) 2011.09.21
:


포스트를 만든 목적

  • 이렇게 하지 않으면, 책을 건성으로 본다.

내용

Dispose 는 무엇인가?

관리되지 않는(unmanaged) 자원을 해제하기 위해서 사용 하는 함수이다.

그러면 unmanaged 자원은 무엇인가?

쉽게 생각해서 "메모리가 아닌 자원" 즉, 윈도우 핸들, 파일 핸들, 소켓 핸들 등 시스템 자원을 뜻한다. 반대로 managed 는.. new List<int>() 등, 메모리 처럼 쓰는 자원들이다.

그러면 표준 Dispose 패턴은 무엇인가?

  1. Dispose를 IDisposable Interface로 구현한다.
  2. Dispose 내부에선 unmanaged 자원을 해제한다.
  3. 사용자가 Dispose를 사용하지 않았을 경우를 대비하여, finalizer를 구현한다.
  4. finalizer 에서 unmanaged 자원을 해제한다.
이 1 ~ 4 을 구현한 Dispose 를 표준 Dispose 패턴이라고 한다.

finalizer 를 구현하면, 성능상에 나쁜 영향을 주는데, 왜 finalizer를 구현해야 하나?

무제한 unmanaged 자원이 늘어나는게 더 나쁜 영향을 준다. 그래도 finalizer를 구현하지 않겠는가?

왜 finalizer를 구현하면 성능에 나쁘나?

  1. finalizer를 구현하면, GC가 자신이 관리하는 finalizer 큐에 저장한다.
  2. GC에서 사용하는 특정 쓰레드가 finalizer 큐를 읽고, 해제해도 되는지 검사한다.
  3. 검사 후 해제되도 된다면, 그때서야 해제한다.

3번이 될때까지 아직도 해제하지 않고 있는 것과, 검사하는 것에 에너지를 사용하기 때문에 성능에 나쁘다.(얼마나 나쁠지는 모르겠다.)

finalizer에선 어떤 일을 해야 하는가?

사용자가 Dispose()를 사용하지 않았을 경우, unmanaged 자원을 해야 해야 한다.

그러면, 어떻게 Dispose를 구현해야 하는가?

반드시 다음과 같은 기능을 수행해야만 한다.

  1. unmanaged 자원 해제
  2. managed 자원의 해제
  3. Dispose() 한 후 다시 Dispose() 호출 후 이상이 없어야 한다.
  4. Dispose() 한 후 unmanaged 자원 사용 시, ObjectDisposed 예외를 발생 시켜야 한다.
  5. finalization 동작을 막아야 한다.

다 좋은데, 상속 기반에서는 어떻게 하나? IDisposable Interface는 비가상 함수지 않는가?

그렇다. 그래서 가상함수로 Dispose() 기능을 수행하는 함수를 만들어야 한다. 기왕 제 3의 함수 만드니까, finalizer 에서 사용 되는 부분도 줄이면 좋겠다.

.. 그런데 managed 자원은 GC(가비지 켈렉터)가 해제해주는데 굳이 해제해 줄 필요가 있는가?

맞는 말이다. 하지만 어차피 사용되지 않을꺼니까, 가비지 켈렉터가 잘 일할 수 있도록, 해제해 주는게 좋다.

어떻게 managed 자원을 해제 하는가?

.. null 로 만들면 된다. 예를 들어 _list.Clear(); _list = null; 이렇게 하면 된다.

자, 이제 코드로 보여 줄 수 있는가?

Dispose Sample Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
 
namespace console
{
    class ConsoleClass
    {       
        public static void Main()
        {
            using (DerivedDisposeSample t =  new DerivedDisposeSample())
            {               
            }
 
        }
    }
 
    public class BaseDisposeSampleClass : IDisposable
    {
        // -- Dispose 두번 이상
        // -- 호출을 막기 위한것
        private bool _isBaseDisposeSmapleClass = false;
 
        // -- managed resource
        private List<int> _ManagedResource = new List<int>();
 
        // -- unmanaged resource
        // -- 사실 FileStream은 finalizer 가 구현 되어 있으므로, unmanaged 라고 보긴 힘들다.
        // -- 예제를 위해 한것이므로 그러려니 하자
        private FileStream _UnManagedResource = new FileStream("hehe.txt", FileMode.OpenOrCreate);
         
        ~BaseDisposeSampleClass()
        {
            // finalizer 가 호출된 시점에선 이미 Dispose()가 호출 되지 않았으므로
            // managed resource 는 지우지 않는다.
            Dispose(false);
        }
 
        // Dispose 호출
        public void Dispose()
        {
            // managed 까지 제거
            Dispose(true);
 
            // managed 까지 지웠으므로,
            // 이 객체는 finalizer 호출하지 말라고 등록한다.
            GC.SuppressFinalize(this);          
        }
 
        protected virtual void Dispose(bool isDisposing)
        {
            Console.WriteLine("BaseDisposeSampleClass::Dispose(bool isDisposing) is called");
 
            // is called?
            if (true == _isBaseDisposeSmapleClass)
                return;
 
            // managed resource release
            if (true == isDisposing)
            {
                _ManagedResource.Clear();
                _ManagedResource = null;
            }
 
            // unmanaged resource release
            _UnManagedResource.Dispose();
 
            // flag on
            _isBaseDisposeSmapleClass = true;           
        }
    }
 
    public class DerivedDisposeSample : BaseDisposeSampleClass
    {
        private bool _isDerivedDisposeSample = false;
 
        protected override void Dispose(bool isDisposing)
        {
            Console.WriteLine("DerivedDisposeSample::Dispose(bool isDisposing) is called");
 
            if (true == isDisposing)
            {
                // managed resource release...
            }
 
            // unmanaged resource release...
            // ...
            // ..
            // .           
            base.Dispose(isDisposing);
 
            // flag on
            _isDerivedDisposeSample = true;           
        }
    }
}

주의 해야 할 점이 있는가?

  • finalizer 와 Dispose 에서, 객체 생명주기를 바꾸는 행동을 하지 말아야 한다. 만약 객체 생명주기를 건들게 되면, 객체는 더 이상 사용하지 않는데도, managed 자원까지 사라지지 않는 일이 발생 한다. .... 어렵다면, 해제하는 작업만 해야 한다고 알아도 된다.

결론

  • 남이 만든거 갔다가 쓰자. :P
  • 남이 만든게 없을 경우, unmanaged 자원이 있을 경우, 표준 Dispose 패턴으로 구현하자.



출처 : http://ikpil.com/1190 


: