SlideShare uma empresa Scribd logo
1 de 50
Code simple, but not simpler

 Discuss ways to develop enterprise
  applications based on “POJOs in
     Action” by Chris Richardson
Who am I?

Viachaslau Churukanau

     Senior Software Engineer, Java world

                        Edmunds.com, room 404
INTRODUCTION
You have to design enterprise
    applications at some moment

But how to develop this skill if:
• There are no appropriate trainings
• The Internet usually provides little,
  contradictory and out of date knowledge
• People tell you “lie”
• Etc.
?
Correct Solution




Read Books and Try
POJOs in Action (2006)
• shows how to address many common and
  complex design issues in back-end logic
  development of enterprise applications with
  fantastic real-world examples
• combines best practices and design wisdom to
  integrate domain-driven design and test-driven
  development for object-oriented applications
• carefully    explains   the     techniques   and
  technologies used at various levels, including
  Spring, JDO, Hibernate, EJB 3, and iBatis.
Key Messages
• Regardless of how the frameworks evolve,
  there are some key concepts that will not
  change
• Every technology has both benefits and
  drawbacks
• Make everything as simple as possible, but
  not simpler (Albert Einstein)
Design Decisions
ORGANIZING THE BUSINESS LOGIC
Domain Model (object-oriented)
Money Transfer Example
Benefits and Drawbacks
+ Improved maintainability and extensibility
+ Persistence framework enables you to easily
map the domain model to the database
- You should have good OOD skills
Transaction Script (Procedural)
Benefits and Drawbacks
+ Easy to Use (no OOD skill required)
+ Can use full range of SQL features
- Code can be difficult to understand and
maintain (complex business logic, explicit load
and save all required data)
- Cost of maintaining handwritten SQL (e.g. add
a column – change multiple queries)
- Lack of portability of SQL
When to Use
• The application must use SQL directly or you
  cannot use a persistence framework
• The business logic is very simple
• The development team lacks the necessary
  OO design skills
ENCAPSULATING THE BUSINESS
LOGIC
EJB session / POJO facade
Benefits and Drawbacks
+ Business Logic is encapsulated and is free of
transaction management (including distributed
transactions), security, remote access, detaching
objects, etc.
- You must write extra code
- It is quite easy for the detachment code and
the presentation tier to get out of sync and for
the POJO façade to only return some of the
objects required by the presentation tier
Exposed Domain Model (Open Session
             in View)
Benefits and Drawbacks
+ Faster development (the business tier does not
contain façades or error-prone detachment logic)
- Less encapsulation (it is quite easy for business
logic to creep into the presentation tier; the
presentation tier has access to the domain objects;
business tier changes affect presentation tier)
- No support for remote access
- Tricky to configure interactions between
transactions, persistence framework, and the
servlet API
ACCESSING THE DATABASE
What’s wrong with using JDBC directly
• Developing and maintaining SQL is difficult
  and time consuming
• There is a lack of portability with SQL
• Writing JDBC code is time consuming and
  error-prone
What if I need SQL?
• You must use the full power of SQL, including
vendor-specific features, in order to get good
performance
• Your DBA might demand complete control over
the SQL statements executed by your
application
• The corporate investment in its relational
databases is so massive that the applications
working with the databases can appear
relatively unimportant
iBatis
• Insulates the application from connections
  and prepared statements, iBATIS maps
  JavaBeans to SQL statements using XML
  descriptor files or annotations
• Supports for database-generated primary
  keys,    automatic      loading    of related
  objects, caching, and lazy loading
Why you don’t want to persist objects
             yourself
1. Lazy Loading (loading all of the objects that
   might be accessed might be extremely
   inefficient)
2. Writing back to the database only those objects
   that have been modified (it would be extremely
   inefficient to save all objects regardless of
   whether they have changed)
3. The database access code must preserve object
   identity by ensuring that there is a single in-
   memory instance of a persistent object when
   processing a request
Solution




Use ORM Framework
Кey features of an ORM framework
• Declarative mapping between the object model
  and database schema
• An API for creating, reading, updating, and
  deleting objects
• A query language
• Support for transactions
• Lazy and eager loading
• Caching
• Detached objects
Benefits and Drawbacks
+ Improved productivity
+ Improved performance
+ Improved portability
+- Sometimes you must use SQL directly
   (performance, etc.)
- Challenging when you’re working with a legacy
   schema (e.g. denormalized)
- You might design a domain model that cannot be
   mapped to the desired database schema
HANDLING CONCURRENCY
IN DATABASE TRANSACTIONS
Read Phenomena
Isolated Database Transactions
• The database ensures that the outcome of
  executing multiple serializable transactions is
  the same as executing them serially.
