Where snake_case is used
- Python: PEP 8 asks for lower case words with underscores for functions, variables and module names.
- Ruby and Rust: methods, variables and functions are written this way.
- SQL: table and column names are commonly snake_case, since unquoted SQL names are not reliably case sensitive and underscores keep several words readable.
- C and C++ standard libraries, and many APIs whose JSON keys follow a Python or Ruby back end.
- File names and command line options that avoid spaces and capitals.
Underscores work in the names of variables in nearly every language, while hyphens do not, because a hyphen reads as a minus sign. That is why kebab-case is for URLs and CSS, and snake_case is for code and data.
snake_case, kebab-case and CONSTANT_CASE
All three split words the same way and differ in the separator and the capitals. snake_case uses underscores and small letters. kebab-case uses hyphens and small letters, which suits web addresses and CSS. CONSTANT_CASE, also called UPPER_SNAKE_CASE, uses underscores and capitals, which suits constants and environment variables. Switch between them in the style row above, or read the whole set in the table at the bottom of the tool.
Naming database columns
Paste the header row of a spreadsheet, one header per line, and you get column names: 'First Name', 'Date of Birth' and 'Postal Code' become first_name, date_of_birth and postal_code. Before you use them, check three things:
- Length. PostgreSQL keeps only the first 63 bytes of an identifier and MySQL allows 64 characters.
- Reserved words. A column called order or group needs quoting in most databases. Rename it, for example to order_total.
- Non-ASCII letters. Accented letters are kept as typed. Some databases and languages accept them and some do not, so transliterate first if yours does not.
How words are split
XMLHttpRequestbecomes xml_http_request. A run of capitals stays together until the capital that starts the next word.userIDbecomes user_id, andversion2Betabecomes version2_beta.- 'Hello, World!' becomes hello_world. Punctuation and spaces are separators, and doubled separators collapse into one underscore.
already_snake_casestays as it is, andkebab-case-inputbecomes kebab_case_input.