什么时候应该劝阻弱类型?

发布于 2024-07-14 11:39:27 字数 202 浏览 15 评论 0原文

什么时候应该劝阻弱类型? 弱类型是否会在大型项目中受到阻碍? 如果左侧是强类型的,如下所示,这会是规则的例外吗?

   int i = 5
   string sz = i
   sz = sz + "1"
   i  = sz

是否有任何语言支持与上述类似的语法? 告诉我更多关于弱类型和相关情况的利弊。

When should weak types be discouraged? Are weak types discouraged in big projects? If the left side is strongly typed like the following would that be an exception to the rule?

   int i = 5
   string sz = i
   sz = sz + "1"
   i  = sz

Does any languages support similar syntax to the above? Tell me more about pros and cons to weak types and situations related.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

很酷又爱笑 2024-07-21 11:39:27

我认为您将“弱类型”与“动态类型”混淆了。

术语“弱类型”意味着“非强类型”,这意味着内存位置的值允许与其类型指示的值不同。

C 是弱类型语言的一个例子。 它允许编写这样的代码:

typedef struct
{
    int x;
    int y;

} FooBar;

FooBar foo;
char * pStr = &foo;
pStr[0] = 'H';
pStr[1] = 'i';
pStr[2] = '\0';

也就是说,它允许将 FooBar 实例视为字符数组。

在强类型语言中,这是不允许的。 要么会生成编译器错误,要么会引发运行时异常,但 FooBar 内存地址在任何时候都不会包含不是有效 FooBar 的数据。

C#、Java、Lisp、Java Script 和 Ruby 是不允许此类行为的语言示例。 它们是强类型的。

其中一些语言是“静态类型”,这意味着变量类型在编译时分配,而一些语言是“动态类型”,这意味着变量类型直到运行时才知道。 “静态与动态”和“弱与强”是正交问题。 例如,Lisp 是一种“强动态类型”语言,而“C”是一种“弱静态类型语言”。

此外,正如其他人指出的那样,“推断类型”和程序员指定的类型之间存在区别。 C# 中的“var”关键字是类型推断的一个示例。 但是,它仍然是静态类型构造,因为编译器在编译时而不是在运行时推断变量的类型。

所以,你的问题真正要问的是:

相对优点是什么?
静态类型的缺点,动态类型
打字、弱打字、强打字、
推断的静态类型和用户
指定静态类型。

我提供了以下所有这些问题的答案:

静态类型

静态类型有 3 个主要好处:

  1. 更好的工具支持
  2. 减少某些类型错误的可能性
  3. 性能

用户体验和准确性由于静态类型提供了额外的信息,静态类型语言中的智能和重构等功能得到了极大的改进。 如果您输入“a”。 在代码编辑器中,并且“a”具有静态类型,那么编译器知道“.”之后可能合法出现的所有内容。 从而可以向您显示准确的完成列表。 可以用动态类型语言支持某些场景,但它们的限制要大得多。

此外,在没有编译器错误的程序中,重构工具可以识别使用特定方法、变量或类型的每个位置。 在动态类型语言中不可能做到这一点。

第二个好处有些争议。 静态类型语言的支持者喜欢这样说。 然而,静态类型语言的反对者认为,他们捕获的错误是微不足道的,并且无论如何他们都会通过测试捕获。 但是,您确实会预先收到有关拼写错误的变量或方法名称之类的通知,这可能会有所帮助。

静态类型语言还可以实现更好的“数据流分析”,与 Microsoft 的 SAL(或类似工具)等工具结合使用可以帮助发现潜在的安全问题。

最后,通过静态类型,编译器可以进行更多优化,因此可以生成更快的代码。

缺点:

静态类型的主要缺点是它限制了您可以执行的操作。 您可以使用动态类型语言编写无法使用静态类型语言编写的程序。 Ruby on Rails 就是一个很好的例子。

动态类型

动态类型的一大优点是它比静态类型强大得多。 你可以用它做很多很酷的事情。

另一个原因是它需要更少的打字。 您不必到处指定类型。

缺点

动态类型有 2 个主要缺点:

  1. 您无法从编译器或 IDE 获得尽可能多的“控制权”。
  2. 它不适合关键性能场景。 例如,没有人用 Ruby 编写操作系统内核。

强类型:

强类型的最大好处是安全性。 强制执行强类型通常需要某种类型的运行时支持。 如果程序可以证明类型安全,那么许多安全问题(例如缓冲区溢出)就会消失。

弱类型:

强类型的最大缺点和弱类型的最大优点是性能。

当您可以以任何您喜欢的方式访问内存时,您就可以编写更快的代码。 例如,数据库只需写出原始字节即可将对象交换到磁盘,而不需要求助于“ISerialized”接口之类的东西。 视频游戏可以通过在大缓冲区上运行单个释放来丢弃与一个级别相关的所有数据,而不是为许多小对象运行析构函数。