• Serializable transactions prevent such
  problems as lost updates and inconsistent
  reads
Benefits and Drawbacks
+ They are simple to use
+     They     prevent   many      concurrency
  problems, including lost updates and
  inconsistent reads
- They produce the high overhead, which can
  reduce performance and scalability
- Fully isolated transactions can fail more
  frequently than less isolated transactions
  because of deadlocks and other concurrency-
  related issues
When to Use
• Read consistency is essential
• The overhead of fully isolated transactions is
  acceptable
Pessimistic locking
Benefits and drawbacks
+ Unlike optimistic locking, pessimistic locking does not
   require any schema changes
+ It prevents a transaction from overwriting another
   transaction’s changes
+ It reduces the probability of deadlocks in databases that
   implement fully isolated transactions by locking rows
   when they read
- All potentially conflicting transactions have to use
   SELECT FOR UPDATE in order for pessimistic locking to
   work, which is potentially error-prone
- Some databases have limitations on how SELECT FOR
   UPDATE can be used
When to Use
• The database schema does not support
  optimistic locking because, for example, the
  tables do not have a version or timestamp
  column or contain values such as floats or
  blobs that cannot be compared
• The application requires some degree of read
  consistency
• You don’t want to incur the overhead of
  serializable transactions
Optimistic locking
Benefits and Drawbacks
+ It is easy to implement and it is supported by
   many persistence frameworks
+ Unlike pessimistic locking, does not prevent an
   application from using certain SQL SELECT
   statement features
- All potentially conflicting transactions must use
   optimistic locking or errors will occur
- No guarantee that a transaction will be able to
   update the rows that it read
- Does not prevent inconsistent reads
When to Use
General recommendation is that an application
should use optimistic locking unless:
• The database schema does not support
  optimistic locking
• The application must be guaranteed to be
  able to update the rows that it read
• The application requires consistent reads
HANDLING CONCURRENCY
IN LONG TRANSACTIONS
Edit-style Use Case
What’s wrong with using a single
        database transaction
• The database transaction would be long-
  running because it encompasses multiple web
  requests and user think time
• The transaction might last until the web
  session timed out if the user could simply walk
  away from the browser without completing
  the use case
• It reduce scalability and concurrency
Pessimistic Offline Lock
Benefits and Drawbacks
+ Ensures that a user can save changes
- Impacts the application globally (don’t forget
   to use it in a new code, etc.)
- Requires a mechanism to forcibly release locks
When to Use
• The probability of conflicts is high
• The consequences of conflicts are severe
• Users typically do not abandon their sessions
  or it’s feasible to implement a lock cleanup
  mechanism
Optimistic Offline Lock
Benefits and Drawbacks
+ It is relatively easy to implement
+ Unlike the Pessimistic Offline Lock pattern, there are no
   locks to clean up if the user abandons the session,
   which is not uncommon in a web application.
- Because the Optimistic Offline Lock pattern only detects
   changes when the user tries to save their changes, it
   only works well when starting over is not a burden on
   the user
- All transactions that update shared data must increment
   the version number whenever they update a row,
   including those that do not use the Optimistic Offline
   Lock pattern
When to Use
• The probability of conflicts is low and the
  consequences of redoing the changes are
  minimal
• Users regularly abandon sessions and you
  don’t want to implement a lock cleanup
  mechanism
Summary

Mais conteúdo relacionado

Destaque

Reporting куда как-зачем by Anton Stoliar
Reporting   куда как-зачем by Anton StoliarReporting   куда как-зачем by Anton Stoliar
Reporting куда как-зачем by Anton StoliarEPAM Systems
 
MS TFS 2010 - Управление проектами и рабочие элементы
MS TFS 2010 - Управление проектами и рабочие элементыMS TFS 2010 - Управление проектами и рабочие элементы
MS TFS 2010 - Управление проектами и рабочие элементыАлександр Шамрай
 
Secr2013 разработчики vs поддержка - Лилия Горбачик
Secr2013 разработчики vs поддержка - Лилия ГорбачикSecr2013 разработчики vs поддержка - Лилия Горбачик
Secr2013 разработчики vs поддержка - Лилия ГорбачикLilia Gorbachik
 
Организация процессов разработки на основе TFS
Организация процессов разработки на основе TFSОрганизация процессов разработки на основе TFS
Организация процессов разработки на основе TFSАлександр Шамрай
 
Independence of testing
Independence of testingIndependence of testing
Independence of testingQA Guards
 
