How to develop good coding habits ?, Develop writing habits

Source: Internet
Author: User

How to develop good coding habits ?, Develop writing habits

(1)The first letter of the class name should be capitalized.

The first letter of the field, method, and object (handle) should be in lowercase. For all identifiers, all the words in them should be placed together, and the first letter of the intermediate word should be capitalized. For example:

ThisIsAClassName

ThisIsMethodOrFieldName

If a constant initialization character appears in the definition, all the letters in the static final basic type identifier are capitalized. In this way, they are constants of the compilation period.

A Java Package is a special case where all these are lowercase letters, even the middle words. All domain name extension names, such as com, org, net, or edu, should be in lower case (this is also one of the differences between Java 1.1 and Java 1.2 ).

(2)Take"Classic format"And includes the definition of the following elements:

Equals ()

HashCode ()

ToString ()

Clone () (implement Cloneable)

Implement Serializable

(3)For each class created by yourself, consider placingMain ()Contains the code used to test the class.

To use a class in a project, we do not need to delete the test code. If any form of modification is made, you can easily return to the test. These codes can also be used as an example of how to use classes.

(4)A method should be designed as a simple functional unit to describe and implement a discontinuous class interface section.

Ideally, the method should be concise. If the length is large, you can divide it into several shorter methods in some way. This also facilitates the reuse of code in the class (sometimes, the methods must be very large, but they should still only do the same thing ).

(5)When designing a class, consider it for the client Programmer (the usage of the class should be very clear ).

Then, let's look at the form of changes that may be made to the person who manages the code (think about how to make them easier ).

(6)Make the class as short and concise as possible, and only solve a specific problem.

The following are some suggestions for class design:

  • A complex switch statement: consider adopting the "multi-form" Mechanism
  • A large number of methods involve very different types of operations: Consider using several classes to implement them separately.
  • Many member variables have major differences in features: Consider using several classes

(7)Make everything as possible"Private"-Private.

A certain part of the database can be "public" (a method, class, or a field), and it will never be taken out. If you forcibly extract the code, it may damage the existing Code of others, so that they have to rewrite and design it. If you only publish what you must publish, You can boldly change anything else. In a multi-threaded environment, privacy is a particularly important factor-only private fields can be protected in non-synchronous use.

(8)Please refer"Huge object syndrome".

For new users who are used to sequential programming and are initially involved in the OOP field, they often prefer to write an ordered execution program first and then embed it into one or two huge objects. According to programming principles, objects should be expressed as the concept of applications rather than the application itself.

(9)If you have to do some unsightly programming, you should at least put the code inside a class.

(10)At any time, as long as you find that classes are closely integrated with each other, you need to consider whether to use internal classes to improve coding and maintenance.

(11)Add comments as detailed as possible and useJavadocAnnotate the Document Syntax to generate your own program documentation.

(12)Avoid using"Magic number"These numbers are difficult to work with the code.

If you need to modify it later, it will undoubtedly become a nightmare, because you do not know whether "100" refers to "array size" or "other completely different things ". Therefore, we should create a constant, use a persuasive descriptive name for it, and use constant identifiers throughout the program. This makes the program easier to understand and maintain.

(13)When it comes to the builder and exceptions, you usually want to discard any exceptions caught in the builder.-If it causes the creation of that object to fail.

In this way, the caller will not blindly continue to think that the object has been correctly created.

(14)After a client programmer runs out of objects, if your class requires any cleanup, consider placing the cleanup code in a well-defined method, using a method similarCleanup ()Such a name clearly indicates its purpose.

In addition, you can place a boolean mark in the class to indicate whether the object has been cleared. In the finalize () method of the class, make sure that the object has been cleared and a class inherited from RuntimeException has been discarded (if not) to indicate a programming error. Before taking a scheme like this, make sure that finalize () can work in your own System (you may need to call System. runFinalizersOnExit (true) to ensure that this row is ).

(15)In a specific scope, if an object must be cleared (not handled by the garbage collection mechanism)

Use the following method: Initialize the object; if successful, immediately enter a try block containing the finally clause to start clearing.

