modelmux 1.0.0

ModelMux - high-performance Rust gateway that translates OpenAI-compatible API requests to Vertex AI (Claude), with streaming, tool calling, and production-grade reliability.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
# SOLID Principles - Detailed Implementation Guide

> **Comprehensive guide with detailed examples for implementing SOLID principles in Rust and other languages.**
> 
> **For quick reference**: Use [`solid_principles_quick_reference.md`]solid_principles_quick_reference.md for daily development.
> **For learning/deep-dives**: This guide provides complete examples and implementation strategies.

## When to Use This Guide

- **Learning SOLID**: First time implementing principles in Rust
- **Complex Refactoring**: Large architectural changes requiring detailed patterns
- **Code Review**: Need specific examples to validate design decisions
- **Debugging Design**: Understanding why current design violates principles
- **Architecture Planning**: Designing new systems following SOLID principles

## Table of Contents
1. [Overview]#overview
2. [Single Responsibility Principle (SRP)]#single-responsibility-principle-srp
3. [Open/Closed Principle (OCP)]#openclosed-principle-ocp
4. [Liskov Substitution Principle (LSP)]#liskov-substitution-principle-lsp
5. [Interface Segregation Principle (ISP)]#interface-segregation-principle-isp
6. [Dependency Inversion Principle (DIP)]#dependency-inversion-principle-dip
7. [AI Development Guidelines]#ai-development-guidelines
8. [Language-Specific Examples]#language-specific-examples

## Overview

SOLID principles are fundamental guidelines for writing maintainable, scalable software. This guide provides comprehensive implementation strategies and detailed Rust examples for AI-assisted development.

**For Quick Reference**: See [`solid_principles_quick_reference.md`](solid_principles_quick_reference.md) for essential patterns and checklists.

## Single Responsibility Principle (SRP)

> A class should have only one reason to change.

### Implementation Strategy
- **Identify responsibilities**: Each class should handle one specific concern
- **Separate concerns**: Business logic, data access, and presentation should be distinct
- **Small, focused classes**: Better than large, monolithic ones

### Good Example (Rust)
```rust
// ❌ Violates SRP - multiple responsibilities
struct UserManager {
    db_connection: String,
    email_service: String,
}

impl UserManager {
    fn save_user(&self, user: &User) {
        // database logic
    }
    
    fn send_email(&self, user: &User) {
        // email logic
    }
    
    fn validate_user(&self, user: &User) -> bool {
        // validation logic
        true
    }
}

// ✅ Follows SRP - single responsibilities
struct UserRepository {
    db_connection: String,
}

impl UserRepository {
    fn save(&self, user: &User) -> Result<(), String> {
        // only database logic
        println!("Saving user: {}", user.name);
        Ok(())
    }
}

struct EmailService {
    smtp_config: String,
}

impl EmailService {
    fn send_welcome_email(&self, user: &User) -> Result<(), String> {
        // only email logic
        println!("Sending welcome email to: {}", user.email);
        Ok(())
    }
}

struct UserValidator;

impl UserValidator {
    fn validate(&self, user: &User) -> ValidationResult {
        // only validation logic
        ValidationResult {
            is_valid: !user.name.is_empty() && user.email.contains('@'),
            errors: Vec::new(),
        }
    }
}

#[derive(Debug)]
struct User {
    name: String,
    email: String,
}

#[derive(Debug)]
struct ValidationResult {
    is_valid: bool,
    errors: Vec<String>,
}
```

### AI Development Guidelines
- **Before adding a method**: Ask "Does this method belong in this class?"
- **When extending functionality**: Consider if a new class is needed
- **Code review prompt**: "What would cause this class to change?"

## Open/Closed Principle (OCP)

> Software entities should be open for extension, closed for modification.

### Implementation Strategy
- **Use abstractions**: Interfaces and abstract classes enable extension
- **Strategy pattern**: For varying algorithms
- **Dependency injection**: To swap implementations
- **Plugin architecture**: For extensible systems

