31 - 编码规范 - 命名与注释

2021-09-01  本文已影响0人  舍是境界

命名

  1. 命名多长最合适?
  1. 利用上下文简化命名
public class User {
  private String userName;
  private String userPassword;
  private String userAvatarUrl;
  //...
}
User user = new User();
user.getName(); // 借助user对象这个上下文
public void uploadUserAvatarImageToAliyun(String userAvatarImageUri);
//利用上下文简化为:
public void uploadUserAvatarImageToAliyun(String imageUri);
  1. 命名要可读、可搜索
  1. 如何命名接口和抽象类?

注释

  1. 注释到底该写什么?
/**
* (what) Bean factory to create beans. 
* 
* (why) The class likes Spring IOC framework, but is more lightweight. 
*
* (how) Create objects from different sources sequentially:
* user specified object > SPI > configuration > default object.
*/
public class BeansFactory {
  // ...
}
public boolean isValidPasword(String password) {
  // check if password is null or empty
  if (StringUtils.isBlank(password)) {
    return false;
  }
  // check if the length of password is between 4 and 64
  int length = password.length();
  if (length < 4 || length > 64) {
    return false;
  }
    
  // check if password contains only a~z,0~9,dot
  for (int i = 0; i < length; ++i) {
    char c = password.charAt(i);
    if (!((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '.')) {
      return false;
    }
  }
  return true;
}
  1. 注释是不是越多越好?

小结

上一篇 下一篇

猜你喜欢

热点阅读