(16)If overwrite (cancel) is required during initialization)Finalize ()Remember to callSuper. finalize ()(IfObjectThis is not necessary if it belongs to our direct superclass ).

In the process of overwriting finalize. the call to finalize () should belong to the last action, rather than the first action, which ensures that they are still valid when basic components are required.

(17)When creating a set of fixed-size objects, transmit them to an array (this operation is more appropriate if you are going to return this set from a method ).

In this way, we can enjoy the benefits of checking the type of arrays during compilation. In addition, to use them, the receiver of the array may not need to "shape" the object into the array.

(18)Try to useInterfaces, Do not useAbstractClass.

If you know that something is ready to be a basic class, the first choice should be to convert it into an interface ). You need to change a method definition or a member variable to an abstract class. The interface mainly describes what the customer wants to do, and a class is committed to (or allowed) specific implementation details.

(19)Within the builder, only work is required to set the object to the correct state.

Avoid calling other methods whenever possible, because those methods may be overwritten or canceled by others, resulting in unpredictable results during the build process (see the detailed description in Chapter 7th ).

(20)Objects should not simply contain some data; their behavior should also be well defined.

(21)Select"New"Or"Creation".

This issue should be considered only when the design requirements must be inherited. If inheritance is used in the scenario where new users are allowed, the entire design becomes unnecessary.

(22)Inheritance and method overwrite are used to represent the differences between actions, while fields are used to represent the differences between States.

An extremely extreme example is to represent colors by inheriting different classes, which should be avoided: A "color" field should be used directly.

(23)To avoid programming problems, make sure that each name corresponds to only one class at any place indicated by the class path.

Otherwise, the compiler may first find another class with the same name and report an error message. If you suspect that you have encountered a class path problem, try to search for the. class file with the same name at every starting point of the class path.

(24)InJava 1.1 AWTUse event in"Adapter"Especially prone to a trap.

If an adapter method is overwritten and the spelling method is not particular, the final result is to add a new method instead of overwriting the existing method. However, this is completely legal, so no error prompts are returned from the compiler or runtime system-except that the Code becomes abnormal.

(25)Eliminate with reasonable design solutions"Pseudo Function".

That is to say, if you only need to create an object of the class, do not restrict your use of the application in advance, and add a "generate only one" comment. Consider encapsulating it into an "Only Child" form. If there is a large amount of scattered code in the main program to create your own objects, consider adopting a creative solution to encapsulate some code.

(26)Be alert"Analysis paralysis".

Remember to know the status of the entire project in advance in any case, and then examine the details. By grasping the global conditions, you can quickly identify unknown factors to prevent the details from falling into the "dead logic.

(27)Be alert"Premature Optimization".

First let it run, and then consider getting faster-But optimization should be performed only when you have to do so and it has been confirmed that there is indeed a performance bottleneck in some code. Unless you use a dedicated tool to analyze the bottleneck, you may be wasting your time. The hidden cost of performance improvement is that your code becomes hard to understand and difficult to maintain.

(28)Remember, reading Code takes much more time than writing code.

A program with clear thinking can be easily understood, but comments, detailed explanations, and examples are often invaluable. They are important to both yourself and those who are later. If you still have doubts about this, think about the setbacks you encounter when trying to find useful information from the online Java documentation. This may convince you.

(29)If you think that you have performed a good analysis, design, or implementation, change your mind slightly.

Try inviting outsiders-not necessarily experts, but people from other departments of the company. Ask them to take a fresh look at your work and see if you can find out what you once turned a blind eye on. In this way, we can often find some key problems in the most suitable period to avoid the financial and energy losses caused by solving the problems after the product is released.

(30)Good design can bring the greatest return.

In short, a specific problem usually takes a long time to find the most appropriate solution. However, once the correct method is found, the work in the future will be much easier, and there will be no need to go through several hours, days, or months of hard work. Our hard work will bring the greatest return (or even immeasurable ). In addition, because I put a lot of effort into it and finally got an outstanding design scheme, the pleasure of success is also exciting. Stick to the temptation to resist the completion of Caocao-doing so is often not worth the candle.

Contact Us

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.