Arquitetura em prática

por Fabio Margarito Martins de Barros

Unity of work

transaction Tudo pessoal?

Outro dia uma amigo me questionou sobre a utilidade do padrão Unity of Work (para facilitar, chamarei de UoW), na visão dele, o padrão não faz sentido e teria pouca utilização. Será que não tem nenhum valor? Para não respondê-lo por e-mail, resolvi postar a resposta.

Segundo Martin Fowller o padrão UoW é definido como:

Mantains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems.

em tradução livre:

Mantém uma lista de objetos afetados por uma transação de negócio, coordena a efetivação das mudanças e soluciona problemas de concorrência.

Para facilitar a compreensão do UoW, trazendo um pouco para a realidade de muitos, imagine o processo de negócio de emissão de uma nota fiscal (processo extremamente simplificado):

  • Emissão da nota fiscal
  • Baixa de itens do estoque
  • Criação de contas a receber

O processo de negócio somente será efetivado, se as três etapas forem concluídas. Como resolvemos este tipo de situação?

Geralmente abre-se uma transação no banco de dados, e se todas as etapas forem concluídas com sucesso, efetivamos a transação, caso contrário, abortamos, ou seja, voltamos ao estado anterior a transação.

O UoW é o cara que abre a transação, efetiva ou aborta, só que trabalhamos com o controle dos objetos (quais foram alterados, quais foram inseridos, excluídos , etc..).

Em um modelo orientado a objetos do nosso problema, a nota fiscal é um objeto, quando emito uma nota, no final das contas, instanciamos um objeto nota e incluímos o estado desejado (número da nota, data de emissão, lista de produtos (outro objeto),etc..) , portanto, a nota torna-se um novo objeto passível de ser persistido no banco de dados.

Se for uma alteração, basicamente retornamos os dados do banco, preenchemos um objeto do tipo nota, alteramos o estado do objeto, e este, posteriormente é persistido no banco. Com a exclusão, o processo é similar. Conseguiram ligar  a expressão “Mantém uma lista de objetos afetados por uma transação de negócio” , com o exemplo exposto? Em nosso exemplo, teríamos outros objetos que serão gerenciados pelo UoW, e por ele conhecer todos, e os respectivos estados, consegue saber se houve algo errado, e abortar, se necessário.

Para a criação de UoW, Fowller em seu artigo sugere a seguinte interface:

unitOfWorkInterface

Sacaram onde o objeto nota fiscal poderia ser incluso em cada situação?

Outro ponto importante, e faz parte da definição do UoW, é o controle de concorrência, que é outro assunto extremamente complicado e extenso, mas posso citar um exemplo:

Imagine duas pessoas, uma sem conhecimento da outra, alterando dados de um mesmo cliente, o que fazer no momento da persistência? Há algumas técnicas, como o bloqueio pessimista, ou seja, no momento que eu resgatar um cliente eu bloqueio este cliente, impedindo que qualquer outro o altere, ou , bloqueio otimista, onde faço a checagem se houve alguma alteração no momento da persistência. Enfim, implementar tudo isto não é algo tão trivial, e como o conceito padrão de projeto, é a solução para um problema recorrente, podemos imaginar que alguém já implementou isto, correto? Com certeza, vejamos alguns exemplos:

  • NHibernate, um ORM opensource bem conhecido: No NHibernate, temos o objeto Session, qual a função do Session? Ele abre a transação e monitora todos os objetos utilizados no processo de negócio.
  • Entity Framework, ORM desenvolvido pela Microsoft: No Entity Framework, temos um objeto similar ao Session do NHibernate, o datacontext.
  • DataSet do .Net Framework: Um dataset, é um banco em memória e desconectado do banco de dados, trocando em miúdos, podemos retornar dados de um banco, alteramos, incluímos dados em memória  e solicitamos que as alterações sejam persistidas.

Conclusão

Não feche os olhos aos padrões, entendê-los é importante, fazem parte do nosso dia-a-dia, e são a melhor forma de reuso de conhecimento gerado a partir do sofrimento de muitos.

Fala sério, também fica bonito em uma reunião técnica, rs…

Quer aprender mais?

[]’s

Fabio Margarito

