毕业设计外文资料翻译-有效的Java:编程语言指南_第1页
毕业设计外文资料翻译-有效的Java:编程语言指南_第2页
毕业设计外文资料翻译-有效的Java:编程语言指南_第3页
毕业设计外文资料翻译-有效的Java:编程语言指南_第4页
毕业设计外文资料翻译-有效的Java:编程语言指南_第5页
已阅读5页,还剩8页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、毕业设计外文资料翻译学 院: 专业班级: 学生姓名: 学 号: 指导教师: 外文出处: Joshua Bloch. Effective JavaM. London:Addison Wesley,2001. 附 件:1.外文资料翻译译文; 2.外文原文 指导教师评语:原文所涉及内容与课题有关联,翻译难度适中。该生所作的译文,术语的使用基本准确,译文内容与原文含义基本相符。译文格式符合规范,按时完成了外文翻译任务。签名: 2015年10月14日外文资料翻译译文有效的Java:编程语言指南第六章 方法本章讨论方法设计的几个方面:如何看待参数和返回值,如何设计方法签名,以及如何记录的方法。 大部分本章

2、中的材料适用于构造以及方法。像第5章,这章的重点是易用性,稳健性和灵活性。项目23:检查的有效性参数大多数方法和构造有一定的限制,对什么样的值引入它们的参数。例如,这种情况并不少见的索引值必须为负,并且对象引用必须是非空。你应该清楚地记录所有这样的限制和与在方法体的开始检查,强制执行。这是一种特殊情况一般原则,你应该尝试尽快发生后,检测错误。如果不这样做使得它不太可能会被检测到的一个错误,并且使得它更难确定错误的来源一旦已检测到。如果一个无效的参数值被传递到一个方法,该方法检查其参数执行前,它会很快就会完全失败,并适当的异常。如果该方法不检查其参数,几件事情都可能发生。可能会失败的方法一个令人

3、困惑的异常处理之中。更糟的是,该方法能正常返回只是默默地计算错误的结果。最糟糕的是,该方法可以正常返回,但留下一些对象在一个妥协的状态,在对一些零散的点导致错误在某个不确定的时间以后的代码。对于公共方法,使用的Javadocthrows标签来记录异常,这将是如果抛出的参数值的限制违反了(第44项)。通常情况下,异常会是抛出:IllegalArgumentException,IndexOutOfBoundsException异常,或NullPointerException异常(42项)。一旦你已经记录了限制方法的参数,而你文件,如果这些限制被违反,将被抛出的异常,这是一个简单的不管执行的限制。下

4、面是一个典型的例子:/* 返回一个BigInteger,其值是(this模m)。这种方法不同于其余方法,因*为它总是返回一个非负的BigInteger。* 参数m的模量,必须明确。* 返回这个m模。* 抛出 ArithmeticException异常,如果m小于等于0。*/public BigInteger mod(BigInteger m) if (m.signum() 0)throw new IllegalArgumentException(start + after + end);this.start = start;this.end = end;public Date start()

5、return start;public Date end() return end;. / 省略乍一看,这个类可能似乎是不可改变的,强制执行不变的开始了一段不遵循其结束。它是,但是,容易被以违反本不变利用这样的事实日期是可变的:/攻击期间实例的内部Date start = new Date();Date end = new Date();Period p = new Period(start, end);end.setYear(78); / 修改内部的p!为了防止这种攻击的一个实例时期的内部,必须使一个每个可变参数的构造函数,使用副本的防守副本代替原件时期实例的组成部分:/修复构造- 使得参数

