【问题标题】:Usage of 'use' or 'using' in programming languages在编程语言中使用“使用”或“使用”
【发布时间】:2012-04-21 05:20:42
【问题描述】:

我一直认为命名空间的主要目标是防止名称冲突和歧义。

#1 来自 php.net 的命名空间修复的问题:

您创建的代码与内部 PHP 之间的名称冲突 类/函数/常量或第三方 类/函数/常量。

但是,大多数语言以某种方式实现“use”关键字,以将其他命名空间别名或导入当前命名空间。我知道它是如何工作的,但我不明白为什么会使用这样的功能。

使用“use”关键字不是有效地破坏了命名空间的用途吗?

namespace core\utils;

class User {
    public static function hello(){
        return "Hello from core!";
    }
}
//---------------------------------------------------

namespace core2\utils;

class User {
    public static function hello(){
        return "Hello from core2!";
    }
}
//---------------------------------------------------

namespace core2;

//causes name collision, we now have two different classes of type 'utils\User'
use core\utils; //without this line the result is 'Hello from core2'

class Main {
    public static function main(){
        echo utils\User::hello();
    }
}

Main::main();
//outputs Hello from core!
?>

我是否遗漏了什么,或者真的普遍不鼓励使用“使用”关键字?

不管怎样,在什么情况下牺牲封装实际上是个好主意?

以前用use,现在不知道什么时候用use。

编辑: 好吧,让我直截了当地说:如果我使用“use”来获取短名称,这比仅在全局命名空间中声明类更好吗?见下文:

namespace core\utils\longname {    
    class User {} //declare our class in some namespace
}

//------------------Other File---------------------------
namespace { //in another file import our long name ns and use the class
    use core\utils\longname\User as User;
    new User();
}

^ 这样的命名空间对这个声明有什么好处:

namespace {    
    class User {} //declare our class in global namespace
}

//------------------Other File---------------------------
namespace { //in another file just use the class
    new User();
}

这两者有什么区别吗?

【问题讨论】:

  • “使用”之所以被使用,是因为它既让人头疼,又与良好的视觉理解背道而驰,必须一直拼出所有内容。
  • 确实如此,但感觉就像我在伤害命名空间。歧义和可读性之间的界限在哪里?
  • 别名应该是多余的。但目前是命名空间的副产品,没有用于其预期目的,而是用于创建标识符分类。
  • 编程总是一个权衡的问题。硬性规定不存在,无论“专家”如何试图说服你。编程的艺术是知道在哪里画出微弱的灰线。

标签: php namespaces


【解决方案1】:

+1 非常有趣的问题

我的意见

关键字use 如此多的用途和功能可以想象

use core\utils\sms\gateway\clickatell\http\SmsSender  as SmsCSender 
use core\utils\sms\gateway\fastSMS\ftp\Smssender as SmsFSender 

现在比较

if(!SmsCSender::send($sms))
{
    SmsFSender::send($sms);
}

if(!core\utils\sms\gateway\clickatell\http\SmsSender::send($sms))
{
    core\utils\sms\gateway\fastSMS\ftp\SmsSender::send($sms);
}

结论

如果没有namespaceuse,我将无法实现如此清晰可读的代码,所以我认为namespace and use complement each other 而不是“使用”破坏了命名空间的目的

【讨论】:

  • 是的,use...as 范式比只有use/using/import/et al 的方案要好得多。不幸的是,它并非在所有语言中都可用,而且当它出现时,有时会有奇怪的限制(或者至少是陈旧的“约定”,使其不太理想)。
  • 当然这可能是大多数人使用“使用”的原因。但是,这与在全局命名空间中声明类不完全相同吗?这样你就不必搞乱“使用”,并且你有干净的代码。当你最终只是将命名空间与“use”合并时,你会继续获得哪些优势?
  • 如果没有全局 ns,该实例将无法实现.. 全局 ns 定义了 use 所作用的路径
猜你喜欢
  • 2016-06-08
  • 2015-12-23
  • 1970-01-01
  • 2012-04-06
  • 1970-01-01
  • 2015-12-20
  • 2013-02-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多