December 14th, 2024

John Carmack on Functional Programming in C++

John Carmack discusses functional programming's benefits in C++, highlighting its ability to clarify code states and reduce multithreading issues. He emphasizes pure functions for improved safety, reusability, and maintainability.

Read original articleLink Icon
John Carmack on Functional Programming in C++

John Carmack discusses the merits and challenges of functional programming within C++. He emphasizes that many software flaws arise from a lack of understanding of code states, particularly in multithreaded environments. Functional programming can help clarify these states, making reasoning about code easier and eliminating thread race conditions in pure systems. While he acknowledges the value of functional programming, he cautions against abandoning mainstream languages like C++ for less common ones, given the complexities of game development, such as cross-platform issues and performance requirements. Carmack advocates for the use of functional programming principles, such as pure functions, which are thread-safe, reusable, and easier to test and maintain. He notes that while not all code can be pure, striving for greater purity can improve overall code quality. He also highlights the tension between object-oriented programming (OOP) and functional programming, suggesting that OOP's mutating states can lead to bugs. Finally, he addresses performance concerns, noting that while pure functions may involve more data copying, the trade-off between performance and productivity is often worth it.

- Functional programming can clarify code states and reduce multithreading issues.

- Pure functions enhance thread safety, reusability, and testability.

- Striving for code purity can improve maintainability and reduce bugs.

- There is a tension between object-oriented and functional programming paradigms.

- Performance trade-offs may arise when using pure functions, but productivity gains are often more significant.

Link Icon 3 comments
By @PeterWhittaker - 5 months
Great summary of the motivation: A large fraction of the flaws in software development are due to programmers not fully understanding all the possible states their code may execute in. In a multithreaded environment, the lack of understanding and the resulting problems are greatly amplified, almost to the point of panic if you are paying attention. Programming in a functional style makes the state presented to your code explicit, which makes it much easier to reason about, and, in a completely pure system, makes thread race conditions impossible.

That is prescient, clear, and worthy of great reflection.

By @mcc1ane - 5 months
(2018) at least