This repository demonstrates the Command-Query Separation (CQS) design principle through practical C# examples. CQS states that every method should either be a command that performs an action OR a query that returns data, but never both.
Command-Query Separation is a design principle that states:
"Asking a question should not change the answer."
- Commands: Methods that change state but return nothing (void)
- Queries: Methods that return data without changing state
- Shopping Cart System - Complete example showing the difference
- WithoutCQS/- Violates CQS (mixed responsibilities)
- WithCQS/- Follows CQS (clear separation)
 
✅ Predictability - Queries produce consistent results
✅ No Hidden Side Effects - Clear what each method does
✅ Easier Debugging - Inspect state safely
✅ Better Testability - Test commands and queries independently
✅ Thread Safety - Queries can run concurrently
✅ Caching Opportunities - Query results can be cached
Commands:
- Change system state
- Return void (or simple success/failure)
- Examples: AddItem(),RemoveItem(),UpdateQuantity()
Queries:
- Return data
- Never modify state
- Examples: GetItem(),GetCount(),CalculateTotal()
- .NET 8.0 SDK or later
- Visual Studio 2022 / VS Code / Rider
# Navigate to either example
cd WithoutCQS
dotnet build
dotnet run
cd ../WithCQS
dotnet build
dotnet run- Separate methods that change state from methods that return data
- Commands should return void
- Queries should have no side effects
- Clear naming makes intent obvious
- Thread safety and caching become easier
✅ Business logic and domain models
✅ Public APIs (RESTful naturally aligns)
✅ Class interfaces
✅ Any code where testing matters
Sometimes violating CQS is acceptable:
- Convenience methods (documented)
- Performance-critical code
- Builder/fluent interfaces
- Private helper methods
- CQRS (Command Query Responsibility Segregation) - Architectural pattern inspired by CQS
- SOLID Principles - Especially Single Responsibility
- YAGNI - Don't build features you don't need
- KISS - Keep it simple
Feel free to submit issues or pull requests with improvements!
MIT License - Free to use for learning and commercial projects.
Created as part of a series on software design principles.