Beyond the Style Guides

D16bc1f94b17ddc794c2dfb48ef59456?s=47 Mosky
May 28, 2015

Beyond the Style Guides

It's a talk about how to write understandable code from understanding human brain at Taipei.py [1] and PyCon HK 2015 [2].

[1]: http://www.meetup.com/Taipei-py/events/222174472/
[2]: http://2015.pycon.hk/

D16bc1f94b17ddc794c2dfb48ef59456?s=128

Mosky

May 28, 2015
Tweet

Transcript

  1. 2.

    It's all about time. I can write a 4x faster

    program than you! But the hardware is super powerful now,
 it may be just 0.0001 ms vs. 0.0004 ms. I can write 4x faster. And human brain haven't changed a lot,
 so it may be even 1 week vs. 1 month. Human Time ⋙ Computer Time
  2. 4.

    How to write faster? Good language, e.g., Python Powerful libraries

    Experience ∈ The things you can't change immediately.
  3. 7.

    Not enough # But it was initialized as
 count =

    '1' # In JavaScript, 
 # there's even no an error.
  4. 10.

    Mosky Python Charmer at Pinkoi The author of the Python

    packages MoSQL, Clime, … The speaker of the conferences, PyCon TW/JP/SG, … Also teaching Python mosky.tw
  5. 11.
  6. 12.
  7. 15.
  8. 16.
  9. 17.
  10. 19.

    A Computer Read the code line by line. Cover all

    of the code, usually. Just complain when it doesn't understand.
  11. 20.

    A Human Brain We can't read code like a computer.

    CPU is super slow, and even can't focus. RAM is tiny, programmer especially. Disk is losing bytes all the time. Nobody to complain. So we prefer to leave code alone.
  12. 21.

    But, computer is always complaining. We jump to the failed

    line. Read back from the line. Finally, 
 we leave immediately after we fix it.
  13. 22.

    Or, new requirement comes. We still jump to the related

    line. Read back from the line. Finally, 
 we also leave immediately after we finish it.
  14. 24.

    Maintainability To understand a random line, 
 how many lines

    do you need to read back? Lesser → Higher maintainability
  15. 25.
  16. 26.

    Nothing But Have a good dictionary. Be exact to avoid

    ambiguity. Be consistent to avoid misleading. Hint, hint, and hint.
  17. 31.

    Be Consistent Saw this in somewhere: apple = Company('apple') Now

    you read: apple Then you will guess it is a company. So don't: apple = Fruit('apple')
  18. 33.

    Type Hint We operate variables. count += 1 parse(input_json) If

    we know how to operate it at first glance,
 it saves time from tracing or running. Not the “Type Hint” in PEP 0484
  19. 34.
  20. 38.

    Object or Dict? user What is the type of user?

    user['name'] # ? user.name # ? user_dict['name'] user_d['name']
  21. 39.

    Is it a bool? new_user A bool? A User instance?

    is_new_user A bool? A Function? new user_is_new
  22. 44.

    Avoid None d = None if failed else {}
 d['key']

    = value
 value = d.get('key') It causes TypeError or AttributeError in Python, and extra effort in other language. Be consistent in type.
  23. 47.

    json['keyword'] # ? Actually the json is a dict-like. JSON:

    JavaScript Object Notation → a string arg_dict = json.loads(arg_json) Transformation You can see the domain and codomain.
  24. 51.

    Structure Hint We operate the variables. If we know how

    to operate it at first glance,
 it saves time from tracing or running. (Yeah, I copied it from the type hint.)
  25. 54.

    # ok
 users = {
 'mosky': User('mosky'),
 …
 } #

    even better
 uid_user_map = {
 'mosky': User('mosky'),
 …
 }
  26. 57.

    Composite If apply structure hint and type hint, It will

    be long. You may shorten. Keep long description in comment or doc.
  27. 59.

    # compromise between meaning and length
 #
 # event key:

    e.g., 'monthers_day'
 # config_d: config dict
 #
 # - start_date: …
 # …
 #
 event_key_config_d_map = {
 'monthers_day': {…}
 }
  28. 60.

    # focus on reducing length
 #
 # ekey: event key


    # config: config dict
 #
 # - start_date: …
 # …
 #
 ekey_config_map = {
 'monthers_day': {…}
 }
  29. 62.

    int n, m
 i, j, k
 twd_int int/range page_no
 birth_month


    birth_day tids_idx bool new, joined
 user_is_new
 new_or_not
 new_bool
  30. 63.

    str name, month_str str/key event_key str/url next_url str / json

    user_json str/html page_html str/sql to_update_sql
  31. 66.

    key → value uid_user_d_map (x, y) uid_user_pair [(x, y), …]

    uid_user_pairs (x, y, z) uid_nick_email_tuple
  32. 67.

    Return Type Hint We operate the variables. If we know

    how to operate it at first glance,
 it saves time from tracing or running. (Yeah, I copied it from type hint, again.)
  33. 70.

    Performance Hint get_name # Memory op. parse_from_json # CPU op.

    query_html
 request_html # IO op. Let reader know the roughy cost.
  34. 71.

    Private Hint “Don't touch me hint” A simple underscore prefix

    (_) Don't use me out of the module or file. Non-privates are just public APIs.
  35. 75.

    Blank Line Use blank line to separate your code into:

    Paragraph Section Like lightweight markup language,
 e.g., Markdown, RST.
  36. 76.

    Paragraph Lines without any blank line. Group similar lines into

    a paragraph. Contains sub-paragraph. Use blank line to separate paragraphs.
  37. 79.
  38. 82.
  39. 83.

    How messy? Are the directions are all same? Usually ↑

    in a file and files. Order your code. Are they point to limited sections or a files? Lesser is better. Section or modularize them.
  40. 85.
  41. 86.

    Reality Don't have time to refactor. They actually work well.

    Make you itch, but won't beat you. You may already understand.
  42. 87.

    So Just Seal It Off Comment the pitfalls. Use #TODO

    rather than really refactor. Assign return value to a better named variable. Wrap them. Just write new code.
  43. 89.
  44. 90.

    Recap We read lines randomly. Type hints and other hints

    Paragraph & section by blank line. Line your functions. Bad smell won't beat you. http://mosky.tw