Sorting Patterns
Basic Sorting
GET /products?sort=price → Sort by price (default: asc)
GET /products?sort=price:asc → Sort by price ascending
GET /products?sort=price:desc → Sort by price descending
Multiple Sort Fields
GET /products?sort=category:asc,price:desc,name:asc
# SQL Equivalent:
# ORDER BY category ASC, price DESC, name ASC
Common Sort Patterns
| Pattern | Example | Notes |
|---|---|---|
sort=field |
?sort=name |
Simple, default asc |
sort=field:direction |
?sort=name:desc |
Explicit direction |
sortBy=field&order=dir |
?sortBy=name&order=desc |
Two params |
order=field:dir |
?order=name:desc |
Alternative |
Sort Implementation
@GetMapping("/products")
public Page<Product> getProducts(
@RequestParam(defaultValue = "createdAt") String sort,
@RequestParam(defaultValue = "desc") String direction,
Pageable pageable) {
Sort.Direction dir = Sort.Direction.fromString(direction);
Sort sortObj = Sort.by(dir, sort);
Pageable sortedPageable = PageRequest.of(
pageable.getPageNumber(),
pageable.getPageSize(),
sortObj
);
return productService.findAll(sortedPageable);
}
Sorting Best Practices
- Default sort — Always provide a default (e.g., createdAt desc)
- Whitelist fields — Only allow sorting on indexed fields
- Case sensitivity — Handle case-insensitive sorting
- Null handling — Define where nulls appear (first/last)
Best Practices
Key Principles
- Follow SOLID principles
- Write clean, readable code
- Test thoroughly
- Document decisions
- Monitor in production
Implementation
- Start simple, refactor as needed
- Use established patterns
- Consider trade-offs
- Review with peers
Continuous Improvement
- Learn from incidents
- Update documentation
- Share knowledge
- Mentor others
Key Points
- Understanding Sorting is essential for production systems
- Always consider scalability and maintainability
- Test thoroughly before deploying to production
- Monitor performance and set up alerting
Common Patterns
- Validation: Always validate input at the boundary
- Error Handling: Use structured error responses
- Logging: Log key events for debugging
- Testing: Unit, integration, and load tests
- Documentation: Keep docs updated with code changes
Practice Problems
Design and implement a solution for Sorting in a backend system. Consider scalability, error handling, and production readiness.
Solution
// Sorting implementation
// Key aspects: validation, error handling, logging, testing
public class Sorting {
// Production-ready implementation
}Identify and handle edge cases for Sorting. What happens under high load, with invalid input, or during failures?
Solution
// Edge case handling:
// 1. Null/empty input -> validation
// 2. High load -> rate limiting, queuing
// 3. Failures -> retries, circuit breaker
// 4. Concurrent access -> locks, idempotencyWrite a testing strategy for Sorting. Include unit tests, integration tests, and performance tests.
Solution
// Test plan:
// - Unit: 80% coverage target
// - Integration: API contracts
// - Performance: latency, throughput
// - Chaos: failure injectionQuiz
1. What is the most common sort URL pattern?
2. Why should you whitelist sortable fields?
3. What is the primary purpose of Sorting?
4. What is a common mistake when implementing Sorting?
Flashcards
Question
Common sort URL pattern?
Click to reveal answer
Answer
?sort=field:asc or ?sort=field:desc
Question
Why whitelist sortable fields?
Click to reveal answer
Answer
Security (prevent info leak) + performance (use indexes)
Question
What is Sorting?
Click to reveal answer
Answer
Sorting is a key concept in backend development.
Question
When to use Sorting?
Click to reveal answer
Answer
Use Sorting when building production systems that require reliability, scalability, and maintainability.
Question
Sorting best practices
Click to reveal answer
Answer
Follow SOLID principles, write clean code, test thoroughly, document decisions, and monitor in production.
Revision Notes
Key Takeaways
- 1.Use sort=field:direction pattern for sorting
- 2.Always provide a default sort order
- 3.Whitelist allowed sort fields for security and performance
- 4.Support multiple sort fields
Interview Tips
- •Design sorting parameters
- •Explain why field whitelisting matters
Cheat Sheet
Sorting
- Pattern:
?sort=field:ascor?sort=field:desc - Multiple:
?sort=category:asc,price:desc - Default: Always provide (e.g., createdAt desc)
- Security: Whitelist sortable fields