본문 바로가기

General

[클린 코드] 1장 깨끗한 코드

코드가 존재하리라

누군가는 코드의 종말이 코앞에 닥쳤다고 주장하지만, 코드가 사라질 가망은 전혀 없다. 

프로그래밍이란, 기계가 실행할 수 있을 정도로 상세하게 요구사항을 명시하는 작업이다. 사실 창의력과 직관을 보유한 우리 인간조차도 고객의 막연한 감정만 갖고는 성공적인 시스템을 구현할 수 없다. 코드는 요구사항을 정밀하게 표현하는 언어이다. 고도로 추상화된 언어 또한 코드이다. 그러므로 코드도 항상 존재하리라.

 

The only valid measurement of code quality: WTFs/m

 

나쁜 코드로 치르는 대가

프로그래머라면 누구나 당연히 나쁜 코드로 고생한 경험이 있다. 나쁜 코드는 개발 속도를 크게 떨어뜨린다. 얽히고 설킨 코드를 해독하느라 더 얽히고 설킨 코드를 추가하게 된다. 나쁜 코드는 실제로 회사를 망하게 할 수 있다. 

나쁜 코드를 짠 이유는 무엇인가? 제대로 짤 시간이 없다고 생각해서, 지겨워서 빨리 끝내려고, 다른 업무가 너무 밀려 후딱 해치우고 밀린 업무로 넘어가려고... 모두가 경험한 상황이다.

자신이 짠 쓰레기 코드를 쳐다보며 나중에 손보겠다고 생각한다. 그래도 대충 짠 프로그램이 돌아간다는 사실에 안도감을 느낀다. 다시 돌아와 나중에 정리하겠다고 다짐하지만, 르블랑의 법칙에 따르면 나중은 결코 오지 않는다. (Later equals never.)

생산성을 증가시키려고 프로젝트에 인력을 추가하지만, 새 인력은 시스템 설계에 대한 조예가 깊지 않다. 설계 의도에 맞는 변경과 설계 의도에 반하는 변경을 구분하지 못한다. 그래서 결국 나쁜 코드가 더 많이 양산된다.

마침내 팀에 반기를 들고 관리층에 재설계를 요구한다. 관리층은 생산성이 바닥이라는 사실을 부인할 수 없다. 결국 원대한 재설계를 추진한다. 이를 위해 새로운 팀이 구성된다. 모두가 새 팀에 합류하고 싶어한다. 처음부터 시작해 진정으로 아름다운 작품을 창조할 기회니까. 하지만 가장 유능한 사람들만 새 팀으로 차출되고, 나머지는 계속해서 현재 시스템을 유지보수한다.

이제 두 팀이 경주를 시작한다. 새로운 팀은 기존 시스템 기능을 100% 제공해야 한다. 그동안 기존 시스템에 가해지는 변경도 모두 따라 잡아야 한다. 그렇지 않으면 새 시스템으로 마이그레이션할 수 없다.

(나쁜 코드의 위험을 이해하지 못하는) 상사의 말을 그대로 따르는 것은 전문가 답지 못하다. 좋은 코드를 사수하는 일은 바로 우리 프로그래머의 책임이다. 그리고 사실 기한을 맞추는 유일한 방법은 언제나 최대한 깨끗하게 코드를 유지하는 습관이다.

 

깨끗한 코드란?

유명하고 노련한 프로그래머들이 말하는 '깨끗한 코드(Clean Code)'

비야네 스트롭스투룹(Bjarne Stroustrup)가 말하는 깨끗한 코드

  • 깨끗한 코드는 한 가지를 제대로 한다. (저자, 나쁜 코드는 너무 많은 일을 하려 애쓰다가 의도가 뒤섞이고 목적이 흐려진다.)
(원문)

I like my code to be elegant and efficient.


The logic should be straightforward to make it hard for bugs to hide,
the dependencies minimal to ease maintenance,
error handling complete according to an articulated strategy,
and performance close to optimal so as not to tempt people to make the code messy with unprincipled optimizations.

Clean code does one thing well.

 

그래디 부치(Grady Booch)가 말하는 깨끗한 코드

  • 깨끗한 코드는 잘 쓴 문장처럼 읽힌다.
  • 결코 설계자의 의도를 숨기지 않는다.
  • 명쾌한 추상화와 단순한 제어문으로 가득하다.
(원문)

Clean code is simple and direct.

Clean code reads like well-written prose.
Clean code never obscures the designer’s intent but rather is full of crisp abstractions and straightforward lines of control.

 

데이브 토마스(Dave Thomas)가 말하는 깨끗한 코드

  • 깨끗한 코드는 작성자가 아닌 사람도 고치기 쉽다.
  • 의미있는 이름이 붙는다.
  • 특정 목적을 달성하는 방법은 단 하나만 제공한다.
(원문)

Clean code can be read, and enhanced by a developer other than its original author.

