Java开发技巧之消除代码异味(6)

    作者:课课家教育更新于: 2016-02-03 13:52:15

    大神带你学编程,欢迎选课

      另一个例子

      让我们来看一下另外一个例子。在当前的系统中,有三种用户:常规用户,管理员和游客。

      常规用户必须每隔90天修改一次密码(更频繁也行)。管理员必须每30天修改一次密码。游客就不需要修改了。

    Java开发技巧之消除代码异味(6)_java编程_java开发_课课家

      常规用户跟管理员可以打印报表。

      先看一下当前的代码:

      class UserAccount {

      final static int USERTYPE_NORMAL = 0;

      final static int USERTYPE_ADMIN = 1;

      final static int USERTYPE_GUEST = 2;

      int userType;

      String id;

      String name;

      String password;

      Date dateOfLastPasswdChange;

      public boolean checkPassword(String password) {

      ...

      }

      }

      class Inventoryapp {

      void login(UserAccount userLoggingIn, String password) {

      if (userLoggingIn.checkPassword(password)) {

      GregorianCalendar today = new GregorianCalendar();

      GregorianCalendar expiryDate = getAccountExpiryDate(userLoggingIn);

      if (today.after(expiryDate)) {

      //提示用户修改密码

      ...

      }

      }

      }

      GregorianCalendar getAccountExpiryDate(UserAccount account) {

      int passwordMaxAgeInDays = getPasswordMaxAgeInDays(account);

      GregorianCalendar expiryDate = new GregorianCalendar();

      expiryDate.setTime(account.dateOfLastPasswdChange);

      expiryDate.add(Calendar.DAY_OF_MONTH, passwordMaxAgeInDays);

      return expiryDate;

      }

      int getPasswordMaxAgeInDays(UserAccount account) {

      switch (account.getType()) {

      case UserAccount.USERTYPE_NORMAL:

      return 90;

      case UserAccount.USERTYPE_ADMIN:

      return 30;

      case UserAccount.USERTYPE_GUEST:

      return Integer.MAX_VALUE;

      }

      }

      void printReport(UserAccount currentUser) {

      boolean canPrint;

      switch (currentUser.getType()) {

      case UserAccount.USERTYPE_NORMAL:

      canPrint = true;

      break;

      case UserAccount.USERTYPE_ADMIN:

      canPrint = true;

      break;

      case UserAccount.USERTYPE_GUEST:

      canPrint = false;

      }

      if (!canPrint) {

      throw new SecurityException("You have no right");

      }

      //打印报表

      }

      }

课课家教育

未登录