【问题标题】:PMD rule DataflowAnomalyAnalysis oddnessPMD规则DataflowAnomalyAnalysis奇数
【发布时间】:2009-07-19 19:16:13
【问题描述】:

我有以下 JUnit 测试:

@Test
public void testRunLocalhost() throws IOException, InterruptedException {
    // Start an AnnouncerThread
    final AnnouncerThread announcer = new AnnouncerThread();
    announcer.start();

    // Create the socket and listen on the right port.
    final DatagramSocket socket = new DatagramSocket();
    assert(socket != null);

    // Create a packet to send.
    final DatagramPacket packet = new DatagramPacket(new byte[0], 0, InetAddress.getByName(AnnouncerThread.GROUP), AnnouncerThread.PORT);
    assert(packet != null);

    // Send the packet.
    socket.send(packet);

    // Listen for the IP from the server.
    final DatagramPacket receivedPacket = new DatagramPacket(new byte[256], 256);
    socket.setSoTimeout(2000); // Only wait 2 seconds.
    socket.receive(receivedPacket);
    socket.close();

    // Get localhost's address.
    final InetAddress localhost = InetAddress.getLocalHost();
    assert(localhost != null);

    // Compare the receive IP to the localhost IP.
    final String receivedIP = new String(receivedPacket.getData());
    if (!receivedIP.startsWith(localhost.getHostAddress())) {
        fail("Received IP: '" + receivedIP + "' not the same as localhost: '" + localhost.getHostAddress() + "'");
    }

    announcer.shutdown();
    announcer.join();
}

而 PMD 给出了以下违规行为:

Found 'UR'-anomaly for variable 'socket' (lines '36'-'36').
Found 'UR'-anomaly for variable 'localhost' (lines '36'-'36').
Found 'UR'-anomaly for variable 'packet' (lines '36'-'36').

我文件中的第 36 行是定义方法的行:

public void testRunLocalhost() throws IOException, InterruptedException {

我不明白这些违规行为在说什么。我应该在哪里定义这三个变量?为什么 AnnouncerThread 不在违规中?它的声明方式与我尝试重新排序声明无济于事的方式相同。

【问题讨论】:

    标签: java pmd


    【解决方案1】:

    这似乎与您在分配这三个最终变量后立即进行的assert 调用有关。

    PMD 文档 (http://pmd.sourceforge.net/rules/controversial.html#DataflowAnomalyAnalysis) 说:

    UR - 异常:存在对之前未定义的变量的引用

    【讨论】:

    【解决方案2】:

    这看起来很奇怪。有趣的是,它发生在为通过“new”分配的对象定义的所有三个变量上,然后您检查它们是否为空。我希望“新”的结果始终有效/不为空 - 否则应该抛出 OutOfMemoryException。不知道是不是这个问题?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-09
      • 2012-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多