- 의문점
알고리즘 문제 풀 때 let 이렇게 변수 많이 쓰고 막 변형시키면 내 코드가 mutable 하다고 까일 때 많은데 (이유 물어보면 뭐 디버깅 힘들다 등)
저게 어디서 나온 개념인지 궁금 그냥 실전에서 나온 얘기인지 항상 궁금했음
답변
What's wrong with mutability and can it be desirable?
Possible Duplicate: At what point do immutable classes become a burden? This is something I never understood. When learning C++, for instance, I had lots of headaches with const issues, as it ...
softwareengineering.stackexchange.com
말뿐인 대답은 가변성이 필요하다는 것입니다. 왜냐하면 아무것도 바꾸지 않는 소프트웨어는 의미가 없기 때문입니다. 궁극적으로, 프로세스의 입력 및 출력에 불과하더라도 최소한 일부 데이터는 변경할 수 있습니다.
하지만, 당신은 왜 당신이 당신의 프로그램의 다양한 부분에서 가변적인 데이터 대신에 불변의 데이터를 사용하는 것을 선택하는지 묻고 있고, 그것에 대한 답은 복잡성이다.
복잡성은 소프트웨어를 어렵게 만드는 것이다. 가변 데이터는 변경될 수 있기 때문에 본질적으로 복잡합니다.
복잡성이 소프트웨어를 어렵게 만드는 이유입니다. 소프트웨어를 사용하면 무엇이든 하기가 어렵기 때문입니다. 그것은 당신의 모든 주 앞에서 옳은 일을 하는 것의 복잡성일 수도 있고, 동시성의 복잡성일 수도 있고, 새로운 요구사항을 충족시키기 위해 코드를 바꾸는 복잡성일 수도 있다.
그러나 궁극적으로 단순한 소프트웨어일수록 작업을 계속하고 시간이 지남에 따라 개선하는 것이 더 쉽습니다. 소프트웨어 비용의 대부분이 실제로 소프트웨어의 전체 수명 동안 작동하도록 유지하는 것이라는 많은 교육, 경험 및 관련 논의가 있다.
변경 가능한 데이터가 소프트웨어를 더 복잡하게 만드는 이유는 데이터에 대해 수행해야 할 생각을 대조해 보면 매우 간단합니다.
데이터가 불변인 경우 데이터의 의미, 처음 할당된 위치 및 데이터가 여기서 어떻게 사용되는지 알아야 합니다.
데이터가 변경 가능한 경우 데이터의 의미, 처음 할당된 위치, 변경 가능 위치, 변경 가능 시기, 이러한 변경이 동시에 발생할 수 있고 잠금이 필요한 경우, 어떤 시퀀스 잠금을 획득해야 하는지, 데이터 변경 시 다른 사용자와의 조정이 필요한지, 그리고 실제로 여기서 변경되는지를 알아야 합니다.
가비지 수집 효율성, 잠금 장치 없는 운영, 효율적인 하위 구조 공유 등과 같은 불변 데이터의 다른 장점이 있지만 기술적 선택이며 멀티 코어 프로세싱이 일반화됨에 따라 중요해지고 있지만 이점의 핵심은 아닙니다.
마지막으로, 언어를 배우는 것이 왜 그렇게 어려운지에 대한 암묵적인 질문에 대해... 분명히, 나는 추측만 할 수 있지만, 내 경험에 따르면, 사람들이 프로그래밍, 프로그래밍 언어, 프로그래밍 패러다임을 배우는 데는 두 가지 원인은 다음과 같다.
첫 번째는 대부분의 교수 문제가 학습을 위한 훌륭한 도구이지만 소프트웨어 공학의 "실제 세계"와 거의 관련이 없다는 것이다. 교육 문제의 규모로 볼 때, 여러분은 아마도 전체 코드 베이스, 엔드 투 엔드를 알고 있을 것입니다. 그리고 그것은 여러분이 모든 것이 어떻게 작동하는지에 대한 그림을 머릿속에 담을 수 있을 만큼 충분히 작습니다.
여러분이 5, 10, 50, 500명의 사람들로 구성된 팀과 함께 50만 줄의 코드를 가지고 일할 때, 여러분이 작업하고 있는 것에 대한 대부분의 코드를 본 적이 없는 코드베이스를 가지고 일할 때, 여러분은 불변의 데이터를 감상하기 시작합니다. 왜냐하면 여러분은 훨씬 더 적게 알 필요가 있기 때문입니다.
두 번째는 "복잡함을 더하다"는 당신의 말은 다른 사람들이 저에게 했던 말을 반영한다는 것입니다. 일반적으로, 그들은 문제의 더 큰 그림에 대해 생각하는 데 많은 시간을 소비하지 않고 단지 무언가가 작동할 때까지 코드를 작성하기를 원했기 때문에 그것이 많은 복잡성을 더한다고 느꼈다.
이제, 나는 이것이 당신에게 사실인지 아닌지 전혀 모르겠어요 - 나는 당신을 만난 적이 없어요 - 하지만 어쩌면 그것은 같은 것일 수도 있어요.
가변 데이터는 코드의 임의의 부분에 있고 먼 효과를 트리거해야 할 때 "Y가 발생하도록 X가 필요합니다"에 대한 쉬운 해결책입니다.
그것은 복잡성을 더합니다. 물론 값을 더 쉽게 변경할 수 있기 때문에 로컬 복잡성은 아닙니다. 원격 복잡성. 눈에 보이지 않는 복잡성.
그것은 변화가 일어나는 곳과 시스템의 행동이 정의되는 곳에 대한 세부사항을 퍼뜨린다. 이 경로를 따라 시스템의 크기를 확장하면 객체 지향 분석과 설계가 해결하려는 문제를 재발견할 수 있습니다.
다시 말씀드리지만, 저는 당신을 모릅니다. 그리고 그것은 당신이 왜 그것을 "복잡함을 더했는지"와 관련이 없을지도 모르지만, 그것은 사람들이 같은 말을 하는 제 경험에서 가장 흔한 패턴입니다.
내가 이해한 것
시스템이 커질수록 코드가 복잡해져서 디버깅하기 힘들다
언제 데이터가 바뀌는지 등등 유지보수에 힘들기 때문에 가급적 지양해야한다.
원문
The glib answer is that mutability is necessary, because software that doesn't change anything is kind of pointless. Ultimately, at least some of your data is going to be mutable - even if it is just the input and output of the process.
Really, though, you are asking why you would choose to use immutable rather than mutable data in various parts of your program, and the answer to that is complexity.
Complexity is the thing that makes software difficult. Mutable data is inherently complex, because it can change.
Complexity is what makes software difficult, because it makes doing anything with it hard. It could be the complexity of doing the right thing in the face of all your state, or the complexity of concurrency, or the complexity of changing code to meet new requirements.
Ultimately, though, the simpler software is the easier it is to keep working, and to improve, over time. There is a lot of education, experience, and related discussion that most of the cost of software is really keeping it working over the full life of the software.
The reason that mutable data makes software more complex is fairly simple, if you contrast the thinking you need to do about the data:
If the data is immutable you need to know what it means, where it was first assigned, and perhaps how it is used here.
If the data is mutable you need to know what it means, where it was first assigned, where it can be changed, when it can be changed, if those changes can happen concurrently and require locks, what sequence locks need to be acquired in, if changing the data needs coordination with others, and if it is actually changed here.
There are other advantages to immutable data, such as garbage collection efficiency, lock-free operation, efficient substructure sharing, and so forth, but they are technical choices - and while they are becoming more important as multi-core processing becomes more common, they are not the heart of the advantage.
Finally, to the implicit question of why you found it so challenging in your learning the language... Obviously, I can only speculate, but in my experience there are two causes for this in people learning programming, programming languages, and programming paradigms:
The first is that most teaching problems are great tools for learning, but have very little to do with the "real world" of software engineering. At the scale of a teaching problem you probably know the entire codebase, end to end, and it is small enough you can hold a picture in your head of how it all works.
When you are working with a team of five, or ten, or fifty, or five hundred people on a codebase with a half million lines of code, where you have never even seen most of the code around what you are working on - well, then you start to appreciate immutable data, because you need to know so much less.
The second is that your comment on "added lots of complexity" mirrors what a bunch of other people have said to me. Generally, they felt it added a lot of complexity because they just wanted to write code until something worked without spending a lot of time thinking about the bigger picture of the problem.
Now, I have no idea if this is true of you or not - I never met you - but maybe it is the same thing.
Mutable data is an easy solution to "I need X to change so that Y happens" when you are in a random part of the code and need to trigger some distant effect.
That adds complexity. Not local complexity, sure, because you can more easily change the value and all. Remote complexity. Invisible complexity.
It spreads out the details of where change happens, and of where the behaviour of the system is defined. As you go down this path, and grow the size of the system, you rediscover the problems that Object Oriented analysis and design came about to combat.
Again, I don't know you, and that may have nothing to do with why you found it "added complexity", but it is the most common pattern in my experience of folks saying the same thing.