Tesi etd-03232026-153601 |
Link copiato negli appunti
Tipo di tesi
Tesi di laurea magistrale
Autore
FRANCO, ARCANGELO
URN
etd-03232026-153601
Titolo
Individuazione automatica di Design Pattern all’interno del codice
Dipartimento
FILOLOGIA, LETTERATURA E LINGUISTICA
Corso di studi
INFORMATICA UMANISTICA
Relatori
relatore Passaro, Lucia C.
relatore Soldani, Jacopo
relatore Soldani, Jacopo
Parole chiave
- analisi di codice
- code analysis
- CodeBERT
- contrastive learning
- design pattern detection
- embeddings
- machine learning
- modelli transformer
- text analytics
- transformer models
Data inizio appello
10/04/2026
Consultabilità
Completa
Riassunto (Inglese)
The thesis addresses the problem of automatically recognizing design patterns within source code, with particular attention to code generated by Large Language Models (LLMs). In the current context of software development, characterized by increasingly complex and modular systems, design patterns represent fundamental tools for ensuring code quality and maintainability. However, the automatic identification of such patterns remains an open challenge, mainly due to the high variability of real-world implementations compared to their canonical definitions.
Traditionally, design pattern detection has been approached through structural code analysis, heuristic techniques, and graph matching methods. Although these approaches offer a high degree of interpretability, they are often rigid and not robust to implementation variability. On the other hand, machine learning and deep learning methods provide greater generalization capabilities, but introduce issues related to the need for large annotated datasets and limited model interpretability.
In this context, the thesis proposes a hybrid approach that combines structural analysis with semantic representations of code. The goal is to leverage the strengths of both perspectives: on the one hand, the precision and transparency of structural rules; on the other, the ability of embeddings to capture deep semantic relationships that are invariant to syntactic variations.
The architecture of the developed system is organized as a multi-stage analysis pipeline. First, the source code is preprocessed using identifier anonymization techniques, with the aim of reducing lexical bias and forcing the model to focus on structural and semantic aspects rather than variable names. Subsequently, structural features are extracted from the Abstract Syntax Tree (AST), which represents the syntactic structure of the code.
The core of the system consists of two main modules: the Structural Score and the Alignment Score.
The Structural Score module evaluates how well the analyzed code satisfies the structural constraints of design patterns. This process is based on a taxonomy of evidence organized into four pillars, including aspects such as class relationships, inheritance hierarchies, and object interaction patterns. The evidence is aggregated using a geometric mean, producing an interpretable score that reflects the degree of structural compliance of the code with respect to a given pattern.
The Alignment Score module, on the other hand, relies on vector representations of code (embeddings) generated using CodeBERT, a Transformer-based neural model trained on source code and natural language. These embeddings map code fragments into a continuous latent space, where geometric proximity between vectors reflects semantic similarity. Within this space, the analyzed code is compared with prototypical representations of different design patterns, allowing the estimation of semantic alignment.
To improve the quality of the latent space, the model is further optimized using Supervised Contrastive Learning techniques. This approach reduces intra-class variance and increases separation between different classes, making the representations more discriminative. In particular, contrastive learning addresses the issue of embedding anisotropy, which tends to compress vectors into narrow regions of the space, thereby limiting the ability to distinguish between different patterns.
The two scores, Structural Score and Alignment Score, are finally combined using a late fusion strategy based on a geometric mean. This enables the integration of structural and semantic information into a more robust final decision, leveraging the complementarity of the two approaches. In cases of ambiguity, a lexicographic ordering strategy is applied to determine the most likely pattern.
The experimental evaluation was conducted using both synthetic datasets generated via LLMs and a manually validated Gold Standard Test Set. The evaluation metrics include precision, recall, and F1-score for classification, as well as metrics specific to latent space analysis, such as Silhouette Score, Mean Alignment, and Uniformity.
The results show that the proposed hybrid approach achieves competitive performance, demonstrating greater robustness compared to purely structural or purely neural approaches. In particular, the system shows a good ability to distinguish between complex patterns, even in the presence of implementation variability. However, some difficulties emerge in discriminating structurally similar patterns, such as Adapter and Strategy, highlighting the intrinsic limitations of the problem.
The ablation study further confirms the significant contribution of the different system components, particularly the contrastive fine-tuning of embeddings, which substantially improves class separability in the latent space.
Finally, the thesis discusses the main limitations of the work. Among these are the restriction to single-file analysis, which prevents capturing cross-file relationships, and the difficulty in recognizing highly atypical pattern implementations. Moreover, the use of automatically generated datasets, while advantageous in terms of scalability, may introduce biases related to generative models.
Possible future directions include extending the analysis to multi-file systems, introducing continuous structural scores, and adapting the framework to different programming languages.
In conclusion, the work demonstrates how a hybrid approach combining structural analysis and semantic representations constitutes a promising solution to the problem of design pattern detection, opening new perspectives for the application of advanced machine learning techniques in the domain of software engineering.
Traditionally, design pattern detection has been approached through structural code analysis, heuristic techniques, and graph matching methods. Although these approaches offer a high degree of interpretability, they are often rigid and not robust to implementation variability. On the other hand, machine learning and deep learning methods provide greater generalization capabilities, but introduce issues related to the need for large annotated datasets and limited model interpretability.
In this context, the thesis proposes a hybrid approach that combines structural analysis with semantic representations of code. The goal is to leverage the strengths of both perspectives: on the one hand, the precision and transparency of structural rules; on the other, the ability of embeddings to capture deep semantic relationships that are invariant to syntactic variations.
The architecture of the developed system is organized as a multi-stage analysis pipeline. First, the source code is preprocessed using identifier anonymization techniques, with the aim of reducing lexical bias and forcing the model to focus on structural and semantic aspects rather than variable names. Subsequently, structural features are extracted from the Abstract Syntax Tree (AST), which represents the syntactic structure of the code.
The core of the system consists of two main modules: the Structural Score and the Alignment Score.
The Structural Score module evaluates how well the analyzed code satisfies the structural constraints of design patterns. This process is based on a taxonomy of evidence organized into four pillars, including aspects such as class relationships, inheritance hierarchies, and object interaction patterns. The evidence is aggregated using a geometric mean, producing an interpretable score that reflects the degree of structural compliance of the code with respect to a given pattern.
The Alignment Score module, on the other hand, relies on vector representations of code (embeddings) generated using CodeBERT, a Transformer-based neural model trained on source code and natural language. These embeddings map code fragments into a continuous latent space, where geometric proximity between vectors reflects semantic similarity. Within this space, the analyzed code is compared with prototypical representations of different design patterns, allowing the estimation of semantic alignment.
To improve the quality of the latent space, the model is further optimized using Supervised Contrastive Learning techniques. This approach reduces intra-class variance and increases separation between different classes, making the representations more discriminative. In particular, contrastive learning addresses the issue of embedding anisotropy, which tends to compress vectors into narrow regions of the space, thereby limiting the ability to distinguish between different patterns.
The two scores, Structural Score and Alignment Score, are finally combined using a late fusion strategy based on a geometric mean. This enables the integration of structural and semantic information into a more robust final decision, leveraging the complementarity of the two approaches. In cases of ambiguity, a lexicographic ordering strategy is applied to determine the most likely pattern.
The experimental evaluation was conducted using both synthetic datasets generated via LLMs and a manually validated Gold Standard Test Set. The evaluation metrics include precision, recall, and F1-score for classification, as well as metrics specific to latent space analysis, such as Silhouette Score, Mean Alignment, and Uniformity.
The results show that the proposed hybrid approach achieves competitive performance, demonstrating greater robustness compared to purely structural or purely neural approaches. In particular, the system shows a good ability to distinguish between complex patterns, even in the presence of implementation variability. However, some difficulties emerge in discriminating structurally similar patterns, such as Adapter and Strategy, highlighting the intrinsic limitations of the problem.
The ablation study further confirms the significant contribution of the different system components, particularly the contrastive fine-tuning of embeddings, which substantially improves class separability in the latent space.
Finally, the thesis discusses the main limitations of the work. Among these are the restriction to single-file analysis, which prevents capturing cross-file relationships, and the difficulty in recognizing highly atypical pattern implementations. Moreover, the use of automatically generated datasets, while advantageous in terms of scalability, may introduce biases related to generative models.
Possible future directions include extending the analysis to multi-file systems, introducing continuous structural scores, and adapting the framework to different programming languages.
In conclusion, the work demonstrates how a hybrid approach combining structural analysis and semantic representations constitutes a promising solution to the problem of design pattern detection, opening new perspectives for the application of advanced machine learning techniques in the domain of software engineering.
Riassunto (Italiano)
La tesi affronta il problema del riconoscimento automatico dei design pattern all’interno di codice sorgente, con particolare attenzione al codice generato da Large Language Models (LLM). Nel contesto attuale dello sviluppo software, caratterizzato da sistemi sempre più complessi e modulari, i design pattern rappresentano strumenti fondamentali per garantire qualità e manutenibilità del codice. Tuttavia, l’identificazione automatica di tali pattern rimane una sfida aperta, principalmente a causa della forte variabilità delle implementazioni reali rispetto alle definizioni canoniche.
Tradizionalmente, il rilevamento dei design pattern è stato affrontato attraverso approcci basati su analisi strutturale del codice, tecniche euristiche e metodi di graph matching. Sebbene tali approcci offrano un elevato grado di interpretabilità, risultano spesso rigidi e poco robusti rispetto alle variazioni implementative. D’altra parte, i metodi basati su machine learning e deep learning permettono una maggiore capacità di generalizzazione, ma introducono problematiche legate alla necessità di grandi dataset annotati e alla scarsa interpretabilità dei modelli.
In questo contesto, la tesi propone un approccio ibrido che combina analisi strutturale e rappresentazioni semantiche del codice. L’obiettivo è sfruttare i punti di forza di entrambe le prospettive: da un lato, la precisione e la trasparenza delle regole strutturali; dall’altro, la capacità degli embedding di catturare relazioni semantiche profonde e invarianti rispetto a variazioni sintattiche.
L'architettura del sistema sviluppato si articola in una pipeline composta da più fasi di analisi. In primo luogo, il codice sorgente viene preprocessato tramite tecniche di anonimizzazione degli identificatori, con l’obiettivo di ridurre il bias lessicale e costringere il modello a concentrarsi sugli aspetti strutturali e semantici piuttosto che sui nomi delle variabili. Successivamente, vengono estratte le feature strutturali a partire dall’Abstract Syntax Tree (AST), che rappresenta la struttura sintattica del codice.
Il cuore del sistema è costituito da due moduli principali: lo Structural Score e l’Alignment Score.
Il modulo Structural Score valuta quanto il codice analizzato rispetti i vincoli strutturali dei design pattern. Questo processo si basa su una tassonomia di evidenze organizzata in quattro pilastri, che includono aspetti come relazioni tra classi, gerarchie di ereditarietà e pattern di interazione tra oggetti. Le evidenze vengono aggregate attraverso una media geometrica, producendo un punteggio interpretabile che riflette il grado di conformità strutturale del codice rispetto a un determinato pattern.
Il modulo Alignment Score, invece, si basa su rappresentazioni vettoriali del codice (embeddings) generate tramite CodeBERT, un modello neurale basato su architettura Transformer addestrato su codice sorgente e linguaggio naturale. Gli embedding consentono di mappare frammenti di codice in uno spazio latente continuo, in cui la vicinanza geometrica tra vettori riflette la similarità semantica. In questo spazio, il codice analizzato viene confrontato con rappresentazioni prototipali dei diversi design pattern, permettendo di stimare il grado di allineamento semantico.
Per migliorare la qualità dello spazio latente, il modello viene ulteriormente ottimizzato tramite tecniche di Supervised Contrastive Learning. Questo approccio consente di ridurre la varianza intra-classe e aumentare la separazione tra classi diverse, rendendo le rappresentazioni più discriminative. In particolare, il contrastive learning affronta il problema dell’anisotropia degli embedding, che tende a comprimere i vettori in regioni ristrette dello spazio, compromettendo la capacità di distinguere tra pattern differenti.
I due punteggi, Structural Score e Alignment Score, vengono infine combinati attraverso una strategia di late fusion basata su media geometrica. Questo consente di integrare le informazioni strutturali e semantiche in una decisione finale più robusta, sfruttando la complementarità dei due approcci. In caso di ambiguità, viene applicata una strategia di ordinamento lessicografico per determinare il pattern più probabile.
La valutazione sperimentale è stata condotta utilizzando sia dataset sintetici generati tramite LLM sia un Gold Standard Test Set validato manualmente. Le metriche utilizzate includono precision, recall e F1-score per la classificazione, oltre a metriche specifiche per l’analisi dello spazio latente, come Silhouette Score, Mean Alignment e Uniformity.
I risultati mostrano che l’approccio ibrido proposto è in grado di ottenere prestazioni competitive, evidenziando una maggiore robustezza rispetto agli approcci puramente strutturali o puramente neurali. In particolare, il sistema dimostra una buona capacità di distinguere tra pattern complessi, anche in presenza di variazioni implementative. Tuttavia, emergono alcune difficoltà nel discriminare pattern strutturalmente simili, come Adapter e Strategy, evidenziando i limiti intrinseci del problema.
L’analisi ablativa conferma, inoltre, il contributo significativo delle diverse componenti del sistema, in particolare del fine-tuning contrastivo degli embedding, che migliora sensibilmente la separabilità delle classi nello spazio latente.
Infine, la tesi discute i principali limiti del lavoro. Tra questi, si evidenzia la limitazione dell’analisi a singoli file, che impedisce di catturare relazioni cross-file, e la difficoltà nel riconoscere implementazioni particolarmente atipiche dei pattern. Inoltre, l’uso di dataset generati automaticamente, sebbene vantaggioso in termini di scalabilità, può introdurre bias legati ai modelli generativi.
Tra le possibili direzioni future, si propone l’estensione dell’analisi a sistemi multi-file, l’introduzione di punteggi strutturali continui e l’adattamento del framework a diversi linguaggi di programmazione.
In conclusione, il lavoro dimostra come un approccio ibrido, che combina analisi strutturale e rappresentazioni semantiche, rappresenti una soluzione promettente per il problema del design pattern detection, aprendo nuove prospettive per l’applicazione di tecniche di machine learning avanzate nel dominio dell’ingegneria del software.
Tradizionalmente, il rilevamento dei design pattern è stato affrontato attraverso approcci basati su analisi strutturale del codice, tecniche euristiche e metodi di graph matching. Sebbene tali approcci offrano un elevato grado di interpretabilità, risultano spesso rigidi e poco robusti rispetto alle variazioni implementative. D’altra parte, i metodi basati su machine learning e deep learning permettono una maggiore capacità di generalizzazione, ma introducono problematiche legate alla necessità di grandi dataset annotati e alla scarsa interpretabilità dei modelli.
In questo contesto, la tesi propone un approccio ibrido che combina analisi strutturale e rappresentazioni semantiche del codice. L’obiettivo è sfruttare i punti di forza di entrambe le prospettive: da un lato, la precisione e la trasparenza delle regole strutturali; dall’altro, la capacità degli embedding di catturare relazioni semantiche profonde e invarianti rispetto a variazioni sintattiche.
L'architettura del sistema sviluppato si articola in una pipeline composta da più fasi di analisi. In primo luogo, il codice sorgente viene preprocessato tramite tecniche di anonimizzazione degli identificatori, con l’obiettivo di ridurre il bias lessicale e costringere il modello a concentrarsi sugli aspetti strutturali e semantici piuttosto che sui nomi delle variabili. Successivamente, vengono estratte le feature strutturali a partire dall’Abstract Syntax Tree (AST), che rappresenta la struttura sintattica del codice.
Il cuore del sistema è costituito da due moduli principali: lo Structural Score e l’Alignment Score.
Il modulo Structural Score valuta quanto il codice analizzato rispetti i vincoli strutturali dei design pattern. Questo processo si basa su una tassonomia di evidenze organizzata in quattro pilastri, che includono aspetti come relazioni tra classi, gerarchie di ereditarietà e pattern di interazione tra oggetti. Le evidenze vengono aggregate attraverso una media geometrica, producendo un punteggio interpretabile che riflette il grado di conformità strutturale del codice rispetto a un determinato pattern.
Il modulo Alignment Score, invece, si basa su rappresentazioni vettoriali del codice (embeddings) generate tramite CodeBERT, un modello neurale basato su architettura Transformer addestrato su codice sorgente e linguaggio naturale. Gli embedding consentono di mappare frammenti di codice in uno spazio latente continuo, in cui la vicinanza geometrica tra vettori riflette la similarità semantica. In questo spazio, il codice analizzato viene confrontato con rappresentazioni prototipali dei diversi design pattern, permettendo di stimare il grado di allineamento semantico.
Per migliorare la qualità dello spazio latente, il modello viene ulteriormente ottimizzato tramite tecniche di Supervised Contrastive Learning. Questo approccio consente di ridurre la varianza intra-classe e aumentare la separazione tra classi diverse, rendendo le rappresentazioni più discriminative. In particolare, il contrastive learning affronta il problema dell’anisotropia degli embedding, che tende a comprimere i vettori in regioni ristrette dello spazio, compromettendo la capacità di distinguere tra pattern differenti.
I due punteggi, Structural Score e Alignment Score, vengono infine combinati attraverso una strategia di late fusion basata su media geometrica. Questo consente di integrare le informazioni strutturali e semantiche in una decisione finale più robusta, sfruttando la complementarità dei due approcci. In caso di ambiguità, viene applicata una strategia di ordinamento lessicografico per determinare il pattern più probabile.
La valutazione sperimentale è stata condotta utilizzando sia dataset sintetici generati tramite LLM sia un Gold Standard Test Set validato manualmente. Le metriche utilizzate includono precision, recall e F1-score per la classificazione, oltre a metriche specifiche per l’analisi dello spazio latente, come Silhouette Score, Mean Alignment e Uniformity.
I risultati mostrano che l’approccio ibrido proposto è in grado di ottenere prestazioni competitive, evidenziando una maggiore robustezza rispetto agli approcci puramente strutturali o puramente neurali. In particolare, il sistema dimostra una buona capacità di distinguere tra pattern complessi, anche in presenza di variazioni implementative. Tuttavia, emergono alcune difficoltà nel discriminare pattern strutturalmente simili, come Adapter e Strategy, evidenziando i limiti intrinseci del problema.
L’analisi ablativa conferma, inoltre, il contributo significativo delle diverse componenti del sistema, in particolare del fine-tuning contrastivo degli embedding, che migliora sensibilmente la separabilità delle classi nello spazio latente.
Infine, la tesi discute i principali limiti del lavoro. Tra questi, si evidenzia la limitazione dell’analisi a singoli file, che impedisce di catturare relazioni cross-file, e la difficoltà nel riconoscere implementazioni particolarmente atipiche dei pattern. Inoltre, l’uso di dataset generati automaticamente, sebbene vantaggioso in termini di scalabilità, può introdurre bias legati ai modelli generativi.
Tra le possibili direzioni future, si propone l’estensione dell’analisi a sistemi multi-file, l’introduzione di punteggi strutturali continui e l’adattamento del framework a diversi linguaggi di programmazione.
In conclusione, il lavoro dimostra come un approccio ibrido, che combina analisi strutturale e rappresentazioni semantiche, rappresenti una soluzione promettente per il problema del design pattern detection, aprendo nuove prospettive per l’applicazione di tecniche di machine learning avanzate nel dominio dell’ingegneria del software.
File
| Nome file | Dimensione |
|---|---|
| Tesi_Mag..._2026.pdf | 9.19 Mb |
Contatta l’autore |
|