【代码大全2 选读】看看骨灰级高手消灭 if-else 逻辑的瑞士军刀长啥样

news2024/10/7 18:23:48

文章目录

    • 1 【写在前面】
    • 2 【心法】这把瑞士军刀长啥样
    • 3 【示例1】确定某个月份的天数(Days-in-Month Example)
    • 4 【示例2】确定保险费率(Insurance Rates Example)
    • 5 【示例3】灵活的消息格式(Flexible-Message-Format Example)
    • 6 【结语】

1 【写在前面】

随手一翻吃灰多年的《代码大全2》,偶然看到一篇讲重构 if-else / case 的三个案例,很有启发,便有了今天这篇分享。

在这里插入图片描述

2 【心法】这把瑞士军刀长啥样

它就是大名鼎鼎的 表驱动方法(table-driven method)。原文是这样说的:

A table-driven method is a scheme that allows you to look up information in a table rather than using logic statements (if and case) to figure it out.

直译:表驱动法是一种 编程模式——从 里面查找信息,而不使用 逻辑语句ifcase

实际开发中,凡是能通过逻辑语句来实现的功能,都可以通过查表来实现(这个语气是不是似曾相识?)。对于简单情况,用逻辑语句更容易也更直白;随着逻辑链越来越复杂,查表法的作用就愈发凸显出来了。例如,要把字符分为 字母标点数字 三类,若用逻辑语句来实现,可能写成:

if ( (('a' <= inputChar) && (inputChar <= 'z')) ||
        (('A' <= inputChar) && (inputChar <= 'Z'))) {
    charType = CharacterType.Letter;
} else if ( (inputChar == ' ') || (inputChar == ',') ||
        (inputChar == '.') || (inputChar == '!') || (inputChar == '(') ||
        (inputChar == ')') || (inputChar == ':') || (inputChar == ';') ||
        (inputChar == '?') || (inputChar == '-')) {
    charType = CharacterType.Punctuation;
} else if ( ('0' <= inputChar) && (inputChar <= '9') ) {
    charType = CharacterType.Digit;
}

而如果用查表法,上述代码也就一句搞定:

charType = charTypeTable[ inputChar ];

前提是数组 charTypeTable 提前建好。这里的核心在于,把程序中的信息存到 数据 里,而非 逻辑 里;放到表中,而非 if 检测中。(… put your program’s knowledge into its data rather than into its logic — in the table instead of in the if tests.)

使用表驱动法必须回答的两方面问题:

  • 怎样从表中查到数据?推荐方法有三——
    • 直接访问(Direct access)
    • 索引访问(Indexed access)
    • 阶梯访问(Stair-step access)
  • 应该在表里存什么内容?即查出的结果是数据(data)还是操作(action)?
    • 存数据:直接放表里即可;
    • 存操作:要么存一段代码逻辑(想想 Lambda 表达式);要么存某个引用(如 Java8 的方法引用)

心法讲完了,来看三个具体案例。

3 【示例1】确定某个月份的天数(Days-in-Month Example)

先不考虑闰年,逻辑语句法可以写成(Visual Basic 版):

If ( month = 1 ) Then
    days = 31
ElseIf ( month = 2 ) Then
    days = 28
ElseIf ( month = 3 ) Then
    days = 31
ElseIf ( month = 4 ) Then
    days = 30
ElseIf ( month = 5 ) Then
    days = 31
ElseIf ( month = 6 ) Then
    days = 30
ElseIf ( month = 7 ) Then
    days = 31
ElseIf ( month = 8 ) Then
    days = 31
ElseIf ( month = 9 ) Then
    days = 30
ElseIf ( month = 10 ) Then
    days = 31
ElseIf ( month = 11 ) Then
    days = 30
ElseIf ( month = 12 ) Then
    days = 31
End If

这是一段如假包换的经典屎山代码。

再来看看查表法怎么重构的:

