Referential Transparency: An expression can be replaced with its value without changing the program's behaviour. If getUser(1) always returns the same User, you can cache or reason about it freely. Referential transparency means an expression can be replaced by its value without changing how the program behaves. If price(42) always returns 19.95, you can replace the call with 19.95 anywhere and nothing changes.
Frequently asked questions about Referential Transparency
How is Referential Transparency used in practice?
That property only holds for pure functions, which have no side effects and do not depend on changing state such as the time or a database.
What should you keep in mind with Referential Transparency?
It makes reasoning and refactoring much safer, because you can move, cache or reorder such calls without fear. Compilers and frameworks can optimise them too. Most application code mixes pure and impure parts. Keeping the calculations referentially transparent, and the database reads and writes in a separate thin layer, gives you code that is both easy to test and easy to change.
Implement proven backend architecture patterns including Clean Architecture, Hexagonal Architecture, and Domain-Driven Design. Use this skill when designing clean architecture for a new microservice, when refactoring a monolith to use bounded contexts, when implementing hexagonal or onion architecture patterns, or when debugging dependency cycles between application layers.