const publishRule = {name: { type: 'string', required: true,format:/^[\u4e00-\u9fa5]{2,10}$/,message:"书名格式错误"}} const authorRule = {author: { type: 'string', required: true,format:/^[\u4e00-\u9fa5]{2,10}$/,message:"作者姓名格式错误"}} const priceRule = {price:{type:"number",require:true,min:0,max:1000,message:"书本定价出错"}} const quantityRule = {quantity:{type:"number",require:true,min:0,message:"书本数量出错"}}耦合度太高,怎么简化
时间: 2023-07-19 18:18:38 浏览: 48
可以将这些规则抽象成一个函数,函数接收属性名、属性值类型、是否必须、格式验证、错误信息等参数,返回一个符合规则的对象。这样可以减少代码重复,提高代码可维护性。
例如,可以定义一个名为 createRule 的函数,接收四个参数,分别是属性名、属性值类型、是否必须和格式验证正则表达式,代码如下:
```
function createRule(name, type, required, format) {
return {
[name]: {
type,
required,
format,
message: `${name}格式错误`
}
}
}
```
然后可以调用这个函数来生成不同的规则对象,例如:
```
const nameRule = createRule('name', 'string', true, /^[\u4e00-\u9fa5]{2,10}$/)
const publishRule = createRule('publish', 'string', true, /^[\u4e00-\u9fa5]{2,10}$/)
const authorRule = createRule('author', 'string', true, /^[\u4e00-\u9fa5]{2,10}$/)
const priceRule = createRule('price', 'number', true, /^[\u4e00-\u9fa5]{2,10}$/)
const quantityRule = createRule('quantity', 'number', true, /^[\u4e00-\u9fa5]{2,10}$/)
```
这样就可以将规则的定义和创建分离开来,提高了代码的可读性和可维护性。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![hpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)