refactor: Introduce factory pattern for barcode invoice handlers#91
Conversation
Refactors `BarcodeReaderService` to use a `BarcodeHandlerFactory` for resolving `IInvoiceBarcodeHandler` implementations based on `InvoiceType`. This change: * Replaces the manual `switch` statement for handler selection within `BarcodeReaderService` with a dedicated factory. * Leverages dependency injection to register and provide all `IInvoiceBarcodeHandler` implementations to the factory. * Enhances extensibility, allowing new invoice types and their corresponding handlers to be added without modifying the `BarcodeReaderService` directly. * Updates the DI configuration to `Append` registrations for barcode handlers, ensuring all implementations are available to the factory.
|
Warning Rate limit exceeded
You’ve run out of usage credits. Purchase more in the billing tab. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (2)
WalkthroughO PR introduz um padrão factory para gerenciar handlers especializados de leitura de código de barras. Cada handler agora expõe seu tipo de nota fiscal correspondente, permitindo que a factory centralize a seleção correta. O ChangesFactory Pattern para Seleção de Barcode Handler
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Suggested labels
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Tip 💬 Introducing Slack Agent: The best way for teams to turn conversations into code.Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.
Built for teams:
One agent for your entire SDLC. Right inside Slack. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
InvoiceReminder.ExternalServices/BarcodeReader/BarcodeHandlerFactory.cs (1)
9-12: ⚡ Quick winMelhorar a mensagem de erro para
InvoiceTypeduplicadoNa Line 11, se dois handlers tiverem o mesmo
InvoiceType, a falha de inicialização fica pouco diagnóstica. Vale validar duplicidade antes e lançar uma exceção explícita com os tipos conflitantes.💡 Sugestão de ajuste
public BarcodeHandlerFactory(IEnumerable<IInvoiceBarcodeHandler> handlers) { - _handlers = handlers.ToDictionary(h => h.InvoiceType, h => h); + var duplicatedTypes = handlers + .GroupBy(h => h.InvoiceType) + .Where(g => g.Count() > 1) + .Select(g => g.Key) + .ToArray(); + + if (duplicatedTypes.Length > 0) + { + throw new InvalidOperationException( + $"Duplicate barcode handlers registered for: {string.Join(", ", duplicatedTypes)}"); + } + + _handlers = handlers.ToDictionary(h => h.InvoiceType, h => h); }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@InvoiceReminder.ExternalServices/BarcodeReader/BarcodeHandlerFactory.cs` around lines 9 - 12, A construção de _handlers em BarcodeHandlerFactory está usando ToDictionary diretamente, o que deixa a falha pouco clara se houver InvoiceType duplicado; antes de chamar ToDictionary, valide a coleção IEnumerable<IInvoiceBarcodeHandler> (por exemplo em BarcodeHandlerFactory constructor) agrupando por InvoiceType, detecte chaves com Count>1 e lance uma ArgumentException/InvalidOperationException explícita que liste os InvoiceType conflitantes (e opcionalmente os tipos das implementações) para facilitar diagnóstico, caso contrário prossiga para popular _handlers.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@InvoiceReminder.ExternalServices/BarcodeReader/BarcodeHandlerFactory.cs`:
- Around line 9-12: A construção de _handlers em BarcodeHandlerFactory está
usando ToDictionary diretamente, o que deixa a falha pouco clara se houver
InvoiceType duplicado; antes de chamar ToDictionary, valide a coleção
IEnumerable<IInvoiceBarcodeHandler> (por exemplo em BarcodeHandlerFactory
constructor) agrupando por InvoiceType, detecte chaves com Count>1 e lance uma
ArgumentException/InvalidOperationException explícita que liste os InvoiceType
conflitantes (e opcionalmente os tipos das implementações) para facilitar
diagnóstico, caso contrário prossiga para popular _handlers.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 8bd01250-319a-4552-9cde-fb49a9f6bf19
📒 Files selected for processing (9)
InvoiceReminder.CrossCutting.IoC/DependencyInjectionConfig.csInvoiceReminder.ExternalServices/BarcodeReader/AccountInvoiceBarcodeHandler.csInvoiceReminder.ExternalServices/BarcodeReader/BankInvoiceBarcodeHandler.csInvoiceReminder.ExternalServices/BarcodeReader/BarcodeHandlerFactory.csInvoiceReminder.ExternalServices/BarcodeReader/BarcodeReaderService.csInvoiceReminder.ExternalServices/BarcodeReader/IBarcodeHandlerFactory.csInvoiceReminder.ExternalServices/BarcodeReader/IInvoiceBarcodeHandler.csInvoiceReminder.UnitTests.ExternalServices/BarcodeReader/BarcodeHandlerFactoryTests.csInvoiceReminder.UnitTests.ExternalServices/BarcodeReader/BarcodeReaderServiceTests.cs
Adds a check during `BarcodeHandlerFactory` initialization to ensure that no two `IInvoiceBarcodeHandler` implementations are registered for the same `InvoiceType`. This prevents potential runtime errors caused by ambiguous handler resolution and guarantees a clear one-to-one mapping between invoice types and their dedicated handlers.
Refactors
BarcodeReaderServiceto use aBarcodeHandlerFactoryfor resolvingIInvoiceBarcodeHandlerimplementations based onInvoiceType.This change:
switchstatement for handler selection withinBarcodeReaderServicewith a dedicated factory.IInvoiceBarcodeHandlerimplementations to the factory.BarcodeReaderServicedirectly.Appendregistrations for barcode handlers, ensuring all implementations are available to the factory.Summary by CodeRabbit
Notas de Lançamento
Refactor
Tests