doulu8537 2014-09-12 17:30
浏览 40

如何组织你的函数中的参数? [关闭]

I am an apologist of clean and readable code, therefore I find that a lot of arguments passed to functions usually do mean nothing, and people need to go through the functions to understand what they are doing and receiving.

Per example:

<?php
function hi($name, $age, $description) {
    echo $name . ' - ' . $age . ' - ' . $description;
}

hi('John', 21, 'I\'m a builder');
?>

Should something like this be a better approach?

<?php
function hi($options) {
    echo $options['name'] . ' - ' . $options['age'] . ' - ' . $options['description'];
}

hi(array(
    'name' => 'John',
    'age' => 21,
    'description' => 'I\'m a builder'
));    
?>

What is your opinion on this?

  • 写回答

2条回答 默认 最新

  • duanmian1085 2014-09-12 17:36
    关注

    I agree with you that too many arguments are a code smell. Only not in the same way as you.

    They are a code smell because it might mean the function / method is doing too much.

    However if you do the latter you don't really fix anything. At least not what you are trying to fix:

    and people need to go through the functions to understand what they are doing and receiving.

    You second example does not fix this at all. It only makes it harder to understand what it does, because instead of being to able to look at the signature of the function now I really have to look at the body of the function to see what on earth the thing needs and does.

    When I look at the signature of:

    function hi($name, $age, $description)
    

    it is clear the function expects a name, age and description. However when looking at the signature of:

    function hi($options)
    

    I will have no idea what it needs. $options can be just about anything.

    Another disadvantage of your second approach is that you have no way ever to add type hints to arguments.

    Don't get me wrong. There are situations where it is perfectly fine to pass an entire array to a function, but I just don't feel this is one of them

    What worries me more in your code is not the fact that there are three arguments, but rather that the function echos data directly instead of returning data. This makes it very inflexible.

    评论

报告相同问题?

悬赏问题

  • ¥15 vue3加ant-design-vue无法渲染出页面
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序