học java (tài liệu FPT) phân2

37 301 0
học java (tài liệu FPT) phân2

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

One of the benefits that Eclipse provides is the ability to run code interactively by using its integrated debugger. Examining variables and expressions while executing code stepbystep is an invaluable tool for investigating problems with your code. This excerpt from Chapter 2 of Eclipse in Action: A guide for Java developers provides an introduction to creating a Java project, running a Java program, and debugging it.Creating a Java ProjectWhen Eclipse is first started, it is in the Resource perspective, a set of panes for managing projects, folders, files, and other resources. In Eclipse parlance, each of these panes is called a view, and a complete set of views is called a perspective. In the Resource perspective, you can navigate or create resources by using the view at the top left, the Navigator view.Before you can do anything else in Eclipse, such as creating a Java program, you need to create a Java project. To create a new Java project, follow these steps:1.Rightclick in the Navigator view to bring up a context menu and select New>Project.2.In the New Project dialog box, Eclipse presents the project options: Java, Plugin Development, and Simple. Because you want to create a Java program, select Java on the left side of the dialog box.3.Select Java Project on the right. If youve installed other types of Java development plugins, various other types of Java projects may potentially be listed here (EJBs and servlets, for example). But the JDT that comes standard with Eclipse only offers support for standard Java applications, so you must choose the Java Project option.4.Click Next to start the New Java Project Wizard. (A wizard is a set of dialog boxes that prompts you through a set of welldefined, sequential steps necessary to perform a specific task. This feature is used extensively throughout Eclipse.)5.The first dialog box prompts you for a project name. This is a simple Hello, world example, so enter Hello. Clicking Next would take you to a dialog box that lets you change a number of Java build settings, but for this example you dont need to change anything.6.Click Finish.7.Eclipse notifies you that this kind of project is associated with the Java perspective and asks whether you want to switch to the Java perspective. Check the Dont Show Me This Message Again box and click Yes.

