楼主: justforregister

Four harmful Java idioms, and how to fix them

[复制链接]
论坛徽章:
131
乌索普
日期:2017-09-26 13:06:30马上加薪
日期:2014-11-22 01:34:242014年世界杯参赛球队: 尼日利亚
日期:2014-06-17 15:23:23马上有对象
日期:2014-05-11 19:35:172014年新春福章
日期:2014-04-04 16:16:58马上有对象
日期:2014-03-08 16:50:54马上加薪
日期:2014-02-19 11:55:14马上有对象
日期:2014-02-19 11:55:14马上有钱
日期:2014-02-19 11:55:14马上有房
日期:2014-02-19 11:55:14
11#
 楼主| 发表于 2009-2-25 23:56 | 只看该作者
An alternate style is package-by-feature:
                     
  • com.blah.painting
  • com.blah.buyer
  • com.blah.seller
  • com.blah.auction
  • com.blah.webmaster
  • com.blah.useraccess
  • com.blah.util
                     Here, items are notgrouped according to their behavioral style. Instead, the behavior ofindividual classes is treated as an implementation detail, and classesare grouped according to the highest possible level of abstraction --the level of the feature -- wherein all items related to a feature (and only to that feature) reside in one and the same package. This is not a revolutionary or heretical idea; this is exactly what                        packages were created for in the first place.                     
                     For example, in a Web application, the com.blah.painting package might consist of these items:                     
                     
  • Painting.java: A model object
  • PaintingDAO.java: A data access object
  • PaintingAction.java: A controller or action object
  • statements.sql: The SQL statements used by the DAO
  • view.jsp: The JSP used to render the result to the user

使用道具 举报

回复
论坛徽章:
131
乌索普
日期:2017-09-26 13:06:30马上加薪
日期:2014-11-22 01:34:242014年世界杯参赛球队: 尼日利亚
日期:2014-06-17 15:23:23马上有对象
日期:2014-05-11 19:35:172014年新春福章
日期:2014-04-04 16:16:58马上有对象
日期:2014-03-08 16:50:54马上加薪
日期:2014-02-19 11:55:14马上有对象
日期:2014-02-19 11:55:14马上有钱
日期:2014-02-19 11:55:14马上有房
日期:2014-02-19 11:55:14
12#
 楼主| 发表于 2009-2-25 23:57 | 只看该作者
It's important to note that, in this style, each package shouldcontain all items related to a feature (and only that feature). Inparticular, the package may contain files other than Java source code.In package-by-feature, the ideal is to pass the deletion test: you should be able to delete a feature by deleting a single directory, without leaving behind any cruft.                     
                     The benefits of this style over package-by-layer are compelling:
                     
  •                            Packages have much higher cohesion and modularity. Coupling between packages is minimized.
  •                            Code is much more self-documenting. The reader gets a general idea of what features are included just by reading the package                              names. In Code Complete, Steve McConnell refers to self-documenting code as "the Holy Grail of legibility."                           
  •                            The design still honors the idea of separation of layers, simply by using separate classes within each feature.
  •                            Related items are in the same place. There is no need to navigate around the source tree to edit closely related items.                                                         

使用道具 举报

回复
论坛徽章:
131
乌索普
日期:2017-09-26 13:06:30马上加薪
日期:2014-11-22 01:34:242014年世界杯参赛球队: 尼日利亚
日期:2014-06-17 15:23:23马上有对象
日期:2014-05-11 19:35:172014年新春福章
日期:2014-04-04 16:16:58马上有对象
日期:2014-03-08 16:50:54马上加薪
日期:2014-02-19 11:55:14马上有对象
日期:2014-02-19 11:55:14马上有钱
日期:2014-02-19 11:55:14马上有房
日期:2014-02-19 11:55:14
13#
 楼主| 发表于 2009-2-25 23:57 | 只看该作者
