3

Click one-click subscribe to the column "Cloud Recommendation", get the official recommended high-quality content, and learn technology without getting lost!

Reusable code reduces duplication of effort. In a software, there will be many similar business scenarios. Abstract these scenarios into reusable code. Reusing code reduces duplication of effort when developing new features.

Reusable code can reduce the number of changes and missed changes due to changes in requirements. Just imagine, if you want to modify the color of the submit button on the entire site, if there are 100 pages with submit buttons on the entire site, and the styles of the buttons on each page are not reused, the amount of changes and the risk of missing changes are very high. If you make it reusable, you only need to change one place.

How to write reusable code?

The more responsibilities a code block has, the harder it is to reuse. To write reusable code is to identify and separate out the reusable parts.

Consider this scenario: the function of code block A is to get interface data and render the UI. The UI of code block B is the same as that of A, but the obtained interface data is different. Code block C gets the same data as A, but the UI is different from A. The code between A, B, and C cannot be reused.

To change it into reusable code is to separate the reusable UI and the code for obtaining interface data.

Below, we look at some common reusable parts and reuse methods.

1. UI display

The UI is presented as a presentation of the appearance, including: HTML and CSS. Data acquisition and event handling are not included.

Using components can realize the reuse of UI display code. Such components are called presentational components. Data and event handling are passed in via properties. Components in component libraries such as Ant Design are display components. Here is a list of news about React's implementation:

import React from 'react'
import s from './style.scss'
import Item, {IItem} from './item'

export interface INewsListProps {
  list: IItem[],
  onItemClick: (id: number) => void
}

const NewsList: FC<INewsListProps> = ({ list, onItemClick }) => {
  return (
    <div className={s.list}>
      {
        list.map(item => (
          <Item
            key={item.id}
            onClick={onItemClick}
            payload={item}
          />
        ))
      }
    </div>
  )
}

export default React.memo(NewsList)

2. Interface call

There are two parts of the interface call that can be reused:

Generic handling of interface requests and responses.
A specific interface call.

3. General processing of interface requests and responses

When the interface is called, some general processing is often done. for example:

For websites with separated front and back ends, a token should be added to the request header of the interface to identify the user.
When the interface reports an error, convert the error code into a user-friendly error message.
Use axios to handle it like this:

// 请求拦截器
axios.interceptors.request.use(...)
// 响应拦截器
axios.interceptors.response.use(...)

Fourth, the specific interface call

The interface calling code is generally placed in a file, such as service.js:

export const fetchList = ...
export const fetchDetail = ...
export const createItem = ...
export const updateItem = ...
export const deleteItem = ...

API calls, as well as loading state management, anti-shake, throttling, error retry, caching and other scenarios. React can use useRequest, and Vue has a similar wheel.

5. Business Process

Many business processes are similar and can be reused. For example, the business process of managing the background list page is similar to this:

When entering the page, get the list data.
Click the search button to obtain list data according to the current query conditions.
Click Pagination to get a list of specified pages.
Custom hooks (called composition API in Vue3) support internal state management and life cycle. Therefore, hooks can be used to encapsulate business processes. The following is the implementation of using Vue3's composite API to encapsulate the list page of the management background:

import { onMounted, reactive, ref, Ref } from 'vue'
export interface Params {
  url: string
  searchConditions: Record<string, any>
}

interface Return<T> {
  searchConditions: Record<string, any>
  resetConditions: () => void
  pagination: Record<string, any>
  fetchList: (isReset: boolean) => void
  list: Ref<T[]>
  isLoading: Ref<boolean>
}

function useList<T extends Record<string, any>> ({
  url,
  searchConditions: initCondition
}: Params): Return<T> {
  const searchConditions = reactive({...initCondition})
  const pagination = reactive({
    pageSize: 10
  })
  const list = ref<T[]>([]) as Ref<T[]>
  const isLoading = ref(false) as Ref<boolean>
  // isReset 为 true 表示搜第一页。
  const fetchList = (isReset: boolean = false): void => ...

  // 进入页面
  onMounted(() => {
    fetchList()
  })

  return {
    searchConditions,
    pagination,
    fetchList,
    list,
    isLoading,
  }
}

export default useList

Recommend a hooks tool library: ahooks. Vue version: ahooks-vue.

6. Data

Some data points are used in multiple places. Such as: login user information, permission data.

This data can be managed with a state management library. React state management generally uses Redux, Mobx or Context API. Vue generally uses Vuex.

Seven, tool function

Utility functions are business agnostic. Such as: format the date, generate a unique id, etc. Lodash and moment.js contain a lot of utility methods.

Summarize

To write reusable code, the essence is to identify and separate the reusable parts. The front end can find reusable parts from UI display, interface calls, business processes, data, and tool functions.

The next level of code quality is: refactorable code. I will cover it in the next article.

Jin Weiqiang's previous wonderful articles are recommended:

about code quality - Preface
Code Quality Layer 5 - just implements functionality
Code Quality Tier 4 - Robust Code
Code Quality Tier 3 - Readable Code

image.png

"Cloud Recommendation" is a high-quality content column of Tencent Cloud Plus community. The cloud recommendation officer specially invites industry leaders to focus on the implementation of cutting-edge technologies and theoretical practice, and continue to interpret hot technologies in the cloud era and explore new opportunities for industry development. Click to subscribe to with one click, and we will regularly push premium content for you.


腾讯云开发者
21.9k 声望17.3k 粉丝