Google Style Guide Notes
Taking these notes to try to get some helpful information about writing better code in some of the languages that I know.
Google Style Guide Notes
Taking these notes to try to get some helpful information about writing better code in some of the languages that I know. I am using this as a reference to take notes on HTML, CSS, JavaScript (TypeScript), Python, and Go style guides. I am mainly taking notes on things I find interesting jere - these aren't exhaustive notes.
HTML And CSS
- Be consistent
HTML
- Always use https for resources
- Indentation should be 2 spaces for HTML and CSS Files
- only use lowercase in HTML (tags) and css
- Remove trailing whitespace
- Use utf-8
- Highlight todos by using the keyword TODO - TODO: action item
- Use HTML 5
- Use HTML according to its purpose
- Use elements for what they have been created for
- Provide alternatives for multimedia - text for images (alt), captions for audio and video files
- Don't use unicode entity references (except where needed)
- Avoid hyphens in ids. Try to limit ids where possible
- Use a new line for every block, list, or table element. Use indentation.
- Break long lines
- use double quotes for attributes
CSS
- Use meaningful class names that are as short as possible while retaining meaning
- try not to use element names in conjunction with classes
- avoid id selectors
- Use short hand properties where possible, e.g.: border: 2px solid green;
- Avoid units when possible
- try to avoid using !important declarations
- alphabetize order of declarations
- indent blocked content
- use a semicolon after each declaration
- use a space between the property and value font-weight: bold
- Use single quotes vs double quotes
Typescript
File consists of:
- Copyright information, if present
- JSDoc with @fileoverview, if present
- Imports, if present
- The file's implementation
- Use relative imports
- Try to limit the number of parent steps ../../../
- Don't use default exports
- Explicitly use type imports when you are only using the type
- Use modules not namespaces
- use const and let - never use var
- One variable per declaration
- Code must use Number() yo parse numeric values, and must chekc its return for NaN values explicitly, unless failing to parse is impossible form context
- Use new Error() instead of just Error() when throwing an Error
- Only throw errors
- Justify why you're not throwing another error when you don't throw an error in a catch block
- Always use triple equals
Type assertions (x as SomeType) and non-nullability assertions (y!) are unsafe. Both only silence the TypeScript compiler, but do not insert any runtime checks to match these assertions, so they can cause your program to crash at runtime.
- Keep try blocks focused. try to limit the amount of code inside try blocks. This will involve defining variables above try blocks
- names should be descriptive
- use uppercase for types
- use camel case for characters
- JsDoc is written in Markdown
Python
- Run pylint over your code using pylintrc
- Use import statements for packages and modules only, not for individual types, classes, or functions
- Nested local functions or classes are fine when used to close over a local variable. Inner classes are fine.
- Don't use too many loops in comprehensions
- whenever possible type annotations should be used in the source
- Don't use semicolons to terminate lines
- Use parentheses sparingly
- Indent code with 4 spaces
- Use docstrings:
def fetch_smalltable_rows(
table_handle: smalltable.Table,
keys: Sequence[bytes | str],
require_all_keys: bool = False,
) -> Mapping[bytes, tuple[str, ...]]:
"""Fetches rows from a Smalltable.
Retrieves rows pertaining to the given keys from the Table instance
represented by table_handle. String keys will be UTF-8 encoded.
Args:
table_handle: An open smalltable.Table instance.
keys: A sequence of strings representing the key of each table
row to fetch. String keys will be UTF-8 encoded.
require_all_keys: If True only rows with values set for all keys will be
returned.
Returns:
A dict mapping keys to the corresponding table row data
fetched. Each row is represented as a tuple of strings. For
example:
{b'Serak': ('Rigel VII', 'Preparer'),
b'Zim': ('Irk', 'Invader'),
b'Lrrr': ('Omicron Persei 8', 'Emperor')}
Returned keys are always bytes. If a key from the keys argument is
missing from the dictionary, then that row was not found in the
table (and require_all_keys must have been False).
Raises:
IOError: An error occurred accessing the smalltable.
"""
class SampleClass:
"""Summary of class here.
Longer class information...
Longer class information...
Attributes:
likes_spam: A boolean indicating if we like SPAM or not.
eggs: An integer count of the eggs we have laid.
"""
def __init__(self, likes_spam: bool = False):
"""Initializes the instance based on spam preference.
Args:
likes_spam: Defines if instance exhibits this preference.
"""
self.likes_spam = likes_spam
self.eggs = 0
@property
def butter_sticks(self) -> int:
"""The number of butter sticks we have."""
- Write TODO comments for code that is temporary, s short-term solution, or good-enough but not perfect
- If a file is to be used as an executable, its main functionality should be in a main() function, and your code should always check `if name == 'main' before executing your main program, so that it is not executed when the module is imported.
- Keep functions small and focused
- Be consistent
Go
Main
- Check out the package sort to see an example of Google coding in Go
- Clarity: the code's purpose and rationale are clear to the reader
- The core goal of readability is to produce code that is clear to the Reader
- Clarity is primarily achieved with effective naming, helpful commentary, and efficient code organization
- Simplicity: the code accomplishes its goal in the simplest way possible
- Go code should be written in the simplest way that accomplishes its goals, both in terms of behavior and performance.
- When there is complexity, add commentary that denotes and explains complexity
- Prefer the way that uses the most standard tools
- Aim to use base types, then check standard library
- Concision: the code has a high signal to noise ratio
- Concise Go code has a high signal to noise ratio. Ot is easy to discern the relevant details, and the naming and structure guide the reader through these details.
- Write idiomatic Go code, like:
// Good:
if err := doSomething(); err != nil {
// ...
}
Maintainability: the code is written such that it can be easily maintained
Code is edited many more times than it is written. Readable code not only makes sense to a reader who is trying to understand how it works, but also to the programmer who needs to change it. Clarity is key.
Maintainable code minimizes its dependencies (both implicit and explicit). Depending on fewer packages means fewer lines of code that can affect behavior.
Consistency: the code is consistent with the broader Google codebase
- Consistent code is code that looks, feels, and behaves like similar code throughout the broader codebase, within the context of a team or package, and even within a single file.
Core Guidelines
- Go source code uses MixedCaps or mixedCaps (camel case) rather than underscores