Top Banner
Beyond the Style Guides Mosky
92

Beyond the Style Guides

Jul 28, 2015

Download

Technology

Mosky Liu
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Beyond the Style Guides

Beyond the Style Guides

Mosky

Page 2: Beyond the Style Guides

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 v.s. 0.0004 ms.!

I can write 4x faster.!

And human brain haven't changed a lot,so it may be even 1 week v.s. 1 month.!

Human Time ⋙ Computer Time

Page 3: Beyond the Style Guides

- Benjamin Franklin

“Time is money.”

Page 4: Beyond the Style Guides

How to write faster?

Good language, e.g., Python!

Powerful libraries!

Experience!

∈ The things you can't change immediately.

Page 5: Beyond the Style Guides

Understandable codebase. i.e., codebase which has high maintainability.!

∈ You can just learn from this share.

Page 6: Beyond the Style Guides

Style Guide?

# It looks okay! count += 1

Page 7: Beyond the Style Guides

Not enough

# But it was initialized as count = '1'

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

Page 8: Beyond the Style Guides

You remain only 10k days in your life.

Page 9: Beyond the Style Guides

Spend time on writing exciting feature, not debugging.

Page 10: Beyond the Style Guides

MoskyPython 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

Page 11: Beyond the Style Guides

Outline

How human brain read code?!

Name thing meaningful but short.!

Paragraphing & Sectioning.!

Find the hidden “lines”.!

Face bad smell healthily.

Page 12: Beyond the Style Guides

Human Brain

Page 13: Beyond the Style Guides

A Computer

Read the code line by line.!

Cover all of the code, usually.!

Just complain when it doesn't understand.

Page 14: Beyond the Style Guides

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.

Page 15: Beyond the Style Guides

But, computer is always complaining.!

We jump to the failed line.!

Read back from the line.!

Finally, we leave immediately after we fix it.

Page 16: Beyond the Style Guides

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.

Page 17: Beyond the Style Guides

We read lines randomly.

Page 18: Beyond the Style Guides

Maintainability

To understand a random line, how many lines do you need to read back?!

Lesser → Higher maintainability

Page 19: Beyond the Style Guides

Name

Page 20: Beyond the Style Guides

Nothing But

Have a good dictionary.!

Be exact to avoid ambiguity.!

Be consistent to avoid misleading.!

Hint, hint, and hint.

Page 21: Beyond the Style Guides

Be Exact

“Apple”!

Which “Apple”?!

“Apple, the company.”!

apple_the_company

Page 22: Beyond the Style Guides

date_a-date_b

Which dates?!

today-joined_date

Page 23: Beyond the Style Guides

user

User's what?!

user_name

user_email

Page 24: Beyond the Style Guides

name

Who’s name?!

user_name

store_name

Page 25: Beyond the Style Guides

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')

Page 26: Beyond the Style Guides

Too Long?

The context helps.!

fruit.py

apple

Page 27: Beyond the Style Guides

Type Hint

We operate variables.!

count += 1

parse(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

Page 28: Beyond the Style Guides

Make It Intuitive

count

should be numeric!

name

string thing!

names

many strings; may be a list

Page 29: Beyond the Style Guides

page

page_no

so should be numeric!

event

event_key

so should be string stuff

Page 30: Beyond the Style Guides

List or Set?

requested_fields & allowed_fields

?!

set(requested_fileds) & allowed_field_set

Page 31: Beyond the Style Guides

List or Generator?

large_rows

large_rows[0] # ?

large_row_gen # generator

large_row_it # iterator

Page 32: Beyond the Style Guides

Object or Dict?

user

What is the type of user?!

user['name'] # ?

user.name # ?

user_dict['name']

user_d['name']

Page 33: Beyond the Style Guides

Is it a bool?

new_user

A bool? A User instance?!

is_new_user

A bool? A Function?!

new

user_is_new

Page 34: Beyond the Style Guides

Is it a function?

Use imperative, i.e., start with a verb.

Page 35: Beyond the Style Guides

.text

.json

A function? A string thing?!

.get_text

.parse_from_json

.text # string thing

Page 36: Beyond the Style Guides

def parse(x, return_dict=False): …

?!

def parse(x, to_return_dict=False): …

Page 37: Beyond the Style Guides

Explicit Unknown

arg

May be tuple, dict, or anything.!

arg_x

Page 38: Beyond the Style Guides

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.

Page 39: Beyond the Style Guides

Some tips!

Raise exception.!

Use zero and infinite.!

Use constant.!

Filter the Nones out.

Page 40: Beyond the Style Guides

Content TypeUser Input!

The “Keys”!

URL!

JSON!

HTML!

SQL!

∈ string thing

Page 41: Beyond the Style Guides

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.

Page 42: Beyond the Style Guides

template.format(name)

If!

template # -> "<a>{}</a>"

name # -> "<script src=…></script>"

!

Page 43: Beyond the Style Guides

template_html.format(escape(name))

Safe :)!

“Making Wrong Code Look Wrong “

Page 44: Beyond the Style Guides

Abstract Type

it — iterator!

seq — sequence!

map — mapping

Page 45: Beyond the Style Guides

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.)

Page 46: Beyond the Style Guides

Map

users

A dict? What are the key and the value?

Page 47: Beyond the Style Guides

uid_user_map uid_user_map['mosky'] # -> User('mosky')

Page 48: Beyond the Style Guides

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

# even better uid_user_map = { 'mosky': User('mosky'), … }

Page 49: Beyond the Style Guides

Tuple

uid, name = uid_name_pair

a, b, c = a_b_c_tuple

Page 50: Beyond the Style Guides

key_value_pairs = sql('select key, value')

for key, value in key_value_pairs: …

key_value_map = dict(key_value_pairs)

Page 51: Beyond the Style Guides

Composite

If apply structure hint and type hint,!

It will be long.!

You may shorten.!

Keep long description in comment or doc.

Page 52: Beyond the Style Guides

Use common abbreviation!

http://abbreviations.com/!

Use acronym, e.g., rlname for really_long_name.!

Do comment if you use them.

Page 53: Beyond the Style Guides

# compromise between meaning and length # # event key: e.g., 'monthers_day' # config_d: config dict # # - start_date: … # … # event_key_config_d_map = { 'monthers_day': {…} }

Page 54: Beyond the Style Guides

# focus on reducing length # # ekey: event key # config: config dict # # - start_date: … # … # ekey_config_map = { 'monthers_day': {…} }

Page 55: Beyond the Style Guides

adj. new_user

past participle joined_date

present participle working_queue

infinitive keys_to_remove

another noun template_args

Page 56: Beyond the Style Guides

intn, m

i, j, k twd_int

int/range

page_no birth_month birth_daytids_idx

bool

new, joined user_is_new new_or_not new_bool

Page 57: Beyond the Style Guides

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

Page 58: Beyond the Style Guides

dict user_d, user_dict

list uids, uid_list

set uid_set

mapping uid_user_map

generator uid_gen

Page 59: Beyond the Style Guides

date start_date

datetime joined_dt

re email_re

decimal total_dec

currency total_currency, total_ccy total_twd

Page 60: Beyond the Style Guides

key uid_user_d_map

(x, y) uid_user_pair

[(x, y), …] uid_user_pairs

(x, y, z) uid_nick_email_tuple

Page 61: Beyond the Style Guides

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.)

Page 62: Beyond the Style Guides

.parse

What we will get?!

.parse_to_tree

Page 63: Beyond the Style Guides

.allow_to_log_in

Allow something to log in?!

.do_allow_to_log_in

If return value is a bool, use yes–no question.

Page 64: Beyond the Style Guides

Performance Hint

get_name # Memory op.

parse_from_json # CPU op.

query_html request_html # IO op.

Let people know the roughy cost.

Page 65: Beyond the Style Guides

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.

Page 66: Beyond the Style Guides

Hints

Type Hint!

Structure Hint!

Return Type Hint!

Performance Hint!

Private Hint

Page 67: Beyond the Style Guides

A random line now is more understandable.

Page 68: Beyond the Style Guides

Blank Line

Page 69: Beyond the Style Guides

Blank Line

Use blank line to separate your code into:!

Paragraph!

Section!

Like lightweight markup language,e.g., Markdown, RST.

Page 70: Beyond the Style Guides

Paragraph

Lines without any blank line.!

Group similar lines into a paragraph.!

Contains sub-paragraph.!

Use blank line to separate paragraphs.

Page 71: Beyond the Style Guides

try: html = read_html_from_cache(url) except IOError: html = request_html(url)

Page 72: Beyond the Style Guides

Section

Paragraphs.!

Group similar paragraphs into a section.!

Avoid sub-section.!

Use two blank lines to separate sections.

Page 73: Beyond the Style Guides

<section A's paragraph 1> <section A's paragraph 2> <section B's paragraph 1> …

Page 74: Beyond the Style Guides

Still don't understand? Try to read a paragraph, then a section.

Page 75: Beyond the Style Guides

The “Lines”

Page 76: Beyond the Style Guides

Dependency

The F function calls the G function.!

F depends on G.!

F → G!

It's a “Line”.

Page 77: Beyond the Style Guides

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.

Page 78: Beyond the Style Guides

At least, easier to trace.

Page 79: Beyond the Style Guides

Bad Smell

Page 80: Beyond the Style Guides

Reality

Don't have time to refactor.!

They actually work well.!

They itch you, but won't beat you.!

You may already understand.

Page 81: Beyond the Style Guides

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.

Page 82: Beyond the Style Guides

Stay focused.

Page 83: Beyond the Style Guides

Recap

Page 84: Beyond the Style Guides

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

Page 85: Beyond the Style Guides

Pinkoi

Page 86: Beyond the Style Guides
Page 87: Beyond the Style Guides

Pinkoi 亞洲最⼤大設計商品購物網站

Page 88: Beyond the Style Guides

Pinkoi a.k.a. 買禮物的好地⽅方

Page 89: Beyond the Style Guides

在找⼈人

Page 90: Beyond the Style Guides

⼀一定有適合你的職缺

Page 91: Beyond the Style Guides

Back-End Engineer Quality Assurance Engineer Data Engineer Search Engineer Android Engineer iOS Engineer

Page 92: Beyond the Style Guides

Pinkoi pinkoi.com/about/pinkoist