SlideShare ist ein Scribd-Unternehmen logo
1 von 12
Shared
Mutability is pure
evil
Avoid it, bro!
Cache
Objetos em cache ajudam muito a vida da
aplicação
- Existem dois tipos de objetos em cache:
- Único da sessão
- Usuário, Relatório, Source
- Divididos entre sessões
- Campanha, oferta, produto
Cache
Estados de um objeto precisam ser alterados
na maioria das aplicações.
- Único da sessão
- Pode mudar que não dá xabú
- Dividido entre sessões
- Alteração no estado em uma sessão
influência outra sessão, causando erros lógicos
Objetos imutáveis
Já dizia o Java effective "Promova a
imutabilidade"
- Objetos imutáveis são seguros
- Objetos imutáveis não tem estados obsoletos
- Objetos imutáveis são thread safe
- Objetos imutáveis são atômicos
Objetos imutáveis
Criar objetos imutáveis é de certa forma
simples (ou não)
public class UsuarioImutavel {
private final String nome;
private final Integer id;
private final Calendar nascimento;
private final Endereco endereco;
public UsuarioImutavel(String nome, Integer id, Calendar nascimento, Endereco endereco) {
this.nome = nome; this.id = id;
this.nascimento = nascimento; this.endereco = endereco;
}
public Integer getId() { return id; }
public String getNome() { return nome; }
public Calendar getNascimento() { return nascimento; }
public Endereco getEndereco() { return endereco; }
Objetos imutáveis
Possíveis Falhas
Possíveis Soluções
public void exemplo2(UsuarioImutavel usuarioImutavel) {
Calendar data = usuarioImutavel.getNascimento();
data.add(Calendar.YEAR, 2);
System.out.println(data.getTime());
}
public void exemplo1(UsuarioImutavel usuarioImutavel) {
Endereco endereco = usuarioImutavel.getEndereco();
endereco.setCEP("12345-678");
}
public Calendar getNascimento() {
Calendar cloneCal = Calendar.getInstance();
cloneCal.setTime(nascimento.getTime());
return cloneCal;
}
Fazer classe Endereco imutável
Objetos imutáveis
Objetos imutáveis são seguros, porém tem um
problema crítico
ELES SÃO IMUTÁVEIS!
Mutabilidade compartilhada
- E se eu precisar mudar o estado de um objeto
divido entre sessões?
- Alteração em uma requisição muda o
comportamento de outra
- Concurrent Exception
- Comportamento imprevisível
Possíveis soluções
Híbrido
Criar uma classe imutável com atributos
mutáveis
- Atributo mutável continua compartilhado!
Clonar objeto na saída do cache
- Atributos imutáveis são os mesmos mas os
mutáveis são únicos para a sessão!
Adserver Approved!
Possíveis soluções
Bag of things
- Criar um objeto auxiliar que sempre
acompanha o objeto imutável
- Objeto tem todos os atributos mutáveis
necessários
Cache
Bag of things
Possíveis soluções
Wrapper
Solução chique baseada no pattern Decorator
(um pouco modificado).
- Proposta parecida com os Wrappers Java
padrão public class WrapperOferta {
private final Oferta oferta;
private String precoFormatado;
public Oferta getOfertaImutavel() { return oferta; }
public void mudaPreco(String novoPreco) { this.precoFormatado = novoPreco; }
public String getPreco() { return precoFormatado; }
}
Qual è la
tua
soluzione?
Ma
che!!

Weitere ähnliche Inhalte

Empfohlen

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

Empfohlen (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

Objetos imutáveis e mutabilidade compartilhada

  • 2. Cache Objetos em cache ajudam muito a vida da aplicação - Existem dois tipos de objetos em cache: - Único da sessão - Usuário, Relatório, Source - Divididos entre sessões - Campanha, oferta, produto
  • 3. Cache Estados de um objeto precisam ser alterados na maioria das aplicações. - Único da sessão - Pode mudar que não dá xabú - Dividido entre sessões - Alteração no estado em uma sessão influência outra sessão, causando erros lógicos
  • 4. Objetos imutáveis Já dizia o Java effective "Promova a imutabilidade" - Objetos imutáveis são seguros - Objetos imutáveis não tem estados obsoletos - Objetos imutáveis são thread safe - Objetos imutáveis são atômicos
  • 5. Objetos imutáveis Criar objetos imutáveis é de certa forma simples (ou não) public class UsuarioImutavel { private final String nome; private final Integer id; private final Calendar nascimento; private final Endereco endereco; public UsuarioImutavel(String nome, Integer id, Calendar nascimento, Endereco endereco) { this.nome = nome; this.id = id; this.nascimento = nascimento; this.endereco = endereco; } public Integer getId() { return id; } public String getNome() { return nome; } public Calendar getNascimento() { return nascimento; } public Endereco getEndereco() { return endereco; }
  • 6. Objetos imutáveis Possíveis Falhas Possíveis Soluções public void exemplo2(UsuarioImutavel usuarioImutavel) { Calendar data = usuarioImutavel.getNascimento(); data.add(Calendar.YEAR, 2); System.out.println(data.getTime()); } public void exemplo1(UsuarioImutavel usuarioImutavel) { Endereco endereco = usuarioImutavel.getEndereco(); endereco.setCEP("12345-678"); } public Calendar getNascimento() { Calendar cloneCal = Calendar.getInstance(); cloneCal.setTime(nascimento.getTime()); return cloneCal; } Fazer classe Endereco imutável
  • 7. Objetos imutáveis Objetos imutáveis são seguros, porém tem um problema crítico ELES SÃO IMUTÁVEIS!
  • 8. Mutabilidade compartilhada - E se eu precisar mudar o estado de um objeto divido entre sessões? - Alteração em uma requisição muda o comportamento de outra - Concurrent Exception - Comportamento imprevisível
  • 9. Possíveis soluções Híbrido Criar uma classe imutável com atributos mutáveis - Atributo mutável continua compartilhado! Clonar objeto na saída do cache - Atributos imutáveis são os mesmos mas os mutáveis são únicos para a sessão! Adserver Approved!
  • 10. Possíveis soluções Bag of things - Criar um objeto auxiliar que sempre acompanha o objeto imutável - Objeto tem todos os atributos mutáveis necessários Cache Bag of things
  • 11. Possíveis soluções Wrapper Solução chique baseada no pattern Decorator (um pouco modificado). - Proposta parecida com os Wrappers Java padrão public class WrapperOferta { private final Oferta oferta; private String precoFormatado; public Oferta getOfertaImutavel() { return oferta; } public void mudaPreco(String novoPreco) { this.precoFormatado = novoPreco; } public String getPreco() { return precoFormatado; } }