能够做这些事情需要弱类型。

类型推断

类型推断可以发挥静态类型的许多优点,而无需进行太多类型的输入。

用户指定类型

有些人就是不喜欢类型推断,因为他们喜欢明确。 这更多的是一种风格。

I think you are confusing "weak typing" with "dynamic typing".

The term "weak typing" means "not strongly typed", which means that the value of a memory location is allowed to vary from what it's type indicates it should be.

C is an example of a weakly typed language. It allows code like this to be written:

typedef struct
{
    int x;
    int y;

} FooBar;

FooBar foo;
char * pStr = &foo;
pStr[0] = 'H';
pStr[1] = 'i';
pStr[2] = '\0';

That is, it allows a FooBar instance to be treated as if it was an array of characters.

In a strongly typed language, that would not be allowed. Either a compiler error would be generated, or a run time exception would be thrown, but never, at any time, would a FooBar memory address contain data that was not a valid FooBar.

C#, Java, Lisp, Java Script, and Ruby are examples of languages where this type of thing would not be allowed. They are strongly typed.

Some of those languages are "statically typed", which means that variable types are assigned at compile time, and some are "dynamically typed", which means that variable types are not known until runtime. "Static vs Dynamic" and "Weak vs Strong" are orthogonal issues. For example, Lisp is a "strong dynamically typed" language, whereas "C" is a "weak statically typed language".

Also, as others have pointed out, there is a distinction between "inferred types" and types specified by the programmer. The "var" keyword in C# is an example of type inference. However, it's still a statically typed construct because the compiler infers the type of a variable at compile time, rather than at runtime.

So, what your question really is asking is:

What are the relative merits and
drawbacks of static typing, dynamic
typing, weak typing, stong typing,
inferred static types, and user
specified static types.

I provide answers to all of these below:

Static typing

Static typing has 3 primary benefits:

  1. Better tooling support
  2. A Reduced likely hood of certain types of bugs
  3. Performance

The user experience and accuracy of things like intellisence, and refactoring is improved greatly in a statically typed language because of the extra information that the static types provide. If you type "a." in a code editor and "a" has a static type then the compiler knows everything that could legally come after the "." and can thus show you an accurate completion list. It's possible to support some scenarios in a dynamically typed language, but they are much more limited.

Also, in a program without compiler errors a refactoring tool can identify every place a particular method, variable, or type is used. It's not possible to do that in a dynamically typed language.

The second benefit is somewhat controversial. Proponents of statically typed languages like to make that claim. Opponents of statically typed languages, however, contend that the bugs they catch are trivial, and that they would get caught by testing anyways. But, you do get notification of things like misspelled variable or method names up front, which can be helpful.

Statically typed languages also enable better "data flow analysis", which when combined with things like Microsoft's SAL (or similar tools) can help find potential security problems.

Finally, with static typing, compilers can do a lot more optimization, and so can produce faster code.

Drawbacks:

The main drawback for static typing is that it restricts the things you can do. You can write programs in dynamically typed languages that you can't write in statically typed languages. Ruby on Rails is a good example of this.

Dynamic Typing

The big advantage of dynamic typing is that it's much more powerful than static typing. You can do a lot of really cool stuff with it.

Another one is that it requires less typing. You don't have to specify types all over the place.

Drawbacks:

Dynamic typing has 2 main draw backs:

  1. You don't get as much "hand holding" from the compiler or IDE
  2. It's not suitable for critical performance scenarios. For example, no one writes OS Kernels in Ruby.

Strong typing:

The biggest benefit of strong typing is security. Enforcing strong typing usually requires some type of runtime support. If a program can proove type safety then a lot of security issues, such as buffer overuns, just go away.

Weak typing:

The big drawback of strong typing, and the big benefit of weak typing, is performance.

When you can access memory any way you like, you can write faster code. For example a database can swap objects out to disk just by writing out their raw bytes, and not needing to resort to things like "ISerializable" interfaces. A video game can throw away all the data associated with one level by just running a single free on a large buffer, rather than running destructors for many small objects.

Being able to do those things requires weak typing.

Type inference

Type inference allows a lot of the benefits of static typing without requiring as much typing.

User specified types

Some people just don't like type inference because they like to be explicit. This is more of a style thing.

日记撕了你也走了 2024-07-21 11:39:27

弱类型是语言简化的一种尝试。 虽然这是一个值得实现的目标,但弱类型却是一个糟糕的解决方案。

