Stylistic changes

This commit is contained in:
Nadia Ridko
2018-01-12 10:59:02 +02:00
committed by Nadia Ridko
parent 3aa3b6c4c2
commit 24d2143b2d

View File

@ -1,7 +1,7 @@
<p align="center"> <p align="center">
<a href="https://github.com/kettanaito/naming-cheatsheet"> <a href="https://github.com/kettanaito/naming-cheatsheet">
<img src="./naming-cheatsheet.png" alt="Naming cheatsheet" /> <img src="./naming-cheatsheet.png" alt="Naming cheatsheet" />
</a> </a>
</p> </p>
# Naming cheatsheet # Naming cheatsheet
@ -9,6 +9,7 @@ Naming things is hard. Let's make it easier.
## Guidelines ## Guidelines
* Pick **one** naming convention and follow it. Whether it is `likeThis`, or `like_this`, or anyhow else, it does not matter. What matters is consistency in your work. * Pick **one** naming convention and follow it. Whether it is `likeThis`, or `like_this`, or anyhow else, it does not matter. What matters is consistency in your work.
```js ```js
/* Bad */ /* Bad */
const pages_count = 5; const pages_count = 5;
@ -22,10 +23,12 @@ const shouldUpdate = true;
const pages_count = 5; const pages_count = 5;
const should_update = true; const should_update = true;
``` ```
* Name, whether of a variable, method, or something else, should be *short*, *descriptive* and *intuitive*: * Name, whether of a variable, method, or something else, should be *short*, *descriptive* and *intuitive*:
* **Short**. Variable should not take long to type, and therefore to remember, * **Short**. Variable should not take long to type and, therefore, to remember,
* **Descriptive**. Name of the variable should reflect what this variable possesses/does in the most efficient way, * **Descriptive**. Name of the variable should reflect what it does/possesses in the most efficient way,
* **Intuitive**. Name of the variable should read naturally, as close to common speach as possible * **Intuitive**. Name of the variable should read naturally, as close to the common speach as possible
```js ```js
/* Bad */ /* Bad */
const a = 5; // "a" could mean anything const a = 5; // "a" could mean anything
@ -38,6 +41,7 @@ const shouldDisplayPagination = (postsCount > 10);
``` ```
* Name should not duplicate the context when the latter is known, and when removing the context from the name does not decrease its readability: * Name should not duplicate the context when the latter is known, and when removing the context from the name does not decrease its readability:
```js ```js
class MenuItem { class MenuItem {
/* Method name duplicates the context it is in (which is "MenuItem") */ /* Method name duplicates the context it is in (which is "MenuItem") */
@ -48,6 +52,7 @@ class MenuItem {
} }
``` ```
* Name should reflect the expected result: * Name should reflect the expected result:
```js ```js
/* Bad */ /* Bad */
const isEnabled = (itemsCount > 3); const isEnabled = (itemsCount > 3);
@ -58,14 +63,15 @@ const isDisabled = (itemsCount <= 3);
return (<Button disabled={isDisabled} />); return (<Button disabled={isDisabled} />);
``` ```
## Pattern ## HC/LC Pattern
There is a useful pattern you may follow when naming your methods:
``` ```
prefix? + action (A) + high context (HC) + low context? (LC) prefix? + action (A) + high context (HC) + low context? (LC)
``` ```
This is not a rule, but rather a useful pattern for naming the variables. To illustrate, take a look at how this pattern may be applied in the table below.
### Example
| Name | Prefix | Action | High context | Low context | | Name | Prefix | Action | High context | Low context |
| ---- | ---- | ------ | ------------ | ----------- | | ---- | ---- | ------ | ------------ | ----------- |
| `getPost` | | `get` | `Post` | | | `getPost` | | `get` | `Post` | |
@ -73,11 +79,11 @@ This is not a rule, but rather a useful pattern for naming the variables.
| `handleClickOutside` | | `handle` | `Click` | `Outside` | | `handleClickOutside` | | `handle` | `Click` | `Outside` |
| `shouldDisplayMessage` | `should` | `Display` | `Message`| | | `shouldDisplayMessage` | `should` | `Display` | `Message`| |
> Keep in mind, that order of the contexts affects the core meaning of a variable. For example, `shouldUpdateComponent` means *you* are about to update a component, while `shouldComponentUpdate` tells you that *component* will update on itself, and you are but controlling whether it should. > **Note:** The order of the contexts affects the core meaning of a method. For example, `shouldUpdateComponent` means *you* are about to update a component, while `shouldComponentUpdate` tells you that *component* will update on itself, and you are but controlling whether it should do that right now.
In other words, high context emphasizes the meaning of the variable. In other words, **high context emphasizes the meaning of the variable**.
## Actions ## Actions
Chosing proper action name may grant explicit descriptiveness to your methods. This is a good place to start when thinking about a method name. Chosing a proper action name may grant explicit descriptiveness to your methods. This is a good place to start when naming your methods.
#### `get` #### `get`
Accesses data immediately (i.e. shorthand getter of internal data). Accesses data immediately (i.e. shorthand getter of internal data).
@ -96,6 +102,7 @@ function fetchPosts(postCount) {
#### `set` #### `set`
Declaratively sets a variable with `valueA` to `valueB`. Declaratively sets a variable with `valueA` to `valueB`.
```js ```js
const fruits = 0; const fruits = 0;
@ -103,46 +110,58 @@ function setFruits(nextFruits) {
fruits = nextFruits; fruits = nextFruits;
} }
setFruits(5); // fruits === 5 setFruits(5);
console.log(fruits) // 5
``` ```
#### `reset` #### `reset`
Sets something back to its initial value. Sets something back to its initial value or state.
```js ```js
const initialFruits = 5; const initialFruits = 5;
const fruits = initialFruits; const fruits = initialFruits;
setFruits(10); // fruits === 10 setFruits(10);
console.log(fruits); // 10
function resetFruits() { function resetFruits() {
fruits = initialFruits; fruits = initialFruits;
} }
resetFruits(); // fruits === 5 resetFruits();
console.log(fruits); // 5
``` ```
#### `remove` #### `remove`
Removes something *from* somewhere. For example, if you have a collection of selected filters on a search page, removing one of them from the collection is `removeFilter`, not `deleteFilter` (and this is how you would naturally say it in English as well): Removes something *from* somewhere. For example, if you have a collection of selected filters on a search page, removing one of them from the collection is `removeFilter`, **not** `deleteFilter` (and this is how you would naturally say it in English as well):
```js ```js
const selectedFilters = ['price', 'availability', 'size']; const selectedFilters = ['price', 'availability', 'size'];
function removeFilter(filterName) { function removeFilter(filterName) {
const filterIndex = selectedFilters.indexOf(filterName); const filterIndex = selectedFilters.indexOf(filterName);
if (filterIndex !== -1) selectedFilters.splice(filterIndex, 1);
if (filterIndex !== -1) {
selectedFilters.splice(filterIndex, 1);
}
return selectedFilters; return selectedFilters;
} }
``` ```
#### `delete` #### `delete`
Completely erazes something from the realms of existance. Imagine you are a blog writer, and you decide to delete one of your posts from the CMS. Once you pressed a shiny "Delete" button you would confirm "Are you sure you want to delete this post?". When you do, you would perform `deletePost` action, not `removePost`. Completely erazes something from the realms of existance.
Imagine you are a content editor, and there is that notorious post you wish to get rid of. Once you clicked a shiny "Delete post" button, the CMS performed a `deletePost` action, **not** `removePost`.
```js ```js
function deletePost(id) { function deletePost(id) {
const return database.find({ id }).delete();
} }
``` ```
#### `compose` #### `compose`
Creates a new data from the existing one. Applicable mostly to strings or objects. Creates a new data from the existing one. Applicable mostly to strings or objects.
```js ```js
function composePageUrl(pageName, pageId) { function composePageUrl(pageName, pageId) {
return `${pageName.toLowerCase()}-${pageId}`; return `${pageName.toLowerCase()}-${pageId}`;
@ -151,6 +170,7 @@ function composePageUrl(pageName, pageId) {
#### `handle` #### `handle`
Handles a dedicated action. Often used in naming the callback methods. Handles a dedicated action. Often used in naming the callback methods.
```js ```js
function handleLinkClick(event) { function handleLinkClick(event) {
event.preventDefault(); event.preventDefault();
@ -165,6 +185,7 @@ Prefixes enhance variables and methods, indicating an additional meaning behind
#### `is` #### `is`
Describes certain characteristic or state of the current context (returns `Boolean`). Describes certain characteristic or state of the current context (returns `Boolean`).
```js ```js
const color = 'blue'; const color = 'blue';
const isBlue = (color === 'blue'); // characteristic const isBlue = (color === 'blue'); // characteristic
@ -177,6 +198,7 @@ if (isBlue && isPresent) {
#### `min`/`max` #### `min`/`max`
Represent minimum or maximum value. Handy when describing boundaries or allowed limits. Represent minimum or maximum value. Handy when describing boundaries or allowed limits.
```js ```js
function PostsList() { function PostsList() {
this.minPosts = 3; this.minPosts = 3;
@ -186,6 +208,7 @@ function PostsList() {
#### `has` #### `has`
Describes whether the current context possesses a certain value or state. Describes whether the current context possesses a certain value or state.
```js ```js
/* Bad */ /* Bad */
const isProductsExist = (productsCount > 0); const isProductsExist = (productsCount > 0);
@ -196,7 +219,8 @@ const hasProducts = (productsCount > 0);
``` ```
#### `should` #### `should`
Reflects a conditional statement (returns `Boolean`) tightly coupled with a certain action. Reflects a positive conditional statement (returns `Boolean`) tightly coupled with a certain action.
```js ```js
const currentUrl = 'https://dev.com'; const currentUrl = 'https://dev.com';
@ -206,14 +230,15 @@ function shouldUpdateUrl(url) {
``` ```
#### `prev`/`next` #### `prev`/`next`
Indicate the previous and next state of the variable in the current context. Useful for descriptive representation of any kind of the state mutation. Indicate the previous and the next state of the variable in the current context. Useful for describing a state mutation.
```jsx ```jsx
function fetchPosts() { function fetchPosts() {
const prevPosts = this.state.posts; const prevPosts = this.state.posts;
const fetchedPosts = fetch('...'); const fetchedPosts = fetch('...');
const nextPosts = prevPosts.merge(fetchedPosts); const nextPosts = prevPosts.merge(fetchedPosts);
return this.setState({ posts: nextPosts }); return this.setState({ posts: nextPosts });
} }
``` ```