Items are package-private by default, as they should be. If an item needs to be visible from another package, then it's changed                              to public. (Note that changing a class to public does not mean that all of its members should be made public as well; there can be a mixture of public and package-private members in the same class.)                           
                                                                           Deleting a feature is often as simple as deleting a single item: a directory.
                                                                           Thereare fewer items in each package, and the overall package structureevolves more naturally. For example, if a package gets too large, thenit can be refactored as desired into two or more new packages. Thealternative package-by-layer style, however, does not scale or evolvein this way at all: its packages contain an arbitrarily large number ofclasses, and you cannot easily refactor the package structure.

使用道具 举报

回复
论坛徽章:
131
乌索普
日期:2017-09-26 13:06:30马上加薪
日期:2014-11-22 01:34:242014年世界杯参赛球队: 尼日利亚
日期:2014-06-17 15:23:23马上有对象
日期:2014-05-11 19:35:172014年新春福章
日期:2014-04-04 16:16:58马上有对象
日期:2014-03-08 16:50:54马上加薪
日期:2014-02-19 11:55:14马上有对象
日期:2014-02-19 11:55:14马上有钱
日期:2014-02-19 11:55:14马上有房
日期:2014-02-19 11:55:14
14#
 楼主| 发表于 2009-2-25 23:57 | 只看该作者
Some frameworks promote a package-by-layer style with conventionalpackage names as a purported advantage: because conventional packagenames are used, programmers always know where to navigate to finditems. But why force them to navigate at all? With the alternativepackage-by-feature style, such tedious navigation is usually notneeded, so it entirely transcends the need for any such namingconvention.
                     
"The single most important factor that distinguishes a well-designed module from a poorly designed one is the degree to which                        the module hides its internal data and other implementation details from other modules."
-- Joshua Bloch, Effective Java

使用道具 举报

回复
论坛徽章:
131
乌索普
日期:2017-09-26 13:06:30马上加薪
日期:2014-11-22 01:34:242014年世界杯参赛球队: 尼日利亚
日期:2014-06-17 15:23:23马上有对象
日期:2014-05-11 19:35:172014年新春福章
日期:2014-04-04 16:16:58马上有对象
日期:2014-03-08 16:50:54马上加薪
日期:2014-02-19 11:55:14马上有对象
日期:2014-02-19 11:55:14马上有钱
日期:2014-02-19 11:55:14马上有房
日期:2014-02-19 11:55:14
15#
 楼主| 发表于 2009-2-25 23:57 | 只看该作者
JavaBeans: Why use them when immutables will do?                     Immutable objects are objects that do not change state (their data, in other words) after construction. Martin Odersky, the                        principal creator of Scala, has recently praised the qualities of immutables. In Effective Java, Joshua Bloch makes a very convincing case in favor of strongly preferring immutable objects. To summarize Bloch's points,                        immutables:                     
                     
  • Are simple
  • Are thread-safe, and require no synchronization
  • Can be shared freely
  • Never need to be defensively copied
  • Never need a copy constructor, or a clone() method
  • Make good building blocks for other classes
  • Make good Map keys and Set elements
  • Have failure atomicity -- that is, they cannot be left in an invalid state when an error occurs
                     "Classesshould be immutable unless there is a very good reason for making themmutable," says Bloch. But his advice seems to have been largelyignored. In place of immutable objects, most applications use JavaBeans(or something similar) instead. JavaBean objects are significantly morecomplex than immutables. Their complexity arises from their large statespace. In a rough sense, you might think of a JavaBean as the diametricopposite of an immutable object: it allows maximal mutability.                     
                     It'scommon to use JavaBeans to model database records. Is that anappropriate design? Think of it this way: if you were modeling a rowfrom a database ResultSet, without any preconceptions or framework constraints whatsoever, what would your design be like? Would it be similar to a                        JavaBean, or would it be significantly different?

使用道具 举报

回复
论坛徽章:
131
乌索普
日期:2017-09-26 13:06:30马上加薪
日期:2014-11-22 01:34:242014年世界杯参赛球队: 尼日利亚
日期:2014-06-17 15:23:23马上有对象
日期:2014-05-11 19:35:172014年新春福章
日期:2014-04-04 16:16:58马上有对象
日期:2014-03-08 16:50:54马上加薪
日期:2014-02-19 11:55:14马上有对象
日期:2014-02-19 11:55:14马上有钱
日期:2014-02-19 11:55:14马上有房
日期:2014-02-19 11:55:14
16#
 楼主| 发表于 2009-2-25 23:58 | 只看该作者
