Programing

누군가 사용하지 않는 코드를 삭제 (또는 유지)하는 장점을 설명 할 수 있습니까?

lottogame 2020. 9. 6. 11:51
반응형

누군가 사용하지 않는 코드를 삭제 (또는 유지)하는 장점을 설명 할 수 있습니까?


프로젝트에서 사용하지 않는 코드를 삭제해야한다는 말을 많이 들었습니다. 그러나 나에게 "왜?"는 명확하지 않습니다.

삭제하지 않은 포인트는 다음과 같습니다.

  • 코드가 이미 작성되었으며 노력이 소요됩니다.
  • 코드는 구문 및 실제 환경에서 테스트 될 수 있습니다.
  • 잘 구성되어 있으면 (그룹화, 개별 패키지, 느슨하게 결합 된 등) 전체 코드 분석이나 리팩토링에 방해가되지 않습니다.
  • 나중에 코드가 사용될 수 있습니다.
  • 삭제되면 작성자가 불편 함을 느낄 수 있습니다.

누군가 사용하지 않는 코드를 삭제 (또는 유지)하는 장점을 설명 할 수 있습니까?


사용하지 않는 코드를 제거해야하는 몇 가지 이유는 다음과 같습니다.

  • 프로젝트에 새로 작업하는 사람은 작업 코드를 이해해야 할뿐만 아니라 사용하지 않는 자료도 이해해야합니다. 이것은 낭비되는 시간이며 혼란을 야기합니다.

  • 누군가가 실수로 '휴면'코드를 포함하여 버그를 유발할 수있는 변경을 수행 할 위험이 있습니다. 내가 작업 한 프로젝트에서 일어난 일이라는 것을 알고 있습니다.

  • 모든 코드의 유지 관리는 관리 부담입니다. 오래된 중복 코드를 보존함으로써 부담이 증가합니다. 예를 들어, 작업 할 코드가 많고 실수 할 가능성이 더 많기 때문에 메인 브랜치의 변경 사항 병합이 더 어려워집니다.

  • 시간이 지남에 따라 점점 더 오래된 사용하지 않는 코드가 코드베이스에 추가됩니다. 이것은 혼란, 잠재적 인 오해 및 관리 오버 헤드를 증가시킵니다.

  • 사용하지 않은 코드가 다시 사용될 가능성은 거의 없습니다. 시간이 지나면 재사용 가능성이 감소합니다. 코드를 제거하고 충분히 중요한 것으로 간주되면 코드를 분기하여 문서화 할 수 있습니다.

  • 코더가 열심히 작업 한 코드에 대한 개인적인 감정은 이해할 수 있습니다. 그러나 전문성을 갖추기 위해서는 더 나은 이익을 위해 그러한 생각을 한쪽으로 치워야합니다. 시간은 아무도를 의미하지 않으며 작동하는 코드베이스에서 기록 코드를 보존 할 장소가 없습니다.


@suspectus는 코드를 삭제하는 이유를 훌륭하게 보여주었습니다. 코드 유지에 대한 개별 총알을 다루고 싶습니다.

  • 코드가 이미 작성되었으며 노력이 소요됩니다.

그러나 이미 작성된 코드가 사용되지 않는 경우 이는 (미래) 가치없이 만 비용이 발생합니다. 그것은 헛된 노력에 투자 된 것이며, 이러한 노력의 미사용 제품을 보존한다고해서 그러한 노력이 입증되는 것은 아닙니다. 우리는 코드가 유용하기 때문에 지금은 작성자의 노력을 기념하는 것이 아니라 유용합니다.

  • 코드는 구문 및 실제 환경에서 테스트 될 수 있습니다.

죄송합니다. 무슨 뜻인지 모르겠습니다.

  • 잘 구성되어 있으면 (그룹화, 개별 패키지, 느슨하게 결합 된 등) 전체 코드 분석이나 리팩토링에 방해가되지 않습니다.

코드베이스에 있으면 아무리 잘 구성되어 있어도 유지 관리 및 이해 부담에 기여합니다. 사실, 될 않도록 구성 할 수 있습니다 부담하지만 사라의 경우는 더 부담이 전혀 없습니다.

  • 나중에 코드가 사용될 수 있습니다.