Posted: Jun 26 2010, 03:21 by fabiomargarito | Comments (28) RSS comment feed |
  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Filed under:

Comments

louis vuitton for sale People's Republic of China said:

louis vuitton for saleWell , the view of the passage is totally correct ,your details is really  reasonable and  you guy give us  valuable  informative post, I totally agree the standpoint of upstairs. I often surfing on this forum when I <a href="http://www.bootsforsale.us" >ugg boots</a>  m free and I find there are so much good information we can learn in this forum!

# July 14 2010, 07:59

Prada Shoes United States said:

Prada Shoes
Great post and writting style, where did you learn how to blog? Cheers.

# September 02 2010, 16:00

nfl jerseys United Kingdom said:

nfl jerseysWe have many nfl jerseys in stock,if you need ,you can to <a href="http://www.nfljerseys2you.com" title="nfl jerseys"> nfl jerseys</a> site.

We produce a variety of  <a href="http://www.yiy919.com"> nfl jerseys</a> .Welcome to buy!

# September 13 2010, 07:45

uggs People's Republic of China said:

uggsInteresting... as always.

# October 30 2010, 07:26

lahore web design Islamic Republic of Pakistan said:

lahore web designWeb Design and Web function are everything when it comes to online traffic and Web sales. If your website is lacking in any way, you are probably losing potential sales through your website. According to recent research by web and online business experts; customers will decide in just 7 seconds whether or not to stay on your website once they get there! This doesn’t leave much room for error does it? As soon as your website is accessed customers are looking for any reason (no matter how small) to click away from your web, you have to have a website that invites users to participate; that’s where we come in. We provide full service web design and web development, all you need to do is provide us with your vision and we’ll make it a reality. Our long list of satisfied web design, website develop and web hosting customers speaks for itself. They have catapulted us into becoming one of the preeminent Lahore web design companies… Respect, Dependability, Capability, and Opportunity have made us one of the most Renowned companies in web design, website development and web hosting feilds; it’s our pleasure to serve our wonderful clients, let us show you what they already know…. Successful websites all share the same basic traits.

# December 03 2010, 17:51

flowers Canada Canada said:

flowers CanadaYour work is very good and I appreciate you and hopping for some more informative posts. Thank you for sharing great information to us.

# December 30 2010, 06:54

valentine day flower delivery Italy Ireland said:

valentine day flower delivery ItalyWith thanks for reveal quite beneficial information.
I am satisfied by the material which you have on this weblog.

# January 18 2011, 11:14

reverse phone number United States said:

reverse phone number  I together with my pals were actually following the best tactics on the website then unexpectedly got a horrible feeling I had not thanked the blog owner for those techniques. All the women were definitely as a result happy to study all of them and have undoubtedly been tapping into those things. Thank you for really being considerably helpful and also for obtaining this kind of useful subject areas millions of individuals are really desirous to learn about. My personal sincere regret for not saying thanks to you sooner.

# February 12 2011, 11:09

hüseyin Turkey said:

hüseyinWith thanks for reveal quite beneficial information.
I am satisfied by the material which you have on this weblog....
<a href="http://www.emlakhaberci.com">Emlak Haberci</a>
<a href="www.ortasinifevsahibioluyor.com">OrtaSinifEvSahibiOluyor</a>
<a href="http://www.konutfirsatlari.com">Konut Firsatlari</a>
<a href="http://www.sonprojeler.com">Son Projeler</a>
<a href="http://www.projehaberleri.net">Proje Haberleri</a>

# May 04 2011, 17:08

hüseyin Turkey said:

# May 04 2011, 17:10

qiulyy08 People's Republic of China said:

qiulyy08The Rathhaus fronts this market-place. It is the only building left in Wittenberg of any pretension. It stands out, surmounted by Attic arches, five on each side, and a portico totally out of keeping, looking as if made of fragments picked up at random and intended for an entirely different purpose
http://www.dooutlet.com
http://www.wholesaleoutletus.com
http://www.jordansneakerclub.com
http://www.nbajerseys-shop.com
http://www.nikeshoxnz2011.com
http://www.cheap-oakleysunglass.com
http://www.karenmillens-outlet.com
http://www.monclergiubbotti-it.com
http://www.monclergiacca2011.com
http://www.nikeonlineoutlet.com
http://www.gladoutlet.com

