使用字符串vs枚举作为工厂方法的参数? [英] Use of strings vs enums as parameter of factory method?

查看:56
本文介绍了使用字符串vs枚举作为工厂方法的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近正在阅读此博客 https://blog.cleancoder.com/uncle-bob/2021/03/06/ifElseSwitch.html 和本段使我感到困惑:

I was recently reading this blog https://blog.cleancoder.com/uncle-bob/2021/03/06/ifElseSwitch.html and this paragraph confused me:

请谨慎使用该令牌x.不要试图使其成为枚举或其他任何东西需要在红线上方进行声明.整数或字符串是一个更好的选择.它可能不是类型安全的.确实,它不能安全输入.但是它将允许您保留组件您的架构的结构.

Be careful with that token x. Don’t try to make it an enum or anything that requires a declaration above the red line. An integer, or a string is a better choice. It may not be type safe. Indeed, it cannot be type safe. But it will allow you to preserve the component structure of your architecture.

如果我们在较高级别的模块中声明一个枚举,那么低级模块是否仍然依赖于高级别模块,还会吗?如果是这样,那么在这种情况下使用枚举有什么问题呢?

If we declare an enum in the higher level module, wouldn't it still be that the low level module depends on the high level module? If so, then what is wrong in using an enum in this case?

推荐答案

唯一可以肯定地回答这个问题的人是罗伯特·C·马丁(Robert C. Martin)本人,但我会尝试尝试.

The only person who can definitely answer that question is Robert C. Martin himself, but I'll try to make an attempt.

据我所知,隐含的情况是 $ input 参数表示运行时输入,而本质上是 not 类型安全的.

As far as I understand it, the implied scenario is that the $input parameter represents run-time input, which is inherently not type-safe.

在许多应用程序体系结构中,软件满足现实世界"存在界限.在原始应用程序中,您可能要求用户为 male 输入 0 ,为 female 输入 1 .在控制台应用程序中,您甚至都不会收到 int -您会得到一个 string .

In many application architectures, there's a boundary where the software 'meets the real world'. In a primitive application, you may ask the user to type 0 for male and 1 for female. In a console application, you're not even going to receive an int - you'll get a string.

在Web应用程序中,您很容易遇到类似的问题.即使您使用单选按钮创建了一个不错的GUI,您也不能完全相信某些恶意用户不会尝试绕过GUI而是给您一个原始的 string -代码中其他地方的错误将起到类似的作用.

In a web application you easily run into a similar problem. Even if you make a nice GUI with, say, radio buttons, you can't fully trust that some malign user wouldn't try to circumvent the GUI to instead give you a raw string - or, that a bug somewhere else in the code is going to do something to a similar effect.

引入枚举不会改变这一点.您仍然必须将原始的 string 解析为一个枚举值.如果接下来要做的是在枚举上进行 switch 转换以生成多态对象,那么您也可以省去中间步骤,因此也可以省去枚举.

Introducing an enum isn't going to change that. You'll still have to parse the raw string into an enum value. If the next thing you do is then to switch on the enum to produce a polymorphic object, you might as well dispense with the intermediary step, and hence, with the enum.

此讨论让人想起亚历克西斯·金(Alexis King)的精彩博文

This discussion is reminiscent of Alexis King's great blog post Parse, don't validate, which makes a similar point: turn something less-structured into something with a better structure.

这篇关于使用字符串vs枚举作为工厂方法的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