Разработка по с использованием Tfs 2012
Разработка по с использованием Tfs 2012Разработка по с использованием Tfs 2012
Разработка по с использованием Tfs 2012Александр Шамрай
 
Development process в большой компании
Development process в большой компанииDevelopment process в большой компании
Development process в большой компанииLilia Gorbachik
 
Optimizing Your Management for Business Expansion
Optimizing Your Management for Business ExpansionOptimizing Your Management for Business Expansion
Optimizing Your Management for Business ExpansionAmanda Collette
 
BBST courses. Стоит ли овчинка выделки?
BBST courses. Стоит ли овчинка выделки?BBST courses. Стоит ли овчинка выделки?
BBST courses. Стоит ли овчинка выделки?OdessaQA
 
Оригинальные решения СМ-Консалт, улучшающие функциональные характеристики инс...
Оригинальные решения СМ-Консалт, улучшающие функциональные характеристики инс...Оригинальные решения СМ-Консалт, улучшающие функциональные характеристики инс...
Оригинальные решения СМ-Консалт, улучшающие функциональные характеристики инс...Александр Шамрай
 
Практическое руководство - использование SVN
Практическое руководство - использование SVNПрактическое руководство - использование SVN
Практическое руководство - использование SVNАлександр Шамрай
 
Journey to 1000 tests a day
Journey to 1000 tests a dayJourney to 1000 tests a day
Journey to 1000 tests a dayBruce McLeod
 
Презентация
ПрезентацияПрезентация
Презентацияkulibin
 

Destaque (20)

Reporting куда как-зачем by Anton Stoliar
Reporting   куда как-зачем by Anton StoliarReporting   куда как-зачем by Anton Stoliar
Reporting куда как-зачем by Anton Stoliar
 
MS TFS 2010 - Управление проектами и рабочие элементы
MS TFS 2010 - Управление проектами и рабочие элементыMS TFS 2010 - Управление проектами и рабочие элементы
MS TFS 2010 - Управление проектами и рабочие элементы
 
Secr2013 разработчики vs поддержка - Лилия Горбачик
Secr2013 разработчики vs поддержка - Лилия ГорбачикSecr2013 разработчики vs поддержка - Лилия Горбачик
Secr2013 разработчики vs поддержка - Лилия Горбачик
 
Организация процессов разработки на основе TFS
Организация процессов разработки на основе TFSОрганизация процессов разработки на основе TFS
Организация процессов разработки на основе TFS
 
Independence of testing
Independence of testingIndependence of testing
Independence of testing
 
MS TFS 2010 - Обзор и архитектура
MS TFS 2010 - Обзор и архитектураMS TFS 2010 - Обзор и архитектура
MS TFS 2010 - Обзор и архитектура
 
Tsahim test
Tsahim testTsahim test
Tsahim test
 
Разработка по с использованием Tfs 2012
Разработка по с использованием Tfs 2012Разработка по с использованием Tfs 2012
Разработка по с использованием Tfs 2012
 
MS TFS 2010 - Управление версиями
MS TFS 2010 - Управление версиямиMS TFS 2010 - Управление версиями
MS TFS 2010 - Управление версиями
 
Development process в большой компании
Development process в большой компанииDevelopment process в большой компании
Development process в большой компании
 
Optimizing Your Management for Business Expansion
Optimizing Your Management for Business ExpansionOptimizing Your Management for Business Expansion
Optimizing Your Management for Business Expansion
 
BBST courses. Стоит ли овчинка выделки?
BBST courses. Стоит ли овчинка выделки?BBST courses. Стоит ли овчинка выделки?
BBST courses. Стоит ли овчинка выделки?
 
Оригинальные решения СМ-Консалт, улучшающие функциональные характеристики инс...
Оригинальные решения СМ-Консалт, улучшающие функциональные характеристики инс...Оригинальные решения СМ-Консалт, улучшающие функциональные характеристики инс...
Оригинальные решения СМ-Консалт, улучшающие функциональные характеристики инс...
 
Практическое руководство - использование SVN
Практическое руководство - использование SVNПрактическое руководство - использование SVN
Практическое руководство - использование SVN
 
Journey to 1000 tests a day
Journey to 1000 tests a dayJourney to 1000 tests a day
Journey to 1000 tests a day
 
Управление проектами в TFS 2008
Управление проектами в TFS 2008Управление проектами в TFS 2008
Управление проектами в TFS 2008
 
Что нового в MS VS Team System 2010 Beta1
Что нового в MS VS Team System 2010 Beta1Что нового в MS VS Team System 2010 Beta1
Что нового в MS VS Team System 2010 Beta1
 