# August 09 2011, 11:16

Cute Quotes United States said:

Cute QuotesA powerful share, I just given this onto a colleague who was doing just a little analysis on this. And he in fact purchased me breakfast as a result of I found it for him.. smile. So let me reword that: Thnx for the treat! But yeah Thnkx for spending the time to discuss this, I really feel strongly about it and love studying more on this topic. If possible, as you become expertise, would you thoughts updating your blog with extra details? It is highly helpful for me. Big thumb up for this blog post!

# August 20 2011, 21:47

Manny said:

MannyHi .EFT Tapping has worked for me as it has for many people. Glad to learn more about it in this site of yours.

# August 21 2011, 07:03

nike shox runing shoes United States said:

nike shox runing shoesnike shox deliver mens
nike shox deliver womens
nike shox experience mens
nike shox experience womens
nike shox navina mens
nike shox navina womens
nike shox turbo mens
nike shox nz 2.0 mens
nike shox nz 2.0 womens
nike shox r4 for men
nike shox r4 for women

# August 31 2011, 12:41

Moncler Jackets United States said:

Moncler JacketsWelcom to visit our http://www.cheapgoosejackets.com/ moncler jackets  online store. Moncler is opened by Rene Ramillon in the French Alpine village of Monatier De Clermont in 1952, stylied with fur, leather, buttons and fashion fabrics, which has captured a metropolitan market in the 80's. We supply series of www.cheapgoosejackets.com/...kets-for-men-c-1.html moncler mens jackets,www.cheapgoosejackets.com/...ts-for-women-c-4.html womens moncler coats  on sale. All styles of moncler coats are fashionable and excellent. www.cheapgoosejackets.com/...oats-for-men-c-2.html mens moncler coats,www.cheapgoosejackets.com/...ids-clothing-c-5.html kids moncler jackets  sale very well online, make you comfortable. We offer the best service, www.cheapgoosejackets.com/...ts-for-women-c-3.html moncler womens jackets,cheap price, top quality and free shipping. Come on and join us. We can meet what you want!

# October 14 2011, 09:05

pacquiao vs marquez replay United States said:

pacquiao vs marquez  replay hi! very useful and very informative blog....(",)

# November 09 2011, 13:56

reverse phone number said:

reverse phone numberThanks  for the Great share.
This really solved my problem, thank you!

# December 09 2011, 16:04

Christian Louboutin Sale People's Republic of China said:

Christian Louboutin SaleHi, I found your post really helpful. It helped me all the way in completing my assignment, I am also giving a reference link of your blog in my case study.

# December 28 2011, 07:32

Cheap Christian Louboutin People's Republic of China said:

Cheap Christian LouboutinI’ve recently started a web site, the information you offer on this website has helped me greatly. Thank you for all of your time & work.

# December 28 2011, 07:33

Cheap Christian Louboutin said:

Cheap Christian LouboutinI’ve recently started a web site, the information you offer on this website has helped me greatly. Thank you for all of your time & work.

# December 28 2011, 07:33

supra trainers said:

supra trainersI will keep your new article. I really enjoyed reading this post, thanks for sharing.

# December 28 2011, 07:34

Windows Hosting United States said:

Windows HostingThis is a very beautiful blog and the pictures are provided here are very nice and it is increasing the beauty of this blog and interface is too good for the visitors to understand the things. And it is glad to comment here.

# January 21 2012, 09:31

Funny Baby United States said:

Funny BabyVery useful information about Remove Blue Shadows from Desktop Icons is provided by this blog and i like to visit such blog which always provides new things to learn.

# January 21 2012, 13:12

carpet cleaning redbank plains United States said:

carpet cleaning redbank plainsI enjoyed reading this post. It is not something very new, yet it's not bad. In adition, merci for letting us know. I wish you keep doing well

# January 31 2012, 13:00

office 2007 People's Republic of China said:

office 2007The publish is certainly the freshest on this treasured topic. I concur collectively together with your conclusions and may eagerly stay up for your future updates. Saying thanks received merely be satisfactory

# February 03 2012, 02:14

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading



Php Haber Scripti : Maltepe Bilgisayar