I think it would be enormously different:                     
                     
  •                            It would likely not include a no-argument constructor, as such constructors carry no data. Does it make sense to model a database ResultSet by creating objects that by design can carry no data, even temporarily? Does a no-argument constructor suggest itself naturally to the mind for this domain? No, it doesn't. (It's                              true that data is often optional, but how often are all columns in a ResultSet optional?)                           
  •                            It would likely not have anything to say about events and listeners.                           
  •                            It would likely notforce you to use mutable objects. In Web applications in particular,model objects often exist only for the duration of a single request.Such objects aren't long-lived, and don't need to change state inresponse to user actions.
  •                            Itwould likely define a data validation mechanism. Such validation is oneof the most important features of database apps, and should besupported directly in the model. (Remember the first thing you learnedabout objects: an object encapsulates both data and operations on thedata. In this case, the operations are the validations.)
  •                            The validation mechanism would allow for reporting errors to the end user.

使用道具 举报

回复
论坛徽章:
131
乌索普
日期:2017-09-26 13:06:30马上加薪
日期:2014-11-22 01:34:242014年世界杯参赛球队: 尼日利亚
日期:2014-06-17 15:23:23马上有对象
日期:2014-05-11 19:35:172014年新春福章
日期:2014-04-04 16:16:58马上有对象
日期:2014-03-08 16:50:54马上加薪
日期:2014-02-19 11:55:14马上有对象
日期:2014-02-19 11:55:14马上有钱
日期:2014-02-19 11:55:14马上有房
日期:2014-02-19 11:55:14
17#
 楼主| 发表于 2009-2-25 23:58 | 只看该作者
The JavaBeans specificationwas created for a very particular problem domain: that of manipulatinggraphical widgets at design time. The specification makes absolutely nomention of databases, because it was not created with databases inmind. As a result, it's not surprising that JavaBeans aren't a verynatural choice for the problem of modeling database records.
                     From a practicalperspective, many widely-used frameworks require applicationprogrammers to use JavaBeans (or something similar) to model databaserecords. This is deeply unfortunate, because it doesn't allowprogrammers to take advantage of the many positive qualities ofimmutable objects.
                     Private members: Why put them up front?                     Old Hollywood movies usually start with the credits -- all of the credits. In a similar way, most Java classes place implementation details (the private members) first. Listing 3 shows a typical example of this style.                     
                     Listing 3. Private members, listed up front                                             public class OilWell implements EnergySource {
   private Long id;
   private String name;
   private String location;
   private Date discoveryDate;
   private Long totalReserves;
   private Long productionToDate;
   
   public Long getId() {
      return id;
   }
   public void setId(Long id) {
      this.id = id;
   }
   
  //..elided
}

使用道具 举报

回复
论坛徽章:
131
乌索普
日期:2017-09-26 13:06:30马上加薪
日期:2014-11-22 01:34:242014年世界杯参赛球队: 尼日利亚
日期:2014-06-17 15:23:23马上有对象
日期:2014-05-11 19:35:172014年新春福章
日期:2014-04-04 16:16:58马上有对象
日期:2014-03-08 16:50:54马上加薪
日期:2014-02-19 11:55:14马上有对象
日期:2014-02-19 11:55:14马上有钱
日期:2014-02-19 11:55:14马上有房
日期:2014-02-19 11:55:14
18#
 楼主| 发表于 2009-2-25 23:59 | 只看该作者
However, placing private items last, notfirst, seems to show more compassion for the reader. When trying tounderstand something -- anything -- you should move from the general tothe specific. More precisely, you should move from a higher to a lowerlevel of abstraction. If you do the reverse, then initially the readerwill likely not know the point of the whole thing, or grasp how thingswork together, and will be confused by trying to remember a number ofpotentially disconnected facts.
                     The whole point ofabstraction is to allow you to ignore details. The higher the level ofabstraction, the more details you can ignore. The more details thereaders of a class can ignore, the happier they are. Holding manydetails in your head is painful, so fewer details are better. Thus, placing private items last seems more compassionate, as it puts off details that may not be necessary at all for the reader's current task                        (whatever that may be).

