General Coding Guidelines

Shorten Names of High Impact Imports

If an imported object is used very often, import it renamed as short identifier and keep the name consistent across code base.

For example, if you type annotate, you probably want import typing as t.

It is not clear at all when this should be used. Use judgement.

Use Types and Type Hints to Encode Information

Use types to encode information and restrict possibilities. Information may be just type information, but also documentation, and more. The proper term is probably semantics.

Make illegal states unrepresentable.

This is a technique to achieve Don’t Repeat Yourself and avoiding hungarian notation.

This idea is related to SOLID, algebraic data types, type theory, types as propositions, and probably more.

There was an excellent web page explaining this but I lost the url :( Anyway, lets take a look at some examples examples in python.

Common:

def foo(uid)
    return None

uid is common term in the (all the) code bases so no need to document right. This is not always the case.

Default:

def foo(uid):
    """
    :param uid: user id, uid > 0
    :type: int
    """

Document everywhere? Not Don’t Repeat Yourself.

Types as documentation:

class UserId(int):
   def __init__(n):
       """
       :param uid: user id
       :type: int
       :raises AssertionError: if n <= 0
       """
       assert n >= 0
       super().__init__(n)

def foo(n:UserId):
   pass

Hungarian notation:

def foo(bar_object_or_cls):
    pass

Better:

def foo(bar):
   """
   :param bar: object or class
   """

Enter Type Hints:

def foo(bar:Union[Bar, Type[Bar]]):
   pass

Warning

In some languages, like Python, liberal use of this technique may have significant performance impact. Some other languages do this with minimal overhead.

SOLID

S.O.L.I.D. is solid.

General notes

  • Programs should be written for people to read, and only incidentally for machines to execute. 1

Backlog

https://en.wikipedia.org/wiki/Inner-platform_effect

1

Structure and Interpretation of Computer Programs by Abelson and Sussman. The same idea is expressed by Eric Raymond’s Rule of Clarity.