douqihou7537 2014-04-09 08:03
浏览 10
已采纳

在编程中使用'hacks'?

I have this example pseudo-code that works, $x basically is an object with keys and values or array with keys and objects as values. $y will be constructed in two different ways.

private function someFunction($x) {
    if (is_object($x)) {
        $y = 'result of something';
    } elseif (is_array($x)) {
        $y = 'result of something';
    } else {
        $y = null;
    }

    return $y;
}

Is this a good practice, if function will not be used anywhere else? 'Non-hack' way probably is to convert object to an array (because it is an array in essence) and then make logic based on count of arrays.

Or am I just thinking to much about writing code 'right way'?

  • 写回答

2条回答 默认 最新

  • doucai9270 2014-04-09 08:11
    关注

    The way of using this function is acceptable as long as the input is controlled by you and you know what you are going to do with the data. However on inputs from uncontrolled sources from outside, you should validate the data beforehand as you would not know for sure if the data is valid.

    What I don't understand is how you reach a point a variable may be two different types: an array or an object.

    If you convert it to array and then process it, or use your own function, the important thing is that your logic flows and the code does what it is intended to do.

    If context is right and the code does what it is intended to do, then your code is just fine.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥35 引用csv数据文件(4列1800行),通过高斯-赛德尔法拟合曲线,在选取(每五十点取1点)数据,求该数据点的曲率中心。
  • ¥20 程序只发送0X01,串口助手显示不正确,配置看了没有问题115200-8-1-no,如何解决?
  • ¥15 Google speech command 数据集获取
  • ¥15 vue3+element-plus页面崩溃
  • ¥15 像这种代码要怎么跑起来?
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