java函数参数做返回值_java – 使用函数的返回是一个好习惯,返回值是作为参数提供的对象吗?...

我只是想问一下这是一个很好的java练习还是有更好的方式(官方方式)来做同样的事情.

首先,我需要更新一些hashmap信息:

Map rows = new HashMap();

这是excel行的对象,对于每个日期(即10月1日,10月2日等)和包含该行信息的对象.

所以,为了获得这些信息,我有一些方法,如:

rows = performQuery1(rows, foo, bar, initDate, endDate);

rows = performQuery2(rows, someDAO, foo);

和…

private HashMap performQuery1(rows, foo, bar, Date, Date) {

// Some code that adds or removes elements from the hashmap "rows"

rows.put(date1, o1);

//Then return the same object

return rows;

}

所以我的问题是:这是一个很好的java练习吗?

rows = performQuery1(rows, foo, bar, initDate, endDate);

rows = performQuery2(rows, someDAO, foo);

或不?

解决方法:

问题确实非常广泛,或者集中在“最佳实践”部分,可能基于意见 – 但主要不是基于意见,因为对于这样的模式存在有效论据.

通常,您有一个方法可以在某处获取数据,并且应该将其放入目标数据结构(可能是集合或您的案例中的映射).

这种方法的签名有几种选择(大致在你的例子中,但这种模式可以推广).

第一个可能是

/**

* Computes ... something, and returns the result as a map

*/

Map execute(Date d0, Date d1) { ... }

第二个可能是

/**

* Computes ... something, and places the results into the

* given map

*/

void execute(Date d0, Date d1, Map results) { ... }

但是,为了获得最大的灵活性,我经常会参考第三个选项(这是您实际询问的选项):

/**

* Computes ... something, and places the results into the

* given map, which is then returned. If the given map is

* null, then a new map will be created and returned.

*/

Map execute(

Date d0, Date d1, Map results) { ... }

这有几个好处:

>您可以方便地让呼叫创建新地图:

Map results = execute(d0, d1, null);

>您可以确定目标数据结构的实现.如果您总是返回一个新地图,那么就没有办法在HashMap或LinkedHashMap之间进行选择.将目标数据结构传递给方法允许您调用

Map results =

execute(d0, d1, new HashMap());

要么

Map results =

execute(d0, d1, new LinkedHashMap());

分别

>您不必为每个呼叫创建新地图.例如,您可以创建一系列调用

Map results = new HashMap();

execute(d0, d1, results);

execute(d2, d3, results);

在给定的地图中累积结果

考虑到它可以简单地模拟两种选择,这种方法的力量可能变得更加明显:

class DB {

// The private method that can emulate both public methods:

private Map executeImpl(

Date d0, Date d1, Map results);

// The implementation that returns a new map

public Map execute(Date d0, Date d1) {

return executeImpl(d0, d1, null);

}

// The implementation that fills a given map

public void execute(Date d0, Date d1, Map results) {

executeImpl(d0, d1, results);

}

}

旁白:Java SDK的某些地方也使用了类似的模式.例如,在不同的应用案例中:BufferedImageOp#filter:

BufferedImage filter(BufferedImage src, BufferedImage dest)

… If the destination image is null, a BufferedImage with an appropriate ColorModel is created.

Returns: The filtered BufferedImage

标签:java,performance,hashmap,theory

来源: https://codeday.me/bug/20190830/1765842.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值