UFO ET IT

얼마나 자주 리팩토링해야합니까?

ufoet 2020. 12. 26. 15:45
반응형

얼마나 자주 리팩토링해야합니까?


몇 주 전에 동료들과 리팩토링에 대해 토론을했는데, "일찍 리팩터링하고 자주 리팩터링"하는 것이 코드가 지저분 해지고 유지 보수가 불가능 해지지 않도록하는 좋은 접근 방식이라고 믿는 소수 인 것 같습니다. 다른 많은 사람들은 그것이 프로젝트의 유지 보수 단계에 속한다고 생각했습니다.

의견이 있으시면 변호 해주십시오.


말씀하신대로 : 일찍 리팩토링하고 자주 리팩토링하세요.

초기 리팩토링은 필요한 변경 사항이 여전히 내 마음에 새롭다는 것을 의미합니다. 리팩토링은 종종 변경 사항이 더 작은 경향이 있음을 의미합니다.

리팩토링을 지연하는 것은 결국 큰 혼란을 야기하여 리팩토링을 더욱 어렵게 만듭니다. 엉망이 된 것을 알아 차리 자마자 정리하면 나중에 문제가되는 것을 막을 수 있습니다.


코드가 작동하는 즉시 리팩터링합니다 (모든 테스트가 통과 됨). 이런 식으로 나는 그것이 내 마음에 여전히 신선 할 때, 그리고 다른 사람이 첫 번째 버전이 얼마나 추악한 지보기 전에 그것을 정리합니다.

초기 체크인 후에는 일반적으로 코드를 만질 때마다 리팩터링합니다. 리팩토링은 별도의 시간을 따로 설정해야하는 것이 아닙니다. 그것은 당신이가는 동안 당신이하는 일이어야합니다.


모자 두 개를 쓰고 코드를 작성합니다. 단지 - 수 - 더 - 일 - 작업 모자와 I-필요 - 이해 -이 - 내일에 모자를. 분명히 두 번째 모자는 리팩토링입니다. 그래서 당신은 무언가를 만들었을 때마다 리팩토링을했지만 중복 된 코드, 긴 메서드, 깨지기 쉬운 오류 처리, 잘못된 변수 이름 등과 같은 냄새를 (필연적으로) 도입했습니다.

리팩토링을 시도하는 동안 (즉, 두 모자를 모두 쓰고) 사소한 작업에는 실용적이지 않습니다. 그러나 다음 날 / 주 / 반복까지 리팩토링을 연기하는 것은 문제의 맥락이 머리에서 사라질 것이기 때문에 매우 나쁩니다. 따라서 가능한 한 자주 모자를 바꾸 되 조합하지 마십시오.


가능한 한 최선을 다해 코드를 다듬을 수 있기 때문에 모든 기회를 리팩토링합니다. 처음부터 유지 관리 할 수없는 코드가 생성되는 것을 방지하기 위해 적극적으로 개발할 때도 이렇게합니다. 또한 종종 수정 불가능 해지기 전에 잘못된 설계 결정을 바로 잡을 수 있습니다.


리팩토링해야하는 세 가지 이유 :

  • 원래 디자인 (아마도 매우 작은 영역에 있지만 그럼에도 불구하고 디자인)이 잘못되었습니다. 여기에는 일반적인 작업을 발견하고 코드를 공유하려는 위치가 포함됩니다.
  • 반복적으로 디자인하고 있습니다.
  • 코드가 너무 나빠서 대대적 인 수리가 필요합니다.

리팩토링하지 말아야 할 세 가지 이유 :

  • "조금 지저분 해 보입니다."
  • "마지막 사람이 한 방식에 전적으로 동의하지 않습니다."
  • "더 효율적일 수 있습니다". (문제는 '마이트'입니다).

"지저분 함"은 논란의 여지가 있습니다. "깨진 창 고치기"또는 "코드 위생"이라고하는 유효한 주장이 있습니다. 이는 작은 것을 미끄러지게하면 큰 것도 미끄러지기 시작한다는 것을 암시합니다. 괜찮고 명심해야 할 좋은 일이지만 비유라는 것을 기억하십시오. 가능한 가장 깨끗한 해결책을 찾기 위해 끊임없이 물건을 우회하는 것을 변명하지 않습니다.

얼마나 자주 리팩터링해야하는지는 좋은 이유가 발생하는 빈도와 테스트 프로세스가 버그를 발생시키지 않도록 보호한다는 확신에 따라 다릅니다.

리팩토링은 그 자체로 목표가 아닙니다. 그러나 무언가가 작동하지 않으면 수정해야합니다. 이는 유지 관리에서와 마찬가지로 초기 개발에서도 마찬가지입니다. 사소하지 않은 변경의 경우 다른 곳에서 변경을 방지하기 위해 단일 장소를 큰 덩어리로 패치하는 것보다 리팩토링하고 새로운 개념을 깔끔하게 통합하는 것이 거의 항상 좋습니다.