Bolor tsahim test 1
Bolor tsahim test 1Bolor tsahim test 1
Bolor tsahim test 1
 
Презентация
ПрезентацияПрезентация
Презентация
 
Управление версиями в TFS 2008
Управление версиями в TFS 2008Управление версиями в TFS 2008
Управление версиями в TFS 2008
 

Semelhante a Чурюканов Вячеслав, “Code simple, but not simpler”

Optimizing Access with SQL Server
Optimizing Access with SQL ServerOptimizing Access with SQL Server
Optimizing Access with SQL ServerPRPASS Chapter
 
Entity Framework: To the Unit of Work Design Pattern and Beyond
Entity Framework: To the Unit of Work Design Pattern and BeyondEntity Framework: To the Unit of Work Design Pattern and Beyond
Entity Framework: To the Unit of Work Design Pattern and BeyondSteve Westgarth
 
Decision CAMP 2014 - Erik Marutian - Using rules-based gui framework to power...
Decision CAMP 2014 - Erik Marutian - Using rules-based gui framework to power...Decision CAMP 2014 - Erik Marutian - Using rules-based gui framework to power...
Decision CAMP 2014 - Erik Marutian - Using rules-based gui framework to power...Decision CAMP
 
Single Page Applications: Your Browser is the OS!
Single Page Applications: Your Browser is the OS!Single Page Applications: Your Browser is the OS!
Single Page Applications: Your Browser is the OS!Jeremy Likness
 
A Beard, An App, A Blender
A Beard, An App, A BlenderA Beard, An App, A Blender
A Beard, An App, A Blenderedm00se
 
Understanding Microservices
Understanding Microservices Understanding Microservices
Understanding Microservices M A Hossain Tonu
 
Debugging,Troubleshooting & Monitoring Distributed Web & Cloud Applications a...
Debugging,Troubleshooting & Monitoring Distributed Web & Cloud Applications a...Debugging,Troubleshooting & Monitoring Distributed Web & Cloud Applications a...
Debugging,Troubleshooting & Monitoring Distributed Web & Cloud Applications a...Theo Jungeblut
 
Learn spring at amc square learning
Learn spring at amc square learningLearn spring at amc square learning
Learn spring at amc square learningASIT Education
 
Oracle Forms Modernization Roadmap
Oracle Forms Modernization RoadmapOracle Forms Modernization Roadmap
Oracle Forms Modernization RoadmapKai-Uwe Möller
 
Optimus XPages: An Explosion of Techniques and Best Practices
Optimus XPages: An Explosion of Techniques and Best PracticesOptimus XPages: An Explosion of Techniques and Best Practices
Optimus XPages: An Explosion of Techniques and Best PracticesTeamstudio
 
Struts 2-overview2
Struts 2-overview2Struts 2-overview2
Struts 2-overview2divzi1913
 
Clean architecture with asp.net core
Clean architecture with asp.net coreClean architecture with asp.net core
Clean architecture with asp.net coreSam Nasr, MCSA, MVP
 
Microservices for java architects it-symposium-2015-09-15
Microservices for java architects it-symposium-2015-09-15Microservices for java architects it-symposium-2015-09-15
Microservices for java architects it-symposium-2015-09-15Derek Ashmore
 
Introduction to Microservices
Introduction to MicroservicesIntroduction to Microservices
Introduction to MicroservicesMahmoudZidan41
 
Struts 2-overview2
Struts 2-overview2Struts 2-overview2
Struts 2-overview2Long Nguyen
 

Semelhante a Чурюканов Вячеслав, “Code simple, but not simpler” (20)

spring
springspring
spring
 
Optimizing Access with SQL Server
Optimizing Access with SQL ServerOptimizing Access with SQL Server
Optimizing Access with SQL Server
 
Entity Framework: To the Unit of Work Design Pattern and Beyond
Entity Framework: To the Unit of Work Design Pattern and BeyondEntity Framework: To the Unit of Work Design Pattern and Beyond
Entity Framework: To the Unit of Work Design Pattern and Beyond
 
Decision CAMP 2014 - Erik Marutian - Using rules-based gui framework to power...
Decision CAMP 2014 - Erik Marutian - Using rules-based gui framework to power...Decision CAMP 2014 - Erik Marutian - Using rules-based gui framework to power...
Decision CAMP 2014 - Erik Marutian - Using rules-based gui framework to power...
 
Hybernat and structs, spring classes in mumbai
Hybernat and structs, spring classes in mumbaiHybernat and structs, spring classes in mumbai
Hybernat and structs, spring classes in mumbai
 
Microservices Architecture
Microservices ArchitectureMicroservices Architecture
Microservices Architecture
 