COM Variants 中使用的弱类型是解决此问题的早期尝试,但它充满了危险,而且坦率地说,它会带来比其价值更多的麻烦。 即使是能够忍受各种垃圾的 Visual Basic 程序员也正确地认为这是一个坏主意,并将 Microsoft 的 ETC(扩展类型转换)反称为“邪恶类型转换”。

不要将推断类型与弱类型混淆。 推断类型是在编译时从上下文推断出的强类型。 一个很好的例子是 var 关键字,它在 C# 中用于声明适合接收 LINQ 表达式值的变量。

相比之下,每次计算表达式时都会推断出弱类型。 问题的示例代码对此进行了说明。 另一个例子是在 C 中使用非类型化指针。非常方便,但会带来麻烦。

推断类型解决了与弱类型相同的问题,但没有引入与弱类型相关的问题。 因此,只要宿主语言可用,它就是首选替代方案。

Weak typing is an attempt at language simplification. While this is a worthy goal, weak typing is a poor solution.

Weak typing such as is used in COM Variants was an early attempt to solve this problem, but it is fraught with peril and frankly causes more trouble than it's worth. Even Visual Basic programmers, who will put up with all sorts of rubbish, correctly pegged this as a bad idea and backronymed Microsoft's ETC (Extended Type Conversion) to Evil Type Cast.

Do not confuse inferred typing with weak typing. Inferred typing is strong typing inferred from context at compile time. A good example is the var keyword, used in C# to declare a variable suitable to receive the value of a LINQ expression.

By contrast, weak typing is inferred each and every time an expression is evaluated. This is illustrated in the question's sample code. Another example would be use of untyped pointers in C. Very handy yet begging for trouble.

Inferred typing addresses the same issue as weak typing, without introducing the problems associated with weak typing. It is therefore a preferred alternative whenever the host language makes it available.

_蜘蛛 2024-07-21 11:39:27

他们几乎总是应该感到沮丧。 我能想到的唯一需要的代码类型是需要一些指针巫术的低级代码。

为了回答你的问题,C 支持这样的代码(当然除了没有字符串类型),这听起来像 PHP 或 Perl 会有的东西(但我可能完全错了)。

They should almost always be discouraged. The only type of code that I can think of where it would be required is low-level code that requires some pointer voodoo.

And to answer your question, C supports code like that (except of course for not having a string type), and that sounds like something PHP or Perl would have (but I could be totally wrong on that).

淡笑忘祈一世凡恋 2024-07-21 11:39:27

什么时候应该阻止弱类型? 弱者是否不鼓励
大项目? 如果左侧是强类型的,如下所示
这会是规则的例外吗?

int i = 5 字符串 sz = i sz = sz + "1" i = sz

是否有任何语言支持与上述类似的语法? 告诉我更多
关于弱类型和相关情况的利弊。

也许

您可以编写自己的库来做到这一点。

在 C++ 中,您可以使用称为“运算符重载”的东西,这意味着您可以声明一种类型的变量以将其初始化为另一种类型的变量。这就是为什么语句:

[std::string str = "Hello World";][1]

具体来说,您将定义一个函数(其中变量的类型是 T,B 是您想要将其设置为的类型)

,即使引号之间的任何文本都被解释为字符数组,

T& T::operator= ( const B s );

请注意,这是一个 字符数组。类的成员函数
另请注意,如果您想自由地使用它,您可能需要某种函数来反转此操作 - 像

B& T::operator= ( const T s);

C++ 这样的函数足够强大,可以让您创建一个通常为弱类型的对象,但如果您想纯粹地对待它弱类型,您将只想创建一个可用作任何原语的变量类型,并且仅使用带有指向 void 的指针的函数。
相信我,当强类型编程可用时,使用它会容易得多。

我个人更喜欢强类型,因为我不需要担心当我不知道变量的用途时出现的错误。 例如,如果我想编写一个函数来与一个人交谈 - 该函数使用了这个人的身高、体重、姓名、孩子的数量等 - 但你给了我一个颜色,我会得到一个错误,因为你可以使用非常简单的算法并不能真正确定颜色的大部分内容。

就弱类型的优点而言,如果您正在编写要在程序(即 Web 浏览器或 UNIX shell)中运行的内容,那么您可能希望习惯松散类型编程。 JavaScript 和 Shell 脚本是弱类型的。

我建议像汇编语言这样的编程语言是唯一的硬件级弱类型语言之一,但是我见过的汇编语言的风格根据分配的大小为每个变量附加一个类型,即word、dword、qword 。

我希望我给了你一个很好的解释,没有在你嘴里说任何话。

"

When should weak types be discouraged? Are weak types discouraged in
big projects? If the left side is strongly typed like the following
would that be an exception to the rule?

int i = 5 string sz = i sz = sz + "1" i = sz

Does any languages support similar syntax to the above? Tell me more
about pros and cons to weak types and situations related.

"

