Types (ระบบประเภท)

Compilers ของเราควรตรวจสอบและบังคับใช้ types ของข้อมูลของเรา หรือ types ของข้อมูลควรถูกตรวจสอบและบังคับใช้ที่ runtime?

เกมชั่งตัวนี้เป็นมาหลายทศวรรษแล้ว—และไม่มีการแก้ไขที่ชัดเจน

Types อาจเข้ามาสู่โลก programming กับ FORTRAN Variables ที่เริ่มจาก I ถึง N เป็น integers; ที่เหลือเป็น floating point

Expressions ใน FORTRAN เป็น integer หรือ floating point ถ้าคุณใช้ variables หรือ constants ของ types ต่างกันใน expression compiler จะบ่นได้

C ไม่มี type checking ที่เข้มงวด คุณสามารถ declare type ของ variable ได้ แต่ compiler ใช้ declaration นั้นแค่สำหรับ memory layout, memory allocation, และ arithmetic operations มัน ไม่ ใช้ declared types เพื่อบังคับใช้ type restrictions ดังนั้น คุณสามารถส่ง integer ไปให้ function ที่ต้อง floating-point ได้ Compiler จะ generate code อย่างสุขสันต์ เมื่อ program ทำงาน มี undefined behavior—มักจะ work ใน lab แต่ crash และ burn ใน production

Pascal และ C++ เป็น statically typed Compiler ตรวจสอบทุกๆ การใช้ declared type เพื่อให้แน่ใจว่า appropriate Stricture เหล่านี้ลด 2 incidence ของ undefined behavior ได้มาก

2 . แต่ไม่ได้กำจัดมันออกไปซะที

Smalltalk, Lisp, และ Logo เป็น dynamically typed Variables ไม่มี declared types Compilers ไม่ apply type restrictions Types ถูกตรวจสอบ runtime ถ้าพบว่า inappropriate program ก็ terminated ในแบบที่ defined ไม่มี undefined behavior แต่คุณ สามารถ แปลกใจจาก abrupt termination ใน runtime

Java และ C# เป็น statically typed Ruby และ Python เป็น dynamically typed Go, Rust, Swift, และ Kotlin เป็น statically typed Clojure เป็น dynamically typed

และความเป็นไปนั้นกลับไปกลับมา pendulum swing บาง decades เราเลือก statically typed languages decades อื่น เราเลือก dynamically typed languages

ทำไมเราตัดสินใจไม่ได้? คำตอบคือ statically typed languages ยาก dynamically typed languages ง่าย Statically typed languages เป็นเหมือน jigsaw puzzles ทุก piece ต้องพอดีในตำแหน่งที่ถูก ในวิธีที่ถูก Dynamically typed languages เป็นเหมือน LEGO bricks หรือ Tinkertoy pieces ง่ายกว่า ที่จะพอดี pieces เข้าด้วยกัน แต่บางครั้ง คุณพอดี piece ผิดเข้าไปในตำแหน่งผิด

วิธีแก้ปัญหาที่ผมเห็น คือ compromise Type checking ควรเป็น formal และ strict แต่ควรถูกตรวจสอบ runtime เมื่อ programmers ตัดสินใจ การ write comprehensive unit tests โดย follow discipline เช่น TDD เป็น good strategy นอกจากนี้มี excellent libraries 3 ที่ allow comprehensive dynamic type checking ใน various languages

3 . ผมชอบ Clojure/spec

วิธีนี้จะทำให้เราเลี่ยงการพอดี piece ผิดเข้าไปในตำแหน่งผิด แต่จะรักษา LEGO feel ของ language