Guide for applying MUSUBIX's 17 learned best practices. Use this when asked about coding patterns, design patterns, or testing patterns that MUSUBIX recommends.
This skill guides you through applying the 17 best practices learned from MUSUBIX virtual projects.
MUSUBIX has learned these best practices from implementing 14+ virtual projects. Apply them consistently for high-quality code.
Use Input DTO objects for entity creation instead of multiple parameters.
// ✅ Recommended: Input DTO
interface CreatePetInput {
name: string;
species: string;
ownerId: string;
}
function createPet(input: CreatePetInput): Pet {
return new Pet(input);
}
// ❌ Avoid: Multiple parameters
function createPet(name: string, species: string, ownerId: string): Pet {
// Hard to extend, easy to mix up parameter order
}
Generate IDs with PREFIX-YYYYMMDD-NNN format for sortability.
// ✅ Recommended: Date-based ID
const id = `PET-20260104-001`; // Sortable, traceable
// ❌ Avoid: UUID only
const id = crypto.randomUUID(); // Not human-readable
Use Value Objects for domain concepts.
// ✅ Recommended: Value Object
interface Price {
readonly amount: number;
readonly currency: 'JPY';
}
// ❌ Avoid: Primitive types
const price: number = 1000; // No currency context
Use interface + factory function instead of classes for Value Objects.
// ✅ Recommended: Interface + Factory Function
interface Price {
readonly amount: number;
readonly currency: 'JPY';
}
function createPrice(amount: number): Result<Price, ValidationError> {
if (amount < 100 || amount > 1_000_000) {
return err(new ValidationError('Price must be between 100 and 1,000,000 JPY'));
}
return ok({ amount, currency: 'JPY' });
}
// ❌ Avoid: Class-based (doesn't work well with TypeScript structural typing)
class Price {
private constructor(readonly amount: number) {}
static create(amount: number): Price { ... }
}
Use Result<T, E> for operations that can fail.
// ✅ Recommended: Result type
type Result<T, E> = { ok: true; value: T } | { ok: false; error: E };
function divide(a: number, b: number): Result<number, Error> {
if (b === 0) return { ok: false, error: new Error('Division by zero') };
return { ok: true, value: a / b };
}
// ❌ Avoid: Throwing exceptions for expected errors
function divide(a: number, b: number): number {
if (b === 0) throw new Error('Division by zero');
return a / b;
}
Define valid status transitions in a Map.
// ✅ Recommended: Transition map
const validTransitions: Record<Status, Status[]> = {
draft: ['active', 'cancelled'],
active: ['completed', 'cancelled'],
completed: [],
cancelled: [],
};
function canTransition(from: Status, to: Status): boolean {
return validTransitions[from].includes(to);
}
Make repositories async for future DB migration.
// ✅ Recommended: Async repository
interface PetRepository {
findById(id: PetId): Promise<Pet | null>;
save(pet: Pet): Promise<void>;
}
// ❌ Avoid: Sync repository (hard to migrate later)
interface PetRepository {
findById(id: PetId): Pet | null;
}
Use dependency injection for services.
// ✅ Recommended: Constructor DI
class PetService {
constructor(
private readonly petRepository: PetRepository,
private readonly auditService: AuditService
) {}
}
Use version field for concurrent edit detection.
// ✅ Recommended: Version field
interface Entity {
id: string;
version: number;
updatedAt: Date;
}
function update(entity: Entity, currentVersion: number): Result<Entity, ConcurrencyError> {
if (entity.version !== currentVersion) {
return err(new ConcurrencyError('Entity was modified'));
}
return ok({ ...entity, version: entity.version + 1 });
}
Record data changes in audit logs.
// ✅ Recommended: Audit logging
interface AuditEntry {
id: string;
entityType: string;
entityId: string;
action: 'CREATE' | 'UPDATE' | 'DELETE';
changes: object;
userId: string;
timestamp: Date;
}
Provide reset functions for test isolation.
// ✅ Recommended: Resettable counter
let petCounter = 0;
export function generatePetId(): string {
return `PET-${Date.now()}-${++petCounter}`;
}
export function resetPetCounter(): void {
petCounter = 0; // For tests
}
Use expiresAt field for time-limited entities.
// ✅ Recommended: Explicit expiry
interface Reservation {
id: string;
createdAt: Date;
expiresAt: Date; // Explicit expiry time
}
function isExpired(reservation: Reservation): boolean {
return new Date() > reservation.expiresAt;
}
Reset ID counters in beforeEach.
beforeEach(() => {
resetPetCounter();
resetReservationCounter();
});
Check method signatures before writing tests.
Use proper ESM setup for Vitest.
// vitest.config.ts
export default defineConfig({
test: {
globals: true,
environment: 'node',
},
});
Test both success and error cases.
it('should succeed with valid input', () => {
const result = createPrice(1000);
expect(result.isOk()).toBe(true);
});
it('should fail with invalid input', () => {
const result = createPrice(-1);
expect(result.isErr()).toBe(true);
});
Test all valid and invalid transitions.
describe('status transitions', () => {
it.each([
['draft', 'active', true],
['draft', 'completed', false],
['active', 'completed', true],
])('%s -> %s should be %s', (from, to, valid) => {
expect(canTransition(from, to)).toBe(valid);
});
});
# Show all best practices
npx musubix learn best-practices
# Filter by category
npx musubix learn best-practices --category code
npx musubix learn best-practices --category design
npx musubix learn best-practices --category test
# High confidence only
npx musubix learn best-practices --high-confidence
musubix-code-generation - Apply patterns in codemusubix-test-generation - Apply test patternsmusubix-sdd-workflow - Full workflow with patterns