### Java Example for Dynamic Query Parameters in MyBatis Source: https://alibaba.github.io/p3c/MySQL%E6%95%B0%E6%8D%AE%E5%BA%93/ORM%E6%98%A0%E5%B0%84 Demonstrates how to pass dynamic start and size parameters to a MyBatis query using a Map. This approach is recommended over iBATIS's built-in queryForList with start and size parameters, which is considered inefficient. ```java Map map = new HashMap(); map.put("start", start); map.put("size", size); ``` -------------------------------- ### Java Code Formatting Example Source: https://alibaba.github.io/p3c/%E7%BC%96%E7%A8%8B%E8%A7%84%E7%BA%A6/%E4%BB%A3%E7%A0%81%E6%A0%BC%E5%BC%8F Demonstrates correct Java code formatting according to specified rules, including brace usage, spacing, indentation, and conditional statements. ```java public static void main(String[] args) { // 缩进4个空格 String say = "hello"; // 运算符的左右必须有一个空格 int flag = 0; // 关键词if与括号之间必须有一个空格,括号内的f与左括号,0与右括号不需要空格 if (flag == 0) { System.out.println(say); } // 左大括号前加空格且不换行;左大括号后换行 if (flag == 1) { System.out.println("world"); // 右大括号前换行,右大括号后有else,不用换行 } else { System.out.println("ok"); // 在右大括号后直接结束,则必须换行 } } ``` -------------------------------- ### Java Line Length and Wrapping Example Source: https://alibaba.github.io/p3c/%E7%BC%96%E7%A8%8B%E8%A7%84%E7%BA%A6/%E4%BB%A3%E7%A0%81%E6%A0%BC%E5%BC%8F Shows how to wrap long lines in Java code that exceed 120 characters, including rules for indentation and placement of operators and method calls. ```java StringBuffer sb = new StringBuffer(); // 超过120个字符的情况下,换行缩进4个空格,点号和方法名称一起换行 sb.append("zi").append("xin")... .append("huang")... .append("huang")... .append("huang"); ``` -------------------------------- ### Constant Class Organization (Recommended) Source: https://alibaba.github.io/p3c/%E7%BC%96%E7%A8%8B%E8%A7%84%E7%BA%A6/%E5%B8%B8%E9%87%8F%E5%AE%9A%E4%B9%89 This example shows the recommended approach for organizing constants into separate classes based on their functionality, rather than using a single large constant class. ```java // Recommended: Cache-related constants in CacheConsts class // System configuration constants in ConfigConsts class ``` -------------------------------- ### Java Design Pattern Naming Example Source: https://alibaba.github.io/p3c/%E7%BC%96%E7%A8%8B%E8%A7%84%E7%BA%A6/%E5%91%BD%E5%90%8D%E9%A3%8E%E6%A0%BC When design patterns are used in modules, interfaces, classes, or methods, the naming should reflect the specific pattern to aid understanding. ```java public class OrderFactory; public class LoginProxy; public class ResourceObserver; ``` -------------------------------- ### Java Comment Formatting Example Source: https://alibaba.github.io/p3c/%E7%BC%96%E7%A8%8B%E8%A7%84%E7%BA%A6/%E4%BB%A3%E7%A0%81%E6%A0%BC%E5%BC%8F Illustrates the correct formatting for single-line comments in Java, requiring a single space after the double-slash delimiter. ```java // 这是示例注释,请注意在双斜线之后有一个空格 String ygb = new String(); ``` -------------------------------- ### Java Layered Naming Conventions (Service/DAO Methods) Source: https://alibaba.github.io/p3c/%E7%BC%96%E7%A8%8B%E8%A7%84%E7%BA%A6/%E5%91%BD%E5%90%8D%E9%A3%8E%E6%A0%BC Conventions for naming methods in Service/DAO layers, using prefixes like get, list, count, save, remove, update. ```java // Get single object: User getUserById(int id); // Get multiple objects: List listUsersByStatus(String status); // Get count: int countActiveUsers(); // Insert: void saveUser(User user); // Delete: void removeUserById(int id); // Update: void updateUserEmail(int id, String email); ``` -------------------------------- ### Java HashMap Initialization Capacity Example Source: https://alibaba.github.io/p3c/%E7%BC%96%E7%A8%8B%E8%A7%84%E7%BA%A6/%E9%9B%86%E5%90%88%E5%A4%84%E7%90%86 Demonstrates the recommendation to specify an initial capacity when initializing a HashMap to avoid performance degradation caused by frequent resizing. The formula initialCapacity = (expected elements / load factor) + 1 is suggested. ```java HashMap map = new HashMap<>(initialCapacity); ``` -------------------------------- ### Double-Checked Locking Implementation (JDK 5+) Source: https://alibaba.github.io/p3c/%E7%BC%96%E7%A8%8B%E8%A7%84%E7%BA%A6/%E5%B9%B6%E5%8F%91%E5%A4%84%E7%90%86 An example illustrating the potential issues with double-checked locking for lazy initialization and the recommended volatile solution for JDK 5 and above to ensure thread safety. ```java class Singleton { private Helper helper = null; public Helper getHelper() { if (helper == null) synchronized(this) { if (helper == null) helper = new Helper(); } return helper; } // other methods and fields... } ``` -------------------------------- ### Java Variable Arguments Example Source: https://alibaba.github.io/p3c/%E7%BC%96%E7%A8%8B%E8%A7%84%E7%BA%A6/OOP%E8%A7%84%E8%8C%83 Demonstrates the correct usage of Java's variable arguments (varargs). Variable arguments should be used for parameters with the same business meaning and must be placed at the end of the parameter list. It is generally recommended to avoid using varargs when possible. ```Java public User getUsers(String type, Integer... ids) {...} ``` -------------------------------- ### Get Current Milliseconds and Nanoseconds (Java) Source: https://alibaba.github.io/p3c/%E5%BC%82%E5%B8%B8%E6%97%A5%E5%BF%97/%E5%85%B6%E4%BB%96 Use `System.currentTimeMillis()` to obtain the current time in milliseconds. For nanosecond precision, use `System.nanoTime()`. In JDK 8 and later, the `Instant` class is recommended for time-related scenarios. ```java // Get current time in milliseconds long currentTimeMillis = System.currentTimeMillis(); // Get current time in nanoseconds (for precise timing) long currentTimeNanos = System.nanoTime(); // In JDK 8+, recommended for time scenarios: import java.time.Instant; Instant now = Instant.now(); ``` -------------------------------- ### Optimize Pagination with Subqueries (SQL) Source: https://alibaba.github.io/p3c/MySQL%E6%95%B0%E6%8D%AE%E5%BA%93/%E7%B4%A2%E5%BC%95%E8%A7%84%E7%BA%A6 This example demonstrates optimizing pagination for large offsets in MySQL by first identifying the required ID range using a subquery and then joining back to the main table. This avoids the performance penalty of skipping many rows directly. ```sql SELECT a.* FROM 表1 a, (select id from 表1 where 条件 LIMIT 100000,20 ) b where a.id=b.id ``` -------------------------------- ### Avoid negating logical operators Source: https://alibaba.github.io/p3c/%E7%BC%96%E7%A8%8B%E8%A7%84%E7%BA%A6/%E6%8E%A7%E5%88%B6%E8%AF%AD%E5%8F%A5 Prefer positive logic over negated conditions for better readability. For example, use `if (x < 628)` instead of `if (!(x >= 628))`. ```java // Prefer this if (value > 10) { // ... } // Avoid this if (!(value <= 10)) { // ... } ``` -------------------------------- ### Java String Split Example with Boundary Check Source: https://alibaba.github.io/p3c/%E7%BC%96%E7%A8%8B%E8%A7%84%E7%BA%A6/OOP%E8%A7%84%E8%8C%83 Illustrates a common pitfall when using String.split() in Java and the recommended way to handle it. When splitting a string, checking the length of the resulting array is crucial to avoid IndexOutOfBoundsException, especially when the delimiter appears at the end or multiple times consecutively. ```Java String str = "a,b,c,,"; String[] ary = str.split(","); // 预期大于3,结果是3 System.out.println(ary.length); ``` -------------------------------- ### Java Comparator Requirements for Sorting Source: https://alibaba.github.io/p3c/%E7%BC%96%E7%A8%8B%E8%A7%84%E7%BA%A6/%E9%9B%86%E5%90%88%E5%A4%84%E7%90%86 Provides an example of a Comparator that violates the three conditions required by Arrays.sort() and Collections.sort() in JDK 7+, potentially leading to IllegalArgumentException. The example highlights the omission of handling equal cases. ```java new Comparator() { @Override public int compare(Student o1, Student o2) { return o1.getId() > o2.getId() ? 1 : -1; } }; ``` -------------------------------- ### Correct Handling of `NullPointerException` Source: https://alibaba.github.io/p3c/%E5%BC%82%E5%B8%B8%E6%97%A5%E5%BF%97/%E5%BC%82%E5%B8%B8%E5%A4%84%E7%90%86 Illustrates the correct and incorrect ways to handle `NullPointerException` in Java. It demonstrates avoiding catching `RuntimeException`s that can be pre-checked and advises against using `try-catch` for predictable null checks. ```java // Correct way: Pre-check for null Object obj = getObject(); if (obj != null) { obj.method(); } else { // Handle the case where obj is null System.out.println("Object is null, cannot call method."); } // Incorrect way: Catching NullPointerException for expected null cases // try { // obj.method(); // } catch (NullPointerException e) { // // This is generally discouraged for predictable null checks // System.err.println("Caught NPE: " + e.getMessage()); // } ``` -------------------------------- ### Java Method Call Parameter Formatting Source: https://alibaba.github.io/p3c/%E7%BC%96%E7%A8%8B%E8%A7%84%E7%BA%A6/%E4%BB%A3%E7%A0%81%E6%A0%BC%E5%BC%8F Demonstrates the correct formatting for method calls with multiple parameters, ensuring a space after each comma. ```java method("a", "b", "c"); ``` -------------------------------- ### Character Length vs. Byte Length in SQL Source: https://alibaba.github.io/p3c/MySQL%E6%95%B0%E6%8D%AE%E5%BA%93/SQL%E8%AF%AD%E5%8F%A5 This example illustrates the difference between LENGTH() and CHARACTER_LENGTH() functions in SQL for measuring string lengths. LENGTH() returns the byte length, while CHARACTER_LENGTH() returns the character count, which is important for handling multi-byte character sets like UTF-8. ```sql SELECT LENGTH("轻松工作"); SELECT CHARACTER_LENGTH("轻松工作"); ``` -------------------------------- ### Parameter Validation Method Extraction Source: https://alibaba.github.io/p3c/%E5%BC%82%E5%B8%B8%E6%97%A5%E5%BF%97/%E5%BC%82%E5%B8%B8%E5%A4%84%E7%90%86 Illustrates the application of the Don't Repeat Yourself (DRY) principle by extracting repetitive parameter validation logic into a private helper method. This promotes code reusability and maintainability. ```java public class MyService { public void processRequest(DTO dto) { if (!checkParam(dto)) { // Handle invalid parameters return; } // ... proceed with processing ... } public void anotherMethod(DTO dto) { if (!checkParam(dto)) { // Handle invalid parameters return; } // ... other logic ... } private boolean checkParam(DTO dto) { // Perform common parameter validation checks here if (dto == null || dto.getProperty() == null) { return false; } // ... more checks ... return true; } // Assume DTO class exists static class DTO { private Object property; public Object getProperty() { return property; } } } ``` -------------------------------- ### Java Variable Declaration Formatting Source: https://alibaba.github.io/p3c/%E7%BC%96%E7%A8%8B%E8%A7%84%E7%BA%A6/%E4%BB%A3%E7%A0%81%E6%A0%BC%E5%BC%8F Illustrates recommended formatting for variable declarations, avoiding unnecessary alignment to improve readability and maintainability. ```java int a = 3; long b = 4L; float c = 5F; StringBuffer sb = new StringBuffer(); ``` -------------------------------- ### Log Exception with Context and Stack Trace (Java) Source: https://alibaba.github.io/p3c/%E5%BC%82%E5%B8%B8%E6%97%A5%E5%BF%97/%E6%97%A5%E5%BF%97%E8%A7%84%E7%BA%A6 When logging exceptions, include both contextual information (e.g., relevant parameters or object states) and the exception's stack trace. This aids in accurate problem diagnosis by providing the 'crime scene' details and the full error path. ```java logger.error(各类参数或者对象toString + "_" + e.getMessage(), e); ``` -------------------------------- ### Avoiding NullPointerException with `Optional` Source: https://alibaba.github.io/p3c/%E5%BC%82%E5%B8%B8%E6%97%A5%E5%BF%97/%E5%BC%82%E5%B8%B8%E5%A4%84%E7%90%86 Demonstrates the recommended approach to prevent NullPointerExceptions (NPEs) using Java 8's `Optional` class. This method helps in handling potentially null values gracefully, making the code more robust. ```java import java.util.Optional; // ... // Example of cascading calls that might result in NPE // String nestedValue = obj.getA().getB().getC(); // Using Optional to prevent NPE Optional optionalObj = Optional.ofNullable(obj); String safeNestedValue = optionalObj .map(YourObjectType::getA) .map(A::getB) .map(B::getC) .orElse("default_value"); // Provide a default value or handle the absence ``` -------------------------------- ### Java Arrays.asList Modification Limitation Example Source: https://alibaba.github.io/p3c/%E7%BC%96%E7%A8%8B%E8%A7%84%E7%BA%A6/%E9%9B%86%E5%90%88%E5%A4%84%E7%90%86 Illustrates that the List returned by Arrays.asList() is a fixed-size view of the original array and does not support add/remove operations, which will result in an UnsupportedOperationException. Changes to the underlying array will reflect in the list. ```java String[] str = new String[] { "you", "wu" }; List list = Arrays.asList(str); // list.add("yangguanbao"); // This would throw UnsupportedOperationException // str[0] = "gujin"; // This change would be reflected in list.get(0) ``` -------------------------------- ### Set Equal JVM Heap Size (Xms and Xmx) Source: https://alibaba.github.io/p3c/%E5%B7%A5%E7%A8%8B%E7%BB%93%E6%9E%84/%E6%9C%8D%E5%8A%A1%E5%99%A8 This recommendation suggests setting the initial Java Virtual Machine (JVM) heap size (Xms) and the maximum heap size (Xmx) to the same value. This prevents performance degradation caused by the JVM resizing the heap after garbage collection, thus reducing pressure on the system during GC events. ```java -Xms ``` ```java -Xmx ``` -------------------------------- ### Use SLF4J API for Logging (Java) Source: https://alibaba.github.io/p3c/%E5%BC%82%E5%B8%B8%E6%97%A5%E5%BF%97/%E6%97%A5%E5%BF%97%E8%A7%84%E7%BA%A6 Applications should use the SLF4J API as a facade for logging frameworks like Log4j and Logback. This promotes maintainability and a unified approach to logging across different classes. It requires importing Logger and LoggerFactory from org.slf4j. ```java import org.slf4j.Logger; import org.slf4j.LoggerFactory; private static final Logger logger = LoggerFactory.getLogger(Abc.class); ``` -------------------------------- ### Java ArrayList subList toArray Conversion Example Source: https://alibaba.github.io/p3c/%E7%BC%96%E7%A8%8B%E8%A7%84%E7%BA%A6/%E9%9B%86%E5%90%88%E5%A4%84%E7%90%86 Demonstrates the correct way to convert an ArrayList to a String array using the toArray(T[] array) method. It specifies that the input array should be of the same type and size as the list to avoid potential issues. ```java List list = new ArrayList(2); list.add("guan"); list.add("bao"); String[] array = new String[list.size()]; array = list.toArray(array); ``` -------------------------------- ### Java Map Iteration using entrySet() Source: https://alibaba.github.io/p3c/%E7%BC%96%E7%A8%8B%E8%A7%84%E7%BA%A6/%E9%9B%86%E5%90%88%E5%A4%84%E7%90%86 Highlights the efficiency of iterating over a Map using entrySet() compared to keySet(). entrySet() retrieves both key and value in a single traversal, whereas keySet() requires an additional lookup for each value. ```java for (Map.Entry entry : map.entrySet()) { KeyType key = entry.getKey(); ValueType value = entry.getValue(); // Process key and value } ``` -------------------------------- ### Java Layered Naming Conventions (Domain Models) Source: https://alibaba.github.io/p3c/%E7%BC%96%E7%A8%8B%E8%A7%84%E7%BA%A6/%E5%91%BD%E5%90%8D%E9%A3%8E%E6%A0%BC Conventions for naming domain model classes: xxxDO for data objects, xxxDTO for data transfer objects, and xxxVO for view objects. ```java // Data Object: public class UserDO {} // Data Transfer Object: public class UserDTO {} // View Object: public class UserVO {} ``` -------------------------------- ### Handling Null Return Values with Comments Source: https://alibaba.github.io/p3c/%E5%BC%82%E5%B8%B8%E6%97%A5%E5%BF%97/%E5%BC%82%E5%B8%B8%E5%A4%84%E7%90%86 Shows how to handle methods that may return null, emphasizing the importance of adding clear comments to explain the conditions under which a null value is returned. This shifts the responsibility of null checking to the caller. ```java /** * Retrieves user data. May return null if the user is not found or * in case of certain remote call failures. * @return User object or null. */ public User getUserById(String userId) { // ... implementation ... if (userNotFound) { return null; } return user; } // Calling code must handle potential null: User user = userService.getUserById("123"); if (user != null) { // Process user data System.out.println(user.getName()); } else { System.out.println("User not found."); } ``` -------------------------------- ### Java Thread Naming for Debugging Source: https://alibaba.github.io/p3c/%E7%BC%96%E7%A8%8B%E8%A7%84%E7%BA%A6/%E5%B9%B6%E5%8F%91%E5%A4%84%E7%90%86 Assign meaningful names to threads and thread pools for easier debugging and troubleshooting during runtime. This helps in identifying the source of issues when exceptions occur. ```java public class TimerTaskThread extends Thread { public TimerTaskThread() { super.setName("TimerTaskThread"); ... } } ``` -------------------------------- ### Java Package Naming Conventions Source: https://alibaba.github.io/p3c/%E7%BC%96%E7%A8%8B%E8%A7%84%E7%BA%A6/%E5%91%BD%E5%90%8D%E9%A3%8E%E6%A0%BC Package names must be entirely in lowercase. Dots should separate single, meaningful English words. Package names should be singular unless a class name has a plural meaning. ```java // Correct: // com.alibaba.ai.util // com.alibaba.ai.util.MessageUtils ``` -------------------------------- ### Configure JVM Heap Dump on OutOfMemoryError Source: https://alibaba.github.io/p3c/%E5%B7%A5%E7%A8%8B%E7%BB%93%E6%9E%84/%E6%9C%8D%E5%8A%A1%E5%99%A8 This configuration applies to the Java Virtual Machine (JVM) and enables the generation of a heap dump file when an OutOfMemoryError (OOM) occurs. This is crucial for diagnosing intermittent OOM errors by providing valuable runtime information at the time of the failure. ```java -XX:+HeapDumpOnOutOfMemoryError ``` -------------------------------- ### Optimize loops by moving operations outside Source: https://alibaba.github.io/p3c/%E7%BC%96%E7%A8%8B%E8%A7%84%E7%BA%A6/%E6%8E%A7%E5%88%B6%E8%AF%AD%E5%8F%A5 To enhance performance, move operations that do not depend on the loop's iteration outside the loop. This includes object instantiation, variable declarations, and unnecessary `try-catch` blocks. ```java // Inefficient loop for (int i = 0; i < items.size(); i++) { MyObject obj = new MyObject(); // Instantiated in each iteration // ... process item } // Optimized loop MyObject obj = new MyObject(); // Instantiated once for (int i = 0; i < items.size(); i++) { // ... process item using obj } ``` -------------------------------- ### Enforce `break` or `return` in `switch` cases Source: https://alibaba.github.io/p3c/%E7%BC%96%E7%A8%8B%E8%A7%84%E7%BA%A6/%E6%8E%A7%E5%88%B6%E8%AF%AD%E5%8F%A5 In a `switch` block, each `case` must either terminate with `break`/`return` or have a comment explaining the fall-through. A `default` statement is mandatory and should be placed last, even if empty. ```java switch (variable) { case 1: // Fall through to case 2 case 2: break; default: // Default logic } ``` -------------------------------- ### Optimize Regex Performance with Pre-compilation (Java) Source: https://alibaba.github.io/p3c/%E5%BC%82%E5%B8%B8%E6%97%A5%E5%BF%97/%E5%85%B6%E4%BB%96 Pre-compiling regular expressions using `Pattern.compile()` significantly improves matching speed. Avoid compiling patterns repeatedly within method bodies. ```java import java.util.regex.Pattern; // Recommended: Compile pattern once outside the method if used multiple times // Pattern pattern = Pattern.compile("your_regex_rule"); // Avoid this inside methods if the pattern is constant and reused: // void someMethod() { // Pattern pattern = Pattern.compile("your_regex_rule"); // // ... use pattern ... // } ``` -------------------------------- ### TODO and FIXME Comments in Java Source: https://alibaba.github.io/p3c/%E7%BC%96%E7%A8%8B%E8%A7%84%E7%BA%A6/%E6%B3%A8%E9%87%8A%E8%A7%84%E7%BA%A6 Outlines the use of special comment markers, TODO and FIXME, for tracking code enhancements and known issues. These comments should include the marker, the author, the date, and optionally an estimated completion date, facilitating code maintenance and issue resolution. ```java public class IssueTracker { // TODO (John Doe, 2023-10-27): Implement user authentication module. [Estimated completion: 2023-11-10] public void setupSecurity() { // ... incomplete implementation ... } // FIXME (Jane Smith, 2023-10-26): Calculation is incorrect for edge cases. Needs immediate correction. public double calculatePrice(double base, double tax) { // ... buggy implementation ... return base * tax; // Incorrect logic } } ``` -------------------------------- ### Placeholder Debug Logging (Java) Source: https://alibaba.github.io/p3c/%E5%BC%82%E5%B8%B8%E6%97%A5%E5%BF%97/%E6%97%A5%E5%BF%97%E8%A7%84%E7%BA%A6 Utilize placeholder arguments in logger methods for debug, trace, and info levels. This prevents the creation of log messages if the logging level is set higher, optimizing performance by avoiding unnecessary string operations and object conversions. ```java logger.debug("Processing trade with id: {} and symbol : {} ", id, symbol); ``` -------------------------------- ### Java Service and DAO Naming Convention (Impl Suffix) Source: https://alibaba.github.io/p3c/%E7%BC%96%E7%A8%8B%E8%A7%84%E7%BA%A6/%E5%91%BD%E5%90%8D%E9%A3%8E%E6%A0%BC For Service and DAO classes, the implementation class should be distinguished from the interface by appending 'Impl' to the interface name. ```java // Interface: public interface CacheService {} // Implementation: public class CacheServiceImpl implements CacheService {} ``` -------------------------------- ### Java Constant Naming Conventions (UPPERCASE_SNAKE_CASE) Source: https://alibaba.github.io/p3c/%E7%BC%96%E7%A8%8B%E8%A7%84%E7%BA%A6/%E5%91%BD%E5%90%8D%E9%A3%8E%E6%A0%BC Constants should be named in all capital letters, with words separated by underscores, ensuring a complete and clear semantic expression. ```java public static final int MAX_STOCK_COUNT = 100; ```