‏הצגת רשומות עם תוויות Design. הצג את כל הרשומות
‏הצגת רשומות עם תוויות Design. הצג את כל הרשומות

Single model - no to presentation model. (DTOs are evil)


How many models do you have in your application?
In a lot application the answer is -3, one for each layer (presentation, business, dal)
In this case each lays need to maintain constraint, adapters, query translation and maintain.



Today, In the POJO revolution when we each layer can handle POJO and don't need a specific class types any more (no need in extends stateless bean, special dal classes ....) we can build a one single POJO model and bypass it between the layers. We don't need any more to maintain constraints, adapters... in each layer.



But still a lot of application want to hide the hibernate model by additional model above it.
By mistake they call it DTO's but the definition is not correct.
The DTO pattern is a pattern that uses in order to solve a case when we need to combine data from some entities. In this case instead of return all entities we use the DTO pattern and created some kind of view (we might also create a view in the underline) on these entities . this view is DTO.
The dto pattern should be avoided as much as possible and I will explain why in another post, but it's still relevant and in some cases it should use in order to avoid loading a lot of entities or to avoid from expose the collection process to the client of this API.


ORM give you the abstraction on the DB layer you shouldn't add another layer to abstract the DB.
ORM can give you all the solution you need in order to solve the DB - Object oriented mismatch and gap between the persistence to the Model.
Adding new layer in the application is height costing for maintains adapters...
You have difficulty to implementing searching, sorting and etc on any object which is not a real model entity.
Exposing direct the model simpler these features.