使用道具 举报

回复
论坛徽章:
131
乌索普
日期:2017-09-26 13:06:30马上加薪
日期:2014-11-22 01:34:242014年世界杯参赛球队: 尼日利亚
日期:2014-06-17 15:23:23马上有对象
日期:2014-05-11 19:35:172014年新春福章
日期:2014-04-04 16:16:58马上有对象
日期:2014-03-08 16:50:54马上加薪
日期:2014-02-19 11:55:14马上有对象
日期:2014-02-19 11:55:14马上有钱
日期:2014-02-19 11:55:14马上有房
日期:2014-02-19 11:55:14
19#
 楼主| 发表于 2009-2-25 23:59 | 只看该作者
Originally, the C++ programming culture placed private items first, just as in Java. However, unlike the Java community, the C++ community quickly came to realize that this was                        an unhelpful convention, and it is now reversed. Here is a comment from a typical C++ style guide:                     
                     
                        Notice that the public interface is placed first in the class, protected next, and private last. The reasons are:                        
                        
  • programmers should care about a class's interface more than implementation
  • when programmers need to use a class they need the interface not the implementation
                        It makes sense then to have the interface first. Placing implementation, the private section, first, is a historical accident, as the first examples used the private-first layout. Over time emphasis has switched, de-emphasizing a class's interface over implementation details.                        
                     
                     Similarly, the Imperial College London C++ Style Guide says, "By placing the public section first, everything that is of interest to a user is gathered in the beginning of the class definition. The protected section may be of interest to designers when considering inheriting from the class. The private section contains details that should have the least general interest."

使用道具 举报

回复
论坛徽章:
131
乌索普
日期:2017-09-26 13:06:30马上加薪
日期:2014-11-22 01:34:242014年世界杯参赛球队: 尼日利亚
日期:2014-06-17 15:23:23马上有对象
日期:2014-05-11 19:35:172014年新春福章
日期:2014-04-04 16:16:58马上有对象
日期:2014-03-08 16:50:54马上加薪
日期:2014-02-19 11:55:14马上有对象
日期:2014-02-19 11:55:14马上有钱
日期:2014-02-19 11:55:14马上有房
日期:2014-02-19 11:55:14
20#
 楼主| 发表于 2009-2-25 23:59 | 只看该作者
One might object that that readers should use Javadoc when trying tounderstand a class, and not the source code. This argument doesn'thold, however, because Javadoc includes no information regardingimplementation details. When maintaining a class, a programmer clearlyneeds access to the source code.
                     For all kinds oftechnical documentation, it's commonplace to put high-level informationat the start -- the table of contents of a book, for instance, or theabstract of an academic paper. Why should a Java class be an exceptionto this rule? Placing private members first just seems like a bad habit waiting to be broken. The reason it exists in the first place is likely early coding                        style documents, such as the Coding Conventions published by Sun. As Joshua Bloch noted, "I wouldn't take that document [Sun's Coding Conventions] too seriously. It is not actively maintained or used at Sun."                     
                     It seems best to arrange code to imitate the same order used by Javadoc: first the constructors, then non-private methods, and finally private fields and methods. That's the only style in which the reader moves naturally from a higher to a lower level of abstraction.

使用道具 举报

回复

您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

TOP技术积分榜 社区积分榜 徽章 团队 统计 知识索引树 积分竞拍 文本模式 帮助
  ITPUB首页 | ITPUB论坛 | 数据库技术 | 企业信息化 | 开发技术 | 微软技术 | 软件工程与项目管理 | IBM技术园地 | 行业纵向讨论 | IT招聘 | IT文档
  ChinaUnix | ChinaUnix博客 | ChinaUnix论坛
CopyRight 1999-2011 itpub.net All Right Reserved. 北京盛拓优讯信息技术有限公司版权所有 联系我们 未成年人举报专区 
京ICP备16024965号-8  北京市公安局海淀分局网监中心备案编号:11010802021510 广播电视节目制作经营许可证:编号(京)字第1149号
  
快速回复 返回顶部 返回列表