Single Page Applications: Your Browser is the OS!
Single Page Applications: Your Browser is the OS!Single Page Applications: Your Browser is the OS!
Single Page Applications: Your Browser is the OS!
 
Spring
SpringSpring
Spring
 
A Beard, An App, A Blender
A Beard, An App, A BlenderA Beard, An App, A Blender
A Beard, An App, A Blender
 
Understanding Microservices
Understanding Microservices Understanding Microservices
Understanding Microservices
 
Grails Services
Grails ServicesGrails Services
Grails Services
 
Debugging,Troubleshooting & Monitoring Distributed Web & Cloud Applications a...
Debugging,Troubleshooting & Monitoring Distributed Web & Cloud Applications a...Debugging,Troubleshooting & Monitoring Distributed Web & Cloud Applications a...
Debugging,Troubleshooting & Monitoring Distributed Web & Cloud Applications a...
 
Learn spring at amc square learning
Learn spring at amc square learningLearn spring at amc square learning
Learn spring at amc square learning
 
Oracle Forms Modernization Roadmap
Oracle Forms Modernization RoadmapOracle Forms Modernization Roadmap
Oracle Forms Modernization Roadmap
 
Optimus XPages: An Explosion of Techniques and Best Practices
Optimus XPages: An Explosion of Techniques and Best PracticesOptimus XPages: An Explosion of Techniques and Best Practices
Optimus XPages: An Explosion of Techniques and Best Practices
 
Struts 2-overview2
Struts 2-overview2Struts 2-overview2
Struts 2-overview2
 
Clean architecture with asp.net core
Clean architecture with asp.net coreClean architecture with asp.net core
Clean architecture with asp.net core
 
Microservices for java architects it-symposium-2015-09-15
Microservices for java architects it-symposium-2015-09-15Microservices for java architects it-symposium-2015-09-15
Microservices for java architects it-symposium-2015-09-15
 
Introduction to Microservices
Introduction to MicroservicesIntroduction to Microservices
Introduction to Microservices
 
Struts 2-overview2
Struts 2-overview2Struts 2-overview2
Struts 2-overview2
 

Mais de EPAM Systems

“Xcore (library) for android platform” by Uladzimir Klyshevich
“Xcore (library) for android platform” by Uladzimir Klyshevich“Xcore (library) for android platform” by Uladzimir Klyshevich
“Xcore (library) for android platform” by Uladzimir KlyshevichEPAM Systems
 
"Как общаться эффективнее" by Natallia Kapatsevich
"Как общаться эффективнее" by Natallia Kapatsevich"Как общаться эффективнее" by Natallia Kapatsevich
"Как общаться эффективнее" by Natallia KapatsevichEPAM Systems
 
"Connections: Что общего у Шотландии и Дональда Трампа?" by Yevgeniy Rozenblat
"Connections: Что общего у Шотландии и Дональда Трампа?" by Yevgeniy Rozenblat "Connections: Что общего у Шотландии и Дональда Трампа?" by Yevgeniy Rozenblat
"Connections: Что общего у Шотландии и Дональда Трампа?" by Yevgeniy Rozenblat EPAM Systems
 
ДмитрийРадченко, "Brief introduction to dundas"
ДмитрийРадченко, "Brief introduction to dundas"ДмитрийРадченко, "Brief introduction to dundas"
ДмитрийРадченко, "Brief introduction to dundas"EPAM Systems
 
Абрамович Максим, "Rad studio xe4"
Абрамович Максим, "Rad studio xe4"Абрамович Максим, "Rad studio xe4"
Абрамович Максим, "Rad studio xe4"EPAM Systems
 
Miniq 11: Time management by Anton Zolotarev & Andrei Artisheuski
Miniq 11: Time management by Anton Zolotarev & Andrei ArtisheuskiMiniq 11: Time management by Anton Zolotarev & Andrei Artisheuski
Miniq 11: Time management by Anton Zolotarev & Andrei ArtisheuskiEPAM Systems
 
Pool and billiards by Olga Nikolaeva
Pool and billiards by Olga NikolaevaPool and billiards by Olga Nikolaeva
Pool and billiards by Olga NikolaevaEPAM Systems
 
The Way of Creating Presentations: Just do it!
The Way of Creating Presentations: Just do it!The Way of Creating Presentations: Just do it!
The Way of Creating Presentations: Just do it!EPAM Systems
 
E-mail Communication: How and Why
E-mail Communication: How and WhyE-mail Communication: How and Why
E-mail Communication: How and WhyEPAM Systems
 
