When writing code, clarity and maintainability are everything. One of the most powerful design principles you can apply to achieve this is CQS - Command Query Separation.
What is CQS?
CQS (Command Query Separation) means:
A function should either do something (a Command) or answer something (a Query) - never both.
- Commands: Change system state, return nothing
- Queries: Return data, change nothing
By applying this rule, your code becomes easier to read, test, and maintain.
Bad Example
Here's an example that mixes a query and a command in a single function:
def configure_interface(device, interface):
status = device.get_interface_status(interface) # ← Query
if status == "down":
device.enable_interface(interface) # ← Command
return status
Why it's bad:
- Does two things: checks state + changes state
- Harder to test
- Breaks single-responsibility principle
Good Example
Here’s an example that demonstrates clear separation using the Command Query Separation (CQS) principle:
# Query – no state change
def is_interface_down(device, interface):
return device.get_interface_status(interface) == "down"
# Command – state change, no return
def enable_interface(device, interface):
if not device.has_interface(interface):
raise ValueError(f"Interface {interface} does not exist")
device.enable_interface(interface)
Usage
if is_interface_down(device, "Gig0/1"): # ← Query
enable_interface(device, "Gig0/1") # ← Command
Final Thoughts
Applying CQS in your code helps you:
- Avoid hidden side effects
- Improve testability
- Write clearer, more predictable logic
Thanks for reading — and happy automating!