keep the failure atomicA failed method call should keep the object in the state it was before it was called, and there are several ways to do so
Using Immutable objects
Check parameter validity before changing state, throw exception early
Put the potentially failed action before the change state, so that the failure can end prematurely without leaving the object in an inconsistent state
Write recovery code (infrequently used), typically for data that has persisted
To ma
1, consider using the static factory method instead of the constructor.Here are some advantages:
The static method factory method has a variable name. For example, a true object defined in a Boolean class with a name that is very intuitive.
Boolean.truepublic static Final Boolean true = new Boolean (true);
You do not have to create new objects every time you call. If creating objects is expensive, using static classes can improve performance.
Any subcla
Chapter II Creating and Destroying objectsThe first one uses the static factory method instead of the constructor, because:
Static factory methods can have different names, that is, the constructor can only be distinguished by different parameters, and static factories can express different purposes in their names.
The static factory method creates a new object without each invocation (in fact because it is static, so it can only be used as static, so it is created early and does not need
.item27; Public classgenericsingletonfactory{//Create object objects first, temporarily override T objects Private StaticUnaryfunctionNewUnaryfunction() { Publicobject Apply (object arg) {returnArg; } }; //according to T, the identity_function is converted to the corresponding type, because Identity_function returns the object type parameter unmodified, so the following type conversion is safe@SuppressWarnings ("Unchecked") Public Staticidentityfunction () {return(una
= = 23) { //Thread pool, which creates a thread pool of a single threads, creates a new thread instead of executing the task if the current thread breaks abruptly when the task is executedExecutorservice executor =Executors.newsinglethreadexecutor (); Finalsetobserver This; Try{executor.submit (NewRunnable () {@Override Public voidrun () {//There's going to be a deadlock.Set.removeobserver (Observer); }}). get (); } Catch(i
the general conventions of Object.hashcode, which prevents the class from working properly with all hash-based collections, such as Hashmap,hashset and Hashtable.always overwrite ToStringThis item is mostly intended to provide the necessary critical information when printing data, because the default ToString method only returns the unsigned hexadecimal representation of the class name [email protected]+ hash code.cover clone with careThe purpose of the Cloneable interface is expressed as an ob
; } Public Static voidMain (string[] args) {Builderdemo demo=NewBuilder (calories). Carbohydrate (43). build (); }}Such code is easy to write and read. Furthermore, constraints can be imposed on their parameters, and the build method can examine these constraints, copy the parameters from the builder to the object, and test them in the object domain.Insufficient builder mode: 1. You need to create the builder before creating the object, which is not applicable in a very performance-oriented
The 16th compound takes precedence over inheritanceIf you are unsure of the relationship between B and a, and B is indeed a, then you should not use B to inherit a, or you will expose the implementation details, and your implementation will be limited to the original implementation, Is-a.The first example of the book cited implements a class extends HashSet class, because the lack of understanding of the AddAll method of the HashSet class (AddAll calls the Add method repeatedly), resulting in a
The static factory method returns the class to which the object belongs, and can not be present when writing a class that contains the static factory method. This flexible, static factory approach forms the basis of the service provider Framework (Provider framework), such as the JDBC API. The service provider framework refers to a system in which multiple service providers implement a service (interface) that provides multiple implementations of the service provider's clients and decouples them
, there are two ways we can solve this problem:
Use the basic type as much as possible within the class.
If you can pre-think that those states will often change, then provide a package-level private matching class, for example, StringBuilder is relative to string.
Also, if, for some reason, you cannot use the final modifier immutable class, but you do not want to be extended, there are other methods in addition to using final.The method is to replace all public constructors wi
:// Dependency Injection provides flexibility and testability Public class spellchecker { private final Lexicon dictionary; Public spellchecker (Lexicon dictionary) { this. Dictionary= Objects.requirenonnull ( dictionary); } Public boolean isValid (String word) {...} Public List Suggestions (String typo) {...}}So the customer needs to use what dictionary is the customer's own decision, and our code does not need to maintain multiple copies.The popular explanation f
field that invokes its Hashcode method on each of these elements.[3] The above computed hash code is saved to the INT variable C, and then executed Result=37*result+c;[4] returns result.3. Always overwrite the ToString method. only override this method, other such as arrays.tostring (), and the toString of the collection class. When you call the output of the class, you invoke the ToString that the class has already implemented.4. Call the Clone method with caution. When you are designing a cla
This is the desired result if any of the following conditions are met:Each instance of a class is inherently unique.Does not care if the class provides a "logical equality" test function.The superclass has overridden equals, and the behavior inherited from the superclass is also appropriate for subclasses.Class is private or package-level private, it can be determined that its Equals method is never called.If a class has its own unique "Roggi" concept (unlike the concept of object equivalence),
Why avoid creating unnecessary objects? The process of creating objects is still more cost-intensive, according to the performance tests given in the book, the time consuming to recreate objects is 250 times times the time consumed by reusing objects. The following is a list of scenarios where objects can be reused.1, String type Note that there is a big difference between string s = "as" and string s = new String ("as"), and the second method of creating a string instance will actually produce
(inkfish original, reprint please indicate the source: http://blog.csdn.net/inkfish/)
In order to seek the performance optimization of Java code, search from the internet to use final keyword compile-time inline optimization method, but really effective. The actual test found that not necessarily, even the performance impact of the huge, eventually abandoned the idea of using final optimization.
Test enviro
Recently in the watercress to see some book reviews, very feel, and there is a call effective Java is said to be very good, download a look, really masterpiece, a lot of things are not read, the skill is still shallow, still have to continue efforts. It feels so good to read that it's much better than a grammar-telling book.
The first part of the object is created and destroyed.
Said 5 principles.
1. Rep
Tips"Effective Java, third Edition" an English version has been published, the second edition of this book presumably many people have read, known as one of the four major Java books, but the second edition of 2009 published, to now nearly 8 years, but with Java 6, 7, 8, and even 9 of the release, the
Tips"Effective Java, third Edition" an English version has been published, the second edition of this book presumably many people have read, known as one of the four major Java books, but the second edition of 2009 published, to now nearly 8 years, but with Java 6, 7, 8, and even 9 of the release, the
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.