枚举与静态常量比较

本文探讨了静态常量在应用中的多种缺陷,包括类型不安全、缺乏命名空间、脆弱性及打印值无提示性等问题,并通过与枚举模式的比较,展示了枚举模式在解决这些问题上的优势。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

静态常量是枚举模式的应用
它有很多缺点:类型不安全(静态常量可以随意增加使用或操作),无命名空间,脆弱(某常量值改变后客户端如果不编译仍能使用,但表现却是未定义的),静态常量打印值为数字,也不具提示性等等

 

 

客户端未编译有待推敲?

 

 

This pattern has many problems, such as:

  • Not typesafe - Since a season is just an int you can pass in any other int value where a season is required, or add two seasons together (which makes no sense).
  • No namespace - You must prefix constants of an int enum with a string (in this case SEASON_ ) to avoid collisions with other int enum types.
  • Brittleness - Because int enums are compile-time constants, they are compiled into clients that use them. If a new constant is added between two existing constants or the order is changed, clients must be recompiled. If they are not, they will still run, but their behavior will be undefined.
  • Printed values are uninformative - Because they are just ints, if you print one out all you get is a number, which tells you nothing about what it represents, or even what type it is.

脆弱性的理解在这里比如是静态常量,修改了,插入或者增加,客户端必须得重新编译来适应新的变化,而枚举的话则不必,比如它可以通过遍历来囊括所有新的变化,客户端代码可以不用改变,这就是用静态常量脆弱性的体现。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值