Perhaps you could program your own library to do that.

In C++ you can use something called an "operator overload", which means that you can declare a variable of one type to be initialized as a variable of another type. That is what makes the statement:

[std::string str = "Hello World";][1]

specifically you would define a function (where the variable's type is T and B is the type you want to set it as)

work, even though any text between quotes is interpreted as an array of chars.

T& T::operator= ( const B s );

Please note that this is a class's member function
Also note that you will probably want to have some sort of function that reverses this manipulation if you want to use it liberally - something like

B& T::operator= ( const T s);

C++ is powerful enough to allow you to make an object generally weakly typed, but if you want to treat it purely weakly typed, you will want to make just a single variable type that can be used as any primitive, and use only functions that take a pointer to void.
Believe me, it is a lot easier to use strongly typed programming when it is available.

I personally prefer strongly typed, because I don't need to worry about the errors that come when I don't know what a variable is meant to do. For example, if I wanted to write a function to talk to a person - and that function used the person's height, weight, name, number of children, etc. - but you gave me a color, I would get an error because you can't really determine most of these things for a color using an algorithm that is very simple.

As far as the pros of weakly typed, you might want to get used to loosely typed programming if you are programming something to be run within a program(i.e. a web browser or a UNIX shell). JavaScript and Shell Script are weakly typed.

I would suggest that a programming language like assembly language is one of the only harware-level weakly typed languages, but the flavor of Assembly language I've seen attaches a type to each variable depending on the allocated size, i.e. word, dword, qword.

I hope I gave you a good explanation and did not put any words in your mouth.

孤独患者 2024-07-21 11:39:27

弱类型本质上不如强类型健壮,因为你没有告诉机器到底要做什么——相反,机器必须弄清楚你的意思。 这通常工作得相当充分,但通常并不清楚结果应该是什么。 例如,字符串乘以浮点值是什么?

Weak types are by their very nature less robust than strong types, because you don't tell the machine exactly what to do - instead the machine has to figure out what you meant. This often works quite adequately, but in general it is not clear what the result should be. What is, for example, a string multiplied by float?

流绪微梦 2024-07-21 11:39:27

是否有任何语言支持与上述类似的语法?

Perl 允许您互换地处理一些数字和字符串。 例如,“5”+“1”将为您提供 6。一般来说,这类事情的问题是很难避免歧义:“5”+1 应该是“51”还是“6”? Perl 通过使用单独的字符串连接运算符并保​​留 + 来进行数字加法来解决这个问题。

其他语言必须弄清楚您是要进行串联还是相加,以及(如果相关)结果将是什么类型或表示形式。

Does any languages support similar syntax to the above?

Perl allows you to treat some numbers and strings interchangeably. For example, "5" + "1" will give you 6. The problem with this sort of thing in general is that it can be hard to avoid ambiguity: should "5" + 1 be "51" or "6"? Perl gets around this by having a separate operator for string concatenation, and reserving + for numeric addition.

Other languages would have to sort out whether you mean to do a concatenation or an addition, and (if relevant) what type or representation the result will be.

海的爱人是光 2024-07-21 11:39:27

我进行了 ASP/VBScript 编码,并在没有允许弱类型的“选项严格”的情况下使用遗留代码。

很多时候这都是地狱,尤其是在经验不足的程序员手中。 我们遇到的所有愚蠢错误都需要很长时间才能诊断。

其中一个愚蠢的例子是这样的:

'Config 
    Dim pass
    pass = "asdasd"


If NOT pass = Request("p") Then
Response.Write "login failed"
REsponse.End()
End If

到目前为止一切都很好,但是如果用户将 pass 更改为整数密码,猜猜它将不再起作用,因为 int pass != string pass (来自 querystring)。 我认为它应该可以工作,但它没有我不记得确切的代码

我讨厌弱类型,而不是愚蠢的调试会话,我可以花额外的时间来输入变量的确切类型。

简而言之,根据我的经验,尤其是在大型项目中,尤其是对于没有经验的开发人员来说,这只是麻烦。

I did ASP/VBScript coding and work with legacy code without "option strict" which allows weak typing.

It was a hell in many times, especially in the hands of less experienced programmers. We got all stupid errors takes ages to diagnose.

One of the stupid examples was like this:

'Config 
    Dim pass
    pass = "asdasd"


If NOT pass = Request("p") Then
Response.Write "login failed"
REsponse.End()
End If

So far so good but if the user changes pass to an integer password, guess what it won't work anymore because int pass != string pass (from querystring). I thought it supposed to work but it didn't I can't remember the exact piece of code.

I hate weak typing, instead of stupid debugging session I can spend extra seconds for typing exact type of a variable.

Simply put, in my experience especially in the big projects and especially with unexperienced developers it's just trouble.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文