7 ms·
A few words on Ruby's type annotations state
- mirekrusin 4y agoCan't they just use `foo :: String`?
- grncdr 4y agoThat’s already valid syntax meaning “resolve the String constant starting at foo”
- mirekrusin 4y agoYes, you're right. The more you think about it the less arguments there are for "just use Crystal".
- transfire 4y agoAs in Elixir/Erlang it would nice if they could be define separately. def [] in Integer => index # ... end def [] in Integer => start, Integer => length # ... end def [] in Range => range # ... end
- RcouF1uZ4gsC 4y agoI am not convinced of the utility of how good type annotations are in the long term. I think static typing is a very fundamental part of language design that affects the entire language. To make static typing ergonomic without massive boilerplate, you also need concepts like generics, co and contra-variance, type inference, and other things that dynamically typed languages never have to really concern themselves with. When you try to bolt it on afterwards, I think you can end up with a lot of foot guns and corner cases and a false sense of security.
- Too 4y agoTypescript and Python managed to pull it off. With a result that in many ways allows both expressing stricter, yet more fluid typing, compared to languages traditionally considered static. The false sense of security they give is not a problem. As with testing, this is not a black or white answer, having more is better than having nothing. You could also argue they are more strict by allowing more richer types like unions and structural typing, letting you strictify things that you in C# or Java would have solved with non type safe Dictionary<String,Object>, instanceof(), overloads galore or layers upon layers of AbstractFactories.
- LesZedCB 4y agoi personally really like the idea of what clojure has done with spec or malli instead of type annotations. it just feels to me more like what rubyists want: pragmatic validation of "does this quack?" but like you say, i'm not sure ergonomics can be brought up to the level of ease/happiness to be used regularly
- itake 4y agoI've worked in multiple systems written in python, ruby, and JS where an untyped dict|hash|object is passed from function to function. In each function, keys are read; keys are written; keys are deleted. Tracking params were actually called by each function was a nightmare. If this "magic" dictionary was sourced from a schemeless api or database, it was impossible to figure out the schema of this dict without running the code in production.
- lloeki 4y ago> I am not convinced of the utility of how good type annotations are in the long term. Anecdata: adding typing (via Sorbet, then RBS) to multiple projects over the years uncovered many corner case (and not-so-corner case but non obvious) bugs, some subtle but critical, before they ended up crashing production. I can vouch with real life experience that it is useful. RBS+Steep is so useful I inadvertently found myself† beginning to write type-first, describing my code in .rbs files then filling in the implementation. Thinking in types has helped me uncovered issues right at the idea stage when I could have produced a smart^Wfatally flawed implementation that would still work thanks to Ruby's dynamism (mind you, Ruby's dynamism is great, it is merely a tool to be wielded at appropriate times) † Which is kinda useful as a "ok this thing works" rule of thumb in my book
- akavi 4y agoHave you used typescript? Because to my eyes, that's a massively successful "bolted on" type system. Sure there're holes in the system, but the utility is significant, especially relative to the cost.
- dalyons 4y agoTypescript is more successful by the numbers than almost all “native” typed languages
- bilalq 4y agoNot just more successful in terms of adoption, but safer even than many "native" typed languages. You can never really tell if a random method in Java can return null without reading through its source and the transitive source of anything it may potentially call. And with dynamic dispatch, this becomes literally impossible. That Java virus of null contaminates other JVM languages like Scala too. It's even worse because you can have Option types that are themselves potentially nullable. Some/None/null is a terrible situation to be stuck in. And then the expressiveness of the type system there is also really pragmatic. You can't natively express union types in Java and many other static languages without writing your own Either monad implementation. Instead, you often wind up with code that has objects with a hodge-podge of field sets that are nullable. It's nothing short of miraculous how well the null-safety situation is in TypeScript. It's built on the back of community-driven types in DefinitelyTyped where the maintainers of libs often aren't the ones writing and keeping types up to date. Nowadays, types are becoming more and more first-party, but it still amazes me how we got to this point.
- codr7 4y agoYeah, I just duplicated a Go method because it wouldn't accept a typed vararg as untyped (...any), and methods can't be generic either. I would rather not have static types at all than a not-quite-complete type system. I find Common Lisp's gradual approach to types very convenient.
- eric-hu 4y agoThe author speaks to this in the blog post too. > The “this can be typed, this can’t” approach would most probably lead to a schism unseen before: splitting of the community into those who prefer type-annotated code and consequently became reluctant to any of the most expressive and dynamic features—and everyone else. I'm an active user of Sorbet at work, and I can see this happening even with my own opinions. On the one hand, I don't want to see the Ruby ecosystem fractured more, but on the other, I've seen clear benefits from helping add static typing to my team's project. I didn't really know much about Steep at the time, so I pushed for Sorbet. My first preference was actually Ruby 3 types, but when I looked into implementing them, I found they provided much weaker guarantees than Sorbet. The tooling also wasn't there.
- al2o3cr 4y agoAn observation about the discussion immediately under "In fact, we in Ruby have several incomplete systems of type-annotations-in-disguise" - to me, that list indicates that fitting all those things into a SINGLE type system is a huge challenge. The spaces of possible types for a JSON API, an ORM, and an interactor's inputs are all different.
- hhthrowaway1230 4y agoRuby needs opt-in inline typing. Much like python. Typing is a language or dsl of what u expect to receive as input and as output. Its a communication mechanism. Leaving out ambigiousness. the job for ruby is to make it not a hassle but a joy to use.
- lloeki 4y agoI disagree with inline. It obscures the code, especially with a language as terse as Ruby. That's a code editor job to present me with types appropriately within its UI (which may be tooltips, autocompletion, virtual text that looks like comments or annotations†...) Having types in separate .rbs files has proven to me to be perfectly usable, and in fact better in many ways. Sorbet's DSL of having `sig { }` present is the worst kind of annotation, as it needs to pollute `Kernel` with `#sig`, even when you disable runtime checking. This is a no-go if you develop anything else than an app (e.g a gem) as you certainly don't want to push Sorbet†† as a dependency to your gem consumers, not the least because `sorbet-static`†† is still only available for `x86_64`. In general Sorbet seems to be designed to type apps, gems being an afterthought. † https://github.com/jubnzv/virtual-types.nvim https://github.com/jubnzv/virtual-types.nvim †† or include a monkyepatch that defines an empty `Kernel#sig` †† https://rubygems.org/gems/sorbet-static https://rubygems.org/gems/sorbet-static
- ezekg 4y agoDid you read the article? It discusses this topic and how it's a hard problem in Ruby vs. Python due to Ruby's syntax choices.
- RangerScience 4y agoTook me a bit thinking through it all, but I arrived at the same place as the author in the end - use the pattern matching system, and if the types don't match then the block you're dispatched to just raises an error. The rest is just finding a satisfying syntax.
- mbell 4y agoThe biggest issue with current attempts at typing in Ruby is the choice of a nominal type system. If there ever was a language that called for structural typing, it's Ruby.
- uticus 4y ago> In my OSS and blogging activities, I am mostly focused on the same concepts: Ruby intuitions and lucid code...the main question is always “how the language leads us to express this in the clearest way possible.” Unfortunately this article itself needs some editing. I stuck through to the end, but it was not enjoyably lucid. > I honestly tried to perform it alongside the reader: since the early drafts of the article, my expectations were that I’d come up with some coherent idea about a possible Ruby typing syntax. My attempt resulted in a deeper understanding of the level of design complexity making it hardly achievable. Plus one for trying it out, I guess. The temptation is there, because Ruby is so flexible. "It works so well for DSLs, maybe it can be expanded to include typing!" The trouble is, the added syntax rules to support typing will never stay in the sweet spot between "enough in the foreground to assist coding" and "enough in the background to not distract from the coding flow." You either live without it, as in Ruby, or learn to mentally parse over it, as in other languages with the Func(String s, Int i) syntax. For myself, I'm fine with the typing being in a separate .rbs file. Especially if my IDE supports it well.
- lloeki 4y ago> For myself, I'm fine with the typing being in a separate .rbs file We type[0] by having one separate .rbs file per .rb file. Works really well with an editor's vertical splits: type outline on one side, code on the other. That, or use something like vim-projectionist[1]. We have a static typing guide for contributors[2], and I'm also accreting common errors and issues behind the scenes to produce a 'rbs+steep by example' to ease folks in. [0]: (WIP: there's a huge codebase to type, but we're progressively getting there) https://github.com/DataDog/dd-trace-rb/tree/master/sig https://github.com/DataDog/dd-trace-rb/tree/master/sig [1]: https://github.com/tpope/vim-projectionist https://github.com/tpope/vim-projectionist [2]: https://github.com/DataDog/dd-trace-rb/blob/master/docs/StaticTypingGuide.md https://github.com/DataDog/dd-trace-rb/blob/master/docs/Stat...
- nine_k 4y ago> this article itself needs some editing. Possibly! But likely the reason is this: > I am writing this on my phone, in a barrack that houses some 200+ of my brothers-in-arms in the Ukrainian army’s training camp; I use short periods of rest between training, mostly at night and on Sundays. I won't expect a lot of text-polishing opportunities in conditions like that. I'd be grateful for any coherent and insightful output, like the article.
- egonschiele 4y agoI had written a code contracts library for Ruby about 10 years ago [1]. I stopped working on it, mainly because it only provided runtime type checking, and I wanted static type checking. Nowadays my main language is typescript. I miss ruby, but can't give up the static typing that typescript provides. I really wish Ruby had a type system with the same level of support. VSCode has phenomenal TS support, and there's a community adding types to projects [2]. This is something I'd like for Ruby also. > An integral part of this informality is relying on Matz’s taste and intuition for everything that affects the language’s core. I think a more defined process would mean a better future for Ruby and Ruby developers. - [1] https://github.com/egonschiele/contracts.ruby https://github.com/egonschiele/contracts.ruby - [2] https://github.com/DefinitelyTyped/DefinitelyTyped https://github.com/DefinitelyTyped/DefinitelyTyped
- bilalq 4y agoThank you for creating contracts! I used it quite heavily in the past. While the lack of static checking was definitely a pain point, I kind of worked around it by having heavy unit test coverage for invalid types. In some ways, it functioned like a literate programming style for asserts. Nowadays, I almost exclusively write things in TypeScript, and yes, the type system there brings so much peace of mind. Doing a community-driven approach like DefinitelyTyped for third-party libs in Ruby seems like it'd be much harder than JS. The culture around metaprogramming and complex overloads seems like it'd be insanely difficult to type.
- egonschiele 4y agoI’m glad you liked it! It’s great to hear from a user. The run time asserts were better than nothing. Contracts made errors easier to debug, because I knew how my app hadn’t failed. Typescript has been awesome for refactoring. If I change something, I just need to follow the type errors.
- parthdesai 4y agohttps://sorbet.org/ https://sorbet.org/ ?
- ezekg 4y agoAs a huge proponent of Ruby's new pattern matching syntax (it has changed the way I write Ruby), I really, really like the idea of defp. So many times I wish I could overload a method, dispatching by pattern. Instead, I have to pattern match in the method body, which causes the method definition to become convoluted: def for_environment(environment) environment = case environment in String => code unless code in UUID_RE return none # no support for filtering via environment codes in UUID_RE => id return none unless env = Environment.find_by(id:) env in Environment => env env in nil nil end ... end I think defp looks and feels very Ruby-like compared to the alternatives (which have the problems you discussed). And Elixir is great, so I can appreciate the inspiration.
- ckolkey 4y agoI completely agree. That really stood out from the article
- grncdr 4y agoWhat's especially nice about this, is that it can be explained as a more or less syntactic transformation. You don't even need a special keyword, just a rule that method bodies beginning with `in PATTERN` are wrapped in an implicit `case [*args, kwargs.any? ? kwargs : nil].compact ... end` expression. Your example method is a bit tricky, because it rebinds an argument and then presumably uses it in the elided bit (the "..."). If the case statement was the entire method body, given proposed syntactic rule it could be written as: def for_environment in String => code unless code in UUID_RE none # no support for filtering via environment codes in UUID_RE => id Environment.find_by(id:) || none in Environment => env env in nil nil end To me this "rhymes" nicely with the ability to write `rescue` blocks at the method level: def foo(params) send_request(params) rescue => e raise if critical_error?(e) end --- That is of course a pretty rough approximation, and the real rules would probably be a bit more complex[0], but it definitely seems achievable and possibly worth doing even without taking the type-annotation aspect into account. [0]: for a start, patterns would need to be extended to allow binding the block argument in a manner equivalent to `def foo(&block)`
- sproketboy 4y agoAdding types after the fact is never going to work out well.
- munificent 4y agoMy experience is that you can have powerful runtime metaprogramming, or you can have good static type checking, but you can't have both. In most of the larger programs I've worked in the value of static typing is immense. In terms of my productivity, the only programming language feature that's possibly had a bigger positive impact is garbage collection. Runtime metaprogramming is very cool, but I've yet to work in a codebase where I felt that the value of it was greater than the value I get from good static analysis. One way to think of static types is that they're a debugger that simultaneously debugs every possible run of the program. And on top of that, you also get code navigation and better performance. It's hard for me to imagine a sufficiently great metaprogramming feature that would be worth giving that up.
- grncdr 4y agoOne approach that I feel is underexplored would be building a language server that is extensible from within the analyzed program. Somewhere adjacent to procedural macros and compiler plugins, there's probably a sweet spot for dynamic languages where your program can simply (and simply would be key to pulling it off) tell the language server what some bit of metaprogramming actually _does_ at runtime. I've played with this idea a bit in Solargraph (especially in regards to Rails) and while the results are promising, the barrier to entry and amount of labour involved is pretty high.
- bobbylarrybobby 4y agoI feel that oftentimes runtime metaprogramming is to make up for code that can't be written down statically. But if you have the right macros then you don't need the metaprogramming to happen at runtime. For instance, Rust has a pretty solid type system (not quite Haskell, but more intricate than Java) and lets you do things like generate serialization and deserialization code for arbitrary structs at compile time, which most languages would do at runtime by inspecting fields or something similar. All this to say, runtime metaprogramming doesn't seem inherently more capable compared to what's possible in the more “static compiler” languages; rather, it seems like an escape hatch for when you can't generate the code you want at compile time.
- 4y ago
- ecshafer 4y agoI do not like Sorbet, and I don't think ruby's type annotation is in a great spot. The claims of Sorbet to allow easy refactoring are just not there imo, and do not reach the level of Java. Sorbet if anything involves more time fighting sorbet, and you still rely on tests for validation. Steep looks better, but I think it needs to be brought in file. Personally if we do bring types, I would like to see an optional typescript like definition def foo(:String x) -> String or similar.
- whakim 4y agoThe article does a good job explaining why Typescript-like type annotations won't work (unless you only allow them in method definitions): most TS-like syntax is already valid Ruby code in one way or another. That aside, I'm curious where specifically you found Sorbet lacking?
- nickjj 4y agoDoes anyone else prefer the Ruby typed parameter syntax over the Python one even though the author says it would likely be rejected by Rubyists? Here's an example from the post: # Python's current type hints def readlines(name: str, chomp: bool = False): vs # Ruby's potentially valid type hints that don't exist today def readlines(String name, Boolean chomp: false) I know with Ruby you often want to put more important things first, because it deserves to be the center of attention but in the above case I think the 2nd one is so much more readable at a glance. There's less syntactic noise with the Ruby example because it avoids the equals sign and excess colons. You could also make a case when calling a function both the type and name of the param itself are really important. If you think of this as a user experience exercise, someone calling your function is the user. As a user I very much like the idea of knowing what I need to pass in and "what I need to pass in" is a combination of a descriptive name and potential type. At a fundamental level, imperative or partially imperative languages are nice because you can typically build upon what you know to do new things in incremental steps. For example if you know how to make a variable and a loop you can combine your knowledge to make a nested loop and mutate a variable without learning any new concepts. The Ruby example feels like you're incrementally adding something new. I don't really need to learn anything new to understand I'm adding types. It's also very clean looking. The Python one looks like a different language. I mean, I know both Python and Ruby and use them regularly but `chomp: bool = False` just looks icky to me. It's like some weird hybrid Python / Ruby combo and takes a few seconds to understand.
- jaxn 4y agoIn Ruby, I would see your example as name having the value str. Chomp would have the value of the result of the operation assigning bool the value of False, which I result of the operation might be true, so would chomp have the value of true? Either way, it looks like an assignment instead of comparison error, so I’d kick it back in a PR no matter how it worked.
- caseyohara 4y agoI think you confused the examples, the first one is Python.