николай фролов, “Gamification“
николай фролов, “Gamification“николай фролов, “Gamification“
николай фролов, “Gamification“EPAM Systems
 
Real time bidding by Danil Melnikov
Real time bidding by Danil MelnikovReal time bidding by Danil Melnikov
Real time bidding by Danil MelnikovEPAM Systems
 
Никита Манько “Code review”
Никита Манько “Code review”Никита Манько “Code review”
Никита Манько “Code review”EPAM Systems
 
Демидюк Павел , “Continuous integration with the real traffic light in m&e of...
Демидюк Павел , “Continuous integration with the real traffic light in m&e of...Демидюк Павел , “Continuous integration with the real traffic light in m&e of...
Демидюк Павел , “Continuous integration with the real traffic light in m&e of...EPAM Systems
 
Agile retrospectives by nick frolov miniq
Agile retrospectives by nick frolov   miniqAgile retrospectives by nick frolov   miniq
Agile retrospectives by nick frolov miniqEPAM Systems
 
Other way to travel by Anna Lukyanenka
Other way to travel by Anna LukyanenkaOther way to travel by Anna Lukyanenka
Other way to travel by Anna LukyanenkaEPAM Systems
 
Computer as a musical instrument by Sergey Moiseychik
Computer as a musical instrument by Sergey MoiseychikComputer as a musical instrument by Sergey Moiseychik
Computer as a musical instrument by Sergey MoiseychikEPAM Systems
 
Антон Золотарев, Екатерина Невельская "По следам SQA days"
Антон Золотарев, Екатерина Невельская "По следам SQA days"Антон Золотарев, Екатерина Невельская "По следам SQA days"
Антон Золотарев, Екатерина Невельская "По следам SQA days"EPAM Systems
 
Сергей Семашко "End to end test: cheap and effective"
Сергей Семашко "End to end test: cheap and effective"Сергей Семашко "End to end test: cheap and effective"
Сергей Семашко "End to end test: cheap and effective"EPAM Systems
 
Alexander Litvinok (software engineer) "bdd wtf"
Alexander Litvinok (software engineer) "bdd wtf"Alexander Litvinok (software engineer) "bdd wtf"
Alexander Litvinok (software engineer) "bdd wtf"EPAM Systems
 

Mais de EPAM Systems (20)

“Xcore (library) for android platform” by Uladzimir Klyshevich
“Xcore (library) for android platform” by Uladzimir Klyshevich“Xcore (library) for android platform” by Uladzimir Klyshevich
“Xcore (library) for android platform” by Uladzimir Klyshevich
 
"Как общаться эффективнее" by Natallia Kapatsevich
"Как общаться эффективнее" by Natallia Kapatsevich"Как общаться эффективнее" by Natallia Kapatsevich
"Как общаться эффективнее" by Natallia Kapatsevich
 
"Connections: Что общего у Шотландии и Дональда Трампа?" by Yevgeniy Rozenblat
"Connections: Что общего у Шотландии и Дональда Трампа?" by Yevgeniy Rozenblat "Connections: Что общего у Шотландии и Дональда Трампа?" by Yevgeniy Rozenblat
"Connections: Что общего у Шотландии и Дональда Трампа?" by Yevgeniy Rozenblat
 
ДмитрийРадченко, "Brief introduction to dundas"
ДмитрийРадченко, "Brief introduction to dundas"ДмитрийРадченко, "Brief introduction to dundas"
ДмитрийРадченко, "Brief introduction to dundas"
 
Абрамович Максим, "Rad studio xe4"
Абрамович Максим, "Rad studio xe4"Абрамович Максим, "Rad studio xe4"
Абрамович Максим, "Rad studio xe4"
 
Miniq 11: Time management by Anton Zolotarev & Andrei Artisheuski
Miniq 11: Time management by Anton Zolotarev & Andrei ArtisheuskiMiniq 11: Time management by Anton Zolotarev & Andrei Artisheuski
Miniq 11: Time management by Anton Zolotarev & Andrei Artisheuski
 
Pool and billiards by Olga Nikolaeva
Pool and billiards by Olga NikolaevaPool and billiards by Olga Nikolaeva
Pool and billiards by Olga Nikolaeva
 
The Way of Creating Presentations: Just do it!
The Way of Creating Presentations: Just do it!The Way of Creating Presentations: Just do it!
The Way of Creating Presentations: Just do it!
 
E-mail Communication: How and Why
E-mail Communication: How and WhyE-mail Communication: How and Why
E-mail Communication: How and Why
 
николай фролов, “Gamification“
николай фролов, “Gamification“николай фролов, “Gamification“
николай фролов, “Gamification“
 
