Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the coding rules of Java function

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

Editor to share with you what the coding rules of the Java function are, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!

Internal function parameters use basic types as much as possible

Case 1: internal function parameters use basic types as much as possible

Phenomenon description:

/ / call code double price = 5.1D _ int number = 9 ~ * double total = calculate (price, number); / / calculate the amount function private double calculate (Double price, Integer number) {return price * number;}

Recommended proposal:

/ / call code double price = 5.1D _ int number = 9 ~ * double total = calculate (price, number); / / calculate the amount function private double calculate (double price, int number) {return price * number;}

Case 2: the return value of the internal function uses the basic type as much as possible

Phenomenon description:

/ / get the total order function public double getOrderAmount (List productList) {double amount = 0.0D; for (Product product: productList) {if (Objects.isNull (product) | | Objects.isNull (product.getPrice ()) | | Objects.isNull (product.getNumber ()) {continue;} amount + = calculate (product.getPrice (), product.getNumber ());} return amount } / / calculate the amount function private Double calculate (double price, double number) {return price * number;}

Recommended proposal:

/ / get the total order function public double getOrderAmount (List productList) {double amount = 0.0D; for (Product product: productList) {if (Objects.isNull (product) | | Objects.isNull (product.getPrice ()) | | Objects.isNull (product.getNumber ()) {continue;} amount + = calculate (product.getPrice (), product.getNumber ());} return amount } / / calculate the amount function private double calculate (double price, double number) {return price * number;}

This is just an example of this phenomenon, and a better way is to use Stream programming.

Main income

Internal functions try to use basic types to avoid packing and unpacking implicitly encapsulated types.

The parameter of the internal function uses the basic type, and the null pointer judgment of the parameter of the internal function is avoided grammatically.

The return value of the internal function uses the basic type, which syntactically avoids the null pointer judgment of the return value of the calling function.

Try to avoid returning arrays and lists as null

Case 1: try to avoid returning an array of null, causing unnecessary null pointer judgment.

Phenomenon description:

/ / call code UserVO [] users = queryUser (); if (Objects.nonNull (users)) {for (UserVO user: users) {/ / process user information}} / / query user function private UserVO [] queryUser () {/ / query user list List userList = userDAO.queryAll (); if (CollectionUtils.isEmpty (userList)) {return null } / / convert user array UserVO [] users = new UserVO [userList.size ()]; for (int I = 0; I)

< userList.size(); i++) { UserDO user = userList.get(i); users[i] = new UserVO(); users[i].setId(user.getId()); users[i].setName(user.getName()); } // 返回用户数组 return users;} 建议方案: // 调用代码UserVO[] users = queryUser();for (UserVO user : users) { // 处理用户信息}// 查询用户函数private UserVO[] queryUser() { // 查询用户列表 List userList = userDAO.queryAll(); if (CollectionUtils.isEmpty(userList)) { return new UserVO[0]; } // 转化用户数组 UserVO[] users = new UserVO[userList.size()]; for (int i = 0; i < userList.size(); i++) { UserDO user = userList.get(i); users[i] = new UserVO(); users[i].setId(user.getId()); users[i].setName(user.getName()); } // 返回用户数组 return users;} 案例二:尽量避免返回的列表为null,引起不必要的空指针判断 现象描述: // 调用代码List userList = queryUser();if (Objects.nonNull(userList)) { for (UserVO user : userList) { // 处理用户信息 }}// 查询用户函数private List queryUser(){ // 查询用户列表 List userList = userDAO.queryAll(); if(CollectionUtils.isEmpty(userList)) { return null; } // 转化用户列表 List userVoList = new ArrayList(userList.size()); for(UserDO user : userList) { UserVO userVo = new UserVO(); userVo.setId(user.getId()); userVo.setName(user.getName()); userVoList.add(userVo); } // 返回用户列表 return userVoList;} 建议方案: // 调用代码List userList = queryUser();for (UserVO user : userList) { // 处理用户信息 }// 查询用户函数private List queryUser(){ // 查询用户列表 List userList = userDAO.queryAll(); if(CollectionUtils.isEmpty(userList)) { return Collections.emptyList(); } // 转化用户列表 List userVoList = new ArrayList(userList.size()); for(UserDO user : userList) { UserVO userVo = new UserVO(); userVo.setId(user.getId()); userVo.setName(user.getName()); userVoList.add(userVo); } // 返回用户列表 return userVoList;} 主要收益 保证返回的数组和列表不为null, 避免调用函数的空指针判断。 封装函数传入参数 案例一:当传入参数过多时,应封装为参数类 Java规范不允许函数参数太多,不便于维护也不便于扩展。 现象描述: // 修改用户函数public void modifyUser(Long id, String name, String phone, Integer age, Integer sex, String address, String description) { // 具体实现逻辑} 建议方案: // 修改用户函数public void modifyUser(User user) { // 具体实现内容}// 用户类@Getter@Setter@ToStringprivate class User{ private Long id; private String name; private String phone; private Integer age; private Integer sex; private String address; private String description;}当传入成组参数时,应封装为参数类 既然参数成组出现,就需要封装一个类去描述这种现象。 现象描述: // 获取距离函数public double getDistance(double x1, double y1, double x2, double y2) { // 具体实现逻辑} 建议方案: // 获取距离函数public double getDistance(Point point1, Point point2) { // 具体实现逻辑}// 点类@Getter@Setter@ToStringprivate class Point{ private double x; private double y;} 主要收益 封装过多函数参数为类,使函数更便于扩展和维护; 封装成组函数参数为类,使业务概念更明确更清晰。 尽量用函数替换匿名内部类的实现 Java匿名内部类的优缺点: 在匿名内部类(包括Lambda表达式)中可以直接访问外部类的成员,包括类的成员变量、函数的内部变量。正因为可以随意访问外部变量,所以会导致代码边界不清晰。 首先推荐用Lambda表达式简化匿名内部类,其次推荐用函数替换复杂的Lambda表达式的实现。 案例一:尽量用函数替换匿名内部类(包括Lambda表达式)的实现 现象描述: // 发送结算数据sendWorkerSettleData(WorkerPushDataType.CHECKER, () ->

{Date beginDate = DateUtils.addDays (currDate,-aheadDays); Date endDate = DateUtils.addDays (currDate, 1); return auditTaskDAO.statCheckerSettleData (beginDate, endDate);})

Recommended proposal:

/ / send settlement data sendWorkerSettleData (WorkerPushDataType.CHECKER, ()-> statCheckerSettleData (currDate, aheadDays)); / / Statistical acceptor settlement data function private List statCheckerSettleData (Date currDate, int aheadDays) {Date beginDate = DateUtils.addDays (currDate,-aheadDays); Date endDate = DateUtils.addDays (currDate, 1); return auditTaskDAO.statCheckerSettleData (beginDate, endDate);}

In fact, there is a simpler way. To calculate the start date and end date before calling the function sendWorkerSettleData (sending operator settlement data), you can directly use the function auditTaskDAO.statCheckerSettleData (beginDate, endDate) instead of anonymous inner class.

Case 2: split the complex anonymous inner class implementation interface into multiple function class interfaces

If the interface implemented by an anonymous inner class has little correlation between several functions, you can split the interface into several functional interfaces to facilitate the use of Lambda expressions.

Phenomenon description:

/ / clear expired data cleanExpiredData ("user log table", new CleanExpiredDataOperator () {@ Override public List queryExpiredDate (Integer remainDays) {return userDAO.queryExpiredDate (remainDays);} @ Override public void cleanExpiredData (Date expiredDate) {userDAO.cleanExpiredData (log);}}) / / clear expired data function private void cleanExpiredData (String tableName, CleanExpiredDataOperator, cleanExpiredDataOperator) {/ / function implementation code} / clear expired API interface CleanExpiredDataOperator {/ / query expiration date public List queryExpiredDate (Integer remainDays); / / clear expired data public void cleanExpiredData (Date expiredDate);}

Recommended proposal:

/ / clear expired data cleanExpiredData ("user log table", userDAO::queryExpiredDate,userDAO::cleanExpiredData); / / clear expired data function private void cleanExpiredData (String tableName, QueryExpiredDateOperator queryExpiredDateOperator, CleanExpiredDataOperator cleanExpiredDataOperator) {/ / function implementation code} / / query expiration date API interface QueryExpiredDateOperator {/ / query expiration date public List queryExpiredDate (Integer remainDays) } / / clear expired API interface CleanExpiredDataOperator {/ / clear expired data public void cleanExpiredData (Date expiredDate);}

Main income

Define functions and specify parameters, clearly defining the code boundaries of anonymous inner classes

Use Lambda expressions to simplify the implementation of anonymous inner classes and make the code more concise.

Using return to simplify unnecessary code

Case 1: delete unnecessary if

Phenomenon description:

/ / whether to pass the function public boolean isPassed (Double passRate) {if (Objects.nonNull (passRate) & & passRate.compareTo (PASS_THRESHOLD) > = 0) {return true;} return false;}

Recommended proposal:

/ / whether to pass the function public boolean isPassed (Double passRate) {return Objects.nonNull (passRate) & & passRate.compareTo (PASS_THRESHOLD) > = 0;}

Case 2: delete unnecessary else

Phenomenon description:

/ / settlement wage function public double settleSalary (Long workId, int workDays) {/ / process if (isQualified (workId)) {return settleQualifiedSalary (workDays) {return settleQualifiedSalary (workDays);} else {return settleUnqualifiedSalary (workDays);}}

Recommended proposal:

/ / settlement wage function public double settleSalary (Long workId, int workDays) {/ / process if (isQualified (workId)) {return settleQualifiedSalary (workDays) {return settleQualifiedSalary (workDays);} return settleUnqualifiedSalary (workDays);}

Case 3: delete unnecessary variables

Phenomenon description:

/ / query user function public List queryUser (Long id, String name) {UserQuery userQuery = new UserQuery (); userQuery.setId (id); userQuery.setName (name); List userList = userDAO.query (userQuery); return userList;}

Recommended proposal:

/ / query user function public List queryUser (Long id, String name) {UserQuery userQuery = new UserQuery (); userQuery.setId (id); userQuery.setName (name); return userDAO.query (userQuery);}

Main income

Simplify unnecessary code to make it look cleaner

Optimize code using temporary variables

In some code, you will often see the writing of a.getB (). GetC (). GetN (), let's call it "cascading calls to functions", the code is not robust and readable. Suggestion: put an end to the cascade call of the function, split it with temporary variables, and check the null pointer of the object.

Case 1: using temporary variables to clarify logic

Phenomenon description:

/ / whether the Tuhao user function private boolean isRichUser (User user) {return Objects.nonNull (user.getAccount ()) & & Objects.nonNull (user.getAccount (). GetBalance ()) & & user.getAccount (). GetBalance (). CompareTo (RICH_THRESHOLD) > = 0;}

This is a favorite of streamlined code control, but the readability is too poor.

Recommended proposal:

/ / whether Tuhao user function private boolean isRichUser (User user) {/ / get user account UserAccount account = user.getAccount (); if (Objects.isNull (account)) {return false;} / / get user balance Double balance = account.getBalance (); if (Objects.isNull (balance)) {return false } / / compare user balance return balance.compareTo (RICH_THRESHOLD) > = 0;}

This scheme increases the number of lines of code, but the logic is clearer.

Sometimes, when the simplicity and readability of the code conflict, individuals prefer to retain the readability of the code.

Case 2: using temporary variables to simplify code

Phenomenon description:

/ / build the user function public UserVO buildUser (UserDO user) {UserVO vo = new UserVO (); vo.setId (user.getId ()); vo.setName (user.getName ()); if (Objects.nonNull (user.getAccount () {vo.setBalance (user.getAccount (). GetBalance ()); vo.setDebt (user.getAccount (). GetDebt ());} return vo;}

This is probably written in order to save a temporary variable.

Recommended proposal:

/ / build user functions public UserVO buildUser1 (UserDO user) {UserVO vo = new UserVO (); vo.setId (user.getId ()); vo.setName (user.getName ()); UserAccount account = user.getAccount (); if (Objects.nonNull (account)) {vo.setBalance (account.getBalance ()); vo.setDebt (account.getDebt ());} return vo;}

Main income

Use temporary variables to clarify the logic and make the business logic clearer.

The use of temporary variables to simplify the code, the name of the variable can tell its meaning, reducing a lot of useless code

If getting the function is complex and time-consuming, the use of temporary variables can improve the running efficiency.

The use of temporary variables to avoid cascade calls of functions can effectively prevent null pointer exceptions.

Keep only the parameters needed by the function

In some code, you will often see the writing of a.getB (). GetC (). GetN (), let's call it "cascading calls to functions", the code is not robust and readable. Suggestion: put an end to the cascade call of the function, split it with temporary variables, and check the null pointer of the object.

Case 1: delete redundant parameters

Phenomenon description:

/ / modify the user status function private void modifyUserStatus (Long userId, Integer status, String unused) {userCache.modifyStatus (userId, status); userDAO.modifyStatus (userId, status); where the unused parameter is a useless parameter. Suggested solution: / / modify the user status function private void modifyUserStatus (Long userId, Integer status) {userCache.modifyStatus (userId, status); userDAO.modifyStatus (userId, status);}

Case 2: replacing objects with attributes

Phenomenon description:

/ / delete the user function private void deleteUser (User user) {userCache.delete (user.getId ()); userDAO.delete (user.getId ());}

Recommended proposal:

/ / delete the user function private void deleteUser (Long userId) {userCache.delete (userId); userDAO.delete (userId);}

Recommended proposal:

When calling a function, the parameter object does not need to be specially built, and the function uses more than 3 properties, so you do not have to use this rule.

Main income

Keep only the parameters needed by the function, clarify the parameters that need to be assigned during the call, and avoid having to construct some useless parameters during the call.

These are all the contents of the article "what are the coding rules of Java functions?" Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report