搞java的同学们可能对无副作用这个概念比较陌生,这是函数式编程中的一个概念,无副作用的意思就是: 一个函数(java里是方法)的多次调用中,只要输入参数的值相同,输出结果的值也必然相同,并且在这个函数执行过程中不会改变程序的任何外部状态(比如全局变量,对象中的属性,都属于外部状态),也不依赖于程序的任何外部状态。

    比如下面的两个方法,就可以认为是无副作用的。

/**
 * 
 * @author leo
 *
 */
public class NoSideEffect {
    
    public static int add(int a, int b) {
        return a+b;
    }
    
    public boolean isEmpty(String s) {
        if (s == null || s.trim().length() == 0) {
            return true;
        } 
        return false;
    }
}

下面是有副作用的例子:

/**
 * 
 * @author leo
 *
 */
public class HasSideEffect {

    public int baseValue;
    
    public int getCount(int addtion) {
        return baseValue + addtion;
    }
}

    无副作用的要求可以很严格,在Fp(functional programing)的语言如lisp clojure中,无副作用的方法中连print都不能有,因为他们认为连屏幕也是外部状态,我个人觉得在写java的无副作用代码时,可以放宽一点,这个度可以自己把握,自己用着爽就ok。

    “线程安全”是java中一个比较常见的概念,线程安全的类,是说不管多少个线程并发访问这个对象,都不会发生不可预期的错误,他们的表现跟单线程访问时一样,是安全可靠的。 无副作用和线程安全的概念有相似之处,无副作用的方法,一定是线程安全的,这两个概念都能够帮助写出并发友好的代码,无副作用的编程还有一个好处,代码会很清爽,因为这个方法里的代码只跟输入输出有关系, 习惯了写无副作用的代码,能够设计出更稳健的程序。 大家可以想象,如果一个系统的代码,到处是状态,到处有千丝万缕的联系,这个系统的可维护性会是怎么样的,写过几年代码的人,可能都会碰到过这种让人头疼的项目。

下面介绍几点我个人积累的关于java无副作用编程的经验:

1. 使用静态方法

    我经常把一些常用的工具方法,甚至小项目中的业务方法写成utils类的静态方法,这些方法尽量写成无副作用的,这样的结果是,数据和操作分开,我感觉用起来比较好。

  1 public class AgentUtils {
  2 
  3     private static long lastMsgIdTime = 0L;
  4 
  5     public static synchronized String createNewMsgId(String clientId) {
  6         long now = System.currentTimeMillis();
  7         if (now <= lastMsgIdTime) {
  8             now = lastMsgIdTime + 1;
  9         }
 10         Date nowTime = new Date(now);
 11         String timeStr = DateFormatUtils.format(nowTime, "yyyyMMddHHmmssSSS");
 12         lastMsgIdTime = now;
 13         return clientId + "_" + timeStr;
 14     }
 15 
 16     public static TASK_REPORT_req createTaskReportAndUpdateLocalState(TASK_ASSIGN_req task, WorkItemState workItemState) {
 17         TASK_REPORT_req req = new TASK_REPORT_req(MsgType.TASK_REPORT);
 18         req.imei = task.imei;
 19         req.taskId = task.taskId;
 20         req.testType = task.testType;
 21         req.workItemState = workItemState;
 22         TaskQueue.updateLocalTestWorkState(req.taskId, req.imei, workItemState);
 23         return req;
 24     }
 25 
 26 //    private static Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss:SSS").create();
 27 
 28     public static Meta getMeta(String message) {
 29         Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss:SSS").create();
 30         BaseMsg warp = gson.fromJson(message, BaseMsg.class);
 31         return warp.meta;
 32     }
 33 
 34     public static Gson getGson() {
 35         Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss:SSS").create();
 36         return gson;
 37     }
 38 
 39     /**
 40      * @param LocalOrRemote 0 :local 1:remote
 41      * @param serverApkPath
 42      * @return
 43      */
 44     public static String downloadAPK(int LocalOrRemote, String serverApkPath, String taskId) throws IOException {
 45         File src = new File(serverApkPath);
 46         String localFileName = buildFullPath(AgentConf.i.apk_file_base_dir, taskId + "_" + src.getName());
 47         
 48         //使用scp实现下载
 49         if (LocalOrRemote == 0) {
 50             FileUtils.copyFileToDirectory(src, new File(AgentConf.i.apk_file_base_dir));
 51             return localFileName;
 52         }
 53         //remote 使用scp实现下载
 54         boolean isShellSuccess = false;
 55 
 56         String shell = AgentConf.i.apk_download_cmd + " " + AgentConf.i.server_ip + " " + serverApkPath + " " + localFileName;
 57         AgentMain.log.info("exec shell:" + shell);
 58         int returncode;
 59         try {
 60             returncode = Runtime.getRuntime().exec(shell).waitFor();
 61         } catch (InterruptedException e) {
 62             e.printStackTrace();
 63             return null;
 64         }
 65         AgentMain.log.info("shell returncode:" + returncode);
 66 
 67         isShellSuccess = returncode == 0;
 68 
 69         // 检查是否成功,修改queue中状态
 70         if (isShellSuccess) {
 71             return localFileName;
 72         } else {
 73             return null;
 74         }
 75     }
 76     /**
 77      * 
 78      * @param LocalOrRemote  0 :local 1:remote
 79      * @param localReprotPaht
 80      * @param serverReportPath
 81      * @throws IOException
 82      */
 83     
 84     public static void uploadReport(int LocalOrRemote, String localReprotPaht, String serverReportPath) throws IOException {
 85         //使用scp实现下载
 86         if (LocalOrRemote == 0) {
 87             FileUtils.copyFile(new File(localReprotPaht), new File(serverReportPath));
 88             return;
 89         }
 90         //remote 使用scp实现下载
 91 
 92         String shell = AgentConf.i.report_upload_cmd + " " + AgentConf.i.server_ip + " " + localReprotPaht + " " + serverReportPath;
 93         AgentMain.log.info("exec shell:" + shell);
 94         int returncode;
 95         try {
 96             returncode = Runtime.getRuntime().exec(shell).waitFor();
 97         } catch (InterruptedException e) {
 98             throw new IOException(e.getMessage(), e);
 99         }
100         AgentMain.log.info("shell returncode:" + returncode);
101         return;
102     }
103 }
View Code

相关文章:

  • 2021-12-03
  • 2021-08-16
  • 2021-12-18
  • 2021-10-03
  • 2022-12-23
  • 2023-01-02
猜你喜欢
  • 2021-11-26
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-11
相关资源
相似解决方案