Real time bidding by Danil Melnikov
Real time bidding by Danil MelnikovReal time bidding by Danil Melnikov
Real time bidding by Danil Melnikov
 
Никита Манько “Code review”
Никита Манько “Code review”Никита Манько “Code review”
Никита Манько “Code review”
 
Демидюк Павел , “Continuous integration with the real traffic light in m&e of...
Демидюк Павел , “Continuous integration with the real traffic light in m&e of...Демидюк Павел , “Continuous integration with the real traffic light in m&e of...
Демидюк Павел , “Continuous integration with the real traffic light in m&e of...
 
Agile retrospectives by nick frolov miniq
Agile retrospectives by nick frolov   miniqAgile retrospectives by nick frolov   miniq
Agile retrospectives by nick frolov miniq
 
Other way to travel by Anna Lukyanenka
Other way to travel by Anna LukyanenkaOther way to travel by Anna Lukyanenka
Other way to travel by Anna Lukyanenka
 
Computer as a musical instrument by Sergey Moiseychik
Computer as a musical instrument by Sergey MoiseychikComputer as a musical instrument by Sergey Moiseychik
Computer as a musical instrument by Sergey Moiseychik
 
Антон Золотарев, Екатерина Невельская "По следам SQA days"
Антон Золотарев, Екатерина Невельская "По следам SQA days"Антон Золотарев, Екатерина Невельская "По следам SQA days"
Антон Золотарев, Екатерина Невельская "По следам SQA days"
 
Сергей Семашко "End to end test: cheap and effective"
Сергей Семашко "End to end test: cheap and effective"Сергей Семашко "End to end test: cheap and effective"
Сергей Семашко "End to end test: cheap and effective"
 
Alexander Litvinok (software engineer) "bdd wtf"
Alexander Litvinok (software engineer) "bdd wtf"Alexander Litvinok (software engineer) "bdd wtf"
Alexander Litvinok (software engineer) "bdd wtf"
 
Dvcs overview
Dvcs overviewDvcs overview
Dvcs overview
 