그만한 가치가있는 것은 인터페이스를 사용하는 것에 대한 핸들이 있고 결과 변경의 범위를 관리 할 수 ​​있다면 인터페이스를 변경하는 것은 아무것도 생각하지 않습니다.


책에서 말했듯이, 당신은

  • 코드를 추가하면 ... 새로운 기능
  • 버그 / 결함을 수정할 때
  • 여러 사람과 코드 검토를 할 때
  • 세 번째로 무언가를 복제 할 때 .. 3 스트라이크 규칙

아이디어를 쏟아 낼 때 많은 경우 내 코드는 매우 밀접하게 결합되고 지저분합니다. 아이디어를 다듬기 시작하면 논리적 분리가 점점 더 명확 해지고 리팩토링을 시작합니다. 그것은 끊임없는 과정이며 모든 사람들이 제안하는 것처럼 '조기 및 자주'해야합니다.


나는이 모토를 따르려고 노력한다 : 당신이 만지는 모든 코드를 예전보다 더 잘 남겨 두라.

수정하거나 기능을 추가 할 때 일반적으로 그 기회를 사용하여 영향을받는 코드에 대해 제한된 리팩토링을 수행합니다. 종종 이렇게하면 의도 한 변경을 더 쉽게 수행 할 수 있으므로 실제로 비용이 들지 않습니다.

그렇지 않으면 리팩토링을위한 전용 시간을 계획해야합니다. 항상 불을 피우고 있기 때문에 할 수없는 경우 (이유가 궁금합니다) 변경 작업이 예상보다 훨씬 어려워지고 "코드 냄새"가 날 때 리팩토링을해야합니다. 참을 수 없습니다.


다음과 같은 경우 리팩터링합니다.

코드를 수정하고 있는데 혼란 스럽습니다. 걸러내는 데 시간이 걸리면 리팩토링이 필요합니다.

새 코드를 만들고있는 중이며 "작동"한 후. 종종 나는 일을하게 될 것이고 코딩을하면서 "이봐, 내가 한 일을 몇 번만 변경하면 20 줄을 다시해야한다"는 것을 깨달았다. 그 시점에서 나는 리팩토링하고 계속합니다.

제 생각에 이런 일을 막아야 할 유일한 것은 시간 제약입니다. 좋든 싫든 때때로 당신은 그것을 할 시간이 없습니다.


그것은 국립 공원과 같습니다. 항상 당신이 찾은 것보다 조금 더 잘 남겨주세요.

나에게 그것은 내가 코드를 열고 무슨 일이 일어나고 있는지 파악하기 위해 머리를 긁어 야 할 때마다 무언가를 리팩토링해야 함을 의미합니다. 나의 주요 목표는 가독성과 이해입니다. 일반적으로 명확성을 위해 변수의 이름을 바꾸는 것입니다. 때로는 방법을 추출하고 있습니다.

예를 들어 (사소한), 만약 내가 본다면

temp = array[i];
array[i] = array[j];
array[j] = temp;

아마도 그것을 swap (i, j) 메서드로 대체 할 것입니다.

컴파일러는 어쨌든 그것을 인라인 할 것이고 swap ()은 모든 사람에게 무슨 일이 일어나고 있는지 의미 론적으로 알려줍니다.

즉, 내 자신의 코드 (처음부터 시작)로 디자인을 위해 리팩터링하는 경향이 있습니다. 나는 종종 구체적인 수업에서 일하는 것이 더 쉽다고 생각합니다. 완료되고 디버깅되면 이전 Extract Interface 트릭을 가져옵니다.

코드에 너무 가까워서 구멍을 알아 채지 못하기 때문에 가독성을 위해 리팩토링하기 위해 동료에게 맡길 것입니다. 결국 나는 내가 무엇을 의미하는지 압니다.


기회에 따라 리팩터링하십시오! 쉬울 때마다하십시오 .

리팩토링이 어려운 경우 잘못된 시간 (코드에 필요하지 않은 경우) 또는 잘못된 코드 부분 (다른 곳에서는 더 나은 효율성을 얻을 수있는 곳)에서 수행하는 것입니다. (또는 아직 리팩토링을 잘하지 못합니다.)

"유지 보수"를위한 리팩토링을 저장하는 것은 팽팽합니다. 리팩토링 유지 관리입니다.


나는 모든 것을 읽을 때마다 리팩토링 하고 더 읽기 쉽게 만들 있습니다. 큰 구조 조정이 아닙니다. 그러나 내가 "이게 뭐가 List포함되어 있니? 오, Integers!" 라고 생각하면 그런 다음 List<Integer>. 또한 IDE에서 메서드를 추출하여 몇 줄의 코드로 좋은 이름을 지정합니다.