It has unit and acceptance tests.
It has meaningful names.
It provides one way rather than many ways for doing one thing.
It has minimal dependencies, which are explicitly defined, and provides a clear and minimal API.

Code should be literate since depending on the language, not all necessary information can be expressed clearly in code alone.

 

마이클 페더스(Michael Feathers)가 말하는 깨끗한 코드

  • 깨끗한 코드는 언제나 누군가 주의깊게 짰다는 느낌을 준다. 고치려고 살펴봐도 딱히 손 댈 곳이 없다.
(원문)

I could list all of the qualities that I notice in clean code, but there is one overarching quality that leads to all of them.

Clean code always looks like it was written by someone who cares.

There is nothing obvious that you can do to make it better.
All of those things were thought about by the code's author, and if you try to imagine improvements, you're led back to where you are, sitting in appreciation of the code someone left for you - code left by someone who cares deeply about the craft.

 

론 제프리스(Ron Jeffries) 가 말하는 깨끗한 코드

  • 중복과 표현력만 신경써도 내가 생각하는 깨끗한 코드라는 목표에 성큼 다가선다.
(원문)

In recent years I begin, and nearly end, with Beck's rules of simple code.

In priority order, simple code:
Runs all the tests;
Contains no duplication;
Expresses all the design ideas that are in the system;
Minimizes the number of entities such as classes, methods, functions and the like.

Of these, I focus mostly on duplication. When the same thing is done over and over, it's a sign that there is an idea in out mind that is not well represented in the code. I try to figure out what it is. Then I try to express that idea more clearly.

Expressiveness to me includes meaningful names, and I am likely to change the names of things several times before I settle in. With modern coding tools such as Eclipse, renaming is quire inexpensive, so it doesn't trouble me to change. 

Expressiveness goes beyond names, however. I also look at whether an object or method is doing more than one thing. If it's an object, it probably needs to be broken into two or more objects. If it's a method, I will always use the Extract Method refactoring on it, resulting in one method that says more clearly what it does, and some submethods saying how it is done.

Duplication and expressiveness take me a very long way into what I consider clean code, and improving dirty code with just these two things in mind can make a huge difference. There is, however, one other thing that I'm aware of doing, which is a bit harder to explain.

After years of doing this work, it seems to me that all programs are made up of very similar elements. One example is "find things in a collection". Whether we have a database of employee records, or a hash map of keys and values, or an array of items of some kind, we often find ourselves wanting a particular item from that collection. When I find that happening, I will often wrap the particular implementation in a more abstract method or class. That gives me a couple of interesting advantages.

I can implement the functionality now with something simple, say a hash map, but since now all the references to that search are covered by my little abstraction, I can change the implementation any time I want. I can go forward quickly while preserving my ability to change later. In addition, the collection abstraction often calls my attention to what's "really" going on, and keeps me from running down the path of implementing arbitrary collection behavior when all I really need is a few fairly simple ways of finding what I want.

Reduced duplication, high expressiveness, and early building of simple abstractions.
That's what makes clean code for me. 

 

워드 커닝햄(Ward Cunningham)이 말하는 깨끗한 코드 

  • 코드를 읽으면서 짐작했던 기능을 각 루틴이 그대로 수행한다면 깨끗한 코드라 불러도 되겠다.
(원문)

You know you are working on clean code when each routine you read turns out to be pretty much what you expected.
You can call it beautiful code when the code also makes it look like the language was made for the problem.

 

우리는 저자다

코드를 짤 때, 독자가 있다는 사실을 기억하기를 바란다. 코드를 작성하는 우리는 저자다. 저자에게는 독자와 잘 소통할 책임도 있다. 독자는 여러분의 노력을 보고 판단을 내릴 것이다.

새 코드를 작성하면서도 우리는 끊임없이 기존 코드를 읽는다. 주변 코드를 읽지 않으면 새 코드를 짜지 못한다. 코드를 읽는 시간 대 작성하는 시간 비율이 10:1을 훌쩍 넘는다. 따라서 읽기 쉬운 코드가 매우 중요하다. 

 

보이스카우트 규칙

Always leave the campground cleaner than you found it.

 

체크아웃할 때보다 좀 더 깨끗한 코드를 체크인한다면 코드는 절대 나빠지지 않는다.

한꺼번에 많은 시간과 노력을 투자해 코드를 정리할 필요가 없다. 변수 이름 하나를 개선하고, 조금 긴 함수 하나를 분할하고, 약간의 중복을 제거하고, 복잡한 if 문 하나를 정리하면 충분하다.

시간이 지날수록 코드가 좋아지는 프로젝트에서 작업한다고 상상해보라. 지속적인 개선이야말로 전문가 정신의 본질이다.

 

 

출처: 도서 클린코드 애자일 소프트웨어 장인 정신, 로버트 C.마틴 지음 | 박재호, 이해영 옮김 | 인사이트