### Good Example (Rust)
```rust
// ❌ Violates OCP - requires modification for new shapes
struct AreaCalculator;

impl AreaCalculator {
    fn calculate_area(&self, shapes: &[ShapeData]) -> f64 {
        let mut total_area = 0.0;
        for shape in shapes {
            match shape.shape_type.as_str() {
                "circle" => total_area += 3.14 * shape.radius.unwrap().powi(2),
                "rectangle" => total_area += shape.width.unwrap() * shape.height.unwrap(),
                // Adding new shape requires modifying this method
                _ => {}
            }
        }
        total_area
    }
}

#[derive(Debug)]
struct ShapeData {
    shape_type: String,
    radius: Option<f64>,
    width: Option<f64>,
    height: Option<f64>,
}

// ✅ Follows OCP - extensible without modification
trait Shape {
    fn area(&self) -> f64;
}

struct Circle {
    radius: f64,
}

impl Shape for Circle {
    fn area(&self) -> f64 {
        3.14 * self.radius * self.radius
    }
}

struct Rectangle {
    width: f64,
    height: f64,
}

impl Shape for Rectangle {
    fn area(&self) -> f64 {
        self.width * self.height
    }
}

struct AreaCalculator;

impl AreaCalculator {
    fn calculate_area(&self, shapes: &[Box<dyn Shape>]) -> f64 {
        shapes.iter().map(|shape| shape.area()).sum()
    }
}

// New shapes can be added without modifying existing code
struct Triangle {
    base: f64,
    height: f64,
}

impl Shape for Triangle {
    fn area(&self) -> f64 {
        0.5 * self.base * self.height
    }
}

// Usage example
fn example_usage() {
    let shapes: Vec<Box<dyn Shape>> = vec![
        Box::new(Circle { radius: 5.0 }),
        Box::new(Rectangle { width: 4.0, height: 3.0 }),
        Box::new(Triangle { base: 6.0, height: 4.0 }),
    ];
    
    let calculator = AreaCalculator;
    let total = calculator.calculate_area(&shapes);
    println!("Total area: {}", total);
}
```

### AI Development Guidelines
- **When adding new behavior**: Create new classes/modules instead of modifying existing ones
- **Design for extension**: Use interfaces and abstract base classes
- **Avoid switch statements**: Use polymorphism instead

## Liskov Substitution Principle (LSP)

> Objects of a superclass should be replaceable with objects of its subclasses without breaking functionality.

### Implementation Strategy
- **Behavioral compatibility**: Subclasses must honor the contract of their parent
- **Preconditions cannot be strengthened**: Subclasses can't be more restrictive
- **Postconditions cannot be weakened**: Subclasses must provide at least the same guarantees

### Good Example (Rust)
```rust
// ❌ Violates LSP - Square changes Rectangle behavior
#[derive(Debug)]
struct Rectangle {
    width: f64,
    height: f64,
}

impl Rectangle {
    fn new(width: f64, height: f64) -> Self {
        Rectangle { width, height }
    }
    
    fn set_width(&mut self, width: f64) {
        self.width = width;
    }
    
    fn set_height(&mut self, height: f64) {
        self.height = height;
    }
    
    fn get_area(&self) -> f64 {
        self.width * self.height
    }
}

// This approach violates LSP if Square inherits Rectangle's behavior
struct Square {
    rectangle: Rectangle,
}

impl Square {
    fn new(side: f64) -> Self {
        Square {
            rectangle: Rectangle::new(side, side),
        }
    }
    
    fn set_width(&mut self, width: f64) {
        // This breaks LSP - changing width also changes height
        self.rectangle.width = width;
        self.rectangle.height = width; // Unexpected behavior!
    }
    
    fn set_height(&mut self, height: f64) {
        // This breaks LSP - changing height also changes width
        self.rectangle.width = height; // Unexpected behavior!
        self.rectangle.height = height;
    }
    
    fn get_area(&self) -> f64 {
        self.rectangle.get_area()
    }
}

// ✅ Follows LSP - proper abstraction using traits
trait Shape {
    fn area(&self) -> f64;
    fn perimeter(&self) -> f64;
}

#[derive(Debug)]
struct Rectangle {
    width: f64,
    height: f64,
}

impl Rectangle {
    fn new(width: f64, height: f64) -> Self {
        Rectangle { width, height }
    }
}

impl Shape for Rectangle {
    fn area(&self) -> f64 {
        self.width * self.height
    }
    
    fn perimeter(&self) -> f64 {
        2.0 * (self.width + self.height)
    }
}

#[derive(Debug)]
struct Square {
    side: f64,
}

impl Square {
    fn new(side: f64) -> Self {
        Square { side }
    }
}

impl Shape for Square {
    fn area(&self) -> f64 {
        self.side * self.side
    }
    
    fn perimeter(&self) -> f64 {
        4.0 * self.side
    }
}

// Both can be used interchangeably as Shape
fn calculate_total_area(shapes: &[Box<dyn Shape>]) -> f64 {
    shapes.iter().map(|shape| shape.area()).sum()
}

fn example_usage() {
    let shapes: Vec<Box<dyn Shape>> = vec![
        Box::new(Rectangle::new(4.0, 5.0)),
        Box::new(Square::new(3.0)),
    ];
    
    let total = calculate_total_area(&shapes);
    println!("Total area: {}", total); // Works correctly for both
}
```

