(评论)
(comments)

原始链接: https://news.ycombinator.com/item?id=43403321

Hacker News 的讨论主要围绕编程中自定义类型的低利用率展开,尤其是在 TypeScript 和 Java 等语言中,尽管 Java 较为复杂。评论者 salmonellaeater 观察到,人们不愿意创建小的、特定类型的变量,例如 “CreateSubscriptionRequest”,而这能够增强可测试性和可维护性,尤其是在 API 处理程序和数据访问对象中。在 TypeScript 中,声明类型很容易,不需要显式实现接口,这种不愿使用自定义类型的情况就更令人费解了。 评论者推测,在 Java 等其他语言中,创建新类型需要将值包装到新类中,这可能会增加阻力。无论如何,讨论都强调了自定义类型在防止错误、简化重构以及最终提高代码质量方面的益处。另一位用户 parpfish 分享了如何将编码重新定义为一系列类型转换,从而提高了代码的可维护性、命名约定和单元测试。

相关文章
  • 别害怕类型 2025-03-22
  • (评论) 2025-03-19
  • (评论) 2024-07-26
  • TypeSpec:一种以 API 为中心的开发新语言 2024-05-01
  • (评论) 2024-05-01

  • 原文
    Hacker News new | past | comments | ask | show | jobs | submit login
    Don't Be Afraid of Types (lmika.org)
    6 points by speckx 1 hour ago | hide | past | favorite | 2 comments










    > I found that there’s a slight aversion to creating new types in the codebases I work in.

    I've encountered the same phenomenon, and I too cannot explain why it happens. Some of the highest-value types are the small special-purpose types like the article's "CreateSubscriptionRequest". They make it much easier to test and maintain these kinds of code paths, like API handlers and DAO/ORM methods.

    One of the things that Typescript makes easy is that you can declare a type just to describe some values you're working with, independent of where they come from. So there's no need to e.g. implement a new interface when passing in arguments; if the input conforms to the type, then it's accepted by the compiler. I suspect part of the reason for not wanting to introduce a new type in other languages like Java is the extra friction of having to wrap values in a new class that implements the interface. But even in Typescript codebases I see reluctance to declare new types. They're completely free from the caller's perspective, and they help tremendously with preventing bugs and making refactoring easier. Why are so many engineers afraid to use them? Instead the codebase is littered with functions that take six positional arguments of type string and number. It's a recipe for bugs.



    my code became much easier to maintain once i stopped thinking of it as writing "algorithms" and "processes" and started thinking of it as a series of type conversions.

    structuring what lives where became easier, naming things became systematic and consistent, and writing unit tests became simple.







    Join us for AI Startup School this June 16-17 in San Francisco!


    Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact



    Search:
    联系我们 contact @ memedata.com