6、防守副本public Period(Date start, Date end) this.start = new Date(start.getTime();this.end = new Date(end.getTime();if (pareTo(this.end) 0)throw new IllegalArgumentException(start + after + end);随着各种新的构造,前面的进攻将对期无影响实例。需要注意的是防御性的副本正在检查的有效性之前进行参数(项目23),和所述有效性检查的副本进行,而不是在 原件。虽然这可能看起来不自然,这是必要的。它可以防止类之间的“窗口脆

7、弱性”过程中的变化,从另一个线程的参数时间参数进行检查和的时候,他们被复制。还要注意,我们没有使用日期的克隆方法,使防守副本。 因为日期是非最终,克隆方法不保证返回一个对象,它的类java.util.Date;它可以返回专门设计一个不受信任的子类的实例对于恶意的恶作剧。这样一个子类可以例如,记录一个参考给每个实例在一个私人静态列表在其创建时间和允许攻击访问这名单。这将使攻击者自由支配的所有实例。为了防止这种攻击,不使用克隆方法,使一个参数,它的类型是一个防守副本由不受信任的第三方子类化。虽然更换构造成功抵御了以前的攻击,它仍然是可能的突变一期的实例,因为它的评估提供了访问它的可变内部:/一个周

8、期实例的内部二次进攻Date start = new Date();Date end = new Date();Period p = new Period(start, end);p.end().setYear(78);/修改P的内部!要对二次进攻防守,仅仅是修改访问返回一个可变的内部字段:/修复评估public Date start() return (Date) start.clone();public Date end() return (Date) end.clone();随着新的构造和各种新的访问,期间确实是不可变的。 没有无论多么恶意和不称职的程序员,根本没有办法,他可能会违反一个

9、周期的开始不遵循其端不变。这是真的,因为没有方式为任何类比期本身以外,以获得任一可变字段中一个周期实例。这些字段的对象中真正的封装。请注意,新的访问,不同的是新的构造函数,却使用了克隆的方法,使防守副本。这是可以接受的(尽管不是必须的),因为我们知道肯定地该堂课的内部Date对象是java.util.Date而不是一些潜在的不受信任的子类。参数复制不只是一成不变的类。任何时候你写方法或构造进入客户端提供的对象到内部数据结构中,想客户所提供的对象是否是潜在可变的。如果是,想想你的类是否能容忍在对象物的变化它被输入到数据之后 结构体。如果答案是否定的,你必须防守复制的对象并进入副本进入数据结构代替

10、原始的。例如,如果您使用的是考虑在内部集实例或作为一个密钥的客户端提供的对象的引用作为元素内部地图实例,你应该知道,集合或映射的不变量会如果插入后,它的对象进行了修改,销毁。他们回国之前,同样适用于内部组件的保护性拷贝客户端。不管是不是你的类是不可变的,你应该返回之前三思而后行的引用的内部组件是可变的。有可能到头来你应该返回防守副本。此外,要记住,非零长度数组始终是至关重要可变的。因此,你之前应该始终内部数组的一个防守副本其返回到客户端。另外,您也可以返回数组的一个不可改变的视图 用户。这两种技术示于第12项。可以说,在所有这一切的真正教训是,你应该在可能的情况,使用一成不变对象为你的对象的组

11、件,以便你不必担心防守复印(第13项)。在我们的时期例的情况下,这是值得指出有经验的程序员经常使用的基元Date.getTime(长回)作为内部时间表示,而不是使用一个Date对象引用。他们这样做这主要是因为日期是可变的。它并不总是适当之前作出一个可变参数的防御性拷贝它集成到一个对象。也有一些方法和构造,其调用表示由一个参数所引用的对象的一个明确的越区切换。当调用这样的方法,客户端的承诺,它将不再直接修改的对象。一种方法或构造函数,希望采取客户端提供的可变对象的控制权,必须使这个明确其文档。含的方法或构造,其调用的类指示控制转移不能保护自己免受恶意客户端。这些类是可以接受的,只有当还有就是类不

12、变量的类和它的客户端或者损害之间的相互信任会伤害任何人,但客户端。的后一种情况的一个例子是包装类模式(第14项)。取决于包装类的性质,客户端可能会破坏类不变量直接访问后,一个对象被包裹着,但是这通常只能会对客户端造成伤害。2.外文原文Chapter 6. MethodsThis chapter discusses several aspects of method design: how to treat parameters and returnvalues, how to design method signatures, and how to document methods. Much

13、 ofthe material in this chapter applies to constructors as well as to methods. Like Chapter 5, thischapter focuses on usability, robustness, and flexibility.Item 23: Check parameters for validityMost methods and constructors have some restrictions on what values may be passed intotheir parameters. F

14、or example, it is not uncommon that index values must be nonnegative andobject references must be non-null. You should clearly document all such restrictions andenforce them with checks at the beginning of the method body. This is a special case of thegeneral principle, and you should attempt to det

15、ect errors as soon as possible after they occur.Failing to do so makes it less likely that an error will be detected and makes it harder todetermine the source of an error once it has been detected.If an invalid parameter value is passed to a method and the method checks its parametersbefore executi

16、on, it will fail quickly and cleanly with an appropriate exception. If the methodfails to check its parameters, several things could happen. The method could fail witha confusing exception in the midst of processing. Worse, the method could return normallybut silently compute the wrong result. Worst

17、 of all, the method could return normally butleave some object in a compromised state, causing an error at some unrelated point in thecode at some undetermined time in the future.For public methods, use the Javadoc throws tag to document the exception that will bethrown if a restriction on parameter

18、 values is violated (Item 44). Typically the exception willbe IllegalArgumentException , IndexOutOfBoundsException , or NullPointerException(Item 42). Once youve documented the restrictions on a methods parameters and youvedocumented the exceptions that will be thrown if these restrictions are viola

19、ted, it is a simplematter to enforce the restrictions. Heres a typical example:/* Returns a BigInteger whose value is (this mod m). This method* differs from the remainder method in that it always returns a* nonnegative BigInteger.* param m the modulus, which must be positive.* return this mod m.* t

20、hrows ArithmeticException if m = 0.*/public BigInteger mod(BigInteger m) if (m.signum() 0)throw new IllegalArgumentException(start + after + end);this.start = start;this.end = end;public Date start() return start;public Date end() return end;. / Remainder omittedAt first glance, this class may appea

21、r to be immutable and to enforce the invariant that thestart of a period does not follow its end. It is, however, easy to violate this invariant byexploiting the fact that Date is mutable:/ Attack the internals of a Period instanceDate start = new Date();Date end = new Date();Period p = new Period(s

22、tart, end);end.setYear(78); / Modifies internals of p!To protect the internals of a Period instance from this sort of attack, it is essential to make adefensive copy of each mutable parameter to the constructor and to use the copies ascomponents of the Period instance in place of the originals:/ Rep

23、aired constructor - makes defensive copies of parameterspublic Period(Date start, Date end) this.start = new Date(start.getTime();this.end = new Date(end.getTime();if (pareTo(this.end) 0)throw new IllegalArgumentException(start + after + end);With the new constructor in place, the previous attack wi

24、ll have no effect on the Periodinstance. Note that defensive copies are made before checking the validity of theparameters (Item 23), and the validity check is performed on the copies rather than onthe originals. While this may seem unnatural, it is necessary. It protects the class againstchanges to

25、 the parameters from another thread during the “window of vulnerability” betweenthe time the parameters are checked and the time they are copied.Note also that we did not use Date s clone method to make the defensive copies. Date is nonfinal, the clone method is not guaranteed to return an object wh

26、ose class isjava.util.Date ; it could return an instance of an untrusted subclass specifically designedfor malicious mischief. Such a subclass could, for example, record a reference to eachinstance in a private static list at the time of its creation and allow the attacker access to thislist. This w

27、ould give the attacker free reign over all instances. To prevent this sort of attack,do not use the clone method to make a defensive copy of a parameter whose type issubclassable by untrusted parties.While the replacement constructor successfully defends against the previous attack, it is stillpossi

28、ble to mutate a Period instance because its accessors offer access to its mutable internals:/ Second attack on the internals of a Period instanceDate start = new Date();Date end = new Date();Period p = new Period(start, end);p.end().setYear(78); / Modifies internals of p!To defend against the second

29、 attack, merely modify the accessors to return defensive copiesof mutable internal fields:/ Repaired accessors - make defensive copies of internal fieldspublic Date start() return (Date) start.clone();public Date end() return (Date) end.clone();With the new constructor and the new accessors in place

30、, Period is truly immutable. Nomatter how malicious or incompetent a programmer, there is simply no way he can violatethe invariant that the start of a period does not follow its end. This is true because there is noway for any class other than Period itself to gain access to either of the mutable f

31、ields ina Period instance. These fields are truly encapsulated within the object.Note that the new accessors, unlike the new constructor, do use the clone method to makedefensive copies. This is acceptable (although not required), as we know with certainty thatthe class of Period s internal Date obj

32、ects is java.util.Date rather than some potentiallyuntrusted subclass.Defensive copying of parameters is not just for immutable classes. Anytime you write a method or constructor that enters a client-provided object into an internal data structure,think about whether the client-provided object is po

33、tentially mutable. If it is, think aboutwhether your class could tolerate a change in the object after it was entered into the datastructure. If the answer is no, you must defensively copy the object and enter the copy intothe data structure in place of the original. For example, if you are consider

34、ing usinga client-provided object reference as an element in an internal Set instance or as a key inan internal Map instance, you should be aware that the invariants of the set or map would bedestroyed if the object were modified after it were inserted.The same is true for defensive copying of inter

35、nal components prior to returning them toclients. Whether or not your class is immutable, you should think twice before returninga reference to an internal component that is mutable. Chances are you should be returninga defensive copy. Also, it is critical to remember that nonzero-length arrays are

36、alwaysmutable. Therefore you should always make a defensive copy of an internal array beforereturning it to a client. Alternatively, you could return an immutable view of the array tothe user. Both of these techniques are shown in Item 12.Arguably, the real lesson in all of this is that you should, where possible, use immutableobjects as components of your objects so that you that dont have to worry about defensivecopying (Item 13). In the case of our Period example, it is worth pointing out thatexperienced programmers of

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论