애자일 학교에서는 YAGNI : You Ai n't Gonna Need It 이라고 말합니다 . 예, 당신 미래에 그것을 사용할 있을지도 모르지만 , 우리는 어떤 종류의 신뢰성으로도 그것을 예측할 수있는 내일의 필요성에 대해 오늘 충분히 알 수 없습니다. 다르게 생각하는 것은 오만함이 오만하다. 우리가 할 수 내일에 대해 알고 것은 : 우리는 우리의 코드베이스가 특징에서 코드 detracts 수정하기 쉽고, 사용되지 않는되고 싶어요.

  • 삭제되면 작성자가 불편 함을 느낄 수 있습니다.

저자는 그것을 극복해야합니다. 우리는 모두 유용하지 않은 것으로 밝혀진 내용을 작성했습니다. 사용중인 코드 본문을 가리킬 수있는 것이 훨씬 낫습니다 (사용하지 않는 부분이 삭제 되었기 때문에). 몇 가지 방법, "실제로 사용 중입니다!"


코드를 집어 들고 의도를 파악하는 것이 충분히 어렵지 않습니까? 그러나 이제 사용하지 않는 부분을 파악해야합니까?


코드가 이미 작성되었으며 노력이 소요됩니다.

또한 불필요합니다. 당신이 그것을 아무것도 사용하지 않는다면, 그것이 무엇을하는지 또는 그것에 얼마나 많은 노력을 쏟았는지에 관계없이 (정의상) 쓸모가 없습니다.

코드는 구문 및 실제 환경에서 테스트 될 수 있습니다.

쓸모 없다면 테스트를해도 쓸모가 없다. 코드가 쓸모 없으면 테스트도 쓸모가 없어야합니다 (주석 코드를 그대로 유지하면 모호함이 생깁니다. 테스트를 유지합니까? 주석 코드의 클라이언트 코드가있는 경우 클라이언트 코드도 주석 처리합니까? )

잘 구성되어 있으면 (그룹화, 개별 패키지, 느슨하게 결합 된 등) 전체 코드 분석이나 리팩토링에 방해가되지 않습니다.

별로. 모든 도구 (소스 제어, 정적 분석, 문서 추출기, 컴파일러 등)는 더 많은 데이터를 처리해야하기 때문에 느리게 실행됩니다 (데이터의 더 크거나 작은 부분은 노이즈 임).

반면에 코드가 구성 되지 않으면 정적 분석, 리팩토링 및 기타 문제가 발생합니다.

도구 입력에 노이즈를 도입하고 올바르게 대처하기를 바랍니다.

정적 분석 도구가 주석 / 코드 비율을 계산하면 어떨까요? 어제까지 (또는 코드가 주석 처리 될 때마다) 관련이있는 내용으로 방금 엉망으로 만들었습니다.

Most relevant of all, commented blocks of code introduce delays in understanding the code for maintenance and further development and such delays almost always cost a lot. Ask yourself this: If you need to understand the implementation of a function, what would you rather have to look at? two lines of clear code, or two lines of code and another twenty-six of comments that are no longer actual?

Code may be used in future

If it is, you will find it in your team's SCM of choice.

If you use a competent SCM and rely on it to keep the dead code (instead of cluttering up the source), you should see not only who deleted that code (commit author), but for what reason (commit message), and what other changes were made along with it (the rest of the diffs for that commit).

When deleted, author may feel uncomfortable

So?

You are (I assume) an entire team of developers that gets payed to make the best software you know how to, not "the best software you know how to without hurting the feelings of X".

It's a part of programming, that most code written will ultimately be discarded; for example, Joel Spolsky said at some point that for his company, approximately 2% of written code sees production.

If you prioritize the ego of developers over the quality of the code base, you will sacrifice the quality of your product, for ... what exactly? Preserving the immaturity of your fellow developers? Protecting the unrealistic expectations of your colleagues?

Edit: I have seen one valid reason to leave commented out code in the source, and it is a very specific case: when the code is written in a weird/un-intuitive form and the clean way of re-writing it doesn't work for a really subtle reason. This should also be applied only after a repeated attempt has been made to correct the issue and every time the attempt has re-introduced the same defect. In such a case, you should add the commented intuitive code as a comment, and explain why it doesn't work (so future developers will not attempt the same change again):

