• 请不要在回答技术问题时复制粘贴 AI 生成的内容
darasion
V2EX  ›  程序员

怎样处理这样的函数传参问题?

  •  
  •   darasion · Apr 11, 2013 · 3644 views
    This topic created in 4818 days ago, the information mentioned may be changed or developed.
    以 php 为例:



    假设有个函数是发表文章:
    function post($title, $content) { ... }

    后来可能需要一些改动比如加入一些作者什么的
    function post($title, $author, $content){ ... }

    再后来,再加入了分类:
    function post($title, $auhor, $content, $cat) { .... }

    以此类推。
    这个函数有可能很多地方都在调用,改了签名可能会影响一大堆的地方。这样显然不好。




    于是有人想了个办法:
    function post($data) { ... }
    $data 是个大数组,不论里边怎么变,都不用改动别的代码了。

    但是这又带来另外一个问题:
    我从函数的签名不知道这个函数都能使用哪些参数,违背了一开始封装的初衷,更恼人的是过了几个月之后,代码的作者都不知道这个函数该怎么用了!


    怎么处理这种经常变更的情况呢?
    4 replies    1970-01-01 08:00:00 +08:00
    skydiver
        1
    skydiver  
       Apr 11, 2013
    加入默认参数啊,

    function post($title, $content) { ... }
    改之后变成
    function post($title, $content, $author='skydiver', $cat='default') { ... }
    AlloVince
        2
    AlloVince  
       Apr 11, 2013
    OOP

    class Post {
    protected $title;
    protected $content;
    public function getTitle(){}
    public function getContent(){}
    }
    fkccp
        3
    fkccp  
       Apr 11, 2013
    默认参数+1
    nkliwenjian
        4
    nkliwenjian  
       Apr 11, 2013
    懒得改到最后只会自己吃亏,加参数加到第三个的时候基本上就应该动手重构了。
    重构的话,基本上这个属于典型的参数对象的,把这一堆参数抽象成一个对象,然后传的时候只需要传一个对象就可以了。当然不叫data了,叫article呗,然后里面是article.title,article.content之类的。
    我倒不觉得有很多地方用就很难改。
    函数内部就不说了,调用的地方基本上就是做个正则表达式替换的事情。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2415 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 6b34f497 · 34ms · UTC 01:23 · PVG 09:23 · LAX 18:23 · JFK 21:23
    ♥ Do have faith in what you're doing.