Чурюканов Вячеслав, “Code simple, but not simpler”

  • 1. Code simple, but not simpler Discuss ways to develop enterprise applications based on “POJOs in Action” by Chris Richardson
  • 2. Who am I? Viachaslau Churukanau Senior Software Engineer, Java world Edmunds.com, room 404
  • 4. You have to design enterprise applications at some moment But how to develop this skill if: • There are no appropriate trainings • The Internet usually provides little, contradictory and out of date knowledge • People tell you “lie” • Etc. ?
  • 6.
  • 7. POJOs in Action (2006) • shows how to address many common and complex design issues in back-end logic development of enterprise applications with fantastic real-world examples • combines best practices and design wisdom to integrate domain-driven design and test-driven development for object-oriented applications • carefully explains the techniques and technologies used at various levels, including Spring, JDO, Hibernate, EJB 3, and iBatis.
  • 8. Key Messages • Regardless of how the frameworks evolve, there are some key concepts that will not change • Every technology has both benefits and drawbacks • Make everything as simple as possible, but not simpler (Albert Einstein)
  • 13. Benefits and Drawbacks + Improved maintainability and extensibility + Persistence framework enables you to easily map the domain model to the database - You should have good OOD skills
  • 15. Benefits and Drawbacks + Easy to Use (no OOD skill required) + Can use full range of SQL features - Code can be difficult to understand and maintain (complex business logic, explicit load and save all required data) - Cost of maintaining handwritten SQL (e.g. add a column – change multiple queries) - Lack of portability of SQL
  • 16. When to Use • The application must use SQL directly or you cannot use a persistence framework • The business logic is very simple • The development team lacks the necessary OO design skills
  • 18. EJB session / POJO facade
  • 19. Benefits and Drawbacks + Business Logic is encapsulated and is free of transaction management (including distributed transactions), security, remote access, detaching objects, etc. - You must write extra code - It is quite easy for the detachment code and the presentation tier to get out of sync and for the POJO façade to only return some of the objects required by the presentation tier
  • 20. Exposed Domain Model (Open Session in View)
  • 21. Benefits and Drawbacks + Faster development (the business tier does not contain façades or error-prone detachment logic) - Less encapsulation (it is quite easy for business logic to creep into the presentation tier; the presentation tier has access to the domain objects; business tier changes affect presentation tier) - No support for remote access - Tricky to configure interactions between transactions, persistence framework, and the servlet API
  • 23. What’s wrong with using JDBC directly • Developing and maintaining SQL is difficult and time consuming • There is a lack of portability with SQL • Writing JDBC code is time consuming and error-prone
  • 24. What if I need SQL? • You must use the full power of SQL, including vendor-specific features, in order to get good performance • Your DBA might demand complete control over the SQL statements executed by your application • The corporate investment in its relational databases is so massive that the applications working with the databases can appear relatively unimportant
  • 25. iBatis • Insulates the application from connections and prepared statements, iBATIS maps JavaBeans to SQL statements using XML descriptor files or annotations • Supports for database-generated primary keys, automatic loading of related objects, caching, and lazy loading
  • 26. Why you don’t want to persist objects yourself 1. Lazy Loading (loading all of the objects that might be accessed might be extremely inefficient) 2. Writing back to the database only those objects that have been modified (it would be extremely inefficient to save all objects regardless of whether they have changed) 3. The database access code must preserve object identity by ensuring that there is a single in- memory instance of a persistent object when processing a request
  • 28. Кey features of an ORM framework • Declarative mapping between the object model and database schema • An API for creating, reading, updating, and deleting objects • A query language • Support for transactions • Lazy and eager loading • Caching • Detached objects
  • 29. Benefits and Drawbacks + Improved productivity + Improved performance + Improved portability +- Sometimes you must use SQL directly (performance, etc.) - Challenging when you’re working with a legacy schema (e.g. denormalized) - You might design a domain model that cannot be mapped to the desired database schema
  • 32. Isolated Database Transactions • The database ensures that the outcome of executing multiple serializable transactions is the same as executing them serially. • Serializable transactions prevent such problems as lost updates and inconsistent reads
  • 33. Benefits and Drawbacks + They are simple to use + They prevent many concurrency problems, including lost updates and inconsistent reads - They produce the high overhead, which can reduce performance and scalability - Fully isolated transactions can fail more frequently than less isolated transactions because of deadlocks and other concurrency- related issues
  • 34. When to Use • Read consistency is essential • The overhead of fully isolated transactions is acceptable
  • 36. Benefits and drawbacks + Unlike optimistic locking, pessimistic locking does not require any schema changes + It prevents a transaction from overwriting another transaction’s changes + It reduces the probability of deadlocks in databases that implement fully isolated transactions by locking rows when they read - All potentially conflicting transactions have to use SELECT FOR UPDATE in order for pessimistic locking to work, which is potentially error-prone - Some databases have limitations on how SELECT FOR UPDATE can be used
  • 37. When to Use • The database schema does not support optimistic locking because, for example, the tables do not have a version or timestamp column or contain values such as floats or blobs that cannot be compared • The application requires some degree of read consistency • You don’t want to incur the overhead of serializable transactions
  • 39. Benefits and Drawbacks + It is easy to implement and it is supported by many persistence frameworks + Unlike pessimistic locking, does not prevent an application from using certain SQL SELECT statement features - All potentially conflicting transactions must use optimistic locking or errors will occur - No guarantee that a transaction will be able to update the rows that it read - Does not prevent inconsistent reads
  • 40. When to Use General recommendation is that an application should use optimistic locking unless: • The database schema does not support optimistic locking • The application must be guaranteed to be able to update the rows that it read • The application requires consistent reads
  • 43. What’s wrong with using a single database transaction • The database transaction would be long- running because it encompasses multiple web requests and user think time • The transaction might last until the web session timed out if the user could simply walk away from the browser without completing the use case • It reduce scalability and concurrency
  • 45. Benefits and Drawbacks + Ensures that a user can save changes - Impacts the application globally (don’t forget to use it in a new code, etc.) - Requires a mechanism to forcibly release locks
  • 46. When to Use • The probability of conflicts is high • The consequences of conflicts are severe • Users typically do not abandon their sessions or it’s feasible to implement a lock cleanup mechanism
  • 48. Benefits and Drawbacks + It is relatively easy to implement + Unlike the Pessimistic Offline Lock pattern, there are no locks to clean up if the user abandons the session, which is not uncommon in a web application. - Because the Optimistic Offline Lock pattern only detects changes when the user tries to save their changes, it only works well when starting over is not a burden on the user - All transactions that update shared data must increment the version number whenever they update a row, including those that do not use the Optimistic Offline Lock pattern
  • 49. When to Use • The probability of conflicts is low and the consequences of redoing the changes are minimal • Users regularly abandon sessions and you don’t want to implement a lock cleanup mechanism

Notas do Editor

  1. No problems with detached objects.
  2. This mechanism assumes that concurrent updates will occur and so incurs an overhead regardless of whether they do.
  3. Optimistic locking derives its name from the fact it assumes that concurrent updates are rare and that instead of preventing them the application detects and recovers from them.