' Initialize Table of "Days Per Month" Data
Dim daysPerMonth() As Integer = _
    { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
days = daysPerMonth( month-1 )

考虑闰年的话,改造查表法也很简单,引入一个标志位变成二维数组就行了(如函数 LeapYearIndex),闰年取 1 否则取 0

days = daysPerMonth( month-1, LeapYearIndex() )

可以想象一下,if-else 逻辑语句法的闰年版长啥样……(此处省略 25,000 字)

4 【示例2】确定保险费率(Insurance Rates Example)

写一个算医保费率的程序,该费率随年龄、性别、婚姻状况及吸烟状况的不同而变化。逻辑语句版实现如下:

// Java Example of a Clumsy Way to Determine an Insurance Rate
if ( gender == Gender.Female ) {
    if ( maritalStatus == MaritalStatus.Single ) {
        if ( smokingStatus == SmokingStatus.NonSmoking ) {
            if ( age < 18 ) {
                rate = 200.00;
            } else if ( age == 18 ) {
                rate = 250.00;
            } else if ( age == 19 ) {
                rate = 300.00;
            }
// ...
            else if ( 65 < age ) {
                rate = 450.00;
            }
        else {
            if ( age < 18 ) {
                rate = 250.00;
            } else if ( age == 18 ) {
                rate = 300.00;
            } else if ( age == 19 ) {
                rate = 350.00;
            }
// ...
            else if ( 65 < age ) {
                rate = 575.00;
            }
        }
    else if ( maritalStatus == MaritalStatus.Married )
//  ...
}

这还只是其中一小部分情况,还没包含已婚女士、所有男士、或者 18 ~ 65 岁人群。按这个思路写下去,写成屎山中的“珠穆朗玛”也只是时间的问题。

那么,换成查表法呢?

书中还是用 VB 来实现(当时的 VB 正如日中天,也可能是因为 VB 对多维数组的支持更友好吧):

首先构建数据表:

' Visual Basic Example of Declaring Data to Set Up an Insurance Rates Table
Public Enum SmokingStatus
    SmokingStatus_First = 0
    SmokingStatus_Smoking = 0
    SmokingStatus_NonSmoking = 1
    SmokingStatus_Last = 1
End Enum

Public Enum Gender
    Gender_First = 0
    Gender_Male = 0
    Gender_Female = 1
    Gender_Last = 1
End Enum

Public Enum MaritalStatus
    MaritalStatus_First = 0
    MaritalStatus_Single = 0
    MaritalStatus_Married = 1
    MaritalStatus_Last = 1
End Enum

Const MAX_AGE As Integer = 125
Dim rateTable ( SmokingStatus_Last, Gender_Last, MaritalStatus_Last, _
                MAX_AGE ) As Double

然后调用该数据表:

' Visual Basic Example of an Elegant Way to Determine an Insurance Rate
rate = rateTable( smokingStatus, gender, maritalStatus, age )

5 【示例3】灵活的消息格式(Flexible-Message-Format Example)

如果前两个示例觉得没啥挑战,那你就太小看写《代码大全2》的这帮大宗师了。下面这个案例要解决的,就是针对查询表中的 key 值(或 index 索引值)复杂到难以用代码完全硬编码的情况:

问题描述

编写一个消息打印程序,所有的消息都存放在某类文件中,通常每个文件大概有 500 条这样的消息,涉及大概 20 种消息类型。这些数据采集自一些水上浮标(buoy),提供水温、漂移、方位等信息。

每条消息都包含一个消息头和一段消息正文。消息头有一个标识消息类型的 ID;消息正文由数量不等的字段构成,每一类消息的格式也不尽相同,如图1、图2所示:

图1
图1 浮标信息没有特定顺序,每条消息用 ID 标识

图2
图2 除了消息 ID 外,每类消息有各自的格式

为了突出重点,具体的输出格式就省略了,书中用伪代码一笔带过,最终的一条关于浮标温度的消息,输出结果大概长这样:

Print "Buoy Temperature Message"

Read a floating-point value
Print "Average Temperature"
Print the floating-point value

Read a floating-point value
Print "Temperature Range"
Print the floating-point value

Read an integer value
Print "Number of Samples"
Print the integer value

Read a character string
Print "Location"
Print the character string

Read a time of day
Print "Time of Measurement"
Print the time of day

拿到这样的需求,映入你脑海的第一方案是怎样的?

是不是也像写逻辑分支那样,分 20 多种情况,写到 20 多个 if-elseselect-case 分支,然后每个分支再实现对应的输出逻辑……是这样吗:(伪代码形式)

While more messages to read
    Read a message header
    Decode the message ID from the message header
    If the message header is type 1 then
        Print a type 1 message
    Else if the message header is type 2 then
        Print a type 2 message
...
    Else if the message header is type 19 then
        Print a type 19 message
    Else if the message header is type 20 then
        Print a type 20 message
End While

或者用面向对象的思想来解决:(伪代码形式)

While more messages to read
    Read a message header
    Decode the message ID from the message header
    If the message header is type 1 then
        Instantiate a type 1 message object
    Else if the message header is type 2 then
        Instantiate a type 2 message object
// ...
    Else if the message header is type 19 then
        Instantiate a type 19 message object
    Else if the message header is type 20 then
        Instantiate a type 20 message object
    End if
End While

作者鄙视道:不管是直接写一堆语句、还是抽成 20 多个子类去分别调用公共接口的方法,本质都一样;而且像这样照搬的面向对象编程,写了还不如不写:写成父级接口+子类实现的多态形式,只会让问题更加复杂,后续扩展看似简单,实则比直接写 if-else 还要麻烦。也要改代码、重新编译打包、重新更新发布……

这种情况下,瑞士军刀怎样证明自己呢?

首先,绕过那 20 多种消息类型,直接看消息正文中每个字段出现过的数据类型,并收集到一起(枚举):

// C++ Example of Defining Message Data Types
enum FieldType {
    FieldType_FloatingPoint,
    FieldType_Integer,
    FieldType_String,
    FieldType_TimeOfDay,
    FieldType_Boolean,
    FieldType_BitField,
    FieldType_Last = FieldType_BitField
};

然后把每类消息按如下形式抽象出来,变成一组配置:

// Example of Defining a Message Table Entry
Message Begin
    NumFields 5
    MessageName "Buoy Temperature Message"
    Field 1, FloatingPoint, "Average Temperature"
    Field 2, FloatingPoint, "Temperature Range"
    Field 3, Integer, "Number of Samples"
    Field 4, String, "Location"
    Field 5, TimeOfDay, "Time of Measurement"
Message End

然后,主程序只需要写成下面的伪代码形式即可:

While more messages to read
    Read a message header
    Decode the message ID from the message header
    Look up the message description in the message-description table
    Read the message fields and print them based on the message description
End While

然后,第 4 行用心法中的那三个方法解决检索的问题。

第 5 行输出模块用下面的伪代码实现:

While more fields to print
    Get the field type from the message description
    case ( field type )
        of ( floating point )
            read a floating-point value
            print the field label
            print the floating-point value
        of ( integer )
            read an integer value
            print the field label
            print the integer value
        of ( character string )
            read a character string
            print the field label
            print the character string
        of ( time of day )
            read a time of day
            print the field label
            print the time of day
        of ( boolean )
            read a single flag
            print the field label
            print the single flag
        of ( bit field )
            read a bit field
            print the field label
            print the bit field
    End Case
End While

这样,20 多个消息类型的实现,就转变成了 6 个基本数据类型的实现,并且后者还无视了消息类型数量的变化——无非是修改配置的活,代码可以一直沿用(只要基本类型一直是这 6 个)。

这样改造后,再写成父接口+子类实现的形式,才是面向对象编程的正确打开方式

所谓好人做到底,送佛送到西,作者还是把大致流程用 C++ 过了一遍(大宗师级别还需要手把手敲代码吗?开什么玩笑):

先声明接口和子类实现:

// C++ Example of Setting Up Object Types
class AbstractField {
    public:
    virtual void ReadAndPrint( string, FileStatus & ) = 0;
};
class FloatingPointField : public AbstractField {
    public:
    virtual void ReadAndPrint( string, FileStatus & ) {
    // ...
}
};
class IntegerField // ...
class StringField // ...
// ...

再声明一个容纳所有六种情况的数组并初始化:

// C++ Example of Setting Up a Table to Hold an Object of Each Type
AbstractField* field[ Field_Last+1];

// C++ Example of Setting Up a List of Objects
field[ Field_FloatingPoint ] = new FloatingPointField();
field[ Field_Integer ] = new IntegerField();
field[ Field_String ] = new StringField();
field[ Field_TimeOfDay ] = new TimeOfDayField();
field[ Field_Boolean ] = new BooleanField();
field[ Field_BitField ] = new BitFieldField();

最后是放到主程序模块:

// C++ Example of Looking Up Objects and Member Routines in a Table
fieldIdx = 1;
while ( (fieldIdx <= numFieldsInMessage) && (fileStatus == OK) ) {
    fieldType = fieldDescription[ fieldIdx ].FieldType;
    fieldName = fieldDescription[ fieldIdx ].FieldName;
    /* This is the table lookup that calls a routine depending on the 
       type of the field just by looking it up in a table of objects. */
    field[ fieldType ].ReadAndPrint( fieldName, fileStatus );
    fieldIdx++;
}

后面的检索实现和瑞士军刀无关,就不介绍了。

6 【结语】

我是看到第三个示例,才下决心写一写这个心得的,因为之前的工作就刚好遇到了类似的情况。当时自认为十分牛逼的写法,只要放到看过这一段、或者真正领悟了表驱动法精髓的开发者面前,也不过是另一堆屎山罢了。拿到需求的第一时间,可能面临的很多因素都是非技术层面的,比如“时间紧、任务重”,或者“立等可取”,“明早出一版”,“这是上面的死命令”……要想甩锅,在职场打拼多年的老油条们谁又不会呢?但我想说的是,自己的代码写成什么样,说到底还是你对自己整个职业生涯的定位决定的。自己写的代码不求流芳百世,但求尽量别遗臭万年、别被后来接盘的某某骂到春秋战国时期就行。

关键的关键,是要明白,这样的问题其实是有瑞士军刀级的解决方案的。从菜鸟成长为高手的过程,往往就是一个不断缩小自我认知领域中“不知道自己不知道”的过程。

P.S.:对《代码大全2》感兴趣的朋友,可以自行感受一下作者那大宗师级别的气场——详见原书第 18 章《表驱动方法》(Chapter 18:Table-Driven Methods

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1898193.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

基于深度学习的图像背景剔除

在过去几年的机器学习领域&#xff0c;我一直想打造真正的机器学习产品。 几个月前&#xff0c;在参加了精彩的 Fast.AI 深度学习课程后&#xff0c;似乎一切皆有可能&#xff0c;我有机会&#xff1a;深度学习技术的进步使许多以前不可能实现的事情成为可能&#xff0c;而且开…

链篦机回转窑球团生产工艺

生球在回转窑氧化焙烧&#xff0c;回转窑头部设有燃烧器&#xff0c;燃料可以采用气体、固体、液体。 来自环冷机一冷却段的高温废气作为二次风进入窑内参与燃烧&#xff0c;烧成成品球进入环冷机。 环冷机采用鼓风冷却&#xff0c;热风风箱分为四段&#xff1a; 一段气体引至…

人工智能系列-numpy(三)

&#x1f308;个人主页&#xff1a;羽晨同学 &#x1f4ab;个人格言:“成为自己未来的主人~” 副本和视图 副本 副本是一个数据的完整的拷贝&#xff0c;如果我们对副本进行修改&#xff0c;它不会影响到原始数据&#xff0c;物理内存不再同一位置。副本一般发生在Pytho…

中英双语介绍英国伦敦(London)

中文版 伦敦简介 伦敦&#xff08;London&#xff09;是英国的首都&#xff0c;也是全球最重要的金融、文化、艺术和交通中心之一。作为一座历史悠久的城市&#xff0c;伦敦融合了现代化的城市生活与丰富的历史遗产。以下是对伦敦的详细介绍&#xff0c;包括其经济状况、高等…

zed摄像头 orin域控掉帧问题

cpu性能并没有吃满&#xff0c;双目摄像头的帧率忽高忽低 原因是域控没有开性能模式&#xff0c;调成MAXN模式就行。

实在智能对话钉钉:宜搭+实在Agent,AI时代的工作方式

比起一个需求需要等产品、技术排期&#xff0c;越来越多的人开始追求把自己武装成「全能战士」&#xff0c;通过低代码工具一搭&#xff0c;一个高效的工作平台便产生了。 宜搭是钉钉自研的低代码应用构建平台&#xff0c;无论是专业开发者还是没有代码基础的业务人员&#xf…

PCL从理解到应用【03】KDTree 原理分析 | 案例分析 | 代码实现

前言 本文分析KDTree的原理&#xff0c;集合案例深入理解&#xff0c;同时提供源代码。 三个案例&#xff1a;K近邻搜索、半径内近邻搜索、近似最近邻搜索。方法对比&#xff0c;如下表所示&#xff1a; 特性K近邻搜索半径内近邻搜索近似最近邻搜索描述查找K个最近邻点查找指…

spdlog一个非常好用的C++日志库(五): 源码分析之线程池thread_pool

目录 1.线程池 2.thread_pool简介 3.多生产者-多消费者阻塞队列模型 3.1.阻塞与非阻塞方式插入数据 3.2.取出数据 3.3.overrun异常处理机制 3.4.其他接口 4.环形队列circular_q 5.thread pool模型 6.thread pool实现 6.1.thread_pool类接口 6.2.构造与析构 6.3.po…

pip install包出现哈希错误解决

如图&#xff0c;当遇到此类错误时&#xff0c;多半是连接不稳定导致的校验失败。我们可以在PC端&#xff0c;或Ubuntu通过浏览器下载.whl安装文件&#xff1a;直接复制报错信息中的网址到浏览器即可弹出下载窗口。

tomcat 安装和优化

tomcatat tomcat和http一样&#xff0c;都是用来处理动态页面的 tomcat也可以作为web服务器&#xff0c;开源的 php.php tomcat.jsp nginx.html tomcat使用java代码写的程序&#xff0c;运行的是java的web服务程序 tomcat的特点和功能&#xff1a; 1、servlet容器&…

【笔记】TimEP Safety Mechanisms方法论

1.TimEPM Overview 三大监控方法: Alive Supervision 实时监督Logical Supervision 逻辑监督Deadline Supervision 限时监督相关模块框图: 相关模块调用框图: 每个MCU核开启内狗(1核1狗),内狗用于监控相应核的TASK超时,超时后软reset MCU内狗时钟需要独立于OS时钟,两…

22_嵌入式微处理器

目录 嵌入式微处理器分类 嵌入式硬件结构 嵌入式微处理器的分类 典型8位微处理器 8位微处理器结构 8051单片机的硬件组成 8051单片机的引脚 时钟电路 MCS-51指令集 典型16位微处理器 16位微处理器结构 MSP430单片机硬件结构 典型32位微处理器 32位微处理器特点 A…

误删分区后的数据拯救:双管齐下恢复策略

在数字化时代&#xff0c;数据的价值日益凸显&#xff0c;而误删分区作为常见的数据安全威胁之一&#xff0c;常常让用户措手不及。本文将深入探讨误删分区的现象&#xff0c;并为您揭示两种高效的数据恢复方案&#xff0c;旨在帮助您在最短时间内找回失去的数据&#xff0c;同…

C++学习笔记二

一、常量 1.用const关键字声明常量变量 const常量变量在定义时必须进行初始化&#xff0c;并且不能通过赋值来改其值 const double gravity { 9.8 }; //首选在类型之前使用const int const sidesInSquare { 4 }; // “east const”风格&#xff0c;可以&#xff0c;但不是首…

小程序分包加载、独立分包、分包预加载等

一、小程序分包加载 小程序的代码通常是由许多页面、组件以及资源等组成&#xff0c;随着小程序功能的增加&#xff0c;代码量也会逐渐增加&#xff0c; 体积过大就会导致用户打开速度变慢&#xff0c;影响用户的使用体验。分包加载是一种小程序优化技术。将小程序不同功能的代…

SpringBoot整合Dubbo的快速使用教程

目录 一、什么是Dubbo? 二、SpringBoot整合Dubbo 1、父工程引入依赖 2、各个Dubbo服务子模块引入依赖 3、服务提供者 &#xff08;1&#xff09;启动类添加注解EnableDubbo &#xff08;2&#xff09;服务类添加注解DubboService &#xff08;3&#xff09;配置文件…

class类和style内联样式的绑定

这里的绑定其实就是v-bind的绑定&#xff0c;如代码所示&#xff0c;div后面的引号就是v-bind绑定&#xff0c;然后大括号将整个对象括起来&#xff0c;对象内先是属性&#xff0c;属性后接的是变量&#xff0c;这个变量是定义在script中的&#xff0c;后通过这个变量&#xff…

数据库国产化之路(一)

数据库国产化之路(一) 1、前言&#xff1a;适配海量数据库过程中的一些记录&#xff0c;备忘用 2、海量数据库基于的pg版本&#xff0c;查看PG_VERSION文件为9.2。 3、MySQL中的IF函数替代&#xff0c;一开始的方案是从网上找了个if函数&#xff0c;后来发现CASE WHEN其实能完成…

【c语言】轻松拿捏自定义类型

&#x1f31f;&#x1f31f;作者主页&#xff1a;ephemerals__ &#x1f31f;&#x1f31f;所属专栏&#xff1a;C语言 目录 前言 一、结构体 1.结构体类型的定义和使用 1.1 结构体类型声明 1.2 结构体变量的创建和初始化 1.3 结构体变量成员的访问 1.4 结构体的特殊声…

[深度学习]卷积理解

单通道卷积 看这个的可视化就很好理解了 https://github.com/vdumoulin/conv_arithmetic/blob/master/README.md 多通道卷积 当输入有多个通道时,卷积核需要拥有相同的通道数. 假设输入有c个通道,那么卷积核的每个通道分别于相应的输入数据通道进行卷积,然后将得到的特征图对…