cleancode思想-函数篇

本文分享了编写干净代码的几个关键原则,包括函数应当遵循单一职责原则、应用向下规则以改善代码可读性、合理控制函数参数数量并使用多态替代条件语句等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

下面是针对cleancode函数方面的分享

1. 只做一件事

  • 应遵循单一职责原则
  • 一个函数只做一件事,且函数名能准确表达出这件事
  • 确保一个函数在同一个抽象层
  • 不能出现副作用

eg:

改进前(缺点:存在副作用,不只是做一件事,不在同一个抽象层)

const viewModel = {
  userList: [],
  firstUser: {},
}

function getUserList () {
  return getUserListRequest().then(response => {
    viewModel.firstUser = response[0]
    return response
  })
}

viewModel.userList = getUserList()

改进后

const viewModel = {
  userList: [],
  firstUser: {},
}

function getUserList () {
  return getUserListRequest().then(response => {
    return response
  })
}

viewModel.userList = getUserList()
viewModel.firstUser = viewModel.userList[0]

我们现在都知道,上一节改进后的getCouponList()函数只做了一件事,

但其实也可以看作是以下2件事:

A.请求接口

B.返回接口的数据

所以这算是一件事还是两件事呢?

因为”请求接口“和”返回接口的数据“,这两件事是在同一个抽象层
的,都是属于getUserList的抽象层,因此是只做了一件事。

2. 向下规则

eg:

改进前:(缺点:getUserList()在调用之后声明,有悖阅读习惯)

const userList = getUserList()

function getUserList () {
  // your code
}

改进后

function getUserList () {
  // your code
}

const userList = getUserList()

3. 函数参数

  • 尽量控制参数数量,因为它们有太多概念性
  • 不要用标识参数,应该把它们拆成两个函数
  • 当函数参数大于3个时,改为以对象方式传入

eg:

改进前(缺点:参数太多,可读性差)

function handleUserInfo (name, age, phone, address) {
  // your code
}

改进后

function handleUserInfo (userInfo) {
  const { name, age, phone, address } = userInfo
  // your code
}

eg:

改进前(缺点:使用标识参数,不符合单一职责原则)

function getUserList (isVip) {
  if (isVip) {
    return ajax.get('/get_vip_list')
  }
  return ajax.get('/get_user_list')
}

改进后

function getUserList () {
    return ajax.get('/get_user_list')
}

function getVipList () {
  return ajax.get('/get_vip_list')
}

4. 多态代替条件语句

eg:

改进前

class Animal {
  private type

  constructor (type) {
    this.type = type
  }

  say () {
    if (this.type === 'dog') {
      console.log('wang wang wang ~~~')
    } else if (this.type === 'duck') {
      console.log('ga ga ga ~~~')
    }
  }

  eyeNumber () {
    console.log('I have two eyes')
  }
}

改进后

class Animal {
  say () {}

  eyeNumber () {
    console.log('I have two eyes')
  }
}

class Dog extends Animal {
  say () {
    console.log('wang wang wang ~~~')
  }
}

class Duck extends Animal {
  say () {
    console.log('ga ga ga ~~~')
  }
}

其他

  • 使用getter和setter函数
  • 函数代码不超过50行
  • 删除重复代码



ps: 转载请注明出处

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值