> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/marcosfabricio3/simple-manager-mobile/llms.txt
> Use this file to discover all available pages before exploring further.

# Best Practices

> Coding standards and best practices for Simple Manager Mobile

## Architecture Patterns

### Service Initialization

<Tip>
  Use `useMemo` when initializing services in hooks to avoid recreating instances on every render.
</Tip>

```typescript theme={null}
const service = useMemo(() => new RecordService(), []);
```

This ensures the service instance is created once and reused across renders.

### Error Handling

<Tip>
  Always use the `getErrorMessage` utility for consistent error handling.
</Tip>

```typescript theme={null}
try {
  await service.create(title, type);
} catch (error) {
  throw new Error(getErrorMessage(error));
}
```

### Data Reloading

<Tip>
  After any mutation operation (create, update, delete), reload the data to keep the UI in sync.
</Tip>

```typescript theme={null}
const create = async (title: string, type: string) => {
  await service.create(title, type);
  await load(); // Reload data after creation
};
```

## Entity Design

### UUID Identifiers

<Tip>
  Use UUID for all entity identifiers instead of auto-incrementing integers.
</Tip>

```typescript theme={null}
import * as Crypto from 'expo-crypto';

const record: Record = {
  id: Crypto.randomUUID(),
  // ...
};
```

### Timestamps

<Tip>
  Always include `createdAt` and `updatedAt` timestamps in ISO format.
</Tip>

```typescript theme={null}
const now = new Date().toISOString();

const record: Record = {
  id: Crypto.randomUUID(),
  title,
  type,
  createdAt: now,
  updatedAt: now,
  isDeleted: false,
};
```

### Soft Deletes

<Tip>
  Use soft deletes (`isDeleted` flag) instead of hard deletes to preserve data history.
</Tip>

```typescript theme={null}
async delete(id: string) {
  await this.repository.softDelete(id);
}
```

## Validation

### Input Normalization

<Tip>
  Always trim and normalize user input before validation.
</Tip>

```typescript theme={null}
const cleanTitle = title.trim();
const cleanType = type.trim();
```

### Validation Results

<Tip>
  Return structured validation results with clear error messages.
</Tip>

```typescript theme={null}
export interface ValidationResult {
  valid: boolean;
  message?: string;
}

export function validateRecord(title: string, type: string): ValidationResult {
  if (cleanTitle.length < 3) {
    return { valid: false, message: "El título debe tener al menos 3 caracteres" };
  }
  return { valid: true };
}
```

### Length Constraints

<Tip>
  Enforce minimum and maximum length constraints at the service layer.
</Tip>

* **Minimum**: 3 characters for meaningful data
* **Maximum**: 50 characters for titles to prevent abuse

## Hooks Pattern

### Return Object Structure

<Tip>
  Export a clear interface from hooks with data and action methods.
</Tip>

```typescript theme={null}
return {
  records,        // State data
  load,          // Read operations
  create,        // Create operations
  update,        // Update operations
  remove,        // Delete operations
  existsByTitle, // Query operations
};
```

### Auto-loading Data

<Tip>
  Use `useEffect` to automatically load data when the hook initializes.
</Tip>

```typescript theme={null}
useEffect(() => {
  load();
}, []);
```

## Repository Pattern

### Single Responsibility

<Tip>
  Keep repositories focused on database operations only. No business logic.
</Tip>

```typescript theme={null}
// ✓ Good - Pure database operation
async create(record: Record) {
  await database.runAsync(/* SQL */);
}

// ✗ Bad - Contains business logic
async create(record: Record) {
  if (record.title.length < 3) { // This belongs in service layer
    throw new Error("Title too short");
  }
  await database.runAsync(/* SQL */);
}
```

### Method Naming

<Tip>
  Use clear, conventional names for repository methods.
</Tip>

* `create()` - Insert new record
* `findAll()` - Retrieve all records
* `findById()` - Retrieve single record
* `update()` - Update existing record
* `softDelete()` - Mark as deleted
* `hardDelete()` - Permanently remove

## File Organization

### Folder Structure

```
src/
├── domain/
│   └── entities/          # Core business objects
├── application/
│   ├── services/          # Business logic
│   └── validators/        # Validation rules
├── infrastructure/
│   ├── database/          # Database setup
│   └── repositories/      # Data access
└── presentation/
    ├── screens/           # Full page components
    ├── hooks/             # Custom hooks
    └── components/        # Reusable UI components
```

<Tip>
  Follow this exact folder structure. Each layer should be clearly separated.
</Tip>

## Type Safety

### Entity Types

<Tip>
  Define strong TypeScript interfaces for all entities.
</Tip>

```typescript theme={null}
export interface Record {
  id: string;
  title: string;
  type: string;
  createdAt: string;
  updatedAt: string;
  isDeleted: boolean;
}
```

### Avoid `any`

<Tip>
  Never use `any` type. Always define proper types or interfaces.
</Tip>

## Performance

### Memoization

<Tip>
  Use `useMemo` for expensive computations or object creation.
</Tip>

<Tip>
  Use `useCallback` for functions passed as props to prevent unnecessary re-renders.
</Tip>

## Summary

Following these best practices ensures:

* **Clean separation** of concerns
* **Consistent patterns** across the codebase
* **Type safety** and fewer runtime errors
* **Maintainable code** that's easy to understand
* **Better performance** through proper optimization
