Skip to content

label your types - a convention for self-documented and more readable code

Notifications You must be signed in to change notification settings

hamidb80/labeledtypes

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

20 Commits
 
 
 
 
 
 
 
 

Repository files navigation

The person who respects another person because of his wealth, 2/3 of his religion is gone - Imam Ali SWT

وَ مَنْ أَتَى غَنِيّاً فَتَوَاضَعَ لَهُ لِغِنَاهُ ذَهَبَ ثُلُثَا دِينِهِ - امام علی ع

Labeled Types

Abstract

Labeling types enables you to write a more self-documented 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 have many lines of codes; as it is not much obvious what they are doing exactly...

Motivation

scenario 1

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

var cars: Table[string, bool]

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

scenario 2

you wanna develop a telegram bot using telebot for example, you come 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]

scenario 3

you've stored list of attedences' names by age.

let namesByAge: seq[seq[string]]

Isn't seq[seq[string]] like a 2D matrix of names ?!?!?! 😵

Solution

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

the labeledtypes package enables you to do this:

scenario 1

var cars: Table[name !: string, isReady !: bool]
# or
var cars: Table[!(name: string), !(isReady: bool)]

scenario 2

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

scenario 3

let namesByAge: seq[(age: int) !> (names: seq[string])] 

Origin of the Idea

I like the idea of named return in golang:

func join(paths ...string) (joined_path string)
func split(sum int) (x, y int)

Installation

nimble install labeledtypes
# or
nimble install https://github.com/hamidb80/labeledtypes

Usage

See tests/test.nim.

Do not Like the ! prefix?

see tests/talternative.nim.

Other Solutions

See other comments on this. it was originally a proposal.

About

label your types - a convention for self-documented and more readable code

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages