强类型语言和静态类型语言有什么区别?

发布于 2024-08-30 01:11:43 字数 23 浏览 7 评论 0原文

另外,其中之一是否暗示着另一个?

Also, does one imply the other?

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

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

发布评论

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

评论(9

黎夕旧梦 2024-09-06 01:11:43

强类型语言和静态类型语言有什么区别?

静态类型语言具有一个类型系统,该系统在编译时由实现(编译器或解释器)进行检查。类型检查会拒绝某些程序,而通过检查的程序通常会附带一些保证;例如,编译器保证不对浮点数使用整数算术指令。

对于“强类型”的含义并没有真正的共识,尽管专业文献中最广泛使用的定义是在“强类型”语言中,程序员不可能绕过类型系统施加的限制。该术语几乎总是用于描述静态类型语言。

静态与动态

静态类型的反面是“动态类型”,这意味着

  1. 运行时使用的值被分类为类型。
  2. 这些值的使用方式存在限制。
  3. 当违反这些限制时,违规行为将报告为(动态)类型错误。

例如Lua,一种动态类型语言,有字符串类型、数字类型、布尔类型等。在 Lua 中,每个值都完全属于一种类型,但这并不是所有动态类型语言的要求。在Lua中,允许连接两个字符串,但不允许连接一个字符串和一个布尔值。

强类型与弱

类型 “强类型”的反义词是“弱类型”,这意味着您可以绕过类型系统。 C 是出了名的弱类型,因为任何指针类型都可以通过简单的转换转换为任何其他指针类型。 Pascal 原本是强类型的,但设计中的疏忽(未标记的变体记录)在类型系统中引入了漏洞,因此从技术上讲,它是弱类型的。
真正强类型语言的示例包括 CLU、Standard ML 和 Haskell。事实上,标准机器学习已经经历了多次修订,以消除该语言广泛部署后发现的类型系统中的漏洞。

这里究竟发生了什么?

总的来说,谈论“强”和“弱”并没有多大用处。类型系统是否存在漏洞并不重要,重要的是漏洞的确切数量和性质、它们在实践中出现的可能性有多大,以及利用漏洞的后果是什么。在实践中,最好完全避免使用“强”和“弱”这两个术语,因为

  • 业余爱好者经常将它们与“静态”和“动态”混为一谈。

  • 显然,“弱类型”被一些人用来谈论隐式转换的相对普遍或不存在。

  • 专业人士无法就这些术语的确切含义达成一致。

  • 总体而言,您不太可能告知或启发您的受众。

可悲的事实是,当谈到类型系统时,“强”和“弱”没有普遍认同的技术含义。如果你想讨论类型系统的相对强度,它最好准确讨论提供和不提供哪些保证。
例如,一个很好的问题是:“是否保证给定类型(或类)的每个值都是通过调用该类型的构造函数之一创建的?”在 C 语言中,答案是否定的。在 CLU、F# 和 Haskell 中,答案是肯定的。对于 C++,我不确定——我想知道。

相比之下,静态类型意味着程序在执行之前会被检查,并且程序可能在启动之前被拒绝。 动态类型意味着在执行期间检查的类型,类型错误的操作可能会导致程序停止或以其他方式发出错误信号在运行时。静态类型的主要原因是排除可能存在此类“动态类型错误”的程序。

其中一个是否暗示另一个?

从迂腐的角度来看,不,因为“强”这个词实际上没有任何意义。但在实践中,人们几乎总是做以下两件事之一:

  • 他们(错误地)使用“强”和“弱”来表示“静态”和“动态”,在这种情况下,他们(错误地)使用“强类型” ”和“静态类型”可互换。

  • 他们使用“强”和“弱”来比较静态类型系统的属性。很少听到有人谈论“强”或“弱”动态类型系统。除了 FORTH 之外,它实际上没有任何类型系统,我想不出有一种动态类型语言可以破坏类型系统。根据定义,这些检查被内置到执行引擎中,并且每个操作在执行之前都会检查其完整性。

无论哪种方式,如果一个人将一种语言称为“强类型”,那么这个人很可能正在谈论静态类型语言。

What is the difference between a strongly typed language and a statically typed language?

A statically typed language has a type system that is checked at compile time by the implementation (a compiler or interpreter). The type check rejects some programs, and programs that pass the check usually come with some guarantees; for example, the compiler guarantees not to use integer arithmetic instructions on floating-point numbers.

There is no real agreement on what "strongly typed" means, although the most widely used definition in the professional literature is that in a "strongly typed" language, it is not possible for the programmer to work around the restrictions imposed by the type system. This term is almost always used to describe statically typed languages.

Static vs dynamic

The opposite of statically typed is "dynamically typed", which means that

  1. Values used at run time are classified into types.
  2. There are restrictions on how such values can be used.
  3. When those restrictions are violated, the violation is reported as a (dynamic) type error.

For example, Lua, a dynamically typed language, has a string type, a number type, and a Boolean type, among others. In Lua every value belongs to exactly one type, but this is not a requirement for all dynamically typed languages. In Lua, it is permissible to concatenate two strings, but it is not permissible to concatenate a string and a Boolean.

Strong vs weak

The opposite of "strongly typed" is "weakly typed", which means you can work around the type system. C is notoriously weakly typed because any pointer type is convertible to any other pointer type simply by casting. Pascal was intended to be strongly typed, but an oversight in the design (untagged variant records) introduced a loophole into the type system, so technically it is weakly typed.
Examples of truly strongly typed languages include CLU, Standard ML, and Haskell. Standard ML has in fact undergone several revisions to remove loopholes in the type system that were discovered after the language was widely deployed.

What's really going on here?

Overall, it turns out to be not that useful to talk about "strong" and "weak". Whether a type system has a loophole is less important than the exact number and nature of the loopholes, how likely they are to come up in practice, and what are the consequences of exploiting a loophole. In practice, it's best to avoid the terms "strong" and "weak" altogether, because

  • Amateurs often conflate them with "static" and "dynamic".

  • Apparently "weak typing" is used by some persons to talk about the relative prevalance or absence of implicit conversions.

  • Professionals can't agree on exactly what the terms mean.

  • Overall you are unlikely to inform or enlighten your audience.

The sad truth is that when it comes to type systems, "strong" and "weak" don't have a universally agreed on technical meaning. If you want to discuss the relative strength of type systems, it is better to discuss exactly what guarantees are and are not provided.
For example, a good question to ask is this: "is every value of a given type (or class) guaranteed to have been created by calling one of that type's constructors?" In C the answer is no. In CLU, F#, and Haskell it is yes. For C++ I am not sure—I would like to know.

By contrast, static typing means that programs are checked before being executed, and a program might be rejected before it starts. Dynamic typing means that the types of values are checked during execution, and a poorly typed operation might cause the program to halt or otherwise signal an error at run time. A primary reason for static typing is to rule out programs that might have such "dynamic type errors".

Does one imply the other?

On a pedantic level, no, because the word "strong" doesn't really mean anything. But in practice, people almost always do one of two things:

  • They (incorrectly) use "strong" and "weak" to mean "static" and "dynamic", in which case they (incorrectly) are using "strongly typed" and "statically typed" interchangeably.

  • They use "strong" and "weak" to compare properties of static type systems. It is very rare to hear someone talk about a "strong" or "weak" dynamic type system. Except for FORTH, which doesn't really have any sort of a type system, I can't think of a dynamically typed language where the type system can be subverted. Sort of by definition, those checks are bulit into the execution engine, and every operation gets checked for sanity before being executed.

Either way, if a person calls a language "strongly typed", that person is very likely to be talking about a statically typed language.

你不是我要的菜∠ 2024-09-06 01:11:43

这经常被误解,所以让我澄清一下。

静态/动态类型

静态类型是将类型绑定到变量的地方。类型在编译时进行检查。

动态类型是将类型绑定到的地方。类型在运行时检查。

例如,在 Java 中:

String s = "abcd";

s 将“永远”是 String。在其生命周期中,它可能指向不同的String(因为s是Java中的引用)。它可能有一个 null 值,但它永远不会引用 IntegerList。这就是静态类型。

在 PHP 中:

$s = "abcd";          // $s is a string
$s = 123;             // $s is now an integer
$s = array(1, 2, 3);  // $s is now an array
$s = new DOMDocument; // $s is an instance of the DOMDocument class

这就是动态类型。

强/弱类型

(编辑警报!)

强类型是一个没有广泛商定含义的短语。大多数使用该术语表示静态类型以外的含义的程序员都使用它来暗示编译器强制执行类型规则。例如,CLU 具有强大的类型系统,不允许客户端代码创建抽象类型的值,除非使用该类型提供的构造函数。 C 具有较强的类型系统,但它可以在一定程度上被“颠覆”,因为程序总是可以将一种指针类型的值转换为另一种指针类型的值。例如,在 C 中,您可以获取 malloc() 返回的值并将其转换为 FILE*,编译器不会尝试阻止您,或者甚至警告你你正在做任何狡猾的事情。

(最初的答案说了一些关于“在运行时不改变类型”的值。我认识很多语言设计者和编译器编写者,但不知道有谁谈论在运行时改变值的类型,除了可能一些非常先进的类型研究系统,这被称为“强更新问题”。)

弱类型意味着编译器不强制执行类型规则,或者这种强制可能很容易被破坏。

这个答案的原文将弱类型与隐式转换(有时也称为“隐式升级”)混为一谈。例如,在 Java 中:

String s = "abc" + 123; // "abc123";

这是代码,是隐式提升的示例:123 在与 "abc" 连接之前隐式转换为字符串。可以说 Java 编译器将该代码重写为:

String s = "abc" + new Integer(123).toString();

考虑一个经典的 PHP“开头为”问题:

if (strpos('abcdef', 'abc') == false) {
  // not found
}

这里的错误是 strpos() 返回匹配的索引,即 0。0 是强制的转换为布尔值 false,因此条件实际上为 true。解决方案是使用 === 而不是 == 来避免隐式转换。

此示例说明了隐式转换和动态类型的组合如何使程序员误入歧途。

与 Ruby 相比:

val = "abc" + 123

这是一个运行时错误,因为在 Ruby 中,对象 123 没有隐式转换,只是因为它碰巧被传递给 + 方法。在 Ruby 中,程序员必须明确进行转换:

val = "abc" + 123.to_s

比较 PHP 和 Ruby 就是一个很好的说明。两者都是动态类型语言,但 PHP 有很多隐式转换,而 Ruby(如果您不熟悉它,可能会感到惊讶)没有。

静态/动态与强/弱

这里的要点是静态/动态轴独立于强/弱轴。人们之所以对它们感到困惑,部分原因可能是强类型与弱类型的定义不那么明确,而且对于强类型和弱类型的确切含义也没有真正的共识。因此,强/弱类型更像是灰色阴影,而不是黑色或白色。

因此,回答你的问题:另一种看待这个问题的方法大部分是正确的,那就是静态类型是编译时类型安全,强类型是运行时类型安全。

原因是静态类型语言中的变量具有必须声明并可以在编译时检查的类型。强类型语言的值在运行时具有类型,并且程序员很难在没有动态检查的情况下破坏类型系统。

但重要的是要了解语言可以是静态/强、静态/弱、动态/强或动态/弱。

This is often misunderstood so let me clear it up.

Static/Dynamic Typing

Static typing is where the type is bound to the variable. Types are checked at compile time.

Dynamic typing is where the type is bound to the value. Types are checked at run time.

So in Java for example:

String s = "abcd";

s will "forever" be a String. During its life it may point to different Strings (since s is a reference in Java). It may have a null value but it will never refer to an Integer or a List. That's static typing.

In PHP:

$s = "abcd";          // $s is a string
$s = 123;             // $s is now an integer
$s = array(1, 2, 3);  // $s is now an array
$s = new DOMDocument; // $s is an instance of the DOMDocument class

That's dynamic typing.

Strong/Weak Typing

(Edit alert!)

Strong typing is a phrase with no widely agreed upon meaning. Most programmers who use this term to mean something other than static typing use it to imply that there is a type discipline that is enforced by the compiler. For example, CLU has a strong type system that does not allow client code to create a value of abstract type except by using the constructors provided by the type. C has a somewhat strong type system, but it can be "subverted" to a degree because a program can always cast a value of one pointer type to a value of another pointer type. So for example, in C you can take a value returned by malloc() and cheerfully cast it to FILE*, and the compiler won't try to stop you—or even warn you that you are doing anything dodgy.

(The original answer said something about a value "not changing type at run time". I have known many language designers and compiler writers and have not known one that talked about values changing type at run time, except possibly some very advanced research in type systems, where this is known as the "strong update problem".)

Weak typing implies that the compiler does not enforce a typing discpline, or perhaps that enforcement can easily be subverted.

The original of this answer conflated weak typing with implicit conversion (sometimes also called "implicit promotion"). For example, in Java:

String s = "abc" + 123; // "abc123";

This is code is an example of implicit promotion: 123 is implicitly converted to a string before being concatenated with "abc". It can be argued the Java compiler rewrites that code as:

String s = "abc" + new Integer(123).toString();

Consider a classic PHP "starts with" problem:

if (strpos('abcdef', 'abc') == false) {
  // not found
}

The error here is that strpos() returns the index of the match, being 0. 0 is coerced into boolean false and thus the condition is actually true. The solution is to use === instead of == to avoid implicit conversion.

This example illustrates how a combination of implicit conversion and dynamic typing can lead programmers astray.

Compare that to Ruby:

val = "abc" + 123

which is a runtime error because in Ruby the object 123 is not implicitly converted just because it happens to be passed to a + method. In Ruby the programmer must make the conversion explicit:

val = "abc" + 123.to_s

Comparing PHP and Ruby is a good illustration here. Both are dynamically typed languages but PHP has lots of implicit conversions and Ruby (perhaps surprisingly if you're unfamiliar with it) doesn't.

Static/Dynamic vs Strong/Weak

The point here is that the static/dynamic axis is independent of the strong/weak axis. People confuse them probably in part because strong vs weak typing is not only less clearly defined, there is no real consensus on exactly what is meant by strong and weak. For this reason strong/weak typing is far more of a shade of grey rather than black or white.

So to answer your question: another way to look at this that's mostly correct is to say that static typing is compile-time type safety and strong typing is runtime type safety.

The reason for this is that variables in a statically typed language have a type that must be declared and can be checked at compile time. A strongly-typed language has values that have a type at run time, and it's difficult for the programmer to subvert the type system without a dynamic check.

But it's important to understand that a language can be Static/Strong, Static/Weak, Dynamic/Strong or Dynamic/Weak.

无人问我粥可暖 2024-09-06 01:11:43

两者都是两个不同轴上的极点:

  • 强类型与弱类型
  • 静态类型与动态类型

强类型意味着变量不会自动从一种类型转换为另一种类型。弱类型则相反:Perl 可以在数字上下文中使用像 "123" 这样的字符串,方法是自动将其转换为 int 123。像 python 这样的强类型语言不会这样做。

静态类型意味着编译器在编译时计算出每个变量的类型。动态类型语言仅在运行时确定变量的类型。

Both are poles on two different axis:

  • strongly typed vs. weakly typed
  • statically typed vs. dynamically typed

Strongly typed means, a variable will not be automatically converted from one type to another. Weakly typed is the opposite: Perl can use a string like "123" in a numeric context, by automatically converting it into the int 123. A strongly typed language like python will not do this.

Statically typed means, the compiler figures out the type of each variable at compile time. Dynamically typed languages only figure out the types of variables at runtime.

爱的那么颓废 2024-09-06 01:11:43

强类型意味着类型之间的转换存在限制。

静态类型意味着类型不是动态的 - 一旦创建变量,您就无法更改其类型。

Strongly typed means that there are restrictions between conversions between types.

Statically typed means that the types are not dynamic - you can not change the type of a variable once it has been created.

゛时过境迁 2024-09-06 01:11:43

上面已经给出了答案。尝试区分强与弱、静态与动态概念。

什么是强类型VS弱类型?

强类型:不会自动从一种类型转换为另一种类型

在 Go 或 Python 等强类型语言中,“2”+ 8 会引发类型错误,因为它们不允许“类型强制” 。

弱(松散)类型:将自动从一种类型转换为另一种类型:
JavaScript 或 Perl 等弱类型语言不会抛出错误,在这种情况下,JavaScript 将结果为“28”,而 perl 将结果为 10。

Perl 示例:

my $a = "2" + 8;
print $a,"\n";

将其保存到 main.pl 并运行 perl main.pl 你会得到输出 10。

什么是 Static VS Dynamic 类型?

在编程中,程序员根据检查变量类型的点来定义静态类型和动态类型。静态类型语言是在编译时进行类型检查的语言,而动态类型语言是在运行时进行类型检查的语言。

  • 静态:在运行时之前检查类型
  • 动态:在执行期间动态检查类型

这意味着什么?

在 Go 中,它会在运行时之前检查键入的内容(静态检查)。这意味着它不仅会翻译和类型检查正在执行的代码,而且还会扫描所有代码,并且在代码运行之前会抛出类型错误。例如,

package main

import "fmt"

func foo(a int) {
    if (a > 0) {
        fmt.Println("I am feeling lucky (maybe).")
    } else {
        fmt.Println("2" + 8)
    }
}

func main() {
    foo(2)
}

将此文件保存在 main.go 中并运行它,您将收到编译失败的消息。

go run main.go
# command-line-arguments
./main.go:9:25: cannot convert "2" (type untyped string) to type int
./main.go:9:25: invalid operation: "2" + 8 (mismatched types string and int)

但这种情况对于 Python 无效。例如,以下代码块将在第一次 foo(2) 调用时执行,并在第二次 foo(0) 调用时失败。这是因为 Python 是动态类型的,它只对正在执行的代码进行翻译和类型检查。 else 块永远不会为 foo(2) 执行,因此“2”+ 8 甚至不会被查看,而对于 foo(0) 调用,它将尝试执行该块并失败。

def foo(a):
    if a > 0:
        print 'I am feeling lucky.'
    else:
        print "2" + 8
foo(2)
foo(0)

您将看到以下输出

python main.py
I am feeling lucky.
Traceback (most recent call last):
  File "pyth.py", line 7, in <module>
    foo(0)
  File "pyth.py", line 5, in foo
    print "2" + 8
TypeError: cannot concatenate 'str' and 'int' objects

Answer is already given above. Trying to differentiate between strong vs week and static vs dynamic concept.

What is Strongly typed VS Weakly typed?

Strongly Typed: Will not be automatically converted from one type to another

In Go or Python like strongly typed languages "2" + 8 will raise a type error, because they don't allow for "type coercion".

Weakly (loosely) Typed: Will be automatically converted to one type to another:
Weakly typed languages like JavaScript or Perl won't throw an error and in this case JavaScript will results '28' and perl will result 10.

Perl Example:

my $a = "2" + 8;
print $a,"\n";

Save it to main.pl and run perl main.pl and you will get output 10.

What is Static VS Dynamic type?

In programming, programmer define static typing and dynamic typing with respect to the point at which the variable types are checked. Static typed languages are those in which type checking is done at compile-time, whereas dynamic typed languages are those in which type checking is done at run-time.

  • Static: Types checked before run-time
  • Dynamic: Types checked on the fly, during execution

What is this means?

In Go it checks typed before run-time (static check). This mean it not only translates and type-checks code it’s executing, but it will scan through all the code and type error would be thrown before the code is even run. For example,

package main

import "fmt"

func foo(a int) {
    if (a > 0) {
        fmt.Println("I am feeling lucky (maybe).")
    } else {
        fmt.Println("2" + 8)
    }
}

func main() {
    foo(2)
}

Save this file in main.go and run it, you will get compilation failed message for this.

go run main.go
# command-line-arguments
./main.go:9:25: cannot convert "2" (type untyped string) to type int
./main.go:9:25: invalid operation: "2" + 8 (mismatched types string and int)

But this case is not valid for Python. For example following block of code will execute for first foo(2) call and will fail for second foo(0) call. It's because Python is dynamically typed, it only translates and type-checks code it’s executing on. The else block never executes for foo(2), so "2" + 8 is never even looked at and for foo(0) call it will try to execute that block and failed.

def foo(a):
    if a > 0:
        print 'I am feeling lucky.'
    else:
        print "2" + 8
foo(2)
foo(0)

You will see following output

python main.py
I am feeling lucky.
Traceback (most recent call last):
  File "pyth.py", line 7, in <module>
    foo(0)
  File "pyth.py", line 5, in foo
    print "2" + 8
TypeError: cannot concatenate 'str' and 'int' objects
软糯酥胸 2024-09-06 01:11:43

数据强制并不一定意味着弱类型,因为有时它的语法糖:

上面的 Java 弱类型示例是因为

String s = "abc" + 123;

它不是弱类型示例,因为它实际上是这样做的:

String s = "abc" + new Integer(123).toString()

如果您正在构造一个新对象,数据强制也不是弱类型。
Java 是弱类型的一个非常糟糕的例子(任何具有良好反射能力的语言很可能都不是弱类型的)。因为语言的运行时总是知道类型是什么(例外可能是本机类型)。

这与 C 不同。C 是弱类型的最佳示例之一。运行时不知道 4 个字节是整数、结构体、指针还是 4 个字符。

语言的运行时真正定义了它是否弱类型,否则它只是意见。

编辑:
经过进一步思考,这不一定是真的,因为运行时不必将运行时系统中的所有类型具体化为强类型系统。
Haskell 和 ML 具有如此完整的静态分析,以至于它们可以从运行时省略类型信息。

Data Coercion does not necessarily mean weakly typed because sometimes its syntacical sugar:

The example above of Java being weakly typed because of

String s = "abc" + 123;

Is not weakly typed example because its really doing:

String s = "abc" + new Integer(123).toString()

Data coercion is also not weakly typed if you are constructing a new object.
Java is a very bad example of weakly typed (and any language that has good reflection will most likely not be weakly typed). Because the runtime of the language always knows what the type is (the exception might be native types).

This is unlike C. C is the one of the best examples of weakly typed. The runtime has no idea if 4 bytes is an integer, a struct, a pointer or a 4 characters.

The runtime of the language really defines whether or not its weakly typed otherwise its really just opinion.

EDIT:
After further thought this is not necessarily true as the runtime does not have to have all the types reified in the runtime system to be a Strongly Typed system.
Haskell and ML have such complete static analysis that they can potential ommit type information from the runtime.

暖树树初阳… 2024-09-06 01:11:43

其中之一并不意味着另一个。对于静态类型的语言来说,这意味着所有变量的类型都是在编译时已知或推断的。

强类型语言不允许您将一种类型用作另一种类型。 C 是一种弱类型语言,是强类型语言所不允许的一个很好的例子。在 C 中,您可以传递错误类型的数据元素,它不会抱怨。在强类型语言中你不能。

One does not imply the other. For a language to be statically typed it means that the types of all variables are known or inferred at compile time.

A strongly typed language does not allow you to use one type as another. C is a weakly typed language and is a good example of what strongly typed languages don't allow. In C you can pass a data element of the wrong type and it will not complain. In strongly typed languages you cannot.

虫児飞 2024-09-06 01:11:43

强类型可能意味着变量具有明确定义的类型,并且在表达式中组合不同类型的变量有严格的规则。例如,如果 A 是整数,B 是浮点数,则关于 A+B 的严格规则可能是 A 转换为浮点数,并将结果作为浮点数返回。如果 A 是整数,B 是字符串,则严格规则可能是 A+B 无效。

静态类型可能意味着类型在编译时分配(或非编译语言的等效类型),并且在程序执行期间不能更改。

请注意,这些分类并不是相互排斥的,实际上我希望它们经常一起出现。许多强类型语言也是静态类型的。

请注意,当我使用“可能”这个词时,是因为这些术语没有普遍接受的定义。正如您从迄今为止的答案中已经看到的那样。

Strong typing probably means that variables have a well-defined type and that there are strict rules about combining variables of different types in expressions. For example, if A is an integer and B is a float, then the strict rule about A+B might be that A is cast to a float and the result returned as a float. If A is an integer and B is a string, then the strict rule might be that A+B is not valid.

Static typing probably means that types are assigned at compile time (or its equivalent for non-compiled languages) and cannot change during program execution.

Note that these classifications are not mutually exclusive, indeed I would expect them to occur together frequently. Many strongly-typed languages are also statically-typed.

And note that when I use the word 'probably' it is because there are no universally accepted definitions of these terms. As you will already have seen from the answers so far.

遇见了你 2024-09-06 01:11:43

恕我直言,最好完全避免这些定义,不仅没有商定的术语定义,确实存在的定义往往侧重于技术方面,例如是否允许混合类型操作,如果不允许,是否存在漏洞绕过限制,例如使用指针按您的方式工作。

相反,再次强调这是一种观点,人们应该关注这个问题:类型系统是否使我的应用程序更可靠?一个特定于应用程序的问题。

例如:如果我的应用程序有一个名为 acceleration 的变量,那么显然该变量的声明和使用方式是否允许将值 "Monday" 分配给 加速度这是一个问题,因为显然加速度不能是工作日(和字符串)。

另一个例子:在 Ada 中,可以定义:subtype Month_Day is Integer range 1..31;,类型 Month_Day 是弱类型,因为它不是独立的类型整数(因为它是子类型),但其范围仅限于 1..31。相比之下: type Month_Day is new Integer; 将创建一个不同的类型,这种类型很强大,因为它不能在没有显式转换的情况下与整数混合 - 但它不受限制并且可以接收值-17,这是毫无意义的。所以技术上它更强,但可靠性较差。
当然,可以声明type Month_Day is new Integer range 1..31;来创建一种独特且受限制的类型。

Imho, it is better to avoid these definitions altogether, not only there is no agreed upon definition of the terms, definitions that do exist tend to focus on technical aspects for example, are operation on mixed type allowed and if not is there a loophole that bypasses the restrictions such as work your way using pointers.

Instead, and emphasizing again that it is an opinion, one should focus on the question: Does the type system make my application more reliable? A question which is application specific.

For example: if my application has a variable named acceleration, then clearly if the way the variable is declared and used allows the assignment of the value "Monday" to acceleration it is a problem, as clearly an acceleration cannot be a weekday (and a string).

Another example: In Ada one can define: subtype Month_Day is Integer range 1..31;, The type Month_Day is weak in the sense that it is not a separate type from Integer (because it is a subtype), however it is restricted to the range 1..31. In contrast: type Month_Day is new Integer; will create a distinct type, which is strong in the sense that that it cannot be mixed with integers without explicit casting - but it is not restricted and can receive the value -17 which is senseless. So technically it is stronger, but is less reliable.
Of course, one can declare type Month_Day is new Integer range 1..31; to create a type which is distinct and restricted.

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