Posts

Showing posts with the label patterns

AI Agent Patterns

Image
Previously, I was blogging about AI Abstractions and the various levels of abstraction. Now, I want to delve deeper into some patterns we can leverage while writing software using LLMs/APIs and building AI Agents. Many people still question the value of Gen AI, and I understand that, scams, delusional objectives and expectations, FUD, and many other incidents . However, for engineering, it's clear that there is value, and engineering as we know it may never be the same again. Agents are interesting because we can tweak how much autonomy we give to them; they could be bound to a straightforward and repetitive task like bumping the minor version of log4j, or could be used for complex tasks like booking a complete week of vacation with car, hotel, plane tickets, experiences, and plans. So imagine there is a dial that we can tune up or down, and how much autonomy we want to give to agents. Besides open-source models like DeepSeek or Llama , the cost remains complicated. However, clou...

Lazy Evaluation Pattern

Image
The lazy Loading pattern is very interesting because allows us to make the code starter and also delays expensive computations to an appropriate moment. There is a way to combine this pattern with Java 8 Functional Interfaces and make it even more interesting and java idiomatic. This pattern is used by Spring and Hibernate. You can use it too. So today I have a video and some POC code. Let's get started!

Re-write or Strangler

Image
In the matrix movie(classical and awesome movie), there is a classic scene where Morpheus challenge Neo's understanding of reality and offers 2 pills the Blue one which would keep the status quo, and the red one, which could be painful but would be the reality.  If you have a successful company with software thats the reality of the industry. In other terns, the discussion can seem as should we re-write the software or should we strangle it. Re-write software and even strangler patterns have cases of success and failure. Before we enter into the trade-offs of this complicated dilemma lets us understand the forces which create problems and opportunities that are around this discussion. Let's talk more about the context and their trade-offs. 

Builder Pattern in Rust

Image
Builder Pattern is useful when we need to create complex objects(structs in rust case). Also if you want to do a fluent DSL Builder is a useful pattern for that as well. Today I will show how we can implement this Pattern in Rust, so I have a simple POC to show and also a video. So Let's get started! 

Testing AWS Lambdas with Java

Image
AWS Lambda is an awesome Serverless implementation. Lambdas are a bit tricky because they are ephemeral and short-lived so either they call another lambda or they will mutate some external state. Either an external data store like RDS, Aurora, S3, Kineses, Elasticache or they will call another microservices that does state mutation. In order to properly test Lambdas, we need to design for testability, the easier thing to do is always create more lambdas because you can check the input and output. So lambdas are not pure functions(functional programming) they often need to have side effects. So AWS has this library that makes it easier to test lambdas for Unit Testing / Mocking but also for localized Phased Integration Tests. You can mock source events like S3 ones, and also mock the context, and just test your lambdas with Junit. So I made a simple POC and video I want to share with you guys. So Let's get started!

LRU Cache in Java

Image
Caches are often used as a cheap way to reduce latency and improve the performance of applications. Often we leverage libraries like Guava because they are rock solid and have lots of functionality but at the same time, all libs using Guava could easily bring a big jar hell and distributed monolith if you dont be cautious about your shared libraries. So if you are building a service might be completely fine to use more libs but as you build shared libs that could be really bad. So It's always precise and lean about your dependencies. So today I want to show that algorithms do not byte(much) and it's not rocket science to create a simple LRU Cache in Java using ZERO libraries. So I recorded a video going through the code and explaining what I did and how the algorithm works. For sure you could be thinking I prefer to use what's already there, sure thats fine. At the same time blotted applications and shared libs are really a nightmare at scale so somethings are better to cop...

CDC vs DW Patterns part 2

Image
The first blot post on this series was focus on the data part. This one will be focused on the code and functionality part.  After explaining the Strangler Pattern and understanding some of the options and the challenges, we will cover how we can combine Strangler and CDC as the ultimate solution for Slice and Dice the Monolith. Migrations are hard and often need to be performed into waves. There is a reason for that. Strangler is a code pattern focused on stopping the bleeding and either easily or more painfully migrating to a new codebase from either a legacy or a poorly designed solution. Some people have issues understanding Strangler, but it's an incremental pattern; even when you do things a bit, atomically, it's incremental(minimum 3 steps). 

CDC vs DW Patterns part 1

Image
There are 3 reasons why these patterns might be beneficial and relevant for you. First of all, if you want to replicate a database because you want to run some analytical workload(I made a recent BigData post that might interest you and related to this topic). The second reason could that you want a new cluster or new database technology.  The third use case can be you slice and dice you monolith, and you want to split one service into 2 or even more services. No matter your use cases, the architectural patterns I will describe in this blog post will help you when you need to migrate data at Scale. Dealing with data is not the same as dealing with services. Data migrations are much harder than service migrations. It's pretty easy to do some rolling wave update and migrate service by service and re-deploy even reset them one by one. However, talking about data, there are extra challenges. 