As I explained above a lot used the term DTO to describe model layer above the ORM layer so in a lot of articles the term DTOs are evil is used in order to describe the general idea of using in additional layer above the entities and not as a specific case solution.
Ask Google for the term - "DTOs are evil" will return a lot of results.
Let's try to explore some of them and some more resources.
In the top of the Google result for "DTOs are evil" we will find adam-bien site with good explanation about the evil in dto:
DTOs aren't dead. The opposite is true. In certain situations, they become the necessary tool or workaround to solve a particular problem….
It is perfect valid to introduce a dedicated DTO to adapt an incompatible domain layer. It is much better, than changing the domain layer to the needs of a particular client …
On the other hand considering a dedicated DTO layer as an investment, rarely pays off and often lead to over-engineered and bloated architectures. At the beginning the DTOs will be identical to your domain layer - without any impedance mismatch. If you are "lucky", you will get few differences over the time. Especially with lightweight platforms like Java EE 6, the introduction of a DTO is a bottom-up, rather than top-down approach. Exactly like it is the case with DAOs.
(For more see - http://www.adam-bien.com/roller/abien/entry/how_evil_are_actually_data )


Another good reference is Rob Harrop's and Jan Machacek's Pro Spring (Chapter 11):
"Honestly, we cannot think of a reason you would want to do this; in our eyes, it seems that this practice has sprung up out of confusion on how certain J2EE patterns should be used."


You will find another interesting discussion for this issue in the following forum – (http://forum.springsource.org/archive/index.php/t-27716.html )
Some good points there:
"In addition, Christian Bauer and Gavin King explore the issue in Chapter 8 of their Hibernate in Action (http://www.amazon.com/gp/product/193239415X/sr=1-1/qid=1155735659/ref=pd_bbs_1/103-9127259-7133451?ie=UTF8&s=books). They note that the data transfer pattern was invented because fine-grained remote access to entity beans was too slow and entity beans were not serializable."

"In the sample applications I have seen, it looks like people have avoided creating data transfer objects. You didn't really give any application-specific reasons for wanting to use data transfer objects, so I would default to using the domain objects directly and saving yourself from the code duplication and all the work to convert to and from the domain objects."

"If the domain model changed, then it is highly likely that the web tier would have to change anyway.
I think there *are* good reasons and situations in which that loose coupling is beneficial, but they are the exception, rather than the rule. After all, the purpose of most web apps is to interrogate the middle tier; they *are* coupled by definition.

If you need to introduce an adapter between the web tier and the middle tier, then you can always do that as and when you need it, but until then just use the POJOs in the domain model."


And if you have some time visit here:
https://forum.hibernate.org/viewtopic.php?f=1&t=928244&sid=c6565b58c62b0eeee2980b7c2b61ee59&start=30


A good summary of the cons and pros can be found
http://blog.xebia.com/2009/05/11/jpa-implementation-patterns-service-facades-and-data-transfers-objects/
Pros and cons of DTO's
Of course it would be silly to say you should always use DTO's in your architecture. As always it depends.   To allow you to make up your own mind, I will list a number of pros and cons of using DTO's:
  1. Con: DTO's cause code duplication. This is especially the case when your DTO's have exactly the same fields as your domain objects, and even more so when they both have getters and setters for those fields. But having DTO's in your architecture allows you to get rid of the getters and setters in your domain objects.
  2. Con: DTO's require you to write boilerplate code to copy properties back and forth. Some people have suggested using a Java Bean mapper framework such as Dozer, Apache Commons BeanUtils, or the Spring Framework's BeanUtils class, but that requires you add getters and setters to your beans and we just decided we did not want to do that anymore!
  3. Pro/Con: DTO's make it impossible to use EntityManger.merge to copy their state to your persistent objects. Instead you'll have to apply the DIY merge pattern as described in my blog on saving (detached) entities. Of course forcing you to do something a particular way, and one that is not 100% satisfying, is not really an advantage. But at least the DTO and the DIY merge work well together.
  4. Pro: DTO's ensure you are not hit by unexpected lazy loading problems in your presentation layer. Or in the case of remote invocations they protect you from lazy loading problems when serializing for transport or, even stranger, on the client.
  5. Pro: The DTO pattern forces you to think about the interface of your application. You can make your DTO's richer than your plain domain objects, e.g. by adding security information to them. Or you can group information from multiple domain objects into one DTO to make the interface easier to use.

Tell don't ask principal

How do you know if your are writing object oriented or procedural?
One good way to know it is by using the "tell don't ask" principal.

Procedural code gets information then makes decisions. Object-oriented code tells objects to do things. 
— Alec Sharp

for more:

Premature optimization is the root of all evil

אני אוהב משפטי "root of evil". צביעה של עולם בשחור ולבן מקלה על החיים.למרבה הצער- העולם הוא לא באמת שחור ולבן.אפילו הביטוי הכול כך החלטי :

"premature optimization is the root of all evil"
שנהגה על ידי Donald Knuth ומשמעו:

"Premature optimization" is a phrase used to describe a situation where a programmer lets performance considerations affect the design of a piece of code. This can result in a design that is not as clean as it could have been or code that is incorrect, because the code is complicated by the optimization and the programmer is distracted by optimizing."
אינו כה חד מבחינת המקורות שלו.הציטוט הוא חלקי ביותר ולא משקף במאה אחוז את הקונטקסט השלם.הציטוט הינו מתוך מאמר שפורסם ב-1974 על ידי KNUTH והמשפט המלא הוא:

"The conventional wisdom shared by many of today's software engineers calls for ignoring efficiency in the small; but I believe this is simply an overreaction to the abuses they see being practiced by pennywise-
and-pound-foolish programmers, who can't debug or maintain their "optimized" programs. In established engineering disciplines a 12% improvement, easily obtained, is never considered marginal; and I believe the same viewpoint should prevail in software engineering. Of course I wouldn't bother making such optimizations on a oneshot job, but when it's a question of preparing quality programs, I don't want to restrict myself to tools that deny me such efficiencies.
There is no doubt that the grail of efficiency leads to abuse. Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil.

כמו כן 12 שנים אחר כך בראיון שנתן עידן KNUTH  את הביטוי.אך היסטוריה היא לא מטרתנו כאן.
גם החלטיות היא לא מטרתנו כאן, אבל כדי לא לפתוח כל מיני סוגריים ותתי סוגריים והסתייגויות, אנסה להתייחס לרעיון הכללי וכל דבר ספציפי כמובן מצריך את ההתייחסות שלו.
אופטימיזציה של מערכת נעשית בשלבים שונים של המערכת:
1.      שלב הארכיטקטורה.
2.      בחירת טכנולוגיות
3.      Height level design
4.      Low level design
5.      Implementation
6.      Bug fixes
בכל שלב יש להשקיע כמות שונה של זמן לגבי אופטימיזציה.
בניית ארכיטקטורה שגויה היא תקלה שקשה להתגבר עליה ולכן מין הסתם כמות המחקר לגבי אופטימיזציה שצריך להשקיע בשלב הזה גדולה הרבה יותר משלב המימוש.

יש כאלה שעל מנת להבחין בהתייחסות לשלבים השונים ממקדים את הציטוט לעיל לכדי הציטוט הבא:

"premature optimization is the root of all evil  micro".

הסבר שאהבתי שמתייחס לציטוט המקורי הוא:
in the absence of measured performance issues you shouldn't optimize becuase you think you will get a performance gain. There are obvious optimizations (like not doing string concatenation inside a tight loop) but anything that isn't a trivially clear optimization should be avoided until it can be measured.
בואו ננסה לצלול לציטוט מתוך דוגמה אמיתית:
Java formatter הוא אובייקט " יקר " ( מה זה יקר? – יקר יחסית לאוביטים אחרים ) ואינו thread safe, לכן מתכנת החליט שהוא יצור – ThreadLocalFormat כדי לעטוף את ה- formatter .
אם נריץ TEST שבודק מהו יקר? נקבל במחשב ממוצע יצירה של 200,000 אוביטים בשנייה.
זה מתכנת שעשה premature . נכון, הוא חסך זמן מחשב, אך האם הוא בכלל היה צריך לחסוך זמן מחשב? האם ב- USE CASE  הספציפי שלו זה מה שקריטי?
זוהי דוגמה שלפני שעשית over design למקום שיכל להיות פשוט.מערכת תוכנה היא מערכת מסובכת מעצם טיבעה. אין טעם להוסיף סיבוך נוסף היכן שלא צריך. במידה ואינך יודע בוודאות כי כתיבה מסוימת עלולה לעלות ב- performance  יקר (אם אינך יודע בדוק לפני) אל תכניס אופטימיזציות. הם רק יסבכו אותך אחר כך בתחזוקה וב- debug . ראיתי מתכנתים שעבדו ימים על גבי ימים כדי לבצע סוג מסויים של פילטור נתונים מתוך רשימה בכמה שפחות מעברים על הרשימה. הם השקיעו ימים כדי להגיע לאלגוריתמים הכי טוב וכזה הגיע אלי השאלה הראשונה שלי הייתה למה לא לעבור על הרשימה 6 פעמים ולא 2 כפי שתכננתם אבל בצורת קוד יותר ברורה?
התשובה שלהם הייתה שמעבר על הרשימה 6 פעמים זה בזבוז שכן בצורה חכמה ניתן להוציא את המידע על ידי שימוש בכל מיני טריקים ורק ורסיות בפעמיים בלבד.
כששאלתי מה ה- impact של לעבור עליה 6 פעמים ולא 2 (נניח כרגע את הרק ורסיות בצד) התשובה הייתה – מדובר בפי 3 זמן.
תשובה זאת אינה מספקת, שכן פי X זמן אינו מדד לכלום. מה אם אגיד לכם שאני יכול לייעל חלק מסוים בתוכנה שלכם שיעבור במאית מהזמן הקודם או שתעדיפו שאייעל חלק אחר שיעבור ב-99 אחוז מהזמן הקודם? אני בטוח שכולנו לא נסכים להצעה כזאת בצורה עיוורת ונשאל מה ה- IMAPCT על התוכנה כולה. בכמה זמן יורד אותו USE CASE ? בכמה יורד חתימת הזיכרון ? בכמה יורד בעיות של contentions ? ...
פי X אינו מדד לכלום.
כנראה שהאוניברסיטה (קורסים לחישוביות ואלגוריתמים ) השפיעו רבות על כולנו וההסתכלות של רבים על עולם התוכנה היא סביב חסם ה- O (http://he.wikipedia.org/wiki/סיבוכיות). כמעט בכל ראיון עבודה ישאלו את המתכנת שאלת סיבוביות , בכמה מעברים מינימאליים תוכל לעשות זאת? בפוסט הבא מתוארת סוג כזאת של שאלה http://j2ee-now.blogspot.com/2007/12/google-interview-questions-part-1.html כפי שנשאלת בראיונות של גוגל. תגובה מעניינת שיש שם היא תגובתו של Riccardo:
That's the typical kind of problem you forget how to solve when you work for years using high level frameworks (in any language); in my career I have never seen a case where a problem of this complexity had to be solved.
מניסיוני ראיתי הרבה מקרים של התעסקות באופטימיזציה באופן שהוא Premature כלומר נטול הוכחות לכך שיש כאן בכלל צורך של אופטמיזיציה. הטענות של המתכנתים הן בסגנון – זה יותר מהר פי X, מה אם ברשימה יהיו מיליון רשומות ? , מה אם יהיו מיליון משתמשים שירצו את אותו מידע... כתיבה נכונה של קוד בצורה של בלוקים שניתנים בקלות לפירוק והרכבה אחרת (Refactor) נותנת לכם את היכולות להתמודד עם הבעיות במציאות ולא בתאוריה. אין צורך לתכנן אלגוריתמים יעיל על סמך כך שברשימה יהיו מיליון רשומות. יש צורך לתכנן אותו על סמך כמה שיש בפועל ולא בתיאוריה.
שימו כל הזמן מול עיניכם שאנו מדברים היום במעבדים שמצבעים מיליארדי פעולות בשנייה. מעבר של 5 או 6  פעמים או אפילו 10 על רשימה לא יהיה מה שישנה להם. לכן אל תזדרזו לעשות אופטימיזציה ללא שאבחנתם שיש בעיות או ברור לכם שיש בעיות (premature).
ובכלל כדאי לבחון מחדש כל מיני דיעות קדומות שלנו לגבי ביצועים. אמונות שנשענות על בסיס בעיות שהיו בעבר ולא קיימות כבר היום לדוגמה – שאלו את עצמכם את אותה שאלה שנשאלתם בראיונות לגבי ביצועים של HashTable  ?
מרבית מאמרי ה- Performance וטיפים לגבי Micro Performance נעשו סביב JVM ישנים. הספר האחרון שעסק בתחום של MIcro Performance יצא במהדורה שנייה עבור JDK 1.4 .  מאז נעשה שיפור דרמטי בנושאי ביצועים כך שהרבה טיפים לא רלוונטים עוד.
ה- Optimizer של ה- JVM מסוגל היום לניסים בעיקר בזכות JIT עד כדי כך שהביצועים יכולים לעלות על ביצועי קוד שנכתב ב- C. שיפורי ביצועים בכל האזורים החל מ- IO וכלה בנושאי Concuurency הביאו לשיפור של לפעמים פי כמה אלפים יותר מהיר בין JDK 1 לבין הגירסה הנוכחית. יש לשים לב שכדי לחוות חלק מהאופטימיזציות יש " לחמם " את ה- JVM.  כאשר אתם בודקים ביצועים קחו זאת בחשבון.ניתן לראות דוגמה בפוסט הבא  - http://avihai-java.blogspot.com/2010/05/arraylist-vs-array-as-sample-to.html
לפוסט יותר מפורט על JIT:
http://www.ibm.com/developerworks/java/library/j-jtp12214/

כדאי לקרוא את הפוסט הבא שמדגים שיקולים רבים שעלינו לשקול מבחינת בדיקת ביצועים נכונה:
http://www.ibm.com/developerworks/java/library/j-benchmark1.html



DB- is RDBMS is the only one solution?



Most leading DB today's are RDBMS (relational database management system) .
The "relation modeling" concepets frist  formulated and proposed in 1969 by E.F. Codd .
The idea is to describe a database as a collection of predicates over a finite set of predicate variables, describing constraints on the possible values and combinations of values. The content of the database at any given time is a finite (logical) model of the database, i.e. a set of relations, one per predicate variable, such that all predicates are satisfied. A request for information from the database (a database query) is also a predicate. (http://en.wikipedia.org/wiki/Relational_model).
However relation modeling cannot suite to any kind of application.
In some application there is no a restrict schema and the model is flexible.
In those cases the traditional "relation modeling" is a bad solution.
Skinny data models are one of the most notorious and problematic abuses of relational Database systems. Unfortunately, they’re sometimes necessary. A skinny data model basically turns each table into a generic data structure that can store sets of name and value pairs, much like a properties file in Java.
The relational model that these databases are built on, however, was designed many years ago, when the World Wide Web and Internet were unheard of. Although the strict schema-based structure these databases adhere to is required in some web applications, such as transaction systems, it is not a good fit for many modern web projects, such as blogs, wikis, and discussion forums, which by their nature are a better fit to a document-oriented database.
Another problem in RDBMS is making schema changes or adding indexes to a database with more than 10 - 20 million rows completely locks the database for hours at a time.
Different solutions are available. Some of them by using in specific db solutions and implemented based on existing RDBMS.
I want to focus on 2 solutions (there are a lot of alternatives), but first disclaimer.
Disclaimer:
When you decide to fall from the standard does it only after you consult with at least two different consultants, who are consider as leaders in these fields.
Falling from the standard has major impacts:
 Impact on - employee training, scalability, performance, bugs and design solutions. When you take the "off road" you are missing all the benefit in the primary road like -  big community, Google answers, books, solutions and so on. So be careful when you take the off road.
If you chose to take the "off road" make sure you isolate you solution as much as possible.
Famous computer scientist Butler W. Lampson (who envisioned the modern personal computer at Xerox way back in 1972) once said, “All problems in computer science can be solved by another level of indirection.” So try to encapsulate your "off road" solution as much as possible. There is a big chance that you will decide to go back to the main road in the future.
Use a solution above RDBS:
This kind of approach pulished by " FriendFeed " they choose to implement their own soltuon above MySql DB - http://bret.appspot.com/entry/how-friendfeed-uses-mysql
In the article they explain why they chose to implemrt thir own solution and not use in an existing one:
Lots of projects exist designed to tackle the problem storing data with flexible schemas and building new indexes on the fly (e.g., CouchDB). However, none of them seemed widely-used enough by large sites to inspire confidence. In the tests we read about and ran ourselves, none of the projects were stable or battle-tested enough for our needs (see this somewhat outdated article on CouchDB, for example). MySQL works. It doesn't corrupt data. Replication works. We understand its limitations already. We like MySQL for storage, just not RDBMS usage patterns.
Use an existing solution for example – CoachDB:
CouchDB is a document-oriented database management system, released under the open source Apache License. In contrast to most database systems, it stores data in a schema-free manner. This means that, unlike traditional SQL-based databases, there are no tables and columns, primary and foreign keys, joins, and relationships. Instead, CouchDB stores data in a series of documents and offers a
JavaScript-based view model for aggregating and reporting on the data.
Coachdb has many more advantage like replication, local data, versioning and many more.
It has a big community and good books.
One small comment – the local data feature is one of his "sexy features". This allows you to install light DB on the client side. Give the client the option to work offline and sync the client db with the server replication later. The same idea as a version control.