// note by <author>: the X parameter here should normally
// be a reference:
// void teleport(dinosaur& X);
// but that would require that we raise another dinosaur and
// kill it every twelve hours
// as such, the parameter is passed by value
void teleport(dinosaur X);

Dead code is polluting your code

Dead code decreases understandability and readability.

Best codes are always reused, and if u have dead codes it reduces reusability

We are driven by modular approach of coding, where we design codes for interaction with our fellow programmers, not for a machine. We should put the most energy to make it easy for he/she to understand our code. The machine will be fine anyway.

Dead or commented code is like false trail signs that only confuse people, so avoid it at all costs.


  • Fear. This makes the team worry more and produce less. The amount of fear goes up exponentially when more dead code is introduced. "We don't know if that bit is used, so we don't dare remove it or touch it."
  • Sweeping changes. If something that needs to be changed everywhere in the system also exists in the dead code, do you change it? It's very hard to know if it is definitely not used somewhere, so it's always a risk. And even if it wouldn't break anything, would the dead code work at all if it would be taken back to use after this change?

    When dealing with a sweeping change the developers will also have to check every place that contains the code and in the case of dead code this is redundant. And checking them takes longer when the code's dead since it's hard to verify that it isn't used anywhere.

  • Mental load. Everytime you need to think about whether something is used or whether you should do something to the dead code, it takes some of your brain power.
  • Wild goose chases. "I need an example on how to use Foobar. Oh it's in these places in the codebase. I'll check the first hit and find out where this is in the UI. Hmm... Can't find it anywhere."
  • Inflated reports (e.g. how many lines of code, classes, routines, changes). Distorts visibility of the project and decisions on what parts of the codebase should be worked on and estimations of future projects.
  • Weakened trust on the codebase. This can result in more time spent on redundant tasks and it breaks the flow of using the codebase. Developers might have to check extremely carefully that everything they use will work in the way they think it should.

It is extremely valuable if you know that a part of the codebase is not used because then you can remove it. If you let it stay then in the future it can be hard or almost impossible to be certain that it is actually not used. For example, some of the things that use code in surprising ways: reflection, dynamically calling routines concatenated from strings, eval, framework magic.

However, if there is a high probability that code will be used in the future, it is easier to add if it's right there along the other code instead of in the version control system. You might not remember any words that the code had after a while so it can be very hard to find the code from the bowels of the VCS. But I'd let dead code exist only rarely and even then I'd comment the code out.


  • Unused code is a bigger search space for both you to read through and anything else that generally scans your code. For example a compiler, IDE, find in file, debugging, static analysis, more to review, file inclusion, checking out from VCS, etc. This slows down those processes and adds significant noise.
  • Unused code isn't always dead code. It may execute in certain circumstances. This can not only offer a vector for bugs and performance issues but can also be a security concern. In respect to performance this can express itself in unexpected ways such as larger downloads.
  • Unused code begets unused code. If you delete a function call and then search for uses of that function to see if its still needed you might see a match from previous unused code and assume you can keep it. The more unused code you have the more hops it is to determine if code is unused.
  • Unused code still often ends up having to be maintained. Lets say A and B depend on C. Out of those B isn't used. You change C and then B wont compile because you've removed a member from a struct in C that B required, now you have to fix B or actively remove it from compilation. You should have simply removed it.

This list might seem simple but each of these manifests in hundreds of different ways adding drag that synergises throughout the entire development process. The inefficiency can often be proven or demonstrated in a straight forward and mathematical manner.

In response to your points...

  • Code is already written, and efforts are spent

But it often must be maintained. It will also show up still in things such as find in file.

  • Code may be tested on syntetical and real environment