대답은 항상이지만보다 구체적으로 :

  • QA로 이동하기 전에 각 작업에 대해 분기 한 다음 각 새 분기에서 분기한다고 가정합니다.
  • 트렁크에서 모든 것을 개발하면 각 커밋 전에.
  • 이전 코드를 유지 관리 할 때 새 작업에 위의 내용을 사용하고 이전 코드의 경우 추가 QA를받을 주요 릴리스에서 리팩토링을 수행합니다.

필요할 때마다. 최소한 리팩토링이 필요한 코드를 변경할 때.


I localize refactoring to code related to my current task. I try to do my refactoring up front. I commit these changes separately since from a functional standpoint, it is unrelated to the actual task. This way the code is cleaner to work with and the revision history is also cleaner.


Continuously, within reason. You should always be looking for ways to improve your software, but you have to be careful to avoid situations where you’re refactoring for the sake of refactoring (Refactorbation).

If you can make a case that a refactoring will make a piece of code faster, easier to read, easier to maintain or easier or provide some other value to the business I say go for it!


"Refactor early, refactor often" is a productive guideline. Though that kind of assumes that you really know the code. The older a system gets, the more dangerous refactoring becomes, and the more deliberation is required. In some cases refactoring needs to be managed tasks, with effort level and time estimates, etc.


If you have a refactoring tool that will make the changes safely, then you should refactor whenever the code will compile, if it will make the code clearer.

If you do not have such a tool, you should refactor whenever the tests are green, if it will make the code clearer.

Make small changes -- rename a method to make what it does clearer. Extract a class to make a group of related variables be clearly related. Refactoring is not about making large changes, but about making things cleaner minute by minute. Refactoring is clearing your dishes after each meal, instead of waiting until every surface is covered in dirty plates.


Absolutely as soon as it seems expedient. If you don't the pain builds up.

Since switching to Squeak (which I now seem to mention every post) I've realised that lots of design questions during prototyping fall away because refactoring is really easy in that environment. To be honest, if you don't have an environment where refactoring is basically painless, I recommend that you try squeak just to know what it can be like.


Refactoring often can often save the day, or at least some time. There was a project I was working on and we refactored all of our code after we hit some milestone. It was a great way because if we needed to rip code out that was no longer useful it made it easier to patch in whatever new thing we needed.


We're having a discussion at work on this right now. We more or less agree that "write it so it works, then fix it". But we differ on the time perspective. I am more "fix it right away", my coworker is more "fix it in the next iteration".

Some quotes that back him up:

Douglas Crockford, Senior Javascript Architect Yahoo:

refactor every 7th sprint.

Ken Thompson (unix man):

Code by itself almost rots and it's gonna be rewritten. Even when nothing has changed, for some reason it rots.

I would like that once done with a task the code submitted is something you can come back to in 2 months and think "yes, I did well here". I do not believe that it is easy to find time to come back later and fix it. believing this is somewhat naive from my point of view.

Edit: spelling error


I think you should refactor something when you're currently working on a part of it. Means if you have to enhance function A, then you should refactor it before (and afterwards?). If you don't do anything with this function, then leave it as it is, as long as you have something else to do.

Do not refactor a working part of the system, unless you already have to change it.


There are many views on this topic, some linked to a particular methodology or approach to development. When using TDD, refactor early and often is, as you say, a favoured approach.

In other situations you may refactor as and when needed. For example, when you spot repetitious code.

When following more traditional methods with detailed up-front design, the refactoring may be less often. However, I would recommend not leaving refactoring until the end of a project. Not only will you be likely to introduce problems, potentially post-UAT, it is often also the case that refactoring gets progressively more difficult. For this reason, time constraints on the classic project cause refactoring and extra testing to be dropped and when maintenance kicks in you may have already created a spaghetti-code monster.


If it ain't broke, don't refactor it.

I'd say the time to refactor belongs in the initial coding stage, and ou can do it as often and as many times as you like. Once its in the hands of a customer, then it becomes a different matter. You do not want to make work for yourself 'tidying' up code only to find that it gets shipped and breaks something.

The time after initial delivery to refactor is when you say you'll do it. When the code gets a bit too smelly, then have a dedicated release that contains refactorings and probably a few more important fixes. That way, if you do happen to break something, you know where it went wrong, you can much more easily fix it. If you refactor all the time, you will break things, you will not know that its broken until it gets QAd, and then you'll have a hard time trying to figure out whether the bugfix/feature code changes caused the problem, or some refactoring you performed ages ago.

Checking for cbreaking changes is a lot easier when the code looks roughly like it used to. Refactor a lot of code structure and you can make it next to impossible, so only refactor when you seriously mean to. Treat it like you would any other product code change and you should be ok.


I think this Top 100 Wordpress blog post may have some good advice. http://blog.accurev.com/2008/09/17/dr-strangecode-or-how-i-learned-to-stop-worrying-and-love-old-code/

ReferenceURL : https://stackoverflow.com/questions/140677/how-often-should-you-refactor

반응형