Skip to main content

trait

Traits (called “oasis” in Soul) define reusable behavior that can be mixed into classes. They provide a way to share code between classes without traditional inheritance, enabling composition over inheritance patterns.

Basic Trait Definition

Define a trait with shared behavior:

Trait with Abstract Methods

Define traits with methods that must be implemented:

Trait with Properties

Traits can define properties and related methods:

Multiple Traits

Mix multiple traits into a single class:

Trait Composition

Compose traits that build on each other:

Trait with Event Handling

Create event-driven traits:

Trait with Lifecycle Methods

Define traits with lifecycle hooks:

Trait with Utility Methods

Create utility traits for common operations:

Trait Conflicts and Resolution

Handle method conflicts between traits:

Best Practices

  1. Single responsibility: Each trait should have a focused purpose
  2. Composition over inheritance: Use traits to compose behavior
  3. Avoid state: Traits should primarily provide behavior, not state
  4. Document requirements: Make trait dependencies clear
  5. Handle conflicts: Resolve method conflicts explicitly
Traits provide a powerful way to share behavior between classes while maintaining clean, modular code. Use them to create reusable components that can be mixed and matched as needed.