Iterator

Image
Trade-offs are super interesting and excellent exercises you can do to have better design and better coding. Let's say we want to do some simple algorithms that return vols from a String. So how many different implementations can we have? So easily we can think about some sort of Utils or generic function that can do the work for us. What if we cant to be Lazy or Early loading or be able to abstract the process? Well and Iterator is an interesting pattern that we can use to help us to abstract state and have more functionality around the data structure. So because there is the Pattern Iterator you might think that there is just one possible implementation right? Actually, there are several different implementations we can do and we can play with different trade-offs. So today I made 2 java videos to co trought this pattern and show some practicality in code. I hope you guys like it, let's get started. 

Java Object Creation Patterns

Image
Java is an old language. 25 years now. Java has several limitations and issues however java is the robust and pretty well-stablished solution for backend, databases, Caches, Search Engineers,  IoT, and much more. Today I want to share some patterns about object creation. I highly recommend you read Effective Java book, which was a huge inspiration for this blog post. So I want to show you guys some useful patterns like Static Factories, Builder, Singletons and Immutable Objects.  So I made a quick video with code, let's get started. 

Pure OO, Inversion of Control(IoC) + Dependency Injection(DI) and The Cake Pattern(FP): Whats really matters?

Image
Software development continues to improve, once you add new languages, design concepts, paradigms(like functional programing) we start having new ways of doing things, so whats really matters? should i change somethings and embrace everything or should i change nothing? In this post i want cover something if you was java developer was the central idea around java development for years. Spring Framework dominate the fields for more than a decade. The real question is not if  you should be using XML or annotations(like Guice ). Either if you should go XML or java Annotations. Thats kind of old discussion, so basically what are the options now a days?

Testes Unitários na prática com Spring, TestNG, Mockito e Maven 2 : Parte 3

Na parte 1 desta séria de postes comentei sobre a integração de soluções para testes como o TestNG e o Mockito mostrando um domínio básico de um aplicação para efetuarmos testes. Na parte 2 mostrei na prática como criar um teste com Spring, testNG e rodar tudo através do Maven 2. Neste post vou falar mais de alguns recursos do TestNG e mostrar como utilizar o Mockito e bem como as possibilidades e cenários de uso deste tipo de soluções para testes. Continuando o assunto com testNG vou falar de alguns recursos da solução utilizando anotações. Anotações de @Before... e @After... O TestNG tem algumas anotações muito úteis. Para setup de testes e grupos de testes, isso nos possibilita montar o ambiente necessário para execução dos testes. Também possibilita a limpeza do cenário dos testes entre uma execução e outra. Confira as anotações: @BeforeClass @AfterClass @BeforeMethod @AfterMethod As anotações de Before e After significam que o método anotado vai rodar antes ou depo...

Testes Unitários na prática com Spring, TestNG, Mockito e Maven 2 : Parte 2

