减少java对象添加中的样板

时间:2016-08-22 15:01:30

标签: java

我想为我的简单对象编写add(),subtract()和equals()方法,允许在字段中使用null。我最终使用python生成样板代码,这告诉我我做错了什么。写这样一个类的DRYer方法是什么?

image.Save(path + name + ".png", ImageFormat.Png);

编辑:我使用==进行空检查,但这是多余的。读者,不要这样做。我将留下错误的代码示例,以确保评论有意义。

编辑2:如果package com.blicket.parser; /** * Created by steve on 8/22/16. */ public class Foo { public Integer bar; public Integer baz; public Integer qux; public boolean equals(Foo b){ if( (this.bar == b.bar || this.bar.equals(b.bar) && (this.baz == b.baz || this.baz.equals(b.baz) && (this.qux == b.qux || this.qux.equals(b.qux) && ){ return true; } else { return false; } } public Foo add(Foo a, Foo b){ Foo c = new Foo(); c.bar = a.bar + b.bar; c.baz = a.baz + b.baz; c.qux = a.qux + b.qux; return c; } } barbaz为空,则尝试删除==检查

qux

抛出public boolean equals(Foo b){ if( this.bar.equals(b.bar) && this.baz.equals(b.baz) && this.qux.equals(b.wux) ){ return true; } else { return false; } }

EDIT 3 Electric Jubilee:看起来正确的答案是

NullPointerException

1 个答案:

答案 0 :(得分:-3)

你应该尝试使用Groovy,它支持+和 - 重载操作:

http://groovy-lang.org/operators.html 第10章运算符重载

https://www.ibm.com/developerworks/library/j-pg10255/

所以你写的不是公共布尔加法(Foo a,Foo b):

def plus(Foo foo){
  this.bar+=foo.bar
  this.baz+=foo.baz
  this.qux*=foo.qux
}

然后你用它作为:

  Foo a = ...
  Foo b = ...
  Foo c = a + b;

所以对你的问题的正确答案是扩展语言而不是生成样板代码。

相关问题