Coding Best Practices Coding Best Practices I Table of Contents I Table of Contents IV Abbreviations Performance Resources management Integrity 10 Design related 13 Code Maintenance 23 Code reliability 32 Miscellaneous 36 IV Abbreviations DB Database DTO Data Transfer Object OOP Object Oriented Programming PROD Production / 37 Coding Best Practices Performance 1.1 Object initialization 1.1.1 Use StringBuffer (Java) or StringBuilder (C#) Problem Use StringBuffer (Java) or StringBuilder (C#) Type Performance / Object initialization - Java Bad code / behavior String result = “”; while (iter.hasNext()){ result += (String)iter.next(); } return result; Description Operation on String (immutable) objects creates a lot of short-live objects StringBuffer in java or StringBuilder in C# provide an alternative Good code / behavior StringBuffer result = new StringBuffer(“”); while (iter.hasNext()){ result.append((String)iter.next()); } return result.toString(); 1.2 Collection usage 1.2.1 Avoid using Hashtable and Vector Problem Avoid using Hashtable and Vector Type Performance / Collection usage – Java Bad code / behavior In un-threaded context: Vector m_aCollection = new Vector(); m_aCollection.get(i) In threaded context: Hashtable m_aCollection = new Hashtable(); if (!m_aCollection.contains(someObject){ m_aCollection.add(someKey, someObject); / 37 Coding Best Practices } Description Accesses to Vector or Hashtable are synchronized =>in unthreaded context, this overhead is unnecessary In threaded context, m_aCollection.contains(someObject) and m_aCollection.add(someKey, someObject); should be in a single synchronized block Therefore, the block of code if (!m_aCollection.contains(someObject){ m_aCollection.add(someKey, someObject); } is not correct although Hashtable already provides the synchronization facility Good code / behavior Use ArrayList, LinkedList, HashMap … and provide synchronization block/method if necessary in threaded context Unthreaded List m_aCollection = new ArrayList(); m_aCollection.get(i) Threaded HashMap m_aCollection = new HashMap(); synchronized(this){ if (!m_aCollection.contains(someObject){ m_aCollection.add(someKey, someObject); } } 1.2.2 Use Iterator instead of indexing for loop Problem Use Iterator instead of indexing for loop in Collections (List,…) Type Performance / Collection usage – Java Bad code / behavior int len = anArrayList.size(); for (int i = 0; i validation fails Assertion cannot throw specific Exception Good code / behavior public void someProcessing(List input){ if (input != null){ // processing } } 26 / 37 Coding Best Practices Note: However, if someProcessing(List input) is private, then the use of Assertion is acceptable, since it this case, normally the same developer will also write the caller of someProcessing and he should know the input condition of that method Assertion in this case is used to prevent programming error Comment 5.2.4 This is true for public methods, but for private, you can still use assertions (because that would be programming errors here) Comparing enum type Problem Comparing enum type Type Code maintenance Bad code / behavior TypeDossierState state = dossier.getState(); if (!(TypeDossierState.CLOSED.equals(state)) { … } // TypeDossierState is implemented as enum type Description The general idea of enum type is that we can not create instance of that class other than the predefined ones Thus we can actually use the == to compare It is more natural and increases readability Good code / behavior TypeDossierState state = dossier.getState(); if (state != TypeDossierState.CLOSED) { … } 5.2.5 Must not forget to put try catch in finally Problem Must not forget to put try catch in finally (if needed) Type Code maintenance Bad code / behavior ObjectOutput output = null; try{ //use buffering OutputStream file = new FileOutputStream( "something.txt " ); OutputStream buffer = new BufferedOutputStream( file ); output = new ObjectOutputStream( buffer ); output.writeObject(quarks); 27 / 37 Coding Best Practices } catch(IOException ex){ // log the error } finally{ if (output != null) { output.close(); } } Description Many finally clauses in turn contain a try catch block This is because many of the methods called in a finally clause can themselves throw an exception Good code / behavior ObjectOutput output = null; try{ //use buffering OutputStream file = new FileOutputStream( "something.txt " ); OutputStream buffer = new BufferedOutputStream( file ); output = new ObjectOutputStream( buffer ); output.writeObject(quarks); } catch(IOException ex){ // log the error } finally{ try { if (output != null) { output.close(); } } catch (IOException ex ){ // log } } 5.2.6 The class and method naming must be clear Problem The class and method naming must be clear Type Code maintenance Bad code / behavior For example: I would like to make a Service to manage the User and the authentication for the user Bad naming: UserService { create(); update(); authenticate(); } 28 / 37 Coding Best Practices Description Good code / behavior If you not know how to name it, please ask the expert or someone who has more experience So with that example, there are different things: • User management • User authentication So make services for that: UserManagementService { createUser(); updateUser(); } AuthenticationService { authenticate(); } 5.2.7 Documentation: comments in the source code Problem Documentation: comments in the source code Type Code maintenance Bad code / behavior There is a method:createUser, and its comments are: create User => It is useless comment Description The code must be documented properly It must be respected by ALL developer Do not put the non-valuable comment When you change the code, please check the comment if it is still valid Make sure that the comment is matched with your code Tip: Think carefully what the code will be developed Then write them down: ALL the things in your mind (i.e the logic or business or algorithm…) Good code / behavior 5.2.8 Try to think about business of method: This method will create a new user for the system It will be used to logon to the system When the user is created, the password must be changed at the first time of logon Use the constants, not hard-code the value Use the constants, not hard-code the value Problem Try to use the ? to prepare the parameters for SQL Do not put directly value! 29 / 37 Coding Best Practices Type Code maintenance Bad code / behavior If (value == 1) { //do something } Or in the query Select user_name, password where visa = ? and active = Description Good code / behavior 5.2.9 If (value == ACTIVE) { //do something } Or in the query Select user_name, password where visa = ? and active = ? Try to put it as parameter with the constant ACTIVE Do not copy / paste the code or comments Problem Do not copy the code and the comment Type Code maintenance Bad code / behavior Description If you copy similar code, it is easy to forget to modify the comment and something the name of parameter Solution: make a generic function to reuse in both cases Good code / behavior 5.2.10 The constants and configurable parameters are different Problem The constants and configurable parameters are different Type Code maintenance Bad code / behavior Description If you think the value will be never changed, or if we change it, we have to rebuild the system Then put it as constants Else make it as configurable parameters, it mean if will be configured when we install it in different environment (TEST, PROD) Because if you put too much for the configuration, then it is difficult for 30 / 37 Coding Best Practices the installation Good code / behavior 31 / 37 Coding Best Practices Code reliability 6.1 Exception handling 6.1.1 Never leave a empty catch block Problem Never leave a empty catch block Type Maintainability / Exception handling – Java, C# Bad code / behavior try{ // something that might cause exception }catch(AException aExc){ // nothing } Description There is no easy way to trace back to original source of error Good code / behavior try{ // something that might cause exception }catch(AException aExc){ // logging // translate with aExc kept in the new exception OR at least comment/justification } 6.1.2 Be specific in throw clause Problem Be specific in throw clause Type Maintainability / Exception handling – Java, C# Bad code / behavior public void aMethod( ) throws Exception Description Difficult to figure out what specific error has occurred Good code / behavior public void aMethod( ) throws ASpecificException 32 / 37 Coding Best Practices 6.1.3 Pass pertinent data to exception Problem Pass pertinent data to exception Type Maintainability / Exception handling – Java, C# Bad code / behavior public class CustomerDAO{ public CustomerDTO loadCustomer(string customerID) throws ObjectNotFoundException{ List customerList = (select statement) if (customerList == 0){ throw new ObjectNotFoundException( “Cannot load customer info”); } // further processing } } public class CustomerService{ public void processingWith2Customers( string firstCustomerID, string secondCustomerID) throws ObjectNotFoundException{ CustomerDTO firstCustomer = customerDAO.loadCustomer(firstCustomerID); CustomerDTO secondCustomer = customerDAO.loadCustomer(secondCustomerID); // some further processing with firstCustomer and // secondCustomer } } Client code: try{ customerService.processingWith2Customers(“1”, “2”); }catch(ObjectNotFoundException exc){ // Oop, not know which customer is not found // If on the GUI, I am to show a message, the best I // can is to display a vague message 33 / 37 Coding Best Practices // “Cannot load customer” } Description Difficult to figure out what action should be carried out next, since there is no or only a little hint from the exception Good code / behavior public class ObjectNotFoundException{ private string m_objectID; public string getObjectID{ return m_objectID; } } public class CustomerDAO{ public CustomerDTO loadCustomer(string customerID) throws ObjectNotFoundException{ List customerList = (select statement) if (customerList == 0){ throw new ObjectNotFoundException( “Cannot load customer info”, customerID); } // further processing } } public class CustomerService{ public void processingWith2Customers( string firstCustomerID, string secondCustomerID) throws ObjectNotFoundException{ CustomerDTO firstCustomer = customerDAO.loadCustomer(firstCustomerID); CustomerDTO secondCustomer = customerDAO.loadCustomer(secondCustomerID); // some further processing with firstCustomer and // secondCustomer } } 34 / 37 Coding Best Practices Client code: try{ customerService.processingWith2Customers(“1”, “2”); }catch(ObjectNotFoundException exc){ // If on the GUI, I am to show a message, at // least I can tell which customerID cannot be // loaded, visa exc.getObjectID(); } 35 / 37 Coding Best Practices Miscellaneous 7.1 Reuse existing components 7.1.1 Do not try to create home-built service, or re-invent things Problem Do not try to create home-built service, or re-invent things Type Reusability Bad code / behavior Implement the sort for collection again Do complicated handlings on string (parse string, …) Handlings for log Implement again a part of common task that other team member has done … Description During development, we can easily fall into the situation when we try to re-invent what already exists (maybe your current language already supports, or maybe the library you are using or even another team member has already done such a service) Try to ask when we feel that the service can be common Good code / behavior Use Collections.sort Use StringTokenizer, StringBuffer, String API, … Use reliable third party utilities Ask other team member when you think a similar service has been done 7.1.2 Sorting Problem Sorting Type Reusability - Java Bad code / behavior None Description When we want to sort an array or a list, not write the algorithm yourself The algorithm is already implemented for you in method 36 / 37 Coding Best Practices Arrays.sort (for array) and Collections.sort (for List) What you have to is to provide a way to compare between two objects you want to sort We have two ways to this: Good code / behavior Let the object implements the interface Comparable Provide a “Comparator” to compare two objects (see code below) Takes for example we want to sort a list persons using their name (case in sensitive) Here is what we have to do: - Create a comparator public class PersonComparator implements java.util.Comparator { public int compare(Object o1, Object o2) { Person p1 = (Person)o1; Person p2 = (Person)p2; } String s1 = p1.getName().toUpperCase(); String s2 = p2.getName().toUpperCase(); return s1.compareTo(s2); } - Compare the list Collections.sort(personList, new PersonComparator()); 7.2 Problem solving 7.2.1 You have a PROBLEM Problem You have a PROBLEM Type Misc Bad code / behavior Try yourself which might be non-standard or good solution Description Good code / behavior ASK someone (more experienced) if you not know or you have doubts Use GOOGLE to find one solution, not think you are only one who has a problem Check you understand the found solution and that it fits your needs If you are not sure, ask someone’s opinion on the solution you have found on the web… 37 / 37

Ngày đăng: 11/07/2016, 14:15

Từ khóa liên quan

Mục lục

  • 1 Performance

    • 1.1 Object initialization

      • 1.1.1 Use StringBuffer (Java) or StringBuilder (C#)

      • 1.2 Collection usage

        • 1.2.1 Avoid using Hashtable and Vector

        • 1.2.2 Use Iterator instead of indexing for loop

        • 1.2.3 List to array

        • 1.2.4 Arrays.asList(...)

        • 2 Resources management

          • 2.1 Resources allocation

            • 2.1.1 Use lazy initialization in memory-extensive applications

            • 2.1.2 Initialize size of collection type

            • 2.1.3 Should declare local variable just before use

            • 2.2 Resources de-allocation

              • 2.2.1 Must not forget to close the stream

              • 3 Integrity

                • 3.1 Object initialization

                  • 3.1.1 Use double checked locking when lazy-initializing object in threaded context where resource is shared

                  • 3.2 Comparing objects

                    • 3.2.1 Comparing two objects ( “==” instead of “.equals”)

                    • 4 Design related

                      • 4.1 Design - OOP

                        • 4.1.1 OOP - Encapsulation: declare a data member is public

                        • 4.1.2 OOP - Encapsulation: Do not make visible things that should not be visible

                        • 4.1.3 OOP - Use inner class in order to avoid using member attributes

                        • 4.1.4 OOP – Isolation between technical handlings and business handlings

                        • 4.1.5 OOP - Isolation between independent businesses

                        • 4.1.6 OOP - Isolation between systems

                        • 4.1.7 OOP - Isolation between the generic algorithm and detail implementation

                        • 4.1.8 Information expert, correct responsibility

                        • 4.1.9 Getter/Setter vs. Overriding

Tài liệu cùng người dùng

Tài liệu liên quan