No post anterior eu comecei a falar de testes com Spring, TestNG, Mockito e Maven. Neste post vou continuar com o assunto. Agora direto ao código e com exemplo práticos, usarei isto para discutir mais sobre o tema. Vamos ao código então, vou mostrar primeiro o código do domínio e depois os serviços para por fim chegar no nosso objetivo os testes. Produto package com.blogspost.diegopacheco.testng.spring.mockito.maven.core.domain; import java.io.Serializable; /** * Pojo que representa a entidade Produto. * O produto pode ser qualquer mercadoria que eh vendida pelo estabelecimento. * Você pode adicionar mapeamento ORM aqui com anotações por exemplo, isso foi * abstraido por conta do foco do post. * * @author Diego Pacheco * @version 1.0 * @since 28/07/2009 * */ public class Produto implements Serializable { private static final long serialVersionUID = 1L; private Long id; private String nome; private String desc; public Produto(){ } public Produto(Long id, String nome, Strin...

Testes Unitários na prática com Spring, TestNG, Mockito e Maven 2 : Parte 1

Image
Neste post vou mostrar como podemos criar testes unitários para aplicações desenvolvidas com Spring usando o TestNG . Além disto usarei o framework para mocks chamado Mockito com isto será possível simular o comportamento de certos objetos para realizar o testes. No final vamos rodar estes testes com o Maven. Se quiser saber mais sobre testes, Q.A e Maven sugiro que leia meus postas anteriores: Testes do Desenvolvedor: Indo além do Debug Q.A Muito mais que Testes Integração Continua: O Verdadeiro Foco G.C ou Q.A? 10 Motivos para Você Usar Maven Maven 2.0.8 + Archiva 1.0.1 + Tomcat 6.0.16 Mais Poder ao Maven com Archiva Testes unitários com o TestNG O testNG é um framework para testes unitários feito em Java para Java :). A solução é bem mais flexível do que o JUnit que é a solução mais tradicional de testes unitários em Java. O testNG prove mais facilidades do que o JUnit principalmente quando realizamos testes em grupos, esta funcionalidade eh útil para testar grupos de funcionalidad...

Qualidade e Produtividade com MVC em PHP

Como Arquiteto de Software não posso deixar de olhar para as outras solução que estão fora do mundo Java. Desenvolver um sistema em Java pode trazer diversas vantagens mas também pode trazer complexidade e custo desnecessário. Aplicações para empresas de pequenas e médio tamanho consideram o uso de PHP com solução para seus sistemas web, dependendo das características e dos requisitos do sistema eu considero o PHP como uma ótima solução. A evolução dos frameworks MVC em PHP foi muito boa nestes últimos anos. O que é MVC mesmo? É um padrão de arquitetura de software largamente utilizado em soluções para Web. Sua principal vantagem é a separação das telas(view) da camada de negócio(model). Você pode usar MVC em um sistema desktop, dependendo do sistema será uma boa escolha. Neste post vou mostrar como pode ser fácil e rápido construir uma solução usando MVC com PHP, neste caso vou usar o framework CodeIgniter . Por que não Java? Por que dependendo do sistema seria só adic...

SCA com Java Parte 2

No post anterior eu falei um pouco sobre SCA e como esse padrão funciona. Agora vou mostrar um exemplo simples de como implementar um composite SCA feito em Java utilizando o Fabric3 .Neste exemplo você vai precisar de: JDK 6 Fabric3 Standalone Server Profile Web do Fabric3 Maven 2 Neste exemplo vou criar um serviço composto de utilidades que será composto pelo serviço de Data. O Serviço de data nada mais faz do que informar a data atual no servidor. Sem mais delongas vamos ao código dos serviços. Cada serviço tem a sua interface de negócio(contrato) e a sua implementação em Java. DateService.java package com.blogspot.diegopacheco.sca.services; /** * Interface do servico de datas * * @author Diego Pacheco * @version 1.0 * @since 17/05/2009 * */ public interface DateService { String getDate(); } Agora vamos a implementação Java. DateServiceImpl.java package com.blogspot.diegopacheco.sca.services; import java.util.Date; /** * Implementação do serv...

SCA com Java Parte 1

Image
SCA é um padrão aberto para construção de serviços. Esse padrão é uma das possibilidades para a implementação de serviços compostos usando SOA, mas não é a única. A idéia não é nem um pouco nova, na verdade se você usa Spring Framework é bem provável que você já venha fazendo algo parecido. A grande diferença do SCA para o que você já faz é que como dito antes SCA é um padrão aberto que prove uma solução para amarração(wire) de serviços e composição de serviços de uma forma padronizada, consistente e independência de fornecedor. Além disso o SCA possibilita a tão sonhada interoperabilidade . A Interoperabilidade é algo fundamental quando falamos de SOA, mas isso pode ser conseguido de outras formas utilizando orquestração de serviços com BPEL e deixando o transporte para um ESB a vantagem de usar SCA sobre essa outra abordagem que descrevi é o fato de que você tem um módulo mais coeso com SCA. Conceitos Básicos de SCA Componente SCA A Figura a cima ilustra do que é composto um compone...

Proxy/Interceptor à la carte com Groovy

Groovy é uma linguagem de script fantástica, tem um poder e facilidade assombrosa. Muitas dessas facilidades não existem quando trabalhamos com Java. Algumas existem mas não são para meros mortais e em muitas vezes temos que envolver diversos outros frameworks para executar o que queremos. O Groovy possui diversas maneiras de se trabalhar com proxy/interceptors e vou mostrar algumas dessas maneiras nesse post. Considere então a seguinte interface Java. package com.blogspot.diegopacheco.groovy.proxy; /** * Interface que representa o contrato de OrdemCompra * * @author Diego Pacheco * @since 17/02/2009 * @version 1.0 * */ public interface OrdemCompra { public void comprar(); } Vamos aplicar o proxy Groovy em cima de uma interface Java, a interface OrdemCompra. Você poderia aplicar esse proxy em uma interface Groovy também. Vou mostrar a primeira fora de proxy com o proxy-o-mate que é um dos módulos do Groovy. package com.blogspot.diegopacheco.groovy.proxy import static org....