Principi di Codice Pulito per XOOPS
Panoramica
Sezione intitolata “Panoramica”Il codice pulito è codice facile da leggere, comprendere e mantenere. Questa guida copre i principi del codice pulito specificamente applicati allo sviluppo di moduli XOOPS.
Principi Fondamentali
Sezione intitolata “Principi Fondamentali”mindmap root((Clean Code)) Readability Meaningful Names Small Functions Comments When Needed Simplicity Single Responsibility DRY Principle KISS Principle Maintainability Consistent Style Error Handling TestingNomi Significativi
Sezione intitolata “Nomi Significativi”Variabili
Sezione intitolata “Variabili”// Bad$d = new DateTime();$u = $memberHandler->getUser($id);$arr = [];
// Good$createdDate = new DateTime();$currentUser = $memberHandler->getUser($userId);$publishedArticles = [];Funzioni
Sezione intitolata “Funzioni”// Badfunction process($data) { ... }function handle($item) { ... }function doStuff($x, $y) { ... }
// Goodfunction publishArticle(Article $article): void { ... }function calculateTotalPrice(array $items): float { ... }function sendNotificationEmail(User $user, string $subject): bool { ... }// Badclass Manager { ... }class Helper { ... }class Utils { ... }
// Goodclass ArticleRepository { ... }class NotificationService { ... }class PermissionChecker { ... }Funzioni Piccole
Sezione intitolata “Funzioni Piccole”Single Responsibility
Sezione intitolata “Single Responsibility”// Bad - does too many thingsfunction processArticle($data) { // Validate if (empty($data['title'])) { throw new Exception('Title required'); } // Save $article = new Article(); $article->setTitle($data['title']); $this->repository->save($article); // Notify $this->mailer->send($article->getAuthor(), 'Article published'); // Log $this->logger->info('Article created'); return $article;}
// Good - each function does one thingfunction validateArticleData(array $data): void{ if (empty($data['title'])) { throw new ValidationException('Title required'); }}
function createArticle(array $data): Article{ $this->validateArticleData($data); return Article::create($data['title'], $data['content']);}
function publishArticle(Article $article): void{ $this->repository->save($article); $this->notifyAuthor($article); $this->logArticleCreation($article);}Lunghezza della Funzione
Sezione intitolata “Lunghezza della Funzione”Mantieni le funzioni brevi - idealmente sotto 20 righe:
// Good - focused functionpublic function getPublishedArticles(int $limit = 10): array{ $criteria = new CriteriaCompo(); $criteria->add(new Criteria('status', 'published')); $criteria->setSort('published_at'); $criteria->setOrder('DESC'); $criteria->setLimit($limit);
return $this->repository->getObjects($criteria);}Principio DRY (Non Ripeterti)
Sezione intitolata “Principio DRY (Non Ripeterti)”Estrai Codice Comune
Sezione intitolata “Estrai Codice Comune”// Bad - repeated codefunction getActiveUsers() { $criteria = new CriteriaCompo(); $criteria->add(new Criteria('level', 0, '>')); $criteria->setSort('uname'); return $this->userHandler->getObjects($criteria);}
function getActiveAdmins() { $criteria = new CriteriaCompo(); $criteria->add(new Criteria('level', 0, '>')); $criteria->add(new Criteria('is_admin', 1)); $criteria->setSort('uname'); return $this->userHandler->getObjects($criteria);}
// Good - shared logic extractedfunction getUsers(CriteriaCompo $criteria): array{ $criteria->add(new Criteria('level', 0, '>')); $criteria->setSort('uname'); return $this->userHandler->getObjects($criteria);}
function getActiveUsers(): array{ return $this->getUsers(new CriteriaCompo());}
function getActiveAdmins(): array{ $criteria = new CriteriaCompo(); $criteria->add(new Criteria('is_admin', 1)); return $this->getUsers($criteria);}Gestione degli Errori
Sezione intitolata “Gestione degli Errori”Usa le Eccezioni Correttamente
Sezione intitolata “Usa le Eccezioni Correttamente”// Bad - generic exceptionsthrow new Exception('Error');
// Good - specific exceptionsthrow new ArticleNotFoundException($articleId);throw new PermissionDeniedException('Cannot edit article');throw new ValidationException(['title' => 'Title is required']);Gestisci gli Errori Correttamente
Sezione intitolata “Gestisci gli Errori Correttamente”public function findArticle(string $id): ?Article{ try { return $this->repository->findById($id); } catch (DatabaseException $e) { $this->logger->error('Database error finding article', [ 'id' => $id, 'error' => $e->getMessage() ]); throw new ServiceException('Unable to retrieve article', 0, $e); }}Commenti
Sezione intitolata “Commenti”Quando Commentare
Sezione intitolata “Quando Commentare”// Bad - obvious comment// Increment counter$counter++;
// Good - explains why, not what// Cache for 1 hour to reduce database load during peak traffic$cache->set($key, $data, 3600);
// Good - documents complex algorithm/** * Calculate article relevance score using TF-IDF algorithm. * Higher scores indicate better match with search terms. */function calculateRelevanceScore(Article $article, array $terms): float{ // ...}Organizzazione del Codice
Sezione intitolata “Organizzazione del Codice”Struttura della Classe
Sezione intitolata “Struttura della Classe”class ArticleService{ // 1. Constants private const MAX_TITLE_LENGTH = 255;
// 2. Properties private ArticleRepository $repository; private EventDispatcher $events;
// 3. Constructor public function __construct( ArticleRepository $repository, EventDispatcher $events ) { $this->repository = $repository; $this->events = $events; }
// 4. Public methods public function publish(Article $article): void { ... } public function archive(Article $article): void { ... }
// 5. Private methods private function validateForPublication(Article $article): void { ... }}Checklist di Codice Pulito
Sezione intitolata “Checklist di Codice Pulito”- I nomi sono significativi e pronunciabili
- Le funzioni fanno una cosa sola
- Le funzioni sono piccole (< 20 righe)
- Nessun codice duplicato
- Adeguata gestione degli errori con eccezioni specifiche
- I commenti spiegano “perché”, non “cosa”
- Formattazione e stile coerente
- Nessun numero magico o stringa
- Le dipendenze sono iniettate, non create
Documentazione Correlata
Sezione intitolata “Documentazione Correlata”- Code Organization
- Error Handling
- Testing Best Practices
- PHP Standards