Code Smell 241- Referential Transparency Violation
Pure functions produce the same output for the same input and have no side effects

I’m a senior software engineer loving clean code, and declarative designs. S.O.L.I.D. and agile methodologies fan.
Search for a command to run...
Pure functions produce the same output for the same input and have no side effects

I’m a senior software engineer loving clean code, and declarative designs. S.O.L.I.D. and agile methodologies fan.
No comments yet. Be the first to comment.
In this series, we will see several symptoms and situations that make us doubt the quality of our developments. We will present possible solutions. Most are just clues. They are no hard rules.
The perfect prompt doesn't instruct the model on what it already knows how to do.

Approve the logic once, then let it run the same way forever.

Different stages need different brains.

One Second Brain doesn't scale past one skull.

Style errors double when nobody enforces them.

TL;DR: Your functions should be replaceable by the computation result.
Readability
Principle of least astonishment violation
Testability
Breaking referential transparency occurs when the code introduces side effects or relies on a mutable state.
This violates the principle that an expression or function can be replaced with its value without changing the program's behavior.
# Global mutable variable
counter = 0
# Function with side effect
def increment_counter():
global counter
counter += 1
return counter
# Function with implicit dependency and non-deterministic
def get_random_number():
import random
return random.randint(1, 100)
# Function with non-deterministic behavior
def get_current_time():
import time
return time.time()
import random
import time
# Function without side effects
def increment_counter(counter):
return counter + 1
# Function without side effects (but not deterministic)
def get_random_number():
return random.randint(1, 100)
# Function without side effects (can also be injected)
def get_current_time(timesource):
return timesource.time()
[X] Semi-Automatic
Many linters warn you when you violate referential transparency
[x] Intermediate
Most AI assistants will avoid violating referential transparency.
Functional programming is known for its ability to enable concise, expressive, and maintainable code, as well as facilitating parallel and concurrent programming due to its emphasis on immutable data and pure functions.
There are many concepts to borrow from it.
Code Smells are my opinion.
Photo by Wilhelm Gunkel on Unsplash
Referential transparency is a very desirable property: it implies that functions consistently yield the same results given the same input, irrespective of where and when they are invoked.
Edward Garson
This article is part of the CodeSmell Series.