nim-lang / RFCs

A repository for your Nim proposals.
135 stars 26 forks source link

labeled types; a path to self documented and more readable code #507

Closed hamidb80 closed 1 year ago

hamidb80 commented 1 year ago

Abstract

Labeling types enables you to write more self-document code, both easy for you to review in the future and for other people to get the idea behind your algorithm.

it is specially good for procs that do many jobs; as it is not much obvious what they are returning as result.

Motivation

scenario 1

assume you're reading someone's code, you came upon something like this:

var cars = Table[string, bool]

wow! what is it? is that a table for (ownerName -> isCrushed) or (carName -> hasWheels) ??

scenario 2

you wanna develop a telegram bot using telebot for example, you came upon UpdateCallback type:

proc(bot: Telebot, update: Update): Future[bool] 

what is Future[bool] for? why a bool? you can't even guess it without reading the docs [RTFM right? :D]

Description

but if you could somehow just label your types, the code would be a lot more readable!

Code Examples

scenario 1

var cars = Table[(name: string), (isReady: bool)]

scenario 2

proc(bot: Telebot, update: Update): (shouldEndWaiting: Future[bool])

Backwards Compatibility

the syntax (label: Type) definitely has conflicts with one-field-tuples:

(name: string)

other syntaxes that I can think of:

name ! string # alternative 1
name :: string # alternative 2
(.name: string.) # alternative 3
[.name: string.] # alternative 4
Varriount commented 1 year ago

I'm not sure the complexity here is worth the possible benefit. Why not just use sensible names for types and variables? With types you can even use type aliases:

type Path = string

proc join(left, right: Path): Path
konsumlamm commented 1 year ago

My first reaction is: That's what (doc) comments are for. What benefit does this have over writing a comment that explains what the table stores or what the proc returns? IDEs can also show the doc comments, so you don't have to open the documentation separately. Sure, there are people not documenting their code, but I doubt that providing new syntax for documenting code would change that.

hamidb80 commented 1 year ago

Thanks for your comments, I'm convinced that it's not necessary.

btw I implmented ! macro to achieve similar to what I've proposed:


macro `!`(namedTuple): untyped = 
  expectKind namedTuple, nnkTupleConstr
  expectLen namedTuple, 1

  namedTuple[0][1]

now this is possible:

Table[!(name: string), !(isReady: bool)]

thanks to the macro system :D