Tag: 编码风格的

为什么还可以使用空白构造函数?

我最近正在阅读一些Java并且遇到了一些新东西(一个成语?)对我来说是新的:在程序中,具有多个构造函数的类也总是包含一个空白构造函数。 例如: public class Genotype { private boolean bits[]; private int rating; private int length; private Random random; public Genotype() { // <= THIS is the bandit, this one right here random = new Random(); } /* creates a Random genetoype */ public Genotype(int length, Random r) { random = r; this.length = length; bits […]

Java在try-catch-finally机制中的返回值

我刚刚遇到以下代码: public class TestFinally { public static void main(String[] args) { int returnValue = function(); System.out.println(“Return value: ” + returnValue); } public static int function() { try { return 1; } catch (Exception e){ return 2; } finally{ return 3; } } } 毫无疑问,运行此代码将产生“返回值:3”的输出。 但是,我很好奇: JVM中内部机制。 有没有人知道VM是否实际上通过覆盖第一个“返回1”来替换堆栈上的返回值? 如果是这样,我在哪里可以找到更多相关信息。 我还没有找到在这种方式下使用的finally机制中返回的用法,并允许在JVM中实现。 如果此代码构造用作返回错误代码的方法,则在我看来有更好的方法来记录错误或返回这些错误代码。 有没有人发现这种结构的用途? 提前谢谢了。 干杯,Vern

Java数组约定:String args与String args

我目前正在教学生作为导师编程惯例。 我告诉他们,他们可以在Oracle Code Conventions中找到大多数约定。 在我上一篇教程中,一名学生询问: public static void main(String args[]) 要么 public static void main(String[] args) 是按惯例书写的,或者是否存在差异。 我之前从未见过第一个版本,所以我非常确定第二个版本是一个约定。 但我没有这个来源。 你能给我一个来源(最好是来自oracle,就像我上面链接过的页面一样),这清楚地说明了哪一个是常规的? 两种表达方式的等价性 我知道两个表达式都是等价的: JLS 7 ,p。 292州: An array type is written as the name of an element type followed by some number of empty pairs of square brackets []. 而且还在p。 293: The [] may appear […]

枚举方法覆盖

我发现Enum的定义如下: public Enum MyEnum { ONE { @Override public int getSomething() { return 1; } }, TWO { @Override public int getSomething() { return 2; } } int getSomething() { return 0; } } 不知何故,我觉得这种实现有些不适,因为我认为理想情况下应该为此目的定义一个字段,类应该类似于: public Enum MyEnum{ ONE(1), TWO(2) private int theSomething; private MyEnum(int something) { theSomething = something; } int getSomething() { return […]

Java:如何有效地检查空指针

有一些模式用于检查方法的参数是否已被赋予null值。 首先是经典之作。 它在自制代码中很常见,并且很明显可以理解。 public void method1(String arg) { if (arg == null) { throw new NullPointerException(“arg”); } } 其次,您可以使用现有框架。 该代码看起来更好一点,因为它只占用一行。 缺点是它可能会调用另一个方法,这可能会使代码运行速度稍慢,具体取决于编译器。 public void method2(String arg) { Assert.notNull(arg, “arg”); } 第三,你可以尝试调用一个没有副作用的方法。 这可能看起来很奇怪,但它比上述版本的令牌更少。 public void method3(String arg) { arg.getClass(); } 我没有看到广泛使用的第三种模式,感觉就像我自己发明了它一样。 我喜欢它的简洁性,因为编译器很有可能完全优化它或将其转换为单个机器指令。 我还使用行号信息编译我的代码,因此如果抛出NullPointerException ,我可以将其追溯到确切的变量,因为每行只有一个这样的检查。 您更喜欢哪种检查?为什么?

在Java中优雅地避免NullPointerException

考虑这一行: if (object.getAttribute(“someAttr”).equals(“true”)) { // …. 显然这行是一个潜在的错误,该属性可能为null ,我们将得到一个NullPointerException 。 所以我们需要将它重构为以下两种选择之一: 第一种选择: if (“true”.equals(object.getAttribute(“someAttr”))) { // …. 第二种选择: String attr = object.getAttribute(“someAttr”); if (attr != null) { if (attr.equals(“true”)) { // …. 第一个选项难以阅读但更简洁,而第二个选项在意图上是明确的,但是很冗长。 在可读性方面,您更喜欢哪个选项?