### AI Development Guidelines
- **Test substitutability**: Can you replace parent with child in all contexts?
- **Honor contracts**: Subclasses must fulfill the same promises as their parents
- **Avoid breaking changes**: Don't change expected behavior in inheritance

## Interface Segregation Principle (ISP)

> Clients should not be forced to depend on interfaces they do not use.

### Implementation Strategy
- **Small, focused interfaces**: Better than large, monolithic ones
- **Role-based interfaces**: Design around client needs
- **Composition over inheritance**: Combine multiple small interfaces

### Good Example (Rust)
```rust
// ❌ Violates ISP - fat trait forces unnecessary dependencies
trait Worker {
    fn work(&self);
    fn eat(&self);
    fn sleep(&self);
}

struct Robot {
    battery_level: u8,
}

impl Worker for Robot {
    fn work(&self) {
        println!("Robot is working with battery level: {}", self.battery_level);
    }
    
    fn eat(&self) {
        // Robot doesn't eat - this method shouldn't exist for Robot
        panic!("Robots don't eat!");
    }
    
    fn sleep(&self) {
        // Robot doesn't sleep - this method shouldn't exist for Robot
        panic!("Robots don't sleep!");
    }
}

// ✅ Follows ISP - segregated traits
trait Workable {
    fn work(&self);
}

trait Feedable {
    fn eat(&self);
}

trait Restable {
    fn sleep(&self);
}

// Additional traits for more specific behaviors
trait Rechargeable {
    fn recharge(&mut self);
    fn battery_level(&self) -> u8;
}

trait Biological {
    fn breathe(&self);
}

#[derive(Debug)]
struct Human {
    name: String,
    energy_level: u8,
}

impl Human {
    fn new(name: String) -> Self {
        Human { name, energy_level: 100 }
    }
}

impl Workable for Human {
    fn work(&self) {
        println!("{} is working with energy level: {}", self.name, self.energy_level);
    }
}

impl Feedable for Human {
    fn eat(&self) {
        println!("{} is eating to restore energy", self.name);
    }
}

impl Restable for Human {
    fn sleep(&self) {
        println!("{} is sleeping to restore energy", self.name);
    }
}

impl Biological for Human {
    fn breathe(&self) {
        println!("{} is breathing", self.name);
    }
}

#[derive(Debug)]
struct Robot {
    model: String,
    battery_level: u8,
}

impl Robot {
    fn new(model: String) -> Self {
        Robot { model, battery_level: 100 }
    }
}

impl Workable for Robot {
    fn work(&self) {
        println!("Robot {} is working with battery level: {}", self.model, self.battery_level);
    }
}

impl Rechargeable for Robot {
    fn recharge(&mut self) {
        self.battery_level = 100;
        println!("Robot {} recharged to 100%", self.model);
    }
    
    fn battery_level(&self) -> u8 {
        self.battery_level
    }
}

// Functions that depend only on what they need
fn manage_workers(workers: &[Box<dyn Workable>]) {
    for worker in workers {
        worker.work();
    }
}

fn manage_biological_entities(entities: &[Box<dyn Biological>]) {
    for entity in entities {
        entity.breathe();
    }
}

fn example_usage() {
    let workers: Vec<Box<dyn Workable>> = vec![
        Box::new(Human::new("Alice".to_string())),
        Box::new(Robot::new("R2D2".to_string())),
    ];
    
    manage_workers(&workers);
    
    // Only humans can be managed as biological entities
    let biological: Vec<Box<dyn Biological>> = vec![
        Box::new(Human::new("Bob".to_string())),
    ];
    
    manage_biological_entities(&biological);
}
```