I'm not sure what you mean by this one. I think it's the same as the last one. You mean that the code is already tested and cleaning it up might mean it needs retesting. That's a cost that's usually worth it because it will pay off 90% of the time and to avoid that it should have been cleaned before going out into production. Nearly all code has two iterations, make it work, make it clean. The reason is has to be tested twice is because someone skipped the last step. If you code is also too expensive to proof read the diff, test (which it likely is if it's messy with lots of unused code), etc then that's another entire problem.

  • If organized well (grouped, separate package, loosely coupled etc) it doesn't disturbs you on overall code analysis or refactoring

Your code should be like this anyway but that only moderately mitigates the problem. It's the strangest argument to hear that something should be organised yet unclean. It's normal to try to keep code modular and reduce dependencies but you also want reusable code and if all of your modules are an island chances are you've not been DRY. You may also find yourself doing excessive decoupling that does nothing but mitigates the problem of unused messy code.

  • Code may be used in future

A lot of people over value written code. If it's not used now it's deadweight and in reality when you go down this path often only a fraction of unused code becomes used code. In all probability unused code is not likely to be usable or used code. The most likely to be reused code is already used code that's doing something.

What's worse is that unused code doesn't have a purpose. When someone comes along and has to change something that ends up impacting unused code they're going to be stumped sitting there trying to figure out what this unused code with no purpose needs to do.

It's easy for people to feel like this when starting out as code takes a lot of effort. Once fluent however and used to it code becomes like riding a bike. You'll find as the cost of writing such a piece of code plummets the cost of keeping it creeps up.

  • When deleted, author may feel uncomfortable

This is the author's problem. On the one hand it is selfish to leave around loads of unused code for others to have to deal with. On the other if an author puts their feelings over code quality then they probably shouldn't be coding. You go down the road with this of you can't fix their code when it's broken because it'll hurt their feelings. It is not a good sign if someone is attached to code simply because it is theirs rather than because it is good. An author should feel happy at their code being cleaned. This is like someone taking out your trash for you and tossing it in the bin.

I would be over the moon if someone did that for me. What might make it easier to get over those feelings is instead of waiting for someone else to do it try doing it yourself. Keep iteratively rewriting a piece of code you've done, making it perform better, move concise, with less excess and more flexible yet with less code each time. Try not to feel good about the quantity of code but how much you can achieve with however little code. This is grinding to level up and once you do that all your code will come out at a good level following so it wont need to be leveled as often.


First of all you should always use a source control tool to manage your projects and hence removing unused code is a good practice as you can always go back using source control to get the removed code. For me the reason to remove unused code is that only the person who know the code is unused knows about it, someone else in the team will come across that code and try to figure out what it does and how it fits in the whole application and will feel disappointed after so much effort that the code is not used at all :)


This discussion is several years old, but I just ran into it...

One thing that I did not see mentioned is the work that must be incurred to remove the unused code. In many cases, the time and effort to remove the unused code is not trivial in nature, plus there are typically additional costs to test and document the refactored system. Just another thing to consider in the decision process.


I think that you can have two cases: - application code : if it unused maybe it is untested and unmantained over the time, maybe you can shift to a "internal code repository" - API code : if you are writing a library then IMHO it's a better choice to maintains it but inside your active development process


Are you sure the code is unused?

It's not enough to check the code still compiles. In C++, if you remove an "unused" implicitly defined method like operator= you're not going to get a compiler error, the class will just silently begin to use a (potentially incorrect) default implementation. In Java or C# the code might be used via reflection. In object-oriented languages, inheritance can play a role (the base class may now be called). In almost any language, another overloaded function may have taken over.

Check the age of the code in version control, not just that it's unused. I've seen code that looked unused but had just been committed, and was actually the first step in another developer's project.

Aggressively remove unused code

You pay to maintain code:

  • Fixing broken builds (engineering time). We recently had a complicated chain of #include change, introducing a new overload to unused code, leading to a reasonably-sized headache for every engineer on a team of dozens of developers.
  • In machine resources on tests (assuming you have self-testing continuous builds). My team recently looked at all of our slowest tests, and many of them were over otherwise unused code. Engineers running tests locally or as part of continuous integration are waiting for tests over unused code.
  • In terms of readability (engineering time again). Your header files represent an API. If they include functions no one would want to use but everyone has to read, your code's learning curve is that much harder.
  • In code searches (engineering time again). Would you clean up your house, your hard drive, or Google Drive? The more you search a domain, the more important it is for it to have relevant content to avoid false positives (or you use more sophisticated search like a web search engine).

I'd say essentially all the code the average developer writes becomes unused on a five year horizon so this activity never stops. Don't let this be you; only write high quality and absolutely necessary code.

참고URL : https://stackoverflow.com/questions/15699995/could-someone-explain-the-pros-of-deleting-or-keeping-unused-code

반응형