<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Wen Tao on Medium]]></title>
        <description><![CDATA[Stories by Wen Tao on Medium]]></description>
        <link>https://medium.com/@taowen?source=rss-baba231b6963------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*5Bv4f7MY89L4QlvC.</url>
            <title>Stories by Wen Tao on Medium</title>
            <link>https://medium.com/@taowen?source=rss-baba231b6963------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 16:33:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@taowen/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[从 Smalltalk 到 Claude Code — 软件进化的新范式]]></title>
            <link>https://medium.com/software-engineering-problems/%E4%BB%8E-smalltalk-%E5%88%B0-claude-code-%E8%BD%AF%E4%BB%B6%E8%BF%9B%E5%8C%96%E7%9A%84%E6%96%B0%E8%8C%83%E5%BC%8F-197c578f74bb?source=rss-baba231b6963------2</link>
            <guid isPermaLink="false">https://medium.com/p/197c578f74bb</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Wen Tao]]></dc:creator>
            <pubDate>Mon, 18 Aug 2025 05:51:25 GMT</pubDate>
            <atom:updated>2025-08-18T05:51:25.837Z</atom:updated>
            <content:encoded><![CDATA[<h3>从 Smalltalk 到 Claude Code — 软件进化的新范式</h3><h4><em>[背景音：咖啡馆环境音，键盘敲击声]</em></h4><p><strong>Alex</strong>: 嘿，Sam！好久不见，最近在搞什么？</p><p><strong>Sam</strong>: Alex！正好想找你聊聊。我最近在用 Claude Code，就是 Anthropic 出的那个命令行工具。你知道吗？用着用着，我突然想起了咱们以前讨论过的 Smalltalk…</p><p><strong>Alex</strong>: 当然记得！那个”代码即数据，数据即代码”的老古董？等等，你不会是想…</p><p><strong>Sam</strong>: 哈哈，你猜对了一半。你知道Smalltalk最革命性的地方是什么吗？</p><p><strong>Alex</strong>: 消息传递？对象导向？</p><p><strong>Sam</strong>: 不，是它彻底抹平了源代码和运行时的边界。在Smalltalk里，你不是在”编写”程序，而是在”雕塑”一个活着的系统。代码是数据，数据是代码，更重要的是 — — 编程环境本身也是可以被编程的数据。</p><p><strong>Alex</strong>: 这和Claude Code有什么关系？</p><p><strong>Sam</strong>: 来，我给你演示一下 Claude Code。但我要分两种模式给你看，你才能理解这种”一切皆数据”的理念如何在AI时代重生。</p><p><strong>Alex</strong>: 两种模式？</p><p><strong>Sam</strong>: 对，先看第一种，默认模式，需要用户确认每一步。<em>[键盘声]</em> 看，我现在输入：”帮我分析一下当前目录下所有 Python 文件的代码复杂度”。</p><pre>$ claude &quot;帮我分析一下当前目录下所有 Python 文件的代码复杂度&quot;</pre><pre>Claude: 我来帮您分析 Python 文件的代码复杂度。首先让我搜索一下有哪些文件。</pre><pre>工具调用: Bash<br>命令: find . -name &quot;*.py&quot; | head -5<br>是否执行？[Y/n]: y</pre><pre>输出:<br>./main.py<br>./utils/helper.py<br>./utils/parser.py<br>./models/user.py<br>./models/product.py</pre><pre>Claude: 找到了 Python 文件。现在我需要安装代码复杂度分析工具。</pre><pre>工具调用: Bash<br>命令: pip install radon<br>是否执行？[Y/n]: y</pre><pre>输出:<br>Successfully installed radon-5.1.0</pre><pre>Claude: 很好，现在执行复杂度分析。</pre><pre>工具调用: Bash<br>命令: radon cc . -s<br>是否执行？[Y/n]: y</pre><pre>输出:<br>main.py<br>    F 15:0 process_data - B (7)<br>    F 45:0 validate_input - A (3)<br>...</pre><p><strong>Alex</strong>: 这就是普通的对话式交互啊，一问一答。</p><p><strong>Sam</strong>: 对，现在看第二种模式 — 开启 bypass permission，不需要用户确认。</p><pre>$ claude --bypass-permission &quot;帮我分析一下当前目录下所有 Python 文件的代码复杂度&quot;</pre><pre>正在搜索 Python 文件...<br>$ find . -name &quot;*.py&quot; | wc -l<br>15</pre><pre>检查工具...<br>$ which radon<br>radon not found</pre><pre>安装分析工具...<br>$ pip install radon<br>Successfully installed radon-5.1.0</pre><pre>执行分析...<br>$ radon cc . -s<br>main.py<br>    F 15:0 process_data - B (7)<br>    F 45:0 validate_input - A (3)<br>...</pre><pre>分析完成。发现 3 个高复杂度函数需要重构。</pre><p><strong>Alex</strong>: 哇，这次是一气呵成，没有停顿！</p><p><strong>Sam</strong>: 注意看区别了吗？第二种模式里，Claude Code 就像在表演独角戏。它不是在和你对话，而是基于上一步的输出（stdout）来决定下一步做什么。</p><p><strong>Alex</strong>: <em>[若有所思]</em> 等等，这让我想起了Smalltalk的workspace…</p><p><strong>Sam</strong>: Exactly! 在Smalltalk里，你在workspace里写的每一行代码都是即时执行的，输出立即可见，然后你基于这个输出继续编写。Claude Code在bypass模式下做的是同样的事 — — 每一步的输出成为下一步的输入。</p><p><strong>Alex</strong>: 所以你是说每一步之间…</p><p><strong>Sam</strong>: 对！每两步之间，实际上是这样的流程：</p><pre>步骤1: find 命令<br>    ↓ (stdout: 文件列表)<br>LLM 分析输出，生成下一步参数<br>    ↓<br>步骤2: 检查 radon 是否存在<br>    ↓ (stdout: command not found)<br>LLM 分析输出，生成下一步参数<br>    ↓<br>步骤3: pip install radon<br>    ↓ (stdout: 安装成功)<br>LLM 分析输出，生成下一步参数<br>    ↓<br>步骤4: radon cc 执行分析</pre><p><strong>Alex</strong>: 所以本质上是 generate_params_by_llm() 在串联整个流程？</p><p><strong>Sam</strong>: Exactly！这就是Smalltalk开发模式的精髓 — — <strong>没有源代码和编译产物的区别</strong>。在传统开发中，你写源代码，编译成二进制，然后运行。但在Smalltalk里，你直接操作的就是运行中的对象。</p><p><strong>Alex</strong>: 而在Claude Code里…</p><p><strong>Sam</strong>: 在Claude Code里，LLM的提示词是文本，输出是文本，更关键的是 — — <strong>生成下一步提示词的规则也是文本</strong>！这完美对应了”一切皆数据”的理念。现在，如果我们把这个过程固化下来，去掉 LLM 调用，直接写成脚本会怎样？</p><pre>#!/bin/bash<br># analyze_complexity.sh - Claude Code 生成过程的固化版本</pre><pre># 步骤1: 搜索文件（原本由 LLM 决定的参数）<br>file_count=$(find . -name &quot;*.py&quot; | wc -l)<br>echo &quot;找到 $file_count 个 Python 文件&quot;</pre><pre># 步骤2: 检查工具（原本由 LLM 根据步骤1输出决定）<br>if ! command -v radon &amp;&gt; /dev/null; then<br>    echo &quot;安装分析工具...&quot;<br>    pip install radon<br>fi</pre><pre># 步骤3: 执行分析（原本由 LLM 根据步骤2输出决定）<br>radon cc . -s</pre><p><strong>Alex</strong>: <em>[恍然大悟]</em> 原来如此！Claude Code 不是在回答问题，而是在<strong>编写并执行一个程序</strong>！</p><p><strong>Sam</strong>: 更准确地说，不管你问什么问题，Claude Code 都在做两件事：</p><ol><li>给你答案</li><li>把制作这个答案的程序也写出来了</li></ol><p>这就是Smalltalk式的开发 — — 你不是在”使用”工具，而是在”塑造”工具。每次交互都在改变系统本身。</p><p><strong>Alex</strong>: 所以当我问”帮我分析代码复杂度”时，我其实是在无意识地让 Claude Code 生成了一个”代码复杂度分析软件”？</p><p><strong>Sam</strong>: Bingo！而且最妙的是，你根本不需要说”生成xxx软件”这样的提示词。你只是在正常提问，软件就自然生成了。</p><p><strong>Alex</strong>: 等等，你是说… <em>[咖啡杯放下的声音]</em> 用户以为自己在对话，实际上是在无意识地编写程序？</p><p><strong>Sam</strong>: Exactly！而且这让我想到一个更深层的问题。想象一下，如果 Claude Code 能记住你之前的操作会怎样？</p><p><strong>Alex</strong>: 你是说像这样？</p><p><strong>Sam</strong>: 对，假设有这样的场景：</p><pre>理想场景（目前Claude Code还做不到）：<br>$ claude &quot;再分析一次代码复杂度&quot;</pre><pre>系统：检测到您刚才执行过类似操作，直接使用已安装的工具...<br>$ radon cc . -s --json &gt; complexity_report.json<br>$ python -c &quot;<br>import json<br>with open(&#39;complexity_report.json&#39;) as f:<br>    data = json.load(f)<br>    # 生成可视化报告...<br>&quot;</pre><p><strong>Alex</strong>: 哇，如果它能记住并优化流程，还加了 JSON 输出和可视化，那就太强了！</p><p><strong>Sam</strong>: 这就引出了我的想法。虽然 Claude Code 现在还是无状态的，每次都要重新开始，但它展示了一个可能性 — — AI 在实时生成程序。那如果我们把这个模式推广，再加上”记忆”能力呢？</p><p><strong>Alex</strong>: 推广到哪里？</p><p><strong>Sam</strong>: 想想看，现在 AI 和软件结合主要有两种模式。我画个图你就明白了：<em>[纸笔声]</em></p><pre>模式1：嫁接式 AI（Grafted AI）<br>┌─────────────────────────────┐<br>│   传统应用（功能固定）        │<br>│  ┌──────┐ ┌──────┐ ┌──────┐│<br>│  │功能A │ │功能B │ │功能C ││<br>│  └──────┘ └──────┘ └──────┘│<br>│                             │<br>│  ┌─────────────────────┐   │<br>│  │  💬 AI助手(后加的)   │   │ ← 像贴膏药<br>│  └─────────────────────┘   │<br>└─────────────────────────────┘<br>问题：两个世界，互不理解<br>案例：Notion AI、Office Copilot、Adobe Firefly</pre><p><strong>Alex</strong>: 对，Notion AI、Office Copilot 都是这样，在原有界面上硬加个对话框。</p><p><strong>Sam</strong>: 体验如何？</p><p><strong>Alex</strong>: 挺割裂的。我在 AI 对话框里完成了任务，但不知道对应按钮在哪。用按钮操作时，AI 又不知道我做了什么。就像左手不知道右手在干嘛。</p><p><strong>Sam</strong>: 那第二种模式呢：</p><pre>模式2：对话式 AI（Conversational AI）<br>┌─────────────────────────────┐<br>│     纯对话界面              │<br>│  ┌─────────────────────┐   │<br>│  │                     │   │<br>│  │   💬 ChatGPT        │   │<br>│  │                     │   │<br>│  └─────────────────────┘   │<br>│                             │<br>│  用户：&quot;创建表格&quot;            │<br>│  AI：&quot;好的，这是表格...&quot;     │<br>└─────────────────────────────┘<br>问题：效率低，缺少直观性<br>案例：ChatGPT、Claude、Gemini、Perplexity</pre><p><strong>Alex</strong>: 这个也有问题，什么都要打字描述，明明点个按钮更快。而且生成的东西没地方放，只能复制粘贴。</p><p><strong>Sam</strong>: Exactly！所以我在想第三种模式 — — 进化式 AI。不是把 AI 嫁接到应用上，也不是让应用变成纯对话，而是让应用从对话中自然生长出来。想象这样一个场景…<em>[翻页声]</em></p><pre>场景：一个自由职业者需要管理财务</pre><pre>传统方式：<br>1. 下载一个记账 App<br>2. 学习这个 App 的界面和概念<br>3. 强迫自己适应它的流程<br>4. 发现不合适，换另一个 App<br>5. 重新学习...</pre><pre>新方式：打开一个空白界面，只有一个对话框</pre><p><strong>Alex</strong>: 空白界面？那怎么用？</p><p><strong>Sam</strong>: 看着，这就是魔法开始的地方：</p><pre>Day 1: 纯对话<br>用户: &quot;记一下，今天客户A付了5000块项目款&quot;<br>系统: &quot;已记录：收入5000元，来源：客户A，类型：项目款&quot;</pre><pre>用户: &quot;还有，午饭花了45&quot;<br>系统: &quot;已记录：支出45元，类型：餐饮&quot;</pre><pre>Day 3: 系统注意到模式<br>用户: &quot;客户B付了3000&quot;<br>系统: &quot;已记录。我注意到您经常记录客户付款，需要我创建一个快捷方式吗？&quot;<br>[显示一个简单表单雏形]</pre><pre>Day 7: 界面开始生成<br>用户打开应用，看到：<br>- 对话框依然在最显眼的位置<br>- 但旁边出现了&quot;快速记账&quot;按钮<br>- 点击后是系统根据历史对话生成的表单</pre><pre>Day 30: 应用成型<br>[完整的个性化财务管理界面]<br>- 专门的客户收款管理（因为用户经常记录）<br>- 简化的支出记录（因为用户只记录金额和大类）<br>- 月度收支对比（系统发现用户月底会问&quot;这个月赚了多少&quot;）<br>- 对话框依然保留，处理所有特殊需求</pre><p><strong>Alex</strong>: 等等，所以界面是根据使用习惯”长”出来的？</p><p><strong>Sam</strong>: 对！这就是我说的 GrowBlank — — 从空白成长为应用。不是预先设计，而是使用中进化。</p><p><strong>Sam</strong>: 没错！这解决了软件开发的核心悖论。你知道为什么那么多项目失败吗？</p><p><strong>Alex</strong>: 需求不清？</p><p><strong>Sam</strong>: 不只是不清，是<strong>根本不可能清楚</strong>！我给你讲个真事。上个月我们公司要做个内部工具，产品经理写了 30 页需求文档。你猜怎么着？</p><p><strong>Alex</strong>: 上线后全改了？</p><p><strong>Sam</strong>: 都没等到上线！开发到一半，业务部门说：”这不是我们要的。”你知道最讽刺的是什么吗？他们也说不清要什么，只能说：”等我用了才知道。”</p><p><strong>Alex</strong>: 啊，经典的”我不知道我要什么，但我知道这不是”综合征。</p><p><strong>Sam</strong>: 对！但 GrowBlank 模式下，这不是 bug，是 feature！用户不需要提前知道自己要什么，他们只需要<strong>开始使用</strong>。系统会从使用中学习并适应。</p><p><strong>Alex</strong>: 等等，我想到个问题。<em>[椅子挪动声]</em> 如果每次都是 AI 生成，怎么保证一致性？比如今天生成个蓝色按钮，明天会不会变成红色？</p><p><strong>Sam</strong>: 好问题！让我用个简单的比喻。你知道为什么你每天起床还认识自己的房间吗？</p><p><strong>Alex</strong>: 因为东西都在固定的位置？</p><p><strong>Sam</strong>: 对，但更深层的原因是 — — 你的房间是持续存在的，不是每天重新生成的。GrowBlank 也是这个原理。</p><p><strong>Alex</strong>: 怎么做到的？</p><p><strong>Sam</strong>: 这就回到了Smalltalk的核心理念。还记得它的 “image” 概念吗？不是图片，而是整个运行系统的完整快照，包括所有对象、状态、甚至正在执行的代码。</p><p><strong>Alex</strong>: 就像… 虚拟机的快照？</p><p><strong>Sam</strong>: 不，比虚拟机快照更深刻。虚拟机快照只是保存了内存状态，但Smalltalk的image保存的是<strong>整个世界</strong> — — 包括你的代码、数据、正在debug的断点、甚至你上次写了一半的方法。</p><p><strong>Alex</strong>: 所以源代码在哪里？</p><p><strong>Sam</strong>: 这就是关键 — — <strong>没有独立的源代码文件</strong>！源代码就存在于image里，作为对象的一部分。你修改一个方法，就是在修改一个活着的对象。这就是为什么Smalltalk的程序不是”启动”的，而是”继续”的。</p><p><strong>Alex</strong>: 等等，这意味着…</p><p><strong>Sam</strong>: 对！编程环境（IDE）、你的程序、甚至编译器，都是同一个image里的对象。你可以在运行时修改IDE的行为，可以调试调试器本身，可以给编译器打补丁。一切都是活的、可塑的数据。</p><p><strong>Alex</strong>: 这和GUI有什么关系？</p><p><strong>Sam</strong>: GUI本身不就是代码吗？一个按钮、一个窗口、一个菜单 — — 在Smalltalk里，这些都是对象，都是数据，都可以被即时修改。你可以右键点击任何UI元素，直接修改它的代码，立即看到效果。没有”编译-运行-测试”的循环，只有持续的雕塑。</p><p><strong>Alex</strong>: 所以GrowBlank借鉴了这个思想？</p><p><strong>Sam</strong>: Exactly！看这个例子：</p><pre>// 用户第一次说&quot;记录支出&quot;时，系统生成并保存了这个组件<br>const ExpenseForm = {<br>  id: &quot;form_expense_001&quot;,<br>  version: 3,  // 已经进化了3次</pre><pre>  // 组件DNA：定义外观和行为<br>  schema: {<br>    amount: { type: &quot;number&quot;, required: true },<br>    category: {<br>      type: &quot;select&quot;,<br>      options: [&quot;餐饮&quot;, &quot;交通&quot;, &quot;购物&quot;, &quot;其他&quot;]<br>    }<br>  },</pre><pre>  // 进化历史<br>  evolution: [<br>    &quot;创建基础表单&quot;,<br>    &quot;添加分类字段&quot;,<br>    &quot;智能预设选项&quot;<br>  ],</pre><pre>  // 用户偏好<br>  preferences: {<br>    color: &quot;blue&quot;,<br>    position: &quot;top-right&quot;,<br>    hotkey: &quot;Cmd+E&quot;<br>  }<br>}</pre><p><strong>Alex</strong>: 哦！所以每个组件都是一个持久化的”活物”，有记忆、会成长，但不会突变？</p><p><strong>Sam</strong>: Exactly！这就是Smalltalk开发模式在AI时代的重生。在Smalltalk里，你可以inspect任何对象，修改它的属性，立即看到变化。在GrowBlank里，用户通过自然语言做同样的事：”把那个表单的按钮改成绿色”，系统就会更新 preferences，这个改变会永久保存。</p><p><strong>Alex</strong>: 所以用户在不知不觉中…</p><p><strong>Sam</strong>: 在进行Smalltalk式的开发！他们在操作活着的对象，塑造运行中的系统，只是用自然语言代替了Smalltalk的消息传递语法。</p><p><strong>Alex</strong>: 嗯… <em>[思考]</em> 但这不会导致过度定制吗？每个用户都有自己独特的应用，没法标准化，没法培训新员工…</p><p><strong>Sam</strong>: 这恰恰是传统思维的误区！为什么一定要标准化？我问你，你用的 VS Code 配置和我的一样吗？</p><p><strong>Alex</strong>: 当然不一样，我有自己的插件、快捷键、主题…</p><p><strong>Sam</strong>: 那影响你们团队协作了吗？</p><p><strong>Alex</strong>: …没有。反而每个人都很高效，因为工具适合自己的习惯。</p><p><strong>Sam</strong>: Bingo！GrowBlank 的哲学是：<strong>标准化数据，个性化界面</strong>。团队共享同一套数据模型，但每个人可以有自己的交互方式。</p><p><strong>Alex</strong>: 有意思… 让我想想实际场景。<em>[喝咖啡声]</em> 比如说，一个创业公司，从零开始用 GrowBlank？</p><p><strong>Sam</strong>: 好例子！我来模拟一下这个过程。第一天，创始人 Alice 坐在电脑前：</p><pre>Alice: 记录一下，今天见了投资人 John，他对我们的产品很感兴趣</pre><pre>系统: 已记录会议笔记。需要设置后续提醒吗？</pre><pre>Alice: 好的，一周后提醒我跟进</pre><pre>[系统后台生成了一个简单的 CRM 种子]</pre><p><strong>Alex</strong>: 等等，系统怎么知道要往 CRM 方向进化？</p><p><strong>Sam</strong>: 它不需要知道！它只是响应使用模式。继续看：</p><pre>Day 3:<br>Alice: 显示所有投资人联系记录</pre><pre>系统: 找到 1 条记录：<br>- John (上次联系：2天前)<br>建议：是否要添加更多字段来追踪？比如投资阶段、金额范围？</pre><pre>Alice: 好主意，添加这些</pre><pre>[CRM 数据模型进化：添加了新字段]</pre><pre>Day 10:<br>Alice: 我需要跟踪每个投资人的状态</pre><pre>系统: 基于您的使用模式，我生成了一个看板视图：<br>[初次接触] → [跟进中] → [尽调] → [条款谈判] → [已完成]<br>需要调整阶段名称吗？</pre><pre>[CRM 获得了看板功能]</pre><p><strong>Alex</strong>: 妙啊，这就是个渐进式的 no-code 平台啊！</p><p><strong>Sam</strong>: 不，比 no-code 更进一步。No-code 你还得”设计”，拖拽组件，设置属性。GrowBlank 是 <strong>no-design</strong>，你只管用。</p><p><strong>Alex</strong>: 但是等一下，<em>[激动]</em> 如果 Alice 雇了一个销售 Bob，Bob 的使用习惯和 Alice 不同怎么办？</p><p><strong>Sam</strong>: 这个问题问得好！让我先给你看个简单的例子。你用过 Google Docs 的多人协作吧？</p><p><strong>Alex</strong>: 用过，多个人可以同时编辑文档。</p><p><strong>Sam</strong>: 对，但 Google Docs 只是让多人编辑同一个文档。GrowBlank 更进一步 — — 多人共同进化同一个应用。我来演示一下：</p><pre>场景：Bob 刚加入公司</pre><pre>Bob 第一天:<br>Bob: 显示所有客户<br>系统: 找到 3 个投资人记录（Alice 之前录入的）<br>Bob: 不对，我要看销售线索，不是投资人</pre><pre>系统: 理解了。您需要区分&quot;投资人&quot;和&quot;销售线索&quot;。<br>     建议创建两个独立模块：<br>     - 融资管理（Alice 主要使用）<br>     - 销售管理（您将主要使用）<br>     这样设置可以吗？</pre><pre>Bob: 好的</pre><pre>[系统开始分化：同一个应用内出现两条进化路径]</pre><p><strong>Alex</strong>: 哦，所以不是强行合并，而是允许分化？</p><p><strong>Sam</strong>: 对！就像细胞分化一样。继续看 Bob 的使用：</p><pre>Bob 继续使用:<br>Bob: 我需要批量导入潜在客户<br>系统: 正在为您生成批量导入功能...</pre><pre>[5分钟后，Alice 那边]<br>系统通知 Alice: Bob 刚刚触发了&quot;批量导入&quot;功能的生成。<br>              这个功能也可能对您的融资模块有用。<br>              要查看并采用吗？</pre><pre>Alice: 让我看看... 嗯，确实有用，我也要用来导入投资人名单</pre><p><strong>Alex</strong>: 所以功能可以跨模块”传播”？</p><p><strong>Sam</strong>: Exactly！这就是集体进化。每个人的创新都可能惠及他人，但不是强制的。系统会识别哪些模式是个人的，哪些是通用的：</p><pre>系统的模式识别：<br>- Bob 喜欢用键盘快捷键 → 个人偏好，只影响 Bob 的界面<br>- Bob 创建的&quot;跟进提醒&quot;功能 → 通用功能，推荐给全团队<br>- Alice 的投资人阶段划分 → 领域特定，只在融资模块使用<br>- 両人都需要的导出报表 → 提取为公共功能</pre><p><strong>Alex</strong>: <em>[兴奋地站起来]</em> 等等，我想到一个更大胆的想法！如果系统能跨公司学习呢？</p><p><strong>Sam</strong>: 有意思！我们可以只分享”进化路径”而不分享具体数据。想象一下，每个公司的应用进化就像是走迷宫，我们不需要知道迷宫长什么样（具体数据），只需要知道大家都是怎么走的（使用模式）。</p><p><strong>Alex</strong>: 哦！就像 Waze 导航，不需要知道每辆车里坐的是谁，只需要知道车流模式。</p><p><strong>Sam</strong>: 完美的类比！系统会分析匿名化的进化路径，发现通用模式。比如：80%的公司在前5天会添加分类系统，70%在2周后需要高级视图，90%在1个月后需要数据分析功能。</p><p><strong>Alex</strong>: 所以新公司加入时，系统可以基于这些模式提供建议？</p><p><strong>Sam</strong>: 对，但不是强制的模板。系统会说：”基于847家类似公司的经验，这些功能的采用率很高…”但每个公司还是会根据实际使用自然进化。</p><p><strong>Alex</strong>: 这简直是应用开发的 GitHub！不对，比 GitHub 更进一步，因为它是活的，会进化的！</p><p><strong>Sam</strong>: 而且解决了开源的一个大问题：你 clone 了别人的代码却改不动，因为你不理解设计决策。但在 GrowBlank 里，你 clone 的是进化路径，然后继续你自己的进化。</p><p><strong>Alex</strong>: <em>[坐下，深呼吸]</em> OK，让我冷静一下。这个愿景很美好，但技术挑战呢？</p><p><strong>Sam</strong>: 确实有挑战。最大的是<strong>意图理解的准确性</strong>。看这个例子：</p><pre>用户: 把昨天的数据删了</pre><pre>系统需要理解:<br>1. &quot;昨天&quot;是指哪个时区的昨天？<br>2. &quot;数据&quot;是指哪些数据？全部还是特定类型？<br>3. &quot;删了&quot;是真删除还是标记删除？<br>4. 用户权限是否允许？</pre><p><strong>Alex</strong>: 对，自然语言的歧义性。</p><p><strong>Sam</strong>: 我们的解决方案是<strong>渐进式确认</strong>。第一次遇到歧义，系统会询问。但它会记住你的偏好：</p><pre>第一次:<br>用户: 删除旧数据<br>系统: 请确认：&quot;旧数据&quot;是指：<br>     A) 30天前的数据<br>     B) 上个版本的数据<br>     C) 其他？<br>用户: A</pre><pre>第二次:<br>用户: 清理旧数据<br>系统: 基于您的习惯，准备删除30天前的数据（共1,234条）。确认？</pre><pre>第N次:<br>用户: 常规清理<br>系统: [直接执行30天数据清理]</pre><p><strong>Alex</strong>: 所以系统不只是学习功能，还学习用户的语言习惯？</p><p><strong>Sam</strong>: 对！每个用户/团队会逐渐形成自己的”方言”。比如在某个团队里，”跑一下”就是指运行测试套件，在另一个团队可能是指部署到测试环境。</p><p><strong>Alex</strong>: 这让我想到一个有趣的问题。如果每个人的应用都不同，那技能和创新如何共享？</p><p><strong>Sam</strong>: 这就引出了技能市场的概念！还记得Smalltalk的Parcels吗？你可以把一组对象打包，分享给其他人。GrowBlank里的技能就像是AI时代的Parcels — — 不只是代码，而是包含了使用模式、进化历史、用户偏好的完整”生命体”。</p><p><strong>Alex</strong>: 所以分享的不只是功能…</p><p><strong>Sam</strong>: 而是整个进化路径！就像Smalltalk社区分享的不只是类库，而是解决问题的完整思路和交互方式。用户可以选择多种分享方式 — 从开源免费到付费订阅，甚至企业定制。最棒的是，这个市场是自然形成的，由用户需求驱动。</p><p><strong>Alex</strong>: 等等，这不就变成了… 每个人都可以是软件供应商？</p><p><strong>Sam</strong>: Bingo！这就是去中心化的软件经济。看看完整的生态：</p><pre>GrowBlank Skills Market 首页</pre><pre>🔥 热门技能<br>├── 智能日程安排 (by Sarah) - 10K+ 安装<br>├── 客户跟进自动化 (by TechCorp) - 8K+ 安装<br>└── 财务报表生成器 (by 金融老王) - 5K+ 安装</pre><pre>💡 场景解决方案<br>├── &quot;初创公司工具包&quot; (15个技能组合) - $29/月<br>├── &quot;销售团队必备&quot; (8个技能组合) - $19/月<br>└── &quot;个人效率提升&quot; (6个技能组合) - $9/月</pre><pre>🎯 定制你的 GrowBlank<br>搜索技能：[_______________]<br>或描述需求：&quot;我需要管理客户投诉...&quot;</pre><p><strong>Alex</strong>: <em>[画图]</em> 让我理理… 所以整个生态系统是这样的：</p><pre>个人进化 → 团队进化 → 公司进化 → 行业模式 → 技能市场<br>    ↑                                              ↓<br>    └──────────────────────────────────────────────┘<br>                      （循环反馈）</pre><p><strong>Sam</strong>: 完美！而且每一层都在让下一次进化更快。新用户不是从零开始，而是站在巨人的肩膀上。</p><p><strong>Alex</strong>: 但是… <em>[皱眉]</em> 这会不会造成同质化？最后大家的应用都长得一样？</p><p><strong>Sam</strong>: 恰恰相反！生物进化告诉我们，即使从同一个祖先开始，在不同环境下也会进化出完全不同的形态。达尔文雀，你知道吧？</p><p><strong>Alex</strong>: 同一种雀，在不同岛屿进化出不同的喙？</p><p><strong>Sam</strong>: 对！GrowBlank 也一样。即使从同一个模板开始，不同公司的独特需求会驱动应用向不同方向进化。</p><pre>电商公司 → 进化出强大的库存管理<br>咨询公司 → 进化出复杂的时间追踪<br>媒体公司 → 进化出内容工作流</pre><p><strong>Alex</strong>: 而且这些特化的部分又可以回到技能市场…</p><p><strong>Sam</strong>: 形成良性循环！创新在边缘产生，然后传播到整体。</p><p><strong>Alex</strong>: <em>[看表]</em> 哇，不知不觉聊了两个小时了。这个想法真的可能改变软件行业！</p><p><strong>Sam</strong>: 你知道最让我兴奋的是什么吗？如果进化方向错了怎么办？</p><p><strong>Alex</strong>: 对啊，系统误解了用户意图，朝错误方向进化？</p><p><strong>Sam</strong>: 这就是为什么要保留”回滚”和”分支”能力，就像Git一样：</p><pre>进化树：<br>主干：当前稳定版本<br>├── 实验分支A：尝试新的交互方式<br>├── 实验分支B：探索不同的数据组织<br>└── 用户可随时切换、合并或放弃</pre><p><strong>Alex</strong>: 所以失败变成了可恢复的小实验？</p><p><strong>Sam</strong>: 对！而且每次”失败”都是学习。用户和系统互相学习，共同进化，像共生体一样。</p><p><strong>Alex</strong>: <em>[收拾东西]</em> 好了，我得走了。但在我走之前，一句话总结 GrowBlank？</p><p><strong>Sam</strong>: <strong>从使用中生长，而非从规划中构建。</strong></p><p><strong>Alex</strong>: 精辟！我的版本是：<strong>每个人都值得拥有为自己量身定制的软件。</strong></p><p><strong>Sam</strong>: 哈哈，都对！这就是 GrowBlank — — 让软件民主化，让每个人都成为自己软件的设计师，只是他们不需要知道自己在设计。</p><p><strong>Alex</strong>: 期待看到它改变世界。下次咱们用 GrowBlank 来组织聚会？</p><p><strong>Sam</strong>: 哈哈，到时候它可能已经进化出完美的聚会组织功能了！</p><p><strong>Alex</strong>: <em>[起身准备离开]</em> 或者它会进化出”取消聚会”功能，因为发现我们都更喜欢在家写代码。</p><p><strong>Sam</strong>: <em>[笑]</em> 那也是一种进化！适者生存嘛。</p><p><strong>Alex</strong>: 说真的，Sam，今天这个对话让我重新思考了很多东西。不只是软件开发，而是我们和工具的关系。</p><p><strong>Sam</strong>: 怎么说？</p><p><strong>Alex</strong>: 我们一直在讨论让软件适应人，但其实… 人和软件是在共同进化的，对吧？就像你说的共生体。</p><p><strong>Sam</strong>: <em>[若有所思]</em> 你说得对。也许真正的革命不是”无代码”或”AI编程”，而是打破创造者和使用者的界限。</p><p><strong>Alex</strong>: 每个人既是用户，也是设计师，还是程序员，只是自己不知道。</p><p><strong>Sam</strong>: 这才是真正的民主化。不是让每个人都学会编程，而是让编程消失在使用中。</p><p><strong>Alex</strong>: <em>[握手]</em> 期待看到这个未来。</p><p><strong>Sam</strong>: 未来？也许已经开始了。从我们用 Claude Code 的那一刻起。</p><p><strong>Alex</strong>: <em>[停下脚步]</em> 你知道吗，Sam？今天你让我理解了一件事。</p><p><strong>Sam</strong>: 什么？</p><p><strong>Alex</strong>: Smalltalk不是失败了，它只是来得太早了。它需要的不是更好的虚拟机或更快的硬件，而是一个能理解人类意图的伙伴 — — AI。</p><p><strong>Sam</strong>: <em>[微笑]</em> 对。Smalltalk给了我们”一切皆对象”，但忘了最重要的对象 — — 人类自己。现在有了LLM，人类的意图、想法、甚至困惑，都变成了可计算的”数据”。</p><p><strong>Alex</strong>: 源代码是文本，输出是文本，提示词是文本，甚至GUI也是文本描述的结构…</p><p><strong>Sam</strong>: 一切皆数据，数据皆可塑。这就是Smalltalk梦想的世界，只是用自然语言代替了消息传递。</p><p><strong>Alex</strong>: 从Smalltalk到Claude Code，再到GrowBlank… 软件开发终于要回归它该有的样子了。</p><p><strong>Sam</strong>: 什么样子？</p><p><strong>Alex</strong>: <strong>像玩泥巴一样自然。</strong></p><p><em>[咖啡馆环境音渐弱，两人的脚步声渐远]</em></p><h3>后记：Smalltalk开发模式的复兴</h3><p>在这次对话中，我们看到了一条清晰的进化路线：</p><p><strong>Smalltalk（1970s）</strong></p><ul><li>一切皆对象</li><li>没有源代码/产物的区别</li><li>Image-based开发</li><li>实时反馈的编程环境</li></ul><p><strong>Claude Code（2024）</strong></p><ul><li>输入输出皆文本</li><li>提示词即程序</li><li>对话即编程</li><li>AI理解人类意图</li></ul><p><strong>GrowBlank（未来）</strong></p><ul><li>使用即开发</li><li>进化代替设计</li><li>个性化的活系统</li><li>人机共生的创造</li></ul><p>Smalltalk的理念没有过时，它只是在等待合适的技术条件。当AI能够理解自然语言，当一切都可以用文本表达，当系统可以从使用中学习 — — Smalltalk梦想的”活的软件”终于成为可能。</p><p><em>“从使用中生长，而非从规划中构建。”</em></p><p><em>— — 一次关于软件进化的咖啡馆对话</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=197c578f74bb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/software-engineering-problems/%E4%BB%8E-smalltalk-%E5%88%B0-claude-code-%E8%BD%AF%E4%BB%B6%E8%BF%9B%E5%8C%96%E7%9A%84%E6%96%B0%E8%8C%83%E5%BC%8F-197c578f74bb">从 Smalltalk 到 Claude Code — 软件进化的新范式</a> was originally published in <a href="https://medium.com/software-engineering-problems">Software Engineering Problems</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Out of the Tar Pit, another approach]]></title>
            <link>https://medium.com/software-engineering-problems/out-of-the-tar-pit-another-approach-b3e701e089ee?source=rss-baba231b6963------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3e701e089ee</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Wen Tao]]></dc:creator>
            <pubDate>Tue, 23 Jul 2019 14:20:53 GMT</pubDate>
            <atom:updated>2019-07-23T22:12:42.968Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is the problem to solve?</h3><p>A problem well-stated is Half-solved</p><p>The challenge was laid out by <a href="https://raw.githubusercontent.com/taowen/lonely-road/master/Brooks-NoSilverBullet.pdf">“No Silver Bullet — Essence and Accident in Software Engineering”</a></p><p>And <a href="https://raw.githubusercontent.com/taowen/lonely-road/master/MoseleyMarks06a.pdf">“Out of the Tar Pit”</a> elaborated the problem statement, and contributed a possible solution.</p><p>I don’t think debating what is essential state, what is accidental state is helpful. But it is clear, the problem is about STATE</p><p>The problem to solve is always the same. It is the big elephant in the room all the time. Imperative programming to manage state is too hard.</p><h3>What is the problem of imperative programming?</h3><p>We can update those states, quite easily actually. Imperative programming is straightforward, it gets things done. Just put together a bunch of CPU instructions to update state, and CPU will do it. The software execution can be drawn as this naive diagram</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*BkT_0dH4sNhHuMANwz5eEw.png" /></figure><p>The external behavior of a software is essentially a ordered series of state update (yellow circles in the diagram). However, the problem is:</p><p><strong>Describe this sequence of state update literally with one to one mapping, will lead to code that is &quot;lengthy&quot;, &quot;tedious&quot;, &quot;fragmented&quot;.</strong></p><p>The most straightforward way, the easist way, is not the best way. Even if, we extracted out lots of nice functions (those blue circles), the code might looks tidier, but still “lengthy”, “tedious”, “fragmented”. Readability is a subjective. “<a href="https://link.zhihu.com/?target=https%3A//www.infoq.com/presentations/Simple-Made-Easy/">Simple Made Easy</a>” suggests “Simple” is objective. I will define simple as following measurable properties:</p><ul><li><strong>Fewer states</strong>: the number of states, smaller is better</li><li><strong>Sequential</strong>: if we have to deal with time ordered state update, let it be sequential</li><li><strong>Continuous</strong>: this line and next line, they are put so close together because they are causally related. On the other thand, if two state update are causally related, they should be put as close as possible.</li><li><strong>Isolated</strong>: state update is already hard enough to reason about. If they are not isolated, we have to pull all of them in my working memory to think about them all in once.</li></ul><p>The goal is not to have zero states, but fewer the better. Then we keep the code sequential/continous/isolated to keep the complexity of state updating code on check. The opposite of those four properties are:</p><ul><li><strong>Excessively</strong> <strong>stateful</strong>: many many states, even unnecessary (or accidental state as described in out of tar pit paper)</li><li><strong>Concurrent or Parallel</strong>: threads or coroutines, they are complex.</li><li><strong>Long range causality</strong>: the application logic is fragmented, connected via a global state called database</li><li><strong>Entangled</strong>: we have to ignore the fact they are components, to reason about them or to optimize them as a big entangled mess.</li></ul><p>The goal is not to eliminate all states, but to keep them as few as possible. There will always be essential states that we have to manage and update with logic in order, that is what business process is all about after all. Even TLA+ evolved as <a href="https://en.wikipedia.org/wiki/PlusCal">PlusCal</a> looks a lot like a imperative program. Imperative style is still the best known form to express temporal logic for human comprehension. But we have to keep it simple, by keeping it sequential, continuous and isolated.</p><h3>What about OOP/DDD?</h3><p>Using object to encapsulate state is a big part of OOP or DDD in particular. DDD in practices boils down to three steps:</p><ol><li>Application service load back the domain model from database</li><li>Use aggregate root to encapsulate all the changes</li><li>The side-effect is in the form of modified domain model or issued new domain events. Application service save the models and publishes the events</li></ol><p>The core idea is “Aggregate Root” can be a black box, nothing can by pass it, that will make our state update code encapsulated in one place. But there are two issues:</p><ul><li>The method on aggregate root, is not very different from a free function taking the aggregate root as first argument. OOP is just ordinal imperative programming.</li><li>The interaction between objects, especially for the business process involving multiple domain concepts. It is hard to decide which aggregate root is the real aggregate root, which should take care of the process. Or put in another way, business process as a function in essence, itself should be the aggregate root.</li></ul><p>We can re-examine the four properties above</p><ul><li><strong>Fewer states</strong>: as long as the state has to be updated manually in the temporal manner, they are still there</li><li><strong>Sequential</strong>: still need thread or coroutine to exploit new hardware.</li><li><strong>Continuous</strong>: the business logic is scatter around. It tends to be less continuous, not more continuous, compared to raw imperative programming.</li><li><strong>Isolated</strong>: domain model isolates the states, but to optimize the data loading, we have to load them in bigger batch to avoid 1+N too many SQL problem.</li></ul><h3>What about pure functional?</h3><p>In <a href="https://raw.githubusercontent.com/taowen/lonely-road/master/MoseleyMarks06a.pdf">“Out of the Tar Pit”,</a> author proposed a style of programming called Functional Relation Programming. It is known as event sourcing in DDD community. I agree, the event (user input) is the only true essential state, everything else can be derived from it, so accidental. But projecting every state from event is not as “easy” as temporal logic expressed by imperative programming. As Rich Hickey suggested, “easy” is subjective. But we can not ignore the fact most people is not familiar with this style, because it is detached from our primary familiarity source, the physical real world.</p><p>The physical world do not store the state as a ledger of events. The god does not derivative your height and weight from the food you have eaten since you have born. We make decision according to the situation. It is just the matter we load the situation from a mutable state, or we derivative the situation from the history on demand in memory. Reasoning based on current state for future, coupled with calculating the current state, will complicate the logic.</p><p>The approach is still not popular after all these years. We are presenting an alternative approach to manage state, which might be more familiar and practical.</p><h3>Simpler State Management</h3><p>The goal is to make it simple</p><ul><li>Fewer states: if one state is not necessary eliminate it. If one state can be derived from other state, make it declarative.</li><li>Make imperative programming sequential / isolated / continuous</li></ul><p>The code is written in TypeScript, but need a special runtime to make it working. You can think it is a new language, with identical syntax with TypeScript.</p><h4>Fewer states by UI binding</h4><p>UI binding is mainstream now. This demo looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/180/1*5cZd8sOhTxlQhKkCh6E93w.gif" /></figure><p>The UI is powered by Web DOM, it is a separate state. Using binding like this we can make it a derived state:</p><pre>&lt;Button @onClick=&quot;onMinusClick&quot;&gt;-&lt;/Button&gt;<br>&lt;span margin=&quot;8px&quot;&gt;{{ value }}&lt;/span&gt;<br>&lt;Button @onClick=&quot;onPlusClick&quot;&gt;+&lt;/Button&gt;</pre><p>The data bind to:</p><pre>export class CounterDemo extends RootSectionModel {<br>    value = 0;<br>    onMinusClick() {<br>        this.value -= 1;<br>    }<br>    onPlusClick() {<br>        this.value += 1;<br>    }<br>}</pre><p>But why binding is eliminating state? Compare code written in these two styles. First, we update these two states in order</p><pre>// update state in temporal order<br>this.value -= 1;<br>this.updateView({msg: this.value})</pre><p>Second, we bind the two state, then update the model</p><pre>// setup the binding in advance<br>&lt;span margin=&quot;8px&quot;&gt;{{ value }}&lt;/span&gt;</pre><pre>// then update the state<br>this.value -= 1</pre><p>The difference is, binding or any declarative style programming, setup the relationship which is true, out of context. This can remove the derived state from temporal reasoning and description. The fewer states need to manually maintained within the time arrow, the better.</p><h4>Fewer states by even more binding</h4><p>If binding can remove state from temporal logic, we need more. Let’s layout all the states within the system:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*AUrnE5Z2lXkVAQLVcuU5xA.jpeg" /></figure><p>Binding UI state to Frontend state only solved a tiny bit of the problem. Who will manage the Frontend state then? We need to question every single state, can we eliminate it? Or, can we derive it from another state? There is obvious quick win here. When presenting the UI, it loads the data from database, all the way up to UI. There might be some transformation, but can be conveniently described as data binding as well. Given this simple application:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*vIp-oT0QzIjVd6Di3L7MwA.gif" /></figure><p>It is just a simple list view, to show some data loaded from database. We can bind the UI directly to some database query:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f1c396d80fb9d5799eba9c98f5f035a/href">https://medium.com/media/5f1c396d80fb9d5799eba9c98f5f035a/href</a></iframe><p>When &quot;from&quot; or &quot;to&quot; changed, the &quot;filteredReservations&quot; will be updated, and the &quot;totalCount&quot; will also be updated, and the UI will be re-rendered with latest value. Binding to database, eliminate a lot of intermediate state between the UI and DB.</p><h4>Fewer states by tight coupling</h4><p>Frontend and backend work together to provide a user interface for the human to interact with. They should be tightly coupled.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/121/1*x487hOwq6mNyuLdVrt84OQ.jpeg" /></figure><p>If the RPC interface is dedicated for the service of the functionality provided by the form, why not merge the two states? Then it become a shared whiteboard between user/frontend/backend:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*Mmij64sQQRZnKBlbLZMsdw.jpeg" /></figure><p>Take this application for example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*j9O-TRMGLowESQtmrfkjFQ.gif" /></figure><p>We can share the form state, with both frontend and backend. Here is the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a5cd4fbe1dffff67695fd207cd553dd/href">https://medium.com/media/0a5cd4fbe1dffff67695fd207cd553dd/href</a></iframe><p>The method saveReservation is marked with &quot;runAt: server&quot;. The form state will be sent to backend for calculation, and then the form state updated in the backend will be rendered back to the UI. Although this is unconventional, but with fewer states, the code should be easier to reason about in theory.</p><p>This concludes the first part, we have seen following ways to reduce states count:</p><ul><li>Derived state: such as computed property, autorun state subscription, database view, materialized view</li><li>Bind the database query, use it as if it is local state</li><li>Share form between frontend and backend</li></ul><h3>Simpler Temporal Logic</h3><p>Declarative style data binding can remove some non-essential state from the system. Now, we need to focus on the temporal logic itself. The first property is sequential.</p><h4>Sequential</h4><p>Sequential single thread programming is simple. Yet, CPU tried very hard to parallelize the execution of the single threaded instruction stream. It will look ahead and speculate, as long as there is no data dependency.</p><p>Most temporal logic in business application can be single threaded, as long as the I/O can run concurrently, this is where co-routine comes in handy. However concurrent programming with co-routine, need to deal with “async” and “await”, it is still more complex than sequential programming. Can we write the program sequentially, and then speculative execution will try run it concurrently?</p><p>This is what <a href="https://wiki.haskell.org/wikiupload/c/cf/The_Haxl_Project_at_Facebook.pdf">Facebook Haxl project</a> has demonstrated to us. The idea is simple, given we have these two tables:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/748679c037ba001d3d2af432ca916b21/href">https://medium.com/media/748679c037ba001d3d2af432ca916b21/href</a></iframe><p>Post has author, and author has inviter. We can map the relation as computed property in code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b404be71ee7097615ec9813d4ea9333/href">https://medium.com/media/3b404be71ee7097615ec9813d4ea9333/href</a></iframe><p>If we express the UI rendering logic sequentially:</p><pre>const author = somePost.author<br>const editor = somePost.editor<br>return new UI({ author, editor })</pre><p>Even the code is sequential, loading author and editor can be executed concurrently, as they are independent from each other. However</p><pre>const author = somePost.author<br>const authorInviter = author.inviter<br>return new UI({ author, authorInviter })</pre><p>Because inviter depends on author, this two lines can not be executed concurrently. We have implemented this kind of “optimization” in TypeScript, with modification of the compiler and a runtime scheduler.</p><h4>Isolated</h4><p>The second property to make temporal logic simple is “isolated”. Here is a frequent case where isolation is broken:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*CG79mmeaJOyqCQO8psJ1DA.png" /></figure><p>If we render this table from the “Post” object defined above, it will lead to so call “1+N” problem. For each row, there will need extra SQL to fetch author name and inviter of the author. This is where we normally ignore isolation, and load them in batch. What we want is automatically batching up the load operations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PZMnJ7aJPskb2w1zdUHs6w.png" /></figure><p>First, all the query in browser need to be batched in one big http query, with all the additional data to be fetched.</p><pre>2019-07-19T11:25:04.136927Z	   27 Query	START TRANSACTION<br>2019-07-19T11:25:04.137426Z	   27 Query	SELECT id, title, authorId FROM Post<br>2019-07-19T11:25:04.138444Z	   27 Query	COMMIT<br>2019-07-19T11:25:04.772221Z	   27 Query	START TRANSACTION<br>2019-07-19T11:25:04.773019Z	   27 Query	SELECT id, name, inviterId FROM User WHERE id IN (10, 9, 11)<br>2019-07-19T11:25:04.774173Z	   27 Query	COMMIT<br>2019-07-19T11:25:04.928393Z	   27 Query	START TRANSACTION<br>2019-07-19T11:25:04.936851Z	   27 Query	SELECT id, name, inviterId FROM User WHERE id IN (8, 7, 9)<br>2019-07-19T11:25:04.937918Z	   27 Query	COMMIT</pre><p>Then in the backend, the SQL queries should be rewritten as IN query. It is implemented by controlled coroutine call stack evaluation. Instead of doing depth-first evaluation, we do breadth-first. So all I/O operation can be collected then to be rewritten as a batch query.</p><p>This way, I/O batching as a cross cutting non-functional concern, no longer complect the essential temporal logic we want to express.</p><h4>Continuous</h4><p>The non-continuous version interleaves the temporal logic like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*HdJCZa5-3U1DQnT8rNBVAw.jpeg" /></figure><p>Although, billing process is more causally related, it can not be written close to each other. Although, contract singed and assignment dispatched has fewer common business, but because they are temporally related, they have to be written one after another in the order of time.</p><p>It is essentially several timelines squashed into one mainline. The POV constantly changes, in this single threaded story telling. The sequential nature is no longer a blessing, but a curse. We need to separate those independent timelines, and describes them in its own encapsulation block. It is called &quot;Process&quot;, as business process.</p><p>Let&#39;s look at this final example</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/1*1nzVbM1AJtQsTokOX7yeqA.gif" /></figure><p>The account life-cycle can be described as a simple state machine. But in normal imperative programming style, it can be written as a continuous temporal logic. Here we have contributed a alternative style:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d048320a5bc849b7495cd03ec6a1bd7/href">https://medium.com/media/2d048320a5bc849b7495cd03ec6a1bd7/href</a></iframe><p>The process() is a function with infinite loop. It is never meant to be executed forever. Every time, this.recv(), the execution breaks, and the control yield to other process.</p><p><strong>locked</strong>: this.commit()</p><p><strong>normal</strong>: this.commit()</p><p>statement will label is a savepoint, just like in the game. The process can be loaded back from that savepoint, and resume. But where is the process saved to? Just ordinary Mysql table:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db8ec34043fe529be3630dd2825d31b1/href">https://medium.com/media/db8ec34043fe529be3630dd2825d31b1/href</a></iframe><p>The label will be saved in the &quot;status&quot; column. Other local variable, will not be saved in database, unless there is a object property with the same name (password, retryCount).</p><p>Business transaction, or moment interval in color uml, is a good fit for this kind of programming style. It also settled the problem of where to put inter-object interaction in DDD, we can put it in Process. Because the code written out this way is not very different from the box/arrow in whiteboard, and it is not very different from original business requirement, it will facilitate the communication between different groups with shared language.</p><p>Unlike BPM or workflow solutions. Process is part of the application, it can be rendered as UI, and sum/avg by the report. We do not need to maintain a extra copy of data (extra states) to feed the &quot;engine&quot;.</p><p>The UI binding of this application looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ce45fd9466f0cf0175cf3e7236e06c0/href">https://medium.com/media/4ce45fd9466f0cf0175cf3e7236e06c0/href</a></iframe><h3>Conclusion</h3><p>We are building a aPaaS product called MulCloud to enable this kind of programming style. It has identical syntax with TypeScript, and inherited a lot of familiar ideas. We believe our approach, not only simplified programming, and because we stand-upon giant shoulders, people will also find it to be easy.</p><p>There is one more caution to leave behind for future innovators:</p><p>MulCloud has to put a lot of effort to build observability solution to allow the developer debug in production. Old-school imperative programming despite the odds, it has one shiny virtue: <strong>it has one-to-one mapping with the instruction stream executed by the CPU</strong>. By building the program in sequential / isolated / continuous way, the source code is detached from the reality, which is concurrent / entangled / with lots of long range causality. When something goes wrong in the wild, it is harder, much harder to debug. Bret Victor has demonstrated a lot of cool ideas on providing more runtime feedback. We borrowed a lot of them, but that deserves another post.</p><p>Simplicity is hard, when simplicity is not the reality.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3e701e089ee" width="1" height="1" alt=""><hr><p><a href="https://medium.com/software-engineering-problems/out-of-the-tar-pit-another-approach-b3e701e089ee">Out of the Tar Pit, another approach</a> was originally published in <a href="https://medium.com/software-engineering-problems">Software Engineering Problems</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What represents the past, present, and future]]></title>
            <link>https://medium.com/software-engineering-problems/what-represents-the-past-present-and-future-f51d1979f354?source=rss-baba231b6963------2</link>
            <guid isPermaLink="false">https://medium.com/p/f51d1979f354</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Wen Tao]]></dc:creator>
            <pubDate>Sat, 03 Nov 2018 07:36:21 GMT</pubDate>
            <atom:updated>2018-11-03T07:38:02.925Z</atom:updated>
            <content:encoded><![CDATA[<h3>What represents the past, present, and future: the future(3)</h3><p>Chapter 1 of this article: <a href="https://medium.com/software-engineering-problems/what-represents-the-past-present-and-future-the-future-1-665966610825">https://medium.com/software-engineering-problems/what-represents-the-past-present-and-future-the-future-1-665966610825</a></p><p>Chapter 2 of this article: <a href="https://medium.com/software-engineering-problems/what-represents-the-past-present-and-future-9a8f8bbde4b6">https://medium.com/software-engineering-problems/what-represents-the-past-present-and-future-9a8f8bbde4b6</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Wm4wkaJCKZ-FSlKj.png" /></figure><p>We have already seen how powerful single coroutine can be. But compact everything in a single coroutine is not an option. From a complexity management perspective, we have to dive and conquer. Also, the future is not single threaded, we have to describe how things happen concurrently.</p><h3>Multi-tasking</h3><p>The first step is to make the scheduler supporting more than one running task. The operating system is an os thread scheduler, which supports more threads than CPU count. But the operating system is a low-level preemptive scheduler, which is fairly complex. Here, what we are going to implement is a simple cooperative scheduler.</p><p>lua version: <a href="https://tio.run/##nZFNDgIhDIX3nILd4GJMpnvPYpCpkYgwgXbh6XH@4jBGFsqKtl/fy0sd65yv7A3Z4GXiS3cmne7qIOT4hmg9qWZqy0Q4dM3SNyEGJuvx@LTo@goNI42@F0KUBvDdAH4ygL3Bpm9u2LPDdcEFo92cSp4KTRNRE6p32g8YKjAU8DaPmPixiNVH8O/WHK9IJdpWjtzANP22w6wV7Kr1DLsZiJxf">https://tio.run/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/0*JFfePMWfrbCAZZZ1.png" /></figure><p>To make the scheduler generic, the tasks need to be maintained in a lua table</p><p>lua version: <a href="https://tio.run/##lZLBbsMgDIbP4yl8S5DaSk17zbNUNDgqGoMIjLRq6rNngWQJSN0hvoDtH/szoIMYxz6YjpQ14MP9fCPhP2vOYLLBKUN1FcPgCYdzNcc762wgZfD0VKjlP@pml/qyS32d1GgkYyyHb97DN7vgmxU@NdC2ExocCvlM1T208MM@tirdlCOs17vjh/fZGY6zV87cPVAGjQuE6sHgN9VZNw5tC0ZpoAeaJIrmkIKb3QgZ15mTrLQrZlaGzaeKIV4p2FsHtwPEKCgDahDK@Xqrw0Hate8EuI3m0IcvrNNUJV40EneNJ2U8umKguRVftag9FgeXl0hA0hqsMu0y69@aXV96q8xnxyNMnEOguNt@8OI1hbf81yLXFLlL9FakInUtU@P4Cw">https://tio.run/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/0*jKyoI_r89H_d69Zr.png" /></figure><p>Combine sleep future with multi-tasking, we have</p><p>lua vesion: <a href="https://tio.run/##rVXbbpwwEFUey1dYeQHUDWJJ03al0l9BBAbFCmsjbKuJqnw79QVjLxhlE5WXXTxzZs7MnDG9qKfp5mbqaVP3iPUAQ9UJLkZgqER/36LIWEao29eK1@zZnneCNBxTYkCJMh0Qg4aSlqURko9BmmgKpFxK4/enfoZKDFXNy4SyjOMzJCn6uuDfdABeP/aQYcJg5MkFt8Mc1iRq6EgFxwSyVwx9m6QRkNZnKB6PmrtmaTDDiAl3uQ8oVl6IcRiOsXHxCzu@iyo@hbqPA2SLq8gWnyJb/FeyjdQFB0O386euTuTM3WSMp3Vy53KYQuYxFFzFI8jxEn2wSqmlw5/gLPWTcNpSqwkDxB1KCLzwSxMqS0RwnyIJJNrPJdGvKodjf8akMnqbBSlL@Z5rh46OqLLyQ5ggPNR4ZKt0LV2SzP2gm4DGOXOrgO7Q0vYFrurZgH@VKF/VstkXb2Mt3cz11z6hSvPFA3oGYQJbYIBPKPg6lMs1T8D@qrzbAL83hcuWwQs0QorrVvuiW5RlAX6b6FomXpt2VPKO4FTE1QY3T9CK3k7RCsABZRsubjO3ipd37xXZP1DHrtp1VHu1e3HmRVxd/N4S6CVfrcDMwFsATZHy8M6nAdmYGyjW0VtKIE53ReK1Ws9gfwP8m2r5HqTp9YjCIiIvaXQnd1bwQXD17/jwLT8dH075jy/uY7I1FAHDT4cotoYiYDg5xP2uYZr@AQ">https://tio.run/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/0*ZSCn7mQXOvRS8Nkz.png" /></figure><p>es2017 await/async internally has a ready_tasks. resolve put the task into this list. We can say es2017 has schedule loop for multi-tasking built-in.</p><h3>Decomposition</h3><p>The scheduler has been extended to support multiple running tasks. The next step is to decompose one business process into many tasks so that we can better manage the complexity. Leaving the question of task granularity aside, there are three ways to decompose a long process:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/0*pLb4jZ1j_k9F5bs9.png" /></figure><p>Every box here is a coroutine. Orchestration is the simplest form:</p><p>lua version: <a href="https://tio.run/##bc7BCsIwDAbge58it7UIwtqzhz1KqREKNR1Z8vxV50S6Lafwhy/8RWNrD6UkuRIsgvNonYH3zJxJ7LBGwzdiFGWC0SDdjemUPyrfK3@iwlGFXoWdmmx33grD5Vdi2z6PV1hqigUi3CBVriqZ8JoYo6CdnPlnjIs@0UbX2gs">https://tio.run/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/0*gAmnYt_m6cKrFypP.png" /></figure><p>The upside of orchestration is simplicity. Following the call graph of A, we can see everything. The downside of orchestration is coupling. If step2 or step3 is not “your business”, it is annoying to invoke them and wait for their return. Choreography is helpful in this kind of case.</p><p>lua version: <a href="https://tio.run/##hY1BCoMwEEX3OcXsMkNLQV13oZ5E0ikE7ETi5PzR1rRCS3GW/89/b0xDzvckTn0Q6DHynEYlA@tN0YuinZWnxp5hq@AEDRmWmzGfWfdvVtstKtPrzqhfuQsxJPXCl2fxYNwDF3lQxp7e4m9piz@6quiOsd2KrQrx@LslynkB">https://tio.run/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/0*7bsZKZmU_aiO1CGx.png" /></figure><p>This form of choreography does not really remove the coupling. The A is aware of B, and B is aware of C. To decouple them, we need a storage service in between, such as message queue or database.</p><p>lua version: <a href="https://tio.run/##tY/BjsIgEIbvfYq5FaIxUc97qD5IQ@k0mSxCA8Nhs/HZq4VUwWSPy23IN//3j4lqWYzTykDXhzgE7WlAH@ALfu9NM0WrmZyFq2AVvmUDz8dqMHggG9CzqLb28KZyqMcQDT/TtPMuMlk8/BCaUWRo9mRZtIFxPrf7jd7BWTZox8J/@Xf/qfSfPv1d4S@Wjm3@emmOaZychz6XAbJAsyIf6qoSRpfY9b3LrUE3TLKtTjasdepK2qNi7FdUTOXNSVtenMkN@kOW70uKMvkiq/Faj51clgc">https://tio.run/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/0*btNmVCMbX8tG4mpi.png" /></figure><p>“A_subscribers” is not an exact representation. The actual role message queue played is complicated. We will make a more accurate representation later.</p><h3>Coordination</h3><p>The goal of decomposition is to split one linear process into smaller blocks. Visually, the blocks come one after another. Unlike decomposition, coordination handles the case where blocks “overlap” with each other. There are broadly two types:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/0*p7_d7ohAKWgfJ1dm.png" /></figure><h3>Fork/Join</h3><p>Fork/join is still orchestration. Say, the boss of A assign a job to A. A splits the job into two jobs, and delegate to his direct report B and C. B and C does the job concurrently, then A collects the results and report back. In this case, B and C are responsible, and A is accountable. The signature of orchestration is clear ownership, the guy on the very top is accountable for everything.</p><p>es2017 version: <a href="https://tio.run/##fc7LDsIgEAXQPV8xO0p8JG3XLrRfgjgaDBkaHhpj/HYEg8ZXymoucDL3KE/SK6fHsCC7w5Skv5CCfSQVtCXYNAKuDPJRlrw1uDT20HAfcISOi8eLwxAdQcdujH3xYYL3n7z/w9cTvK3cYIAtrErTV1Y5D2/ZoY8m5MsWZiDPUhfynNTvgvqfz6sUpVsuk9Id">https://tio.run/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/0*5sUCl7tp8jiVmcPQ.png" /></figure><p>Fork/join does not necessarily wait for all of them. If one document needs a signature from one VP. The request can send to all VP. If one of them approved, the flow can proceed.</p><p>es2017 version: <a href="https://tio.run/##fZDBbsIwEETv@Yq9xW5TlIQzlYAf6KE3hJBjtpUrY0feDahCfHswYGikRvg269nn8fyovSIdTMtvzm@x7786p9l4B2QRW0GovduShGMG8QTkLjhweICP4HeGUAQkb/cIs3cg5E@zQ9/xfVpAAsALVGVZSpmdskzRr9PweGkh7vhojWs4sf5b5MTYQp3L6406KMMpUyWHWeoR4vIJcTpCrCUMkdMR5PwJskpIiwwNzC4femgd9XKgm40Pm8sw9TcJSqNYNQXo9Z8r1tdZjq4KXlPS2@L/BMmaF2np2nBM2/dn">https://tio.run/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/0*jXbbrh1f1VM_X5vP.png" /></figure><p>There are more questions we can chase:</p><ul><li>What if we want to wait 2 out of 3?</li><li>When promise.race returned, what will happen to other still running coroutine? Can we cancel it?</li><li>What if more than one coroutine await for the same promise?</li></ul><h3>Communication</h3><p>Another form of coordination is multiple concurrent tasks collaborate equally. Effective collaboration is hard. Having multiple peer teams working together without a boss orchestrating them often leads to chaos. Effective collaboration builds on top of communication.</p><p>One coroutine should be able to “call” another coroutine.</p><p>es2017 version: <a href="https://tio.run/##rVNNb8IwDL33V/hGonVF2xGJSewXTNoRTSikBjqFBCUpE5r621m@KA102mU59MN@9rOfnU92ZIbr5mAfparxfOaCGQPvfId1K1DDdwHucCWN1S23ShOabP7YXWMqg/qI2sAcvrvgic9gJszHlLBHu1O1GcZqtK2WIPEL3rTaNwYJ0WiUOGLpnJ/ILYX5yyDilnEZkn944gzjTyKcXT5KuIMkshn0rCMQX8YsvTN31/91dNA1Z0LkTa8k27vcVVWlf6a3/yCEQBsl1q7/EVUycI0Ojn/CfM5YpMsZcalosxw0cx8UW1gdmWjRhUZsxQ4HcSKetNci9F6MTIEMU@SIVMgFuMxkHeQtszI@6P2AuqIIsvXbPQ@q99tOaFHEC7Dw4ows/yYM8naCm6zV6J1OwVimrQvXqrWNxGsRzJwkh00ruW2UhAVZX7LFCaSJFld5TSuss7Iv1gzqr8K2rUuYsLpeKYmTEp5oX7QSWAm1JTGcjjC/kt@Jb7niffaaXxtPtLM@I3Ha05tNTfvtPPAAT0V@gToKl7Gs0ziC9uSVBiPLjIsS1m5GTlsn6aG1/uv5fP4B">https://tio.run/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/0*LLS6KRi32fB-FKQs.png" /></figure><p>A park itself at scheduler. So that when B calls A, the scheduler can wake it up. However the assumption, the server will start before the client is not valid. What if B calls A before A is ready to serve? We need to park the client at scheduler in this case.<br>Complete Implementation: <a href="https://github.com/dexscript/scheduler.ts/blob/master/src/scheduler.ts">https://github.com/dexscript/scheduler.ts/blob/master/src/scheduler.ts</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/0*vjiIolCe8TdmF5Oc.png" /></figure><p>Now, we have a way to do synchronous “RPC” between coroutines. To identify the server, we have upgraded the nameless coroutine to “actor” with an identifier. The current implementation is single threaded, as javascript is single threaded. However, the “RPC” can be extended to call an actual remote actor on a remote machine.</p><p>The “scheduler.stub” is a syntax sugar to make the call looking nicer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/0*GQBU7xcdP_OY1H7i.png" /></figure><p>A quick recap</p><ul><li>Function/Object/Coroutine to describe a process</li><li>Active process is a coroutine with well-defined scheduler protocols</li><li>Active process is very expressive that can represent a complete long-running business process</li><li>A proper scheduler can do cooperative multitasking</li><li>Upgrade active process to “actor” that can RPC between each other</li></ul><p>In the next chapter, we are going to represent complex collaboration with actors</p><p>See also</p><p><a href="https://medium.com/software-engineering-problems/what-represents-the-past-present-and-future-9a8f8bbde4b6">What represents the past, present, and future: the future(2)</a></p><p><a href="https://medium.com/software-engineering-problems/what-represents-the-past-present-and-future-the-future-1-665966610825">What represents the past, present, and future: the future(1)</a></p><p><a href="https://medium.com/software-engineering-problems/what-makes-code-unreadable-to-human-45fa30544386">What makes code unreadable</a></p><p><a href="https://medium.com/software-engineering-problems/what-makes-up-the-software-20f607da9155?source=collection_detail----1d0a7ad41f0e-----2---------------------">What makes good software architecture</a></p><p><a href="https://medium.com/software-engineering-problems/4-major-problems-of-programming-language-c6974c24e083?source=collection_detail----1d0a7ad41f0e-----3---------------------">3 Roles of Programming Languages</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f51d1979f354" width="1" height="1" alt=""><hr><p><a href="https://medium.com/software-engineering-problems/what-represents-the-past-present-and-future-f51d1979f354">What represents the past, present, and future</a> was originally published in <a href="https://medium.com/software-engineering-problems">Software Engineering Problems</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What represents the past, present, and future]]></title>
            <link>https://medium.com/software-engineering-problems/what-represents-the-past-present-and-future-9a8f8bbde4b6?source=rss-baba231b6963------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a8f8bbde4b6</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[lua]]></category>
            <dc:creator><![CDATA[Wen Tao]]></dc:creator>
            <pubDate>Thu, 25 Oct 2018 15:52:15 GMT</pubDate>
            <atom:updated>2018-11-03T07:37:54.318Z</atom:updated>
            <content:encoded><![CDATA[<h3>What represents the past, present, and future: the future(2)</h3><p>Chapter 1 of this article: <a href="https://medium.com/software-engineering-problems/what-represents-the-past-present-and-future-the-future-1-665966610825">https://medium.com/software-engineering-problems/what-represents-the-past-present-and-future-the-future-1-665966610825</a></p><p>Chapter 3 of this article: <a href="https://medium.com/software-engineering-problems/what-represents-the-past-present-and-future-f51d1979f354">https://medium.com/software-engineering-problems/what-represents-the-past-present-and-future-f51d1979f354</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/0*DbxhKwAwxfpzfQ5B.png" /></figure><h3>Active process</h3><p>In the previous simple process, the coroutine is passive. It waits for future instruction and just does what was told. This contradicts with the requirement document, which normally describes a task as if it is alive. It knows what it is doing, and it knows what it should do next.<br>In this chapter, we are going to explore the ways to make the future representation more active.</p><h3>Time scheduler</h3><p>The first example is about sleep.</p><p>lua version: <a href="https://tio.run/##rVFBboMwEDyXV6xywZYIChB64y0RNZtgFWxkr6VWVd9ObYNI4dBT92TP7szO2INr5/nulCCpFVjRY@cGZNTad56Ar761t1EbzGC0jwxa87DQgNBGO5IKc4PWjb8J8g5MadqIHKhHFVuhDJIzyxVVtzG8ODQNpHZAnNIDR9scP1A4QnaKA3CCPI9ecotCq87yneIhR4CTZ0j3VtxCgy2kyUhFzO8g6YPwzJsgnIp06T6TfkocOrY6zOBr3dyU33/plP@kU6VrjuB89wPCYOtfZovFk0P88xn86OQonIr6eikur9e6eIkxd1gVsXKH1RGr5vkH">https://tio.run/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fhp9fnaitn0Ib1OB.png" /></figure><p>es2017 version: <a href="https://tio.run/##rZDBboMwDIbvPIVvJBVD0N0qsdMeYTeEpgxcxpYmCCfdJsSzM6dA1e02aT5YSvz7s3@/qbOieuh6d2dsg/N89KZ2nTVA9Ss2XqNwit4ljBFwaHRwVhoKCL@pwU8n5LUyNtbgAUJOgszzozxRm4AaWqq4q6wmzly69HRHEEG80UMM6PxgLs/pKmIGFEUBMWnEPr7VE7qn7oTWOyEkFA@/9l5Gp4S1NQ3BDvIsy@SKn6Jos7sD8i/5c@gRG55byGpMtW2FwQ94VA6FTNtlomB2TA77PF54Xx3qBsp1xwTGdehhP1V/4e3/mXfPPHYarPHtb2xGP081z98">https://tio.run/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rAvALK8WnyhNFkmx.png" /></figure><h3>Call with continuation</h3><p>coroutine.yield(&#39;sleep&#39;, {seconds=2}) is awkward. Why sub1_task can not put itself into sleep mode directly? Because it does not have reference to itself. Some language provides “call with continuation” which essentially allow the coroutine to get its remaining calculation as a continuation, and pass that to another function as callback. We can simulate that in lua</p><p>lua version: <a href="https://tio.run/##nVHLboMwEDyXr1jlgpEICtAop3wLcswmWHFs5IfUKsq3U9uhAVTUSvXF9uzOemYsHB0GoRgVYARi35yddRrhCJKLJDk7ySxXEgzrsHUCSZaAX/wMRCq74GRgO5SxHJZGDz6vKNu4W2quOVB9MX6@pSeBhZM9ZVeymBN7lSnwA5mzSDaxChsoikguDDIlW/NsXJEd4I6a5qY05nAzl9ejTGnlLJdYaDTuhiRIWlr6Jv5tZ5ZJgGZhBUlkcrsq9D7VH7E@afvkKNqfU92pbAJpJrrXXFris7Lcm8lySI3FvkxnL4467mNox@rxG7X6P7VOR8WBtciaaaT@H18GsmT1H3J4Fme5Jtst@Mbe2XAq9@@7sjocqt1btLnA6ohVC2wfsXoYvgA">https://tio.run/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XM9uZaBTgIE0F3H9.png" /></figure><p>“Future” concept is introduced, it wraps the task continuation along with its requirement. When the requirement fulfilled, the task execution will be resumed.</p><h3>Async and await</h3><p>Notice that we did not give es2017 version in above example. Because es2017 has its own version of “future” builtin.</p><p>es2017 version: <a href="https://tio.run/##pVC9bsMgEN55itsClZuASSNLUTr1ATp0r7B9TWgxWAZiRVWf3cVpUJOxKtOJ776/e1dH5ZtB9@Heuhan6S3aJmhnwRvEnnpsnG09g08C6a1WMKB35oigPeTdDI0HtNAoY7CF@gQew4vu0MVQQDggBOU/YNTGQI2zTOywPVMHDHGwYHGE58F12iPNLrvHK5n8W8AlFtyB4JwztiVfhCh/sg38Foi1eJ09aU6fOImPS@P2dDZ7UgEpW@5/DCgrYOED9mLBzutqVDpc7lCyvyiU/1aQSSFVuupASLpwOkIfwzyJhzUXUkheVpLn3DfAupKbHOcG2FSyyi7T9A0">https://tio.run/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3mySqT7cXdksbASl.png" /></figure><p>Although the code looks very different. The underlying mechanism is actually very similar. The compiler/interpreter of es2017 will turn “await” into a continuation passed to the promised given.</p><p>We can change the lua code to work like the javascript promise. It just returns a function called “resolve” to capture the task continuation and register it to somewhere, then yield execution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AsKBz4W7l-zG1byM.png" /></figure><h3>Network client</h3><p>Time scheduler is simple. It does not need to return value back into the task. If the coroutine needs to play the role of a network client. It needs a way to get the result back.</p><p>lua version: <a href="https://tio.run/##bVDbasMwDH33V@gtMayB9j3fUrJEoaau7dlyyhj79ky2u7QxNRiEpHPR0XFYV23HQcOoFRo6z5GiR@jBKC3EHM1IyhoIaKazx3FpaQjXD/D4JQXwK@AN9ZPG/bbT8//NezV9KcrIehtJGey@FeqpLcQeecE89jqPwQn28Gopfh7PSSlbkgAZ5rwy1DaB0B0b@dKqL2iCvSHMwxWT0YiBGilrihNTZNWEYddPq6PHgbDdTEjxnLHZeMOHThkeDkyLxFxwR7gMC6ZICeiyyYuiuwuqyzm/AfMhuCicdgQ1NDi2vLszOGsCNu@9SpGUuO8ipSpnmIs6qbpZaP8xp3X9Aw">https://tio.run/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NIEzkTCvXdB6RYDW.png" /></figure><p>Returning value is not a hard job as it turns out. The caller and callee share a “future” object so that they can send request and response via this object. With es2017 await syntax, return value back into coroutine is much simpler.</p><p>es2017 version: <a href="https://repl.it/@taowen/es2017-client">https://repl.it/@taowen/es2017-client</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AHoRHzgnUeJ9CZu9.png" /></figure><h3>Network server</h3><p>At this point, we have already seen how coroutine can compute, sleep and call external service. Now, we need to make the coroutine a server. We only present es2017 version here, the lua code will be pretty much the same as “network client example”.</p><p>es2017 version: <a href="https://repl.it/@taowen/es2017-server">https://repl.it/@taowen/es2017-server</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AQxbMUN7bZ8CDIQt.png" /></figure><p>The difference between client and server is, for the server, it needs two await, but for the client, it only needs one await. One for retrieving request from the scheduler, one for sending back a response. For TCP socket, writing can be blocked by the kernel when the buffer is full. So sending back response is also an async operation.</p><h3>Passive Process V.S. Active Process</h3><p>We have checked out several examples of the active process. It can do the following things:</p><ul><li>sleep</li><li>as a client to call another service</li><li>as a server to be called by another service</li></ul><p>Compared to the passive process from the first chapter, the active process is indeed very active. It has control of its own destiny. For a direct comparison, let’s say we have two steps, and one sleep between them.</p><p>Passive version: <a href="https://tio.run/##lZBBDoMgEEX3nmLiRtyQ6L5naSz8pqQUDDBJe3qq0qjRVVny/3sDY3nI@c5OJeMdRQuMIkJ5p2Nb0XR8lHhDcYKol5hqkpLWDpyuqk3At@6ahvgUhR6DcUk0MWHsmnKlfPCcjIP8GFh9LvbNyTrjYtYeFQGRX/hFZ6j/G1IPaLYQLS3Q3KHLjlUBw7SK9Z/FfXxg2WO3hf1@2jYk5y8">https://tio.run/</a></p><p>Active version: <a href="https://tio.run/##hVHLqsMgEN37FUM3UQhC7r7fEqyZNFKjwQf0UvrtudGkNaGFOwvFOTPnzBx1FPOsrRQavEac2j6G6JCQPhoZlDVrmgbhbzUId/UMliDp2DfAGR6l5plxaZ2NQRnkvwp1lzkYQdPt2eOlaROwoalvcsoEWvmAU1OxIrUN8fAoren8uXl@1P9UHwJywC5qpGut6oEaGw6zMwgDmgyncLgk12eiSnfZbNkziItGHs0k5I0eeHKt9RzvKGNAesoonIDz3My3ydk3@4zSOT0I347WYQ2jv75Fi5cOfRxxZ9drpVfj/@vsPMlmJa6DhnQolvnfn8PIV/0aVrDwzfMf">https://tio.run/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vK-gOA5wCkKRYCT6.png" /></figure><p>It is really no different from “passive” v.s. “active” sense. From sub1_task point of view, the passive version use “coroutine.yield” directly to wait for the scheduler to wake it up, the active version use “sleep” which in turn uses “coroutine.yield” to wait for the scheduler. Both versions essentially do the same thing, they call “yield” to park itself.</p><p>The difference is about predefined protocol. The active version has a protocol between scheduler and task. If the task park itself to “sleep_future”, the scheduler has the responsibility to wake it up in the specified time. Just like you use os.execute(“sleep 1”), the operating system has the responsibility to wake your os thread up 1 second later.</p><p>The benefit of the active process is the scheduler become infrastructure, all unstable business logic is isolated in the task. For the passive process, both sub1_task and schedule will need to be modified if the process needs to be updated.</p><p>The scheduler becomes an extensible platform, the tasks are plugins to reuse platform capability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/0*ZuCkJwUbVhngBkmb.png" /></figure><h3>Coroutine UI</h3><p>The task parked in the scheduler is anonymous. This is a problem. If we do not know what are you waiting for, how can we know what to give? We know the sub1_task want to know if step1_add or step2_add. This is a “User Interface Problem” essentially.</p><p>Here is an example process we want to describe</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/0*l7q8D7Es8LlTyVXz.png" /></figure><p>When the task is launched, it will present the user with two options, either to add or sub. Then the calculation result will be displayed back. One second later, the UI will change back to the two options to let the user do the second calculation. This forms an infinite loop.</p><p>This process can be represented by this code</p><p>es2017 version: <a href="https://jsfiddle.net/taowen/L0p516xv/56/">https://jsfiddle.net/taowen/L0p516xv/56/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/0*35xnksT1goFYKGxl.png" /></figure><p>Just like the scheduler can expose API “sleep”, “recv”, “reply”, it can also provide “user_input” as a reusable infrastructure. Of course, the scheduler can not know what the user interface will look alike, so it takes the argument to define the UI component to use and the model to render the view. Here is the source code of scheduler</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/0*N3QGY05lNqxHUH20.png" /></figure><p>The user_input the render the view by setting three variables:</p><ul><li>step_ui: which component to render the view</li><li>step_ui_input: the model of the view</li><li>step_callback: what to do when the user submitted the form</li></ul><p>As we have already learned, how “await” “promise” and “resolve” works, it is obvious when the user submitted the form, resolve callback will resume the execution of sub1_task. The actually view rendering and form submission implementation is irrelevant to the topic here. You can play with code at <a href="https://jsfiddle.net/taowen/L0p516xv/56/">https://jsfiddle.net/taowen/L0p516xv/56/</a></p><p>The scheduler.user_input is provided as a generic tool. It can be used regardless of the business logic we need to describe. The vocabulary of “active process” is expanded. There will be more “future” can be represented by coroutine.</p><h3>Coroutine hibernation</h3><p>We can not put the coroutine UI into production, because there is a serious flaw. The coroutine needs to stay alive in computer memory for the whole time. If the user decided to click the button tomorrow, we can not keep the process alive that long. We need to click the “hibernate” button so that the state can be dumped to disk so that we can save resources only resuming the process when needed.</p><p>This example requires a special version of lua interpreter: <a href="https://github.com/fnuecke/eris">https://github.com/fnuecke/eris</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/0*gqRTbpKQF4eyDx4q.png" /></figure><p>We have expanded what the scheduler can do further. This time, the “hibernate” function allow the task to dump itself into the disk. The representation of the future is totally encapsulated into one coroutine “fib”.</p><h3>Coroutine database</h3><p>The hibernation implementation is also seriously flawed. The “continuation.data” is written in an alien binary format. Represent the future using an object such as “order” does not have this problem. We normally would create a table called “order” to save the unfinished order processes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/0*mAYWTfMeKSa1hmEV.png" /></figure><p>To represent the order process using coroutine, it would look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/0*OUunOokACP8I1Zpq.png" /></figure><p>The order_status column of the order table is a cursor tracking the position of execution. It is essentially the position of “coroutine.yield” in the coroutine. So we can represent the order_status with lua label. When persisting the coroutine, the “program counter” can be translated to “order_status”, and mapped to a database column.</p><h3>Summary</h3><p>Now, we can represent calculation logic, UI and database by the active process. The coroutine yield control to its scheduler for reusing predefined and stable atomic operation. All those unstable business logic can be encapsulated in a single coroutine.</p><p>Using the active process to describe “long-term future” is unconventional. Looking a coroutine to “invoke” a UI or database is mind-blowing. But it is a plausible representation, and sometimes come in handy.</p><p>See also</p><p><a href="https://medium.com/software-engineering-problems/what-represents-the-past-present-and-future-the-future-1-665966610825">What represents the past, present, and future: the future(1)</a></p><p><a href="https://medium.com/software-engineering-problems/what-makes-code-unreadable-to-human-45fa30544386">What makes code unreadable</a></p><p><a href="https://medium.com/software-engineering-problems/what-makes-up-the-software-20f607da9155?source=collection_detail----1d0a7ad41f0e-----2---------------------">What makes good software architecture</a></p><p><a href="https://medium.com/software-engineering-problems/4-major-problems-of-programming-language-c6974c24e083?source=collection_detail----1d0a7ad41f0e-----3---------------------">3 Roles of Programming Languages</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a8f8bbde4b6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/software-engineering-problems/what-represents-the-past-present-and-future-9a8f8bbde4b6">What represents the past, present, and future</a> was originally published in <a href="https://medium.com/software-engineering-problems">Software Engineering Problems</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What represents the past, present, and future]]></title>
            <link>https://medium.com/software-engineering-problems/what-represents-the-past-present-and-future-the-future-1-665966610825?source=rss-baba231b6963------2</link>
            <guid isPermaLink="false">https://medium.com/p/665966610825</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[lua]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Wen Tao]]></dc:creator>
            <pubDate>Tue, 23 Oct 2018 01:18:07 GMT</pubDate>
            <atom:updated>2018-11-03T07:37:37.121Z</atom:updated>
            <content:encoded><![CDATA[<h3>What represents the past, present, and future: the future(1)</h3><p>Chapter 2 of this article: <a href="https://medium.com/software-engineering-problems/what-represents-the-past-present-and-future-9a8f8bbde4b6">https://medium.com/software-engineering-problems/what-represents-the-past-present-and-future-9a8f8bbde4b6</a></p><p>Chapter 3 of this article: <a href="https://medium.com/software-engineering-problems/what-represents-the-past-present-and-future-f51d1979f354">https://medium.com/software-engineering-problems/what-represents-the-past-present-and-future-f51d1979f354</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*O97GbaErKzttHXOM.png" /></figure><p>Our software builds a cyberspace for intelligent agents to interact with each other. Using machine learning algorithms to build intelligent agents is a hot topic. But most of the code written is still about building the virtual environment itself. The code and runtime describe what could and would happen in this environment, which is about “the future”. To solve ambiguity, code and runtime must resolve what is really happening at “the present”. The code and runtime also need to faithfully record what has happened in “the past”. To maintain the integrity and lay a solid foundation, all three things should be done properly, otherwise, we perceive the anomaly as “a bug”. Most prominent cyberspace is the online multiplayer game as the article cover suggests.</p><p>As the business interest is rapidly shifting to build more intelligent agent, the cyberspace building technique became a commodity, some good old wisdom might be lost and forgotten. The current mainstream approach is mature and working but is far from elegant. This series of three articles attempt to summarize my observation on the possible representations of “the past”, “the present” and “the future”. Some of them deserve more attention.</p><p>What represents “the future”? This seems to be a quite obvious question. The so-called business logic has many many ways to express. We are going to go through some very junior concepts from “future representation” point of view. Then we can see it is not actually as simple as we thought.</p><h3>Source code</h3><p>“the future” lives in the document, in the source code, and in the runtime. The language we are going to use is lua 5.3 and es2017 (ECMAScript 2017). All code can be tried online at <a href="https://tio.run/">https://tio.run/</a>.</p><h3>Simple process</h3><p>We are going to describe a very trivial process: result = (a+b)*3. The “some_important_business_process” describes the process of taking a, b and computing the result.</p><h3>Function</h3><p>The simplest way to describe “what could and would happen” is using a function.<br>lua version: <a href="https://tio.run/##hY69DgIhEIR7nmLKQ@8KtbLwWQggJiTcQtjl@ZEoMcbGbWbn259Marb3RyMvMRM478HEveQqlsS4xpECsyk1@6GLXeG0wqiUvU2ogVsS3GBxhPsa@MEuL/9Zmc0BfnJplSZVge5Q6ufpvzSnFWetSo0ky/tIY9tw7f0J">https://tio.run/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/0*BunIN7l1MyvZ43hA.png" /></figure><p>es2017 version: <a href="https://tio.run/##hY6xDsIwDET3fMWNLRQqYGLgW6o0BBSU2lXsdEF8e6igqsTELed7sq172MmKS2HUHfHVl3LL5DQwQXjwXRhGTmpJuz5LIC/SjYnd7JVt0Nd4GsyKXpG85Ki4wGKLfsVuJqdPWheWYQO3cM2JFmpexvx8@1fj0OBYG8ckHP0@8r36ntZoW5xLeQM">https://tio.run/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/0*q2_WvsomoXtWL6ba.png" /></figure><h3>Partial function</h3><p>In the previous function, we take both a and b as the input. However, we might not know all the things from the beginning. To tell the story gradually, we take “a” first and then take “b”.</p><p>lua version: <a href="https://tio.run/##hZDBbsMgDIbvPIWPsCaRtp162GFPEhlKKzRiEJjnT0lJMm5FQlj@/duf8QXX9V7IsAsEERM79PI@wDRNSkA9Phj0oEOh2296ZPgBRu3tFNH8ybMqWS6J4Oj0L/SibM5CL@/ZUnXTLN3Edk@kHBY7uyWGxEg865Id2ZznmIKpr8QBdA@abC6eKyXCBXQnmJr73ln3kj34ANPv0LIviubcRtXq43PeEA3wqcQ4NpfLlcMEYkcFt33EOXzT5ZcSMTli2dIKqvG6rk8">https://tio.run/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/0*d_swNOp2pKadKGHx.png" /></figure><p>es2017 version: <a href="https://tio.run/##hZC/UsMwDMZ3P4VGB4J7wMTA0CfJKa5bzLlWzpJZuD57UP40l054sSX9PumTv/EH2Zc4yEumUxjHc81eImUYsEjEZM8tOOd6qvl0LBdu4NeAnhKklgwbbhXCXX3POI8pWfmK/NhrjmbRLLmZm9n6MV1DF68DFcEsXV855sDcDYW83hZb6O@zUhCdxTUJfALCM/Rb2mvmfTW8AuvjCfx@kSWrDibVNETJ@xf846WF18YcDosqsjrwlCXmitMm5sHdxNi3xijBlIJLdLFLsQFt8TGOfw">https://tio.run/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/0*zH8mH9OPjM9Hdmuf.png" /></figure><p>The variable “proc” captured “a” into itself. It is a continuation which execution can continue from it.</p><h3>Object</h3><p>Having one initial input and one final output is not enough to describe what is to come. The complete representation of the future must describe what would happen given more input in the future. To represent this, the normal choice is to use an object to store the process, and a couple of methods to be called when the story unfolds.</p><p>lua version: <a href="https://tio.run/##nZHdasMwDIXv/RS6TLY20PRqgz2LcVwVDI4cbJkOSp89808oZXQzm2@MrHP0yZKNal2t08pCcDNKMy/OsyKWUwyGMAS5eKfTDR9wvYmGaJDS0Ak/k7ihFOIcSbNx1FIOhJdO9QLS2TpFe84E5BlZsZosdtfbrlWolsjmQSW7KqFHjp7Kq0A6/aGtwLgcumzcwfRQ22OIlkt/hfQK03fSpvkHcCzAStOJcfyJu0UvoH@F14FmQntlZRGHXuz31WACKNCO2FBU@Qfi3kLOv9cBjb1YvCHuarKHZD8@UY7dE@Hbun4B">https://tio.run/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/0*Iq8tvnXBt_TI95cT.png" /></figure><p>es2017 version: <a href="https://tio.run/##hZDBbsIwDIbveYoc000UAacdeJbKDRYEhbiKne0w8eyd01YIgQY@xLL1@Xf8n@Eb2OcwyCrRAccxolimC3bhMlAWSNL1hUNC5m7I5DXbvfURNP8aq@EpseTihbKDZmnWkFPgFpSGqXWdXhYcNq5/4jJyiaLwMvVp@xuQUUpO99yD4Nbd69UTvCrtXm1Yqg/r36@5mipZr9fphD/vDHKbxqzX80BgC9UiCamABEqT1u0vlWlnT7aNqVZSxDbS0c1IY1VoZ555Pfk//Gsc/wA">https://tio.run/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/0*2gfsAqD5tPwnh_Vf.png" /></figure><p>The variable “proc” here is same as previous “proc”. It is a continuation which execution can continue from it.</p><h3>State machine</h3><p>However, using object does not exactly represent the process. As step1 and step2 are equal. There is no place defining step1 should happen before step2. A more accurate representation is a state machine:</p><p>lua version: <a href="https://tio.run/##rZLRasMgFIbvfQrvmmyt0PRqgz7JGGLMKRPMMeiRFUqfPVMTtox1CxvzRsz5z/9/OWqjGkfrtLI8uB6k6QfnSSHJNgaDEIIcvNNp50d@ubIVkZDSYAfnJF5RMnaKqMk4XFMKhNdK1YynNZOCPeUEoB5IkWotVJfrds1ossjNQqV29XFEOJMMBEP6vMn7flOKHih6LBoG2P2CuZhUuXHL20WwhxAtFfiCcc/bHzCaLxizwR9omkKzHKNOMYfv0ObTHde3@dDY/2HLpvOghBBLvnS5L66bgZ4@Ezwvwyfh0qQgTC45Z/05lke2r9luNzWYwBXXDslgVPk/2Pt4cv2xUDc1G7xBqqZazVP34Zbwhu5hHN8A">https://tio.run/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/0*iFEPjY7vjABwyQg0.png" /></figure><p>es2017 version: <a href="https://tio.run/##jZJNboMwEIX3nMI7TH8chay6yEmqCg3OKHFlbGSP20pVzk49QKOENk29YMTw5ntPHl7hDaIOpqdH53c4DBZJRN9hY7reBwJHTZuicRhj0wevcxVboS3k@lmIfLR3kULS5IOEam7yoYOJCrIaLlsOP6iJhH3@VHJdl6PgOD7Hhmx/gALGZCmPzNh70d7A1uVJEJBScOeghWMtzw35EnTGbP6KML/dCX09h0vW/i8ET0mlFIR9XEbpkA5@N/s@X5q8LPGTWGmwVrL0QXxTZ7djwUzeJQfE91vrluuqWK2mARMF8MLJuARkvBtZp3thzRhN1lXB/4W3qKzfy0lRiczZFL/Ir6qfhuEL">https://tio.run/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/0*zAalUgdrhIQnyyC9.png" /></figure><p>The “next_step” is a cursor, that keeps track of execution status. In x86–64 CPU, there is an instruction pointer register called “RIP” which is similar to “next_step” concept here.</p><h3>Coroutine</h3><p>Coroutine works like a state machine but looks like a function. It takes much less code to express the same idea. There are two styles of coroutine, one with “yield” (also known as “generator”), one with “async/await”. We are going to look at how “yield” works first.</p><p>lua version: <a href="https://tio.run/##hZBLDsIgEIb3nGKWoNZEu3LhWRpKx4SEQsNj4elxaKutRi0bIPP9DzBJ5nxLVkXtLATXY6P7wfkobWzaFLTFEJrBO0U7l4IBLeOUNNDCFZTzLkWCjneNpuPruceQTCRIwh7acfCJT8hapIivx/tLPh92oP56oO0Ym0xK3bdyyqOMyDeeJ1hVTVodqLRylsRJlp9hi1fJ65EX7gAnMUc2h6XwD/Ys2OC1jc/GQGk12xR@UV1yfgA">https://tio.run/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/0*2YWa0WAsue2z0Ygo.png" /></figure><p>es2017 version: <a href="https://tio.run/##hY/RDoIgFIbveYpzKbZ05VUXPYtDPDUagpODq7WenUCdrdUmN8B/vo/93MQonBxUT3tjWwzh4o0kZU0OznZYq663AwlDdeOdMuhc3Q9Wxj0THJ4M4tJI0MAZHgp1uyYDOq8pxgJ20EzxBCyDlZMRqabbaiyHHOSv9mIsWalEJLc6HjgryxlWLjaR1pAyXqQfshQXBu@UcfbV@DM4chYVZzUW2l6zmShGoT1yiC9X7I@04ZxCeAM">https://tio.run/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/0*tiTU_KLed24o1klO.png" /></figure><p>Yield kill two birds with one stone. It returns value to the caller and gets input back. Visually, it looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/0*SmYYhp2mBrbg-njt.png" /></figure><h3>Coroutine object I</h3><p>The coroutine is always resumed by the same function name, such as “next” or “resume”. It is less expressive than “step1” or “step2”. We can wrap the coroutine as an object to make the code looks better.</p><p>lua version: <a href="https://tio.run/##lZLBbsMgDIbvPAVHsqWRmp02ac@CgLgSEoEIjLap6rNnENJE7Tol5QLCn//f2JgoxtE4JQwNrgeu@8F5FBa5jEFbCIEP3qm00096vpANqOFc2w6@E7xBEnKKVqF2dotsLHwxURGa1lwpmFN2AOwBBQppgJ0v9ZZQkcjJTb5JCsp5FzFBjfIgENi1JlbY1VLe0D8aTPeH8RCiwQQK@krlErxPK9h9ci7nbblbpObDC1W79MB25bBCOdwDW55d4h4wejs1g6SkJ6YREIbjJFdTeSP2v@dEPm/TTgo7PWaD0s15vnt@1rGac3i9tj0DH@WlbUUGry1e@0wPhzSoh3DLHrDv4/gL">https://tio.run/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/0*wvCAy95sGUEca2Ke.png" /></figure><p>es2017 version: <a href="https://tio.run/##lZDBbsMgDIbP4yl8JJ1K1fS0w54lItTbmChE2FSrpj175rAm2pRDNC4G@/8/bL/bqyWX/cD7mM44ji8lOvYp7oDSBTt/GVJmG7nrC/mIRN2Qk5OobQOfCuQEZOjhGW4ew3nJZKQSWNIWHqGv6Sq4FxadE8mpvhbH/bIDt7Z9qY2@jEROfBvQEONwFN48k@6nlh8ycskR@M2TifjBkv43tv2NnRexAk9cNQFEvbXOY6MOB6hiT7I0lyL7WOz0Q2XMyD/LrYU6p24bJR5KAU1Ir/pHYq42FGxA0Ce1drV6w/Q0jt8">https://tio.run/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/0*je87lK5U-diJAEUa.png" /></figure><h3>Coroutine object II</h3><p>Although we have added method “step1” and “step2”, but they are not forced to be invoked in that order. Also, what if we want to have two options for “step1”? Say, it could be “step1_add” or “step1_sub”. Let’s upgrade the coroutine object to version 2.</p><p>lua version: <a href="https://tio.run/##jVPbjoIwEH3nK/om3UUS9Wkf/JamwKgkpSW9qBvj/jo7tVhUJEhi0Jkz55y5KBzvOqFKLohRDbC6aZW2XFpWOFNLMIa1WpX4JltyuSYzoJyxWlZwRvDOydLWSqYGxC4jkjdAE4JPUDsiRPPTHuwIUO8waw8gb7/8o8E6LcnxFgBZJQ/BqMP13tBY4klzH0Id/4qJIN@APagKc172VadUWjmLjeUajGvg5jD3LWZ9IY1O/Ce5e5ibYS7hlPLHMXhmdGHAIjG3vBCQXq7ZHFGgiLaQYfBcauAW0jgXOtX6UPJbg6hGQN@8sDGIa0nvtVuyMBbaFeNVtaDPywqD9KV@9OR7WEVeRBAIA28JjStmCJeThE8VoLXS6cJJOLdQWkCfA7g/oXtbr5MIapT89bbW7yx9KhCG6Xe0SUbt9F@@SBlzE2aSQBs0pi@UPv43fDRcaH8ln9zniiYsGxz6VB53cym26ytZLtGBExUpgMQ7QI1a2jg7xGzeE63x0kbYn677Bw">https://tio.run/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/0*dHmec8p3Nsfu-ZjX.png" /></figure><p>es2017 version: <a href="https://tio.run/##jVNNc4IwEL3nV2xPBKs46s2O/6H3TocJYdW0mDBJ8GMcfjtNAFGhreYCyb59u/vy8sX2zHAtcjuRKsWqWheSW6EkGLXDWOxypS2TNk4KIyQaE@dacfelLIQzAbcytOAPYQWX5BG9BC8AjabIbHf0sUO7VekYmN6YT5d5EpilXdgchOVb2oBuqfzizCAExmI@i1maBsu7qF9NMcfK4LWuECUDTKKRff/Ja4rkf97J87wprplLG9LZrVYHCAqJxxy5xTToIOVVKcl22NOpr6ZYA/UweFmtmgnmQV@1p4r5m/L3uCCDkdufEfAuNuilpGH99W6IXCHb7jXaQkuQeIB3rY4n6gHjmwY3aJedefyOWjcw2jH8boGW8JJBvTp9zA2uIWs6undeeJdS9iQpwzdSEnJj8EePYhaS6bSZv74G9w4OIsta9fHIMfcNk@uTcKQdvPYdPSdLmJchOCKuCqdwgtC5nXAljcowytSGNgzRnmUF1vjJjAxZXRMPshZV9QM">https://tio.run/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/0*ZPis7MPmj9v4S76a.png" /></figure><p>We can see coroutine and object are very similar, and coroutine is more powerful. But without direct syntax support, writing method for coroutine is cumbersome.<br>This concludes the first chapter. We have used these ways to implement a very simple process</p><ul><li>function</li><li>object =&gt; state machine</li><li>coroutine =&gt; coroutine object</li></ul><p>Function is inadequate in real-world usage. So we either choose object or coroutine to represent the future. Object is explicit about its expectation but implicit about its state. Coroutine is explicit about its state but implicit about its expectation. We have tried to merge object and coroutine into one with limited success.</p><p>Also, we have learned many forms of continuation</p><ul><li>partial function</li><li>object instance</li><li>coroutine instance</li></ul><p>Continuation will form the foundation of complex scheduling in following chapters.</p><p>See also:</p><p><a href="https://medium.com/software-engineering-problems/what-represents-the-past-present-and-future-9a8f8bbde4b6">What represents the past, present, and future: the future(2)</a></p><p><a href="https://medium.com/software-engineering-problems/what-makes-code-unreadable-to-human-45fa30544386?source=collection_detail----1d0a7ad41f0e-----1---------------------">What makes code unreadable</a></p><p><a href="https://medium.com/software-engineering-problems/what-makes-up-the-software-20f607da9155?source=collection_detail----1d0a7ad41f0e-----2---------------------">What makes good software architecture</a></p><p><a href="https://medium.com/software-engineering-problems/4-major-problems-of-programming-language-c6974c24e083?source=collection_detail----1d0a7ad41f0e-----3---------------------">3 Roles of Programming Languages</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=665966610825" width="1" height="1" alt=""><hr><p><a href="https://medium.com/software-engineering-problems/what-represents-the-past-present-and-future-the-future-1-665966610825">What represents the past, present, and future</a> was originally published in <a href="https://medium.com/software-engineering-problems">Software Engineering Problems</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What makes code slow to execute]]></title>
            <link>https://medium.com/software-engineering-problems/what-makes-code-slow-to-execute-9061bd2ec1a?source=rss-baba231b6963------2</link>
            <guid isPermaLink="false">https://medium.com/p/9061bd2ec1a</guid>
            <category><![CDATA[hardware]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[big-data]]></category>
            <dc:creator><![CDATA[Wen Tao]]></dc:creator>
            <pubDate>Sun, 30 Sep 2018 08:08:55 GMT</pubDate>
            <atom:updated>2018-10-02T23:24:19.836Z</atom:updated>
            <content:encoded><![CDATA[<p>“Within the light cone is destiny” — Cixin Liu</p><p>Performance is primarily determined by the algorithm of the code. There is no question of that. Some algorithm written in python is a lot slower than written in c. To me, this is also an algorithm problem, if you think the code and its language as a whole. It takes a lot more machine instruction to do the same thing in python than c. The sequence of machine instructions is an algorithm.</p><p>x86 instruction can be seen as a high-level language for micro-code used internally in the CPU. When CPU decode the x86 instruction to micro-code with speculative execution will cause significant performance difference. This can also be categorized as an algorithm (of increasing concurrency) problem, and it is not what I want to talk about here.</p><p>Besides the algorithm, what else can makes code slow to execute on the machine? The answer is “data locality”, it takes time to read and write the data for computation. There are multiple examples of it</p><ul><li>CPU Cache</li><li>GPU Architecture</li><li>Distributed Map/Reduce</li><li>Heap Management</li></ul><p>Walking through these examples, we can see why Heterogeneous Computing is inevitable, and programming model in mainstream programming languages is overly simplified.</p><h3>CPU Cache</h3><p>Consider this example <a href="https://stackoverflow.com/questions/9936132/why-does-the-order-of-the-loops-affect-performance-when-iterating-over-a-2d-arra">https://stackoverflow.com/questions/9936132/why-does-the-order-of-the-loops-affect-performance-when-iterating-over-a-2d-arra</a></p><p>Iterate matrix column-wise</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;stdlib.h&gt;</pre><pre>main () {<br>  int i,j;<br>  static int x[4000][4000];<br>  for (i = 0; i &lt; 4000; i++) {<br>    for (j = 0; j &lt; 4000; j++) {<br>      x[j][i] = i + j; }<br>  }<br>}</pre><p>Iterate matrix row-wise</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;stdlib.h&gt;</pre><pre>main () {<br>  int i,j;<br>  static int x[4000][4000];<br>  for (j = 0; j &lt; 4000; j++) {<br>     for (i = 0; i &lt; 4000; i++) {<br>       x[j][i] = i + j; }<br>   }<br>}</pre><p>Row-wise version is 3x to 10x times faster than column-wise version. When the memory address is written continuously, the write can be combined into a single request to save the time on the round-trip.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*b31hiO4ynbDLRrXWEFF4aQ.png" /></figure><p>According to <a href="https://en.wikipedia.org/wiki/CPU_cache">https://en.wikipedia.org/wiki/CPU_cache</a>, as the x86 microprocessors reached clock rates of 20 MHz and above in the 386, small amounts of fast cache memory began to be featured in systems to improve performance. The biggest problem of processor design is that the memory cannot keep up with the speed of the processor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*b31hiO4ynbDLRrXWEFF4aQ.png" /></figure><p>We can see the chart above, modern CPU can crunch a lot of numbers per second. The theoretical data transfer rate to keep the cpu busy is way higher than the bandwidth currently main memory can provide.</p><p>The latency between CPU and main memory is ultimately governed by the speed of light. We have to bring the memory closer to CPU to lower the latency. But on-chip memory (L1/L2/L3 cache) cannot be too large, otherwise, the circuit will be long, and latency will be high.</p><h3>GPU Architecture</h3><p>In the design of CPU, the cache is invisible, the memory is coherent. You do not need to take care of the synchronization between the cache and memory of all sockets. Although you do need to use a memory barrier to declare the actions sequence on one memory address as if they have contended directly on the memory itself directly. To make this happen, CPU need high-speed ring/mesh to synchronize the cache between sockets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*b31hiO4ynbDLRrXWEFF4aQ.png" /></figure><p>This programming model prevents the cores from growing. It is too costly to maintain the illusion of direct memory sharing between cores because the latency of data transfer is inevitable. The memory change needs to be broadcasted to all cache.</p><p>GPU architecture is different. It solves the memory latency issue by making the “cache” explicit. Instead of calling it “cache”, it is just another layer of memory you can use.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*b31hiO4ynbDLRrXWEFF4aQ.png" /></figure><p>In this programming model, there is not just one “heap” of memory, instead the variable need to be explicit about its scope. For example</p><pre>__global__ void parallel_shared_reduce_kernel(float *d_out, float* d_in){<br>    int myID = threadIdx.x + blockIdx.x * blockDim.x;<br>    int tid = threadIdx.x;<br>    extern __shared__ float sdata[];<br>    sdata[tid] = d_in[myID];<br>    __syncthreads();</pre><pre>    //divide threads into two parts according to threadID, and add the right part to the left one, <br>    //lead to reducing half elements, called an iteration; iterate until left only one element<br>    for(unsigned int s = blockDim.x / 2 ; s&gt;0; s&gt;&gt;=1){<br>        if(tid&lt;s){<br>            sdata[tid] += sdata[tid + s];<br>        }<br>        __syncthreads(); //ensure all adds at one iteration are done<br>    }<br>    if (tid == 0){<br>        d_out[blockIdx.x] = sdata[myId];<br>    }<br>}</pre><p>Variable either has no prefix, or __shared__ or __global__. In CPU programming, we need to guess how the cache works. Instead, we can just ask in GPU programming.</p><h3>Distributed Map/Reduce</h3><p>Map/Reduce can handle big data distributed because it avoids data transfer to do computation on the node where data originally is</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*b31hiO4ynbDLRrXWEFF4aQ.png" /></figure><p>The data sent from “map” nodes to “reduce” nodes is substantially smaller than original input because partial computation has already been done.</p><h3>Heap Management</h3><p>Big heap is hard to manage. In modern c++ or rust, we use ownership to manage the memory. Essentially, instead of managing the whole heap as a connected object graph using the garbage collector, the heap is divided into smaller scopes. For example</p><pre>class widget {  <br>private:  <br>  gadget g;   // lifetime automatically tied to enclosing object  <br>public:  <br>  void draw();  <br>};  <br>  <br>void functionUsingWidget () {  <br>  widget w;   // lifetime automatically tied to enclosing scope  <br>              // constructs w, including the w.g gadget member  <br>  …  <br>  w.draw();  <br>  …  <br>} // automatic destruction and deallocation for w and w.g  <br>  // automatic exception safety,   <br>  // as if &quot;finally { w.dispose(); w.g.dispose(); }&quot;</pre><p>There are a lot of cases, the lifetime of one memory address aligned well with function enter/exit and object construction/destruction. There are cases, explicit annotation of the lifetime will be needed</p><pre>fn substr&lt;&#39;a&gt;(s: &amp;&#39;a str, until: u32) -&gt; &amp;&#39;a str;</pre><p>Lifetime declaration like &#39;a is similar with __shared__ in CUDA. Explicit lifetime management like c++ and rust is one extreme. Multi-thread safe garbage collected language like Java and Go is another extreme. Language like Nim partition the memory by threads, which lies in the middle of the spectrum. To ensure the memory in the different partition does not accidentally shared, memory needs to be copied when crossing the boundary. Again, minimizing cost of memory copy is a data locality problem.</p><p>JVM has garbage collection. Instead of annotating the source code statically, it tries to figure out what goes with what in the runtime by dividing the big heap into rough generations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*b31hiO4ynbDLRrXWEFF4aQ.png" /></figure><p>It will a lot easier to deal with heap management problem if we do not share big heap in the first place. There will be cases having multiprocessor sharing memory be beneficial (<a href="https://en.wikipedia.org/wiki/Symmetric_multiprocessing">https://en.wikipedia.org/wiki/Symmetric_multiprocessing</a>). But for a lot of cases, co-locating data and computation (actor programming model) will be easier.</p><h3>Co-locate data and computation</h3><p>Instruction per clock is not growing very fast.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*b31hiO4ynbDLRrXWEFF4aQ.png" /></figure><p>Main memory access latency is nearly flat</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*z525WR6wPsGnEAw-.png" /></figure><p>Having to deal with more than one processors, each with its own memory (Heterogeneous Computing) is likely to be pervasive. It is a clear trend that we need to ensure the data and computation co-located with each other in this paradigm. The problem is how to properly partition the data and computation, in the way data copy or message passing is minimized.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9061bd2ec1a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/software-engineering-problems/what-makes-code-slow-to-execute-9061bd2ec1a">What makes code slow to execute</a> was originally published in <a href="https://medium.com/software-engineering-problems">Software Engineering Problems</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What makes code unreadable]]></title>
            <link>https://medium.com/software-engineering-problems/what-makes-code-unreadable-to-human-45fa30544386?source=rss-baba231b6963------2</link>
            <guid isPermaLink="false">https://medium.com/p/45fa30544386</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[language]]></category>
            <category><![CDATA[internet]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Wen Tao]]></dc:creator>
            <pubDate>Fri, 28 Sep 2018 12:56:13 GMT</pubDate>
            <atom:updated>2018-09-29T07:18:44.960Z</atom:updated>
            <content:encoded><![CDATA[<p>“Any fool can write code that a computer can understand. Good programmers write code that humans can understand.” — Martin Fowler</p><p>Readable code is all about how our brain interpret the source code, what affects its performance. There are four major reasons that make the code unreadable:</p><ul><li>Too many or too long: when your brain need to track # of variables, # of lines of logic</li><li>Non-local logic: we prefer continuous, linear and isolated logic.</li><li>What you see is not what you get: we are forced to imagine how the code works in the runtime when it is vastly different from the source code form. Such as meta programming, multi threading with shared memory.</li><li>Unfamiliar concept: we use name and reference to link one concept to another. When the linking is not strong, we will have trouble and say it does not “make sense”</li></ul><p>Let’s talk about them one by one. Examples taken from</p><ul><li><a href="https://medium.com/@egonelbre/psychology-of-code-readability-d23b1ff1258a">Psychology of Code Readability</a></li><li><a href="https://www.learncpp.com/cpp-tutorial/4-2a-why-global-variables-are-evil/">Why global variables are evil</a></li><li><a href="https://blog.hellojs.org/asynchronous-javascript-from-callback-hell-to-async-and-await-9b9ceb63c8e8">Asynchronous JavaScript: From Callback Hell to Async and Await</a></li></ul><h3>Too many or too long</h3><p>We have limited power to hold variables in our working memory. Keeping track of the change in head consumes exponentially more power every step.</p><pre>// more variable<br>sum1 = v.x<br>sum2 := sum1 + v.y<br>sum3 := sum2 + v.z<br>sum4 := sum3 + v.w</pre><pre>// less variable<br>sum = sum + v.x<br>sum = sum + v.y<br>sum = sum + v.z<br>sum = sum + v.w</pre><p>Every variable has the potential to be changed. If the sum1, sum2, sum3, sum4 is const, it is less stressful.</p><pre>// longer execution path to track<br>public void SomeFunction(int age)<br>{<br>    if (age &gt;= 0) {<br>        // Do Something<br>    } else {<br>        System.out.println(&quot;invalid age&quot;);<br>    }<br>}</pre><pre>// shorter execution path to track<br>public void SomeFunction(int age)<br>{<br>    if (age &lt; 0){<br>        System.out.println(&quot;invalid age&quot;);<br>        return;<br>    }<br>    <br>    // Do Something<br>}</pre><p>Return early cuts down the execution paths we need to track in the head. The shorter path to reach a conclusion, the better.</p><h3>Non-local logic</h3><p>We prefer continuous, linear and isolated logic. Let me explain what I mean</p><ul><li>continuous: the line 2 should be related to line 1, they are put together to express close causality</li><li>linear: you read code from top to bottom, the code executes from top to bottom</li><li>isolated: all you need to care about is in one place</li></ul><pre>// continuous, linear, isolated<br>private static boolean search(int[] x, int srchint) {<br>  for (int i = 0; i &lt; x.length; i++)<br>     if (srchint == x[i])<br>        return true;<br>  return false;<br>}</pre><p>Logic locality is most common problem, and it is subjective. What you cares about defines what does “local” mean to you. Refactoring is re-factoring, it is all about shuffling the logic around, re-organize it in certain ways to make it readable.</p><p>There are three reasons to make the logic non-local.</p><ul><li>coding style: global variable, simd intrinsics v.s. spmd style gpu computing, callback v.s. coroutine</li><li>generalization: to reuse the code, we need to entangle multiple execution paths into one</li><li>non-functional requirements: it is temporal and spatial co-located (both in source code and runtime)</li></ul><h3>Non-local logic: coding style</h3><p>Communicate through global variable will make the causality implicit, making the required logic pieces harder to be put back together.</p><pre>// declare global variable<br>int g_mode;<br> <br>void doSomething()<br>{<br>    g_mode = 2; // set the global g_mode variable to 2<br>}<br> <br>int main()<br>{<br>    g_mode = 1; // note: this sets the global g_mode variable to 1.  It does not declare a local g_mode variable!</pre><pre>    doSomething();</pre><pre>    // Programmer still expects g_mode to be 1<br>    // But doSomething changed it to 2!<br> <br>    if (g_mode == 1)<br>        std::cout &lt;&lt; &quot;No threat detected.\n&quot;;<br>    else<br>        std::cout &lt;&lt; &quot;Launching nuclear missiles...\n&quot;;<br> <br>    return 0;<br>}</pre><p>It is trivial to translate same logic from using global variable to passing context explicitly via arguments. It is the coding style we choose to make code unreadable.</p><p>Second example is about SIMD programming. Write code to drive SIMD executor, we need to take care of multiple “data lane” at the same time. Notice the %ymm0 is 256bit register, 8 data lane for 32 bit:</p><pre>LBB0_3:<br>	vpaddd    %ymm5, %ymm1, %ymm8<br>	vblendvps %ymm7, %ymm8, %ymm1, %ymm1<br>	vmulps    %ymm0, %ymm3, %ymm7<br>	vblendvps %ymm6, %ymm7, %ymm3, %ymm3<br>	vpcmpeqd  %ymm4, %ymm1, %ymm8<br>	vmovaps   %ymm6, %ymm7<br>	vpandn    %ymm6, %ymm8, %ymm6<br>	vpand     %ymm2, %ymm6, %ymm8<br>	vmovmskps %ymm8, %eax<br>	testl     %eax, %eax<br>	jne       LBB0_3</pre><p>Instead of specifying how to apply same operation on multiple data lane, writing code to deal with one “data lane” is much simpler:</p><pre>float powi(float a, int b) {<br>    float r = 1;<br>    while (b--)<br>        r *= a;<br>    return r;<br>}</pre><p>It takes <a href="https://ispc.github.io/ispc.html">https://ispc.github.io/ispc.html</a> to compile the code from SPMD style to SIMD style, they are equivalent.</p><p>The third example is about callback v.s. co-routine</p><pre>const verifyUser = function(username, password, callback){<br>   dataBase.verifyUser(username, password, (error, userInfo) =&gt; {<br>       if (error) {<br>           callback(error)<br>       }else{<br>           dataBase.getRoles(username, (error, roles) =&gt; {<br>               if (error){<br>                   callback(error)<br>               }else {<br>                   dataBase.logAccess(username, (error) =&gt; {<br>                       if (error){<br>                           callback(error);<br>                       }else{<br>                           callback(null, userInfo, roles);<br>                       }<br>                   })<br>               }<br>           })<br>       }<br>   })<br>};</pre><p>compared to</p><pre>const verifyUser = async function(username, password){<br>   try {<br>       const userInfo = await dataBase.verifyUser(username, password);<br>       const rolesInfo = await dataBase.getRoles(userInfo);<br>       const logStatus = await dataBase.logAccess(userInfo);<br>       return userInfo;<br>   }catch (e){<br>       //handle errors as needed<br>   }<br>};</pre><p>Co-routine makes the logic linear, going from top to bottom. The code written in callback style, going from left to right. But they are equivalent. We can choose the coding style to make code more readable, given the programming language allow us to do so.</p><h3>Non-local logic: Generalization</h3><p>To generalize, you have to specialize. If you need to support specialized code for 10 products sharing majority of common code. How often do you need to reason 10 products logic together? Very often, you are thinking about how 1 specific product type works. But reading the generalized code, you are forced to skip over the code for other 9 kinds. The skipping causes real cognitive load.</p><p>Here is a simple example</p><pre>public double PrintBill()<br>{<br>    double sum = 0;<br>    foreach (Drink i in drinks)<br>    {<br>        sum += i.price;<br>    }<br>    drinks.Clear();<br>    return sum;<br>}</pre><p>We think PrintBill is too useful, we have to reuse it. But for happy hour, we need to take discount on some drink. The code become</p><pre>interface BillingStrategy<br>{<br>    double GetActPrice(double rawPrice);<br>}</pre><pre>// Normal billing strategy (unchanged price)<br>class NormalStrategy : BillingStrategy<br>{<br>    public double GetActPrice(Drink drink)<br>    {<br>        return drink.price;<br>    }<br>}</pre><pre>// Strategy for Happy hour (50% discount)<br>class HappyHourStrategy : BillingStrategy<br>{<br>    public double GetActPrice(Drink drink)<br>    {<br>        return drink.price * 0.5;<br>    }<br>}</pre><pre>public double PrintBill(BillingStrategy billingStrategy)<br>{<br>    double sum = 0;<br>    foreach (Drink i in drinks)<br>    {<br>        sum += billingStrategy.GetActPrice(i);<br>    }<br>    drinks.Clear();<br>    return sum;<br>}</pre><p>To generalize PrintBill to both happy hour and normal hour, we have to specialize on billing strategy. To read the generalized code, it is certainly less readable than original version.</p><p>Also to support all kinds of cases, the code can not be specific for just one scenario. This will create a lot of “variation point”. It is very possible, for certain scenario the variation is simply a empty impl to fill the hole. For example, if we need extra service charge for normal hours. The code looks like</p><pre>interface BillingStrategy<br>{<br>    double GetActPrice(double rawPrice);<br>}</pre><pre>// Normal billing strategy (unchanged price)<br>class NormalStrategy : BillingStrategy<br>{<br>    public double GetActPrice(Drink drink)<br>    {<br>        return drink.price;<br>    }<br>    public double GetExtraCharge()<br>    {<br>        return 1;<br>    }<br>}</pre><pre>// Strategy for Happy hour (50% discount)<br>class HappyHourStrategy : BillingStrategy<br>{<br>    public double GetActPrice(Drink drink)<br>    {<br>        return drink.price * 0.5;<br>    }<br>    public double GetExtraCharge()<br>    {<br>        return 0;<br>    }<br>}</pre><pre>public double PrintBill(BillingStrategy billingStrategy)<br>{<br>    double sum = 0;<br>    foreach (Drink i in drinks)<br>    {<br>        sum += billingStrategy.GetActPrice(i);<br>    }<br>    sum += billingStrategy.GetExtraCharge();<br>    drinks.Clear();<br>    return sum;<br>}</pre><p>If you are maintaining the logic for happy hour, the line sum += billingStrategy.GetExtraCharge(); is completely irrelevant to you. But you are forced to read it anyway.</p><p>Also there are many ways to write “branching” code. function overload, class template, object polymorphism, function object, jump table, and plain if/else. Why do we need so many ways to express a simple “if”? It is absurd.</p><h3>Non-local logic: Non-functional requirements</h3><p>Functional and non-functional code are tangled together making the code hard to interpret by human. The primary goal of the source code should be describing the causality chain of everything. When some x happen, but y did not follow, we perceive it as a bug, which is what I mean as causality chain. To make this causality chain executed on physical hardware, there are a lot of details to be specified. For example:</p><ul><li>the value is allocated on stack or heap</li><li>the argument is passed as copy or pointer</li><li>how to log the execution so that we can trackback when debugging</li><li>how to execute concurrent “business” processes, on single thread, multi threads, multi machines, over multi days</li></ul><p>Here is an example on error handling</p><pre>err := json.Unmarshal(input, &amp;gameScores)<br>if ShouldLog(LevelTrace) {<br>  fmt.Println(&quot;json.Unmarshal&quot;, string(input))<br>}<br>metrics.Send(&quot;unmarshal.stats&quot;, err)<br>if err != nil {<br>   fmt.Println(&quot;json.Unmarshal failed&quot;, err, string(input))<br>   return fmt.Errorf(&quot;failed to read game scores: %v&quot;, err.Error())<br>}</pre><p>The functional code is just json.Unmarshal(input, &amp;gameScores), and if err != nil return. We added a lot non-functional code to handle the error. Skipping over those code is non-trivial.</p><h3>What you see is not what you get</h3><p>We are forced to imagine how the code works in the runtime when it is vastly different from the source code form. For example:</p><pre>public class DataRace extends Thread {<br>  private static volatile int count = 0; // shared memory<br>  public void run() {<br>    int x = count;<br>    count = x + 1;<br>  }</pre><pre>  public static void main(String args[]) {<br>    Thread t1 = new DataRace();<br>    Thread t2 = new DataRace();<br>    t1.start();<br>    t2.start();<br>  }<br>}</pre><p>Count is not always x+1, given there are other thread doing the same thing in parallel, they might override your x+1 with their x+1.</p><p>Meta-programming also requires a lot of imagination power. Unlike function call, you can not jump into the function you called to checkout what you are building upon. For example</p><pre>int main() {<br>    for(int i = 0; i &lt; 10; i++) {<br>        char *echo = (char*)malloc(6 * sizeof(char));<br>        sprintf(echo, &quot;echo %d&quot;, i);<br>        system(echo);<br>    }<br>    return 0;<br>}</pre><p>Code is generated on the fly. There is no easy way to checkout the generated source code to reason about its correctness.</p><h3>Unfamiliar concept</h3><p>We use name and reference to link one concept to another. When the linking is not strong, we will have trouble and say it does not “make sense”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FBk5CDt_XgandAn3.png" /></figure><p>We think the game on the left is a lot easier than the game on the right. Why? Because ladder and fireare familiar concept mapped to your real life. We build new experience on top of existing experience. If the code is detached from the requirement, and detached from real life concept, it will be hard to understand.</p><pre>func getThem(theList [][]int) [][]int {<br>	var list1 [][]int<br>	for _, x := range theList {<br>		if x[0] == 4 {<br>			list1 = append(list1, x)<br>		}<br>	}<br>	return list1<br>}</pre><p>is less readable than</p><pre>func getFlaggedCells(gameBoard []Cell) []Cell {<br>	var flaggedCells []Cell<br>	for _, cell := range gameBoard {<br>		if cell.isFlagged() {<br>			flaggedCells = append(flaggedCells, cell)<br>		}<br>	}<br>	return flaggedCells<br>}</pre><pre>type Cell []int</pre><pre>func (cell Cell) isFlagged() bool {<br>	return cell[0] == 4<br>}</pre><p>Because [][]int is unfamiliar, but []Cell mapped to life experience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/0*W0w8Kupw3WJLR-F5.png" /></figure><p>Linking concept from code to life experience is done via “name”, which is just a string. Linking concept between code modules can rely on “reference”. You define function, and reference the function. You define type, and reference the type. From IDE, you can click the ref to go to its definition. When the linking is strong and clear, we can read the code a lot quicker.</p><p>Concepts come from decomposition. Every time we decompose we give it a name. There are three kinds of decomposition:</p><ul><li>Spatial Decomposition</li><li>Temporal Decomposition</li><li>Layer Decomposition</li></ul><p>When we feel the problem is big, we can always break it down by this three methods, just remember to name the concept broken down properly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45fa30544386" width="1" height="1" alt=""><hr><p><a href="https://medium.com/software-engineering-problems/what-makes-code-unreadable-to-human-45fa30544386">What makes code unreadable</a> was originally published in <a href="https://medium.com/software-engineering-problems">Software Engineering Problems</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What makes good software architecture]]></title>
            <link>https://medium.com/software-engineering-problems/what-makes-up-the-software-20f607da9155?source=rss-baba231b6963------2</link>
            <guid isPermaLink="false">https://medium.com/p/20f607da9155</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Wen Tao]]></dc:creator>
            <pubDate>Thu, 27 Sep 2018 08:42:46 GMT</pubDate>
            <atom:updated>2018-10-23T01:31:29.356Z</atom:updated>
            <content:encoded><![CDATA[<p>“All models are wrong, some models are useful” — George Box</p><p>There is no universal standard on good or bad. Here are my AAA principles on defining good software architecture:</p><ul><li>Accountable: good software architecture makes each team hold accountability for its corresponding business objective</li><li>Autonomous: good software architecture should allow each team to move on largely independently without being blocked by others too frequently</li><li>Amortized: good software architecture promote forward thinking, allows the upfront cost of infrastructure amortized</li></ul><p>Accountable &gt;&gt; Autonomous &gt; Amortized. In the 90s, code reuse (Amortization) is hot in object-oriented community. Then SOA/DDD emphasize a lot on Autonomy. But I found both Amortization and Autonomy are ambiguous for guiding the boundary definition in practice. It is hard to convince people, X is better than Y. Really, the functionality of a module should derive from its responsibility.</p><h3>Developers can not estimate</h3><p>“Accountable” really is the key here. I see “the lack of accountability” is the biggest crisis of software development, it is bigger than “unable to manage so-called complexity”.</p><p>It is not a secret that developers can not estimate. It brings a lot of very fundamental problems to good software engineering:</p><ul><li>Because we never know how many people are really needed, middle-management will just add as many people as head-count allows. Why? It is simple, they get paid according to how many people they are currently managing.</li><li>There is no business value to refactor the software to keep it “maintainable”. What does maintainable mean? Throw enough people to the problem, it can always be solved. Software engineering is not rocket science, how hard can it be?</li></ul><p>To solve this problem is not about figuring the magic of story estimation, instead, we should not need to estimate if we are working with the business owner as the same team. Every software team will have one and only one corresponding business team, they share exactly the same OKR. It is important to be responsible for only ONE thing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*j-rUD6qDIs8jYtSS.png" /></figure><p>This is a typical organization chart of the business. Every smaller team will have their OKR aligned with their parent team. The key results of OKR will be measurable so that each team can be accountable for something.</p><p>Typical bad software architecture looks like this: There are a lot of small teams owning their micro-services. The business owner typically needs support from multiple micro-services to accomplish their goal. Every requirement will need to be communicated to different software team again and again. The software team can not name a clear business objective for their micro-service, and because of that, they can not tell what contribution are they making to the business.</p><p>Let me emphasize again: the NO.1 goal of software architecture is to make software team accountable for the business.</p><h3>Bounded Context</h3><p>In the large scale, architecture is about bounded contexts (read DDD for more details). This is just the business organization chart reflected in the software world:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/0*1jHWZl3FADtaDj17.png" /></figure><p>Take the e-commerce domain as an example, the business is divided into several bounded contexts. There is no single team can cover the business process across the bounded contexts. This is generally a good thing here, the big problem is decomposed into smaller problems, and the team of business and technology can work together in one bounded context towards the common goal.</p><h3>Cyberspace &amp; Agents</h3><p>One bounded context is still too large for one team. At least we believe that is the case in micro-service mindset. How to break it further down into more manageable pieces? My model is “cyberspace &amp; agents”. What we are building as programmer essentially boils down to two things:</p><ul><li>the cyberspace</li><li>somewhat intelligent agents interact with us in the cyberspace</li></ul><p>The cyberspace is a virtual world just like the physical one we live in, it is based on causality. There are two kinds of laws:</p><ul><li>natural law: how nature itself works</li><li>social law: a man-made system which mimics the natural law to create social order</li></ul><p>Gravity is an example of natural law, “you pay your debt” is an example of social law. Both of them works the same way, given some causes, some effects must happen according to the law. We use C/C++/Java/Go/… whatever you like to describe it. From ray tracing algorithm, word processor to the e-commerce platform, it is more or less the same about baking some rules into the system. The “law” need to be static and predictable, like cement, builds the real world.</p><p>On top of the cyberspace we built, we as human interaction with each other, from social network to trading. The role played by the human is increasingly replaced by artificial intelligent agents we wrote. For example, instead of editors pick the content, it is the robot that is generating the news and preparing the homepage for you. The agent is getting more and more complex, someday they will emerge from cyberspace to physical space.</p><p>The two kinds of code work very differently. The cyberspace derives cause to effect to maintain natural/social order. The intelligent agent gathers effect to infer a model to maximize some objective. It is crucial to distinguish the intelligent part from the rest of the system. We as human need the rules to be static to build stable expectation. If the “law” keeps changing, the cyberspace will be like a “magical” place which lose the connection with our experience in the real world.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/0*OtHcdIdW_8IlUrbS.png" /></figure><p>The model, the view and the control is the cyberspace. Human and robot are the intelligent agents. The model maintains the data integrity according to the causality defined by the natural or social law. The view and control provide an interface to human/robot for their convenience.</p><h3>Ownership == Authorship</h3><p>The cyberspace part is still too large. It is normally multi-step business process. For example</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*ehF8M0hT_epfYJgj.png" /></figure><p>And bounded contexts correlate with each other. For example</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/0*KgjwYQI97Dnkxfet.png" /></figure><p>The problem of accountability originates from the programming language we use does not cover the whole causality chain. We can draw a flow chart on the whiteboard as a whole, but we have to break it down into many small services/functions to implement it. The workflow engine is frequently brought up because it mapped so nicely to the problem domain, but BPMN is not a programming language.</p><p>There is strong causality between the steps. The promotion displayed on the product detail will need to be displayed in the shopping cart, will be displayed in the checkout, and will be applied to the final receipt. The “function” we use, can only be used to describe casualty within 500ms time span. We have to chop the process into small steps, or into different services serving users of different roles, the causality is hidden inside the messy implementation. The software runs like a relay match, one service pass on the responsibility to another. Ideally, the code should reflect the flow chart, read like the flow chart.</p><p>To make it worse, there is no hard line on who should do what, which frequently leads to debate on responsibilities between teams. Highly political environment makes developers unhappy. Meanwhile, ironically there is no one can be accountable for the whole thing when things go south, as everybody just cut a small piece from the whole.</p><p>The current best practice to fix this problem is to put a facade team on top of everything. “Ownership = Authorship”, we are only willing to own what we write. This is human nature. To give these guys a sense of ownership, we allow a thin proxy/wrapper or orchestration service to glue micro-services back. This often will lead to low autonomy.</p><p>The ideal programming language should provide “function” to describe the business process. Several concurrent causality chains will correlate with each other by message passing. This way, we can assign a separate software team to every business process. They can be 100% accountable for what they are responsible for. Together with the human operator and robots as one team, be responsible for loss and be responsible for the gain, instead of being a shared cost center.</p><h3>Unit of Collaboration</h3><p>There is one more thing that is broken. The module unit provided by the language, such as assemblies/packages/classes used to be the unit we collaborate with each other. This is no longer true. Software modules need to be versioned and deployed separately to support multiple teams working independently.</p><p>But do we “always” need to use different language with different tools for different microservices? The language difference and disconnected tooling make the cross-team communication even harder. You can own your process, own your service, but that should not stop you from sharing the same language with your buddy fellows. One programming language plays 3 different roles: it connects the machines, the developer and the team. Today, the programming languages served primarily as tool to connect machines with people, leaving teams disconnected in the big picture.</p><p>The solution should think the software as a whole, instead of being limited by the narrow view of single “os process”. The cost of introducing a new micro-service should be as cheap as starting a separate thread backed by function in a separate package. The ideal programming language should not treat all function calls evenly.</p><p>See also</p><p><a href="https://medium.com/software-engineering-problems/what-represents-the-past-present-and-future-the-future-1-665966610825">What represents the past, present, and future: the future(1)</a></p><p><a href="https://medium.com/software-engineering-problems/what-makes-code-unreadable-to-human-45fa30544386?source=collection_detail----1d0a7ad41f0e-----2---------------------">What makes code unreadable</a></p><p><a href="https://medium.com/software-engineering-problems/4-major-problems-of-programming-language-c6974c24e083?source=collection_detail----1d0a7ad41f0e-----4---------------------">3 Roles of Programming Languages</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20f607da9155" width="1" height="1" alt=""><hr><p><a href="https://medium.com/software-engineering-problems/what-makes-up-the-software-20f607da9155">What makes good software architecture</a> was originally published in <a href="https://medium.com/software-engineering-problems">Software Engineering Problems</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3 Roles of Programming Languages]]></title>
            <link>https://medium.com/software-engineering-problems/4-major-problems-of-programming-language-c6974c24e083?source=rss-baba231b6963------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6974c24e083</guid>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Wen Tao]]></dc:creator>
            <pubDate>Thu, 27 Sep 2018 04:18:36 GMT</pubDate>
            <atom:updated>2018-09-30T10:20:17.042Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*lEcnNOr5onYegA8rk9BFaw.jpeg" /></figure><p>One programming language plays 3 different roles: it connects the machines, the developer and the team. There are serious flaws in existing programming languages for these roles. If we can solve the 3 problems listed blew, it does not only make the developer experience superb, it will certainly have substantial return financially.</p><h3>Problem of Accountability</h3><p>The biggest crisis of the software development is the lack of accountability. Ideally, there will be one team to be accountable for the whole thing, then they can delegate responsibilities to lower level teams like what was promised by structured programming. Instead, what we are facing in the micro-service world is the responsibilities are relayed from one to many other in a fragmented way, causing great communication overhead for the business owner. And more importantly, this leaves no one can be accountable for the end result.</p><p>Why this is related to programming language? Because every function, every class we write is about breaking down the problem. Language is not just about describing the logic, it also shapes our worldview on how to break the big thing down to small things, and how to put them back together.</p><h3>Problem of Readability</h3><p>It is often we need to read a lot of code to find out what we want. The information density is low. It is often twisted to follow the causality in the code. Code reuse inevitably will hurt the readability, as you need to skip the code irrelevant to your use case. Non-functional requirements entangled with already complex functional logic. Error handling is a common problem to make the code unreadable.</p><p>Making code readable is more than naming your variable properly. The programming language needs to provide construct like co-routine, AOP, multi-dispatch to allow certain kind of coding style.</p><h3>Problem of Heterogeneous Computing</h3><p>Parallel or distributed execution in the mainstream programming language is implemented as compiler vectorization hint or library. Mainstream programming language largely resembles the worldview of PDP-11 with just one sequential CPU. Nowadays, It is very common to have a different kind of execution engines (SIMD, GPU) in the same machine, and it is more and more common to utilize more of them in one piece of software. And the memory model is no longer just one big heap, there could be multiple stages of heap for multiple executors. The programming language should provide a more faithful abstraction of the actual execution device, instead of constraining the thinking and expression in an out-dated computation model.</p><h3>The Vision</h3><p>The ideal programming language should provide these properties</p><ul><li>Responsibility is broken down from very top to very bottom, there is always a team be accountable for the whole.</li><li>Good logic locality, do not need to jump over multiple places to find out what is going on</li><li>The same language can be used to describe SIMD/GPU/MicroServices and interop between them</li></ul><p>In the end, it is all about readability for humankind. You can inspect the code from different conceptual levels, and reason about its correctness (compliance with your mental models) without hurting your eyes and brain.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6974c24e083" width="1" height="1" alt=""><hr><p><a href="https://medium.com/software-engineering-problems/4-major-problems-of-programming-language-c6974c24e083">3 Roles of Programming Languages</a> was originally published in <a href="https://medium.com/software-engineering-problems">Software Engineering Problems</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go test coverage for multi package project]]></title>
            <link>https://medium.com/@taowen/go-test-coverage-for-multi-package-project-d4f36f2b573a?source=rss-baba231b6963------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4f36f2b573a</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[test]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Wen Tao]]></dc:creator>
            <pubDate>Fri, 02 Mar 2018 09:13:24 GMT</pubDate>
            <atom:updated>2018-03-02T09:13:24.473Z</atom:updated>
            <content:encoded><![CDATA[<p>If your code has more than one package. How go test coverage works might be confusing. Here is a quick guide</p><p><strong>One source code package, multiple test packages</strong></p><pre>$ tree -L 1<br>.<br>├── my_pkg.go<br>├── my_pkg_impl.go<br>├── api_tests<br>└── regression_tests</pre><p>All the source code is in one package. But the tests are defined in multiple sub packages. We need a small bash script to get merged coverage data from all those tests.</p><pre>#!/usr/bin/env bash</pre><pre>set -e<br>echo &quot;&quot; &gt; coverage.txt</pre><pre>for d in $(go list ./... | grep -v vendor); do<br>    go test -coverprofile=profile.out -coverpkg=github.com/your/pkg $d<br>    if [ -f profile.out ]; then<br>        cat profile.out &gt;&gt; coverage.txt<br>        rm profile.out<br>    fi<br>done</pre><p>The coverpkg need to be the package under test, you need to modify it yourself.</p><p><strong>One test package, multiple source packages</strong></p><pre>.<br>├── my_test.go<br>├── sub_pkg1<br>└── sub_pkg2</pre><p>If there is only one test package, but multiple packages under test (which we need coverage data for). We can run one go test command do it:</p><pre>go test -coverprofile=profile.out -coverpkg=github.com/your/pkg/sub_pkg1,github.com/your/pkg/sub_pkg2 .</pre><p>coverpkg parameter takes comma as delimiter to specify multiple target packages.</p><p><strong>Multiple test packages, multiple source packages</strong></p><p>Just combine the two mentioned above</p><pre>#!/usr/bin/env bash</pre><pre>set -e<br>echo &quot;&quot; &gt; coverage.txt</pre><pre>for d in $(go list ./... | grep -v vendor); do<br>    go test -coverprofile=profile.out -coverpkg=github.com/your/pkg/sub_pkg1,github.com/your/pkg/sub_pkg2 $d<br>    if [ -f profile.out ]; then<br>        cat profile.out &gt;&gt; coverage.txt<br>        rm profile.out<br>    fi<br>done</pre><p><strong>Show coverage with WEB UI</strong></p><p>using <a href="http://travis-ci.org/">travis</a> and <a href="https://codecov.io/gh">codecov</a>, all you need is</p><pre>language: go</pre><pre>go:<br>  - 1.8.x<br>  - 1.x</pre><pre>before_install:<br>  - go get -t -v ./...</pre><pre>script:<br>  - ./test.sh</pre><pre>after_success:<br>  - bash &lt;(curl -s <a href="https://codecov.io/bash">https://codecov.io/bash</a>)</pre><p>the test.sh is the bash script we produced above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I0kGsJIXspDAcIbyIEc6kQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4f36f2b573a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>