### AI Development Guidelines
- **Design client-specific interfaces**: Focus on what clients actually need
- **Avoid God interfaces**: Split large interfaces into focused ones
- **Think in terms of roles**: What role does this client play?

## Dependency Inversion Principle (DIP)

> High-level modules should not depend on low-level modules. Both should depend on abstractions.

### Implementation Strategy
- **Dependency injection**: Inject dependencies rather than creating them
- **Inversion of control containers**: Use IoC frameworks where appropriate
- **Abstract interfaces**: Define contracts that both layers can depend on

### Good Example (Rust)
```rust
use std::fs::OpenOptions;
use std::io::Write;

// ❌ Violates DIP - high-level depends on low-level
struct FileLogger {
    file_path: String,
}

impl FileLogger {
    fn new(file_path: String) -> Self {
        FileLogger { file_path }
    }
    
    fn log(&self, message: &str) {
        println!("Writing to file {}: {}", self.file_path, message);
        // In real implementation, would write to file
    }
}

struct OrderService {
    logger: FileLogger, // Direct dependency on concrete implementation
}

impl OrderService {
    fn new() -> Self {
        // High-level module creating low-level dependency
        OrderService {
            logger: FileLogger::new("orders.log".to_string()),
        }
    }
    
    fn process_order(&self, order: &Order) {
        // Process order logic
        println!("Processing order: {}", order.id);
        
        // Tightly coupled to FileLogger - can't easily test or change
        self.logger.log(&format!("Order {} processed", order.id));
    }
}

// ✅ Follows DIP - both depend on abstraction
trait Logger {
    fn log(&self, message: &str);
    fn flush(&self) {}
}

struct FileLogger {
    file_path: String,
}

impl FileLogger {
    fn new(file_path: String) -> Self {
        FileLogger { file_path }
    }
}

impl Logger for FileLogger {
    fn log(&self, message: &str) {
        println!("File Logger - Writing to {}: {}", self.file_path, message);
        // In real implementation, would write to file
    }
    
    fn flush(&self) {
        println!("Flushing file buffer for: {}", self.file_path);
    }
}

struct DatabaseLogger {
    connection_string: String,
}

impl DatabaseLogger {
    fn new(connection_string: String) -> Self {
        DatabaseLogger { connection_string }
    }
}

impl Logger for DatabaseLogger {
    fn log(&self, message: &str) {
        println!("Database Logger - Writing to DB: {}", message);
        // In real implementation, would write to database
    }
}

struct ConsoleLogger;

impl Logger for ConsoleLogger {
    fn log(&self, message: &str) {
        println!("Console: {}", message);
    }
}

// High-level module depends on abstraction
struct OrderService<T: Logger> {
    logger: T,
    order_counter: u32,
}

impl<T: Logger> OrderService<T> {
    fn new(logger: T) -> Self {
        OrderService { 
            logger,
            order_counter: 0,
        }
    }
    
    fn process_order(&mut self, order: &Order) -> Result<String, String> {
        // Validate order
        if order.amount <= 0.0 {
            let error_msg = format!("Invalid order amount: {}", order.amount);
            self.logger.log(&format!("ERROR: {}", error_msg));
            return Err(error_msg);
        }
        
        // Process order logic
        self.order_counter += 1;
        let confirmation = format!("CONF-{:06}", self.order_counter);
        
        // Log through abstraction - doesn't know or care about implementation
        self.logger.log(&format!("Order {} processed successfully. Confirmation: {}", order.id, confirmation));
        
        Ok(confirmation)
    }
    
    fn get_order_stats(&self) -> u32 {
        self.order_counter
    }
}

// Domain model
#[derive(Debug)]
struct Order {
    id: String,
    amount: f64,
    customer_id: String,
}

impl Order {
    fn new(id: String, amount: f64, customer_id: String) -> Self {
        Order { id, amount, customer_id }
    }
}

// Dependency injection through constructor
fn example_usage() {
    // Can easily swap logger implementations
    let file_logger = FileLogger::new("orders.log".to_string());
    let mut order_service = OrderService::new(file_logger);
    
    let order1 = Order::new("ORD-001".to_string(), 100.50, "CUST-123".to_string());
    match order_service.process_order(&order1) {
        Ok(confirmation) => println!("Order confirmed: {}", confirmation),
        Err(error) => println!("Order failed: {}", error),
    }
    
    // Easy to switch to different logger without changing OrderService
    let db_logger = DatabaseLogger::new("postgres://localhost:5432/orders".to_string());
    let mut db_order_service = OrderService::new(db_logger);
    
    let order2 = Order::new("ORD-002".to_string(), 250.75, "CUST-456".to_string());
    db_order_service.process_order(&order2);
    
    // Console logger for development
    let console_logger = ConsoleLogger;
    let mut dev_service = OrderService::new(console_logger);
    
    let order3 = Order::new("ORD-003".to_string(), -10.0, "CUST-789".to_string());
    dev_service.process_order(&order3); // Will log error
}

// Easy testing with mock logger
#[cfg(test)]
mod tests {
    use super::*;
    
    struct MockLogger {
        logs: std::cell::RefCell<Vec<String>>,
    }
    
    impl MockLogger {
        fn new() -> Self {
            MockLogger {
                logs: std::cell::RefCell::new(Vec::new()),
            }
        }
        
        fn get_logs(&self) -> Vec<String> {
            self.logs.borrow().clone()
        }
    }
    
    impl Logger for MockLogger {
        fn log(&self, message: &str) {
            self.logs.borrow_mut().push(message.to_string());
        }
    }
    
    #[test]
    fn test_order_processing_success() {
        let mock_logger = MockLogger::new();
        let mut service = OrderService::new(mock_logger);
        
        let order = Order::new("TEST-001".to_string(), 100.0, "CUST-001".to_string());
        let result = service.process_order(&order);
        
        assert!(result.is_ok());
        let logs = service.logger.get_logs();
        assert_eq!(logs.len(), 1);
        assert!(logs[0].contains("TEST-001"));
        assert!(logs[0].contains("processed successfully"));
    }
    
    #[test]
    fn test_order_processing_failure() {
        let mock_logger = MockLogger::new();
        let mut service = OrderService::new(mock_logger);
        
        let invalid_order = Order::new("TEST-002".to_string(), -50.0, "CUST-002".to_string());
        let result = service.process_order(&invalid_order);
        
        assert!(result.is_err());
        let logs = service.logger.get_logs();
        assert_eq!(logs.len(), 1);
        assert!(logs[0].contains("ERROR"));
    }
}
```

### AI Development Guidelines
- **Inject, don't create**: Pass dependencies as parameters
- **Define interfaces first**: Think about what you need, not how it's implemented
- **Test with mocks**: DIP makes testing much easier

## AI Development Guidelines

### Before Writing Code
1. **Identify the single responsibility** - What is this class/module supposed to do?
2. **Design for extension** - How might this need to change in the future?
3. **Define interfaces** - What contract should this fulfill?
4. **Consider dependencies** - What does this need from other components?

### During Implementation
1. **Keep methods small** - Each method should have one clear purpose
2. **Use descriptive names** - Make the responsibility obvious from the name
3. **Avoid deep inheritance** - Prefer composition over inheritance
4. **Inject dependencies** - Don't create dependencies inside classes

### Code Review Checklist
- [ ] Does each class have a single, clear responsibility?
- [ ] Can new behavior be added without modifying existing code?
- [ ] Are subclasses truly substitutable for their parents?
- [ ] Are interfaces focused and client-specific?
- [ ] Do high-level modules avoid depending on implementation details?

### Refactoring Signals
- **Large classes** → Split by responsibility (SRP)
- **Switch statements** → Use polymorphism (OCP)
- **Type checking in client code** → Fix inheritance hierarchy (LSP)
- **Empty method implementations** → Segregate interfaces (ISP)
- **Direct instantiation of dependencies** → Use dependency injection (DIP)

## Language-Specific Examples

### Python
- **SRP**: Use modules and classes appropriately
- **OCP**: Leverage duck typing and protocols
- **LSP**: Be careful with method overrides
- **ISP**: Use Protocol classes (Python 3.8+)
- **DIP**: Use dependency injection frameworks like `dependency-injector`

### TypeScript/JavaScript
- **SRP**: Use ES6 modules and classes
- **OCP**: Leverage interfaces and function composition
- **LSP**: Maintain behavioral contracts in inheritance
- **ISP**: Create focused interface definitions
- **DIP**: Use constructor injection and IoC containers

### Java
- **SRP**: Single-purpose classes and packages
- **OCP**: Abstract classes and interfaces
- **LSP**: Proper inheritance hierarchies
- **ISP**: Multiple small interfaces
- **DIP**: Spring Framework dependency injection

### C#
- **SRP**: Classes with single concerns
- **OCP**: Interfaces and virtual methods
- **LSP**: Proper inheritance design
- **ISP**: Role-based interfaces
- **DIP**: Built-in dependency injection container

### Rust
- **SRP**: Modules and structs with clear purposes; use `impl` blocks to group related functionality
- **OCP**: Traits for abstraction, generics for type flexibility, enum variants for extensible behavior
- **LSP**: Careful trait implementation ensuring behavioral contracts; avoid panicking in trait methods
- **ISP**: Small, focused traits; use trait composition rather than large trait hierarchies
- **DIP**: Trait objects (`Box<dyn Trait>`) and generic parameters for dependency injection; constructor injection pattern

## Common Violations and Solutions

### SRP Violations
- **Problem**: God classes doing everything
- **Solution**: Extract related methods into separate classes

### OCP Violations
- **Problem**: Modifying existing code for new features
- **Solution**: Use strategy pattern or plugin architecture

### LSP Violations
- **Problem**: Subclasses throwing exceptions for inherited methods
- **Solution**: Redesign inheritance hierarchy or use composition

### ISP Violations
- **Problem**: Interfaces with many unrelated methods
- **Solution**: Break into smaller, role-specific interfaces

### DIP Violations
- **Problem**: Classes creating their own dependencies
- **Solution**: Use constructor injection, trait objects, or dependency injection containers

## Rust-Specific SOLID Implementation Patterns

### Ownership and SOLID Principles

Rust's ownership system naturally enforces some SOLID principles:

```rust
// SRP: Clear ownership boundaries
struct DatabaseConfig {
    url: String,
    timeout: u64,
}

struct Database {
    config: DatabaseConfig,  // Owned configuration
}

impl Database {
    fn new(config: DatabaseConfig) -> Self {
        Database { config }
    }
}

// OCP: Using trait objects for runtime polymorphism
trait PaymentProcessor {
    fn process_payment(&self, amount: f64) -> Result<String, String>;
}

struct PaymentService {
    processors: Vec<Box<dyn PaymentProcessor>>,
}

impl PaymentService {
    fn add_processor(&mut self, processor: Box<dyn PaymentProcessor>) {
        self.processors.push(processor);
    }
}
```

### Error Handling and SOLID

Rust's `Result` type naturally supports LSP:

```rust
trait DataStore {
    type Error;
    fn save(&self, data: &str) -> Result<(), Self::Error>;
    fn load(&self, id: &str) -> Result<String, Self::Error>;
}

// All implementations must return Results, maintaining behavioral compatibility
struct FileStore;
struct DatabaseStore;

impl DataStore for FileStore {
    type Error = std::io::Error;
    
    fn save(&self, data: &str) -> Result<(), Self::Error> {
        // Implementation that properly handles errors
        Ok(())
    }
    
    fn load(&self, id: &str) -> Result<String, Self::Error> {
        Ok(format!("loaded-{}", id))
    }
}
```

### Dependency Injection with Lifetimes

```rust
// Advanced DIP with lifetimes for borrowed dependencies
struct Service<'a, L: Logger> {
    logger: &'a L,
    name: String,
}

impl<'a, L: Logger> Service<'a, L> {
    fn new(logger: &'a L, name: String) -> Self {
        Service { logger, name }
    }
    
    fn do_work(&self) -> Result<(), String> {
        self.logger.log(&format!("Service {} starting work", self.name));
        // Work logic here
        self.logger.log(&format!("Service {} completed work", self.name));
        Ok(())
    }
}
```

## Conclusion

SOLID principles are not just theoretical concepts—they're practical tools for creating maintainable, testable, and extensible software. When working with AI assistants:

1. **Start with principles in mind**: Design following SOLID from the beginning
2. **Refactor incrementally**: Apply principles gradually to existing code
3. **Use principles as review criteria**: Check each principle during code review
4. **Document architectural decisions**: Record why you chose specific patterns

Remember: These principles guide good design but shouldn't be followed blindly. Use judgment to apply them appropriately to your specific context and requirements.