Google Guava是否比Apache Collections“更难”使用?[已关闭]
我正在考虑要求我的团队,混合技能水平,使用谷歌番石榴。在Guava之前,我会使用Apache Collections(或其通用版本)。
与Apache Collections相反,Guava在某些方面似乎更强大,但对于经验不足的程序员来说可能不太容易使用。这里有一个领域,我认为可以举例说明这一点。
我继承的代码包含大量循环访问本质上是异构值映射的列表,探测它们的值,执行空检查,然后执行一些微不足道的事情:
boolean foo( final List< MapLike > stuff, final String target ) {
final String upperCaseTarget = target.toUpperCase(0;
for( MapLike m : stuff ) {
final Maplike n = (MapLike) m.get( "hard coded string" );
if( n != null ) {
final String s = n.get( "another hard code string" );
if( s != null && s.toUpperCase().equals( upperCaseTarget ) ) {
return true ;
}
}
return false ;
}
我最初的想法是使用Apache Collections Transformers:
boolean foo( final List< MapLike > stuff, final String target ) {
Collection< String> sa = (Collection< String >) CollectionUtils.collect( stuff,
TransformerUtils.chainedTransformer( new Transformer[] {
AppUtils.propertyTransformer("hard coded string"),
AppUtils.propertyTransformer("another hard coded string"),
AppUtils.upperCaseTransformer()
} ) );
return sa.contains( target.toUpperCase() ) ;
}
使用番石榴,我可能会走两种方式:
boolean foo( final List< MapLike > stuff, final String target ) {
Collection< String > sa = Collections2.transform( stuff,
Functions.compose( AppUtils.upperCaseFunction(),
Functions.compose( AppUtils.propertyFunction("another hard coded string"),
AppUtils.propertyFunction("hard coded string") ) ) );
return sa.contains( target.toUpperCase() ) ;
// or
// Iterables.contains( sa, target.toUpperCase() );
// which actually doesn't buy me much
}
与Apache Collections相比,Functions.compose( g, f )颠倒了“直观”的顺序:函数是从右到左应用的,而不是TransformerUtils.chainedTransformer的“明显”从左到右。
一个更微妙的问题是,随着番石榴返回实时视图,调用实时视图可能会多次应用(组合)函数,所以我真正应该做的是:contains
return ImmutableSet.copy( sa ).contains( target.toUpperCase() ) ;
但是我转换后的集合中可能有 null,所以我不能完全做到这一点。当然,我可以将其转储到java.util.Collection中。
但对于我的(经验不足的)团队来说,这并不明显,即使在我解释之后,也可能在编码的热度中被遗漏。我希望也许Iterables.contains()会“做正确的事情”,并知道一些魔术实例来区分实时取景代理和普通的旧集合,但事实并非如此。这使得番石榴可能更难使用。
也许我在我的实用程序类中编写一些类似于静态方法的东西来处理这个问题?
// List always uses linear search? So no value in copying?
// or perhaps I should copy it into a set?
boolean contains( final List list, final Object target ) {
return list.contains( target ) ;
}
// Set doesn't use linear search, so copy?
boolean contains( final Set set, final Object target ) {
//return ImmutableSet.copy( set ).contains( target ) ;
// whoops, I might have nulls
return Sets.newHashSet( set ).contains( target ) ;
}
或者也许只复制超过一定大小的集?
// Set doesn't use linear search, so copy?
boolean contains( final Set set, final Object target ) {
final Set search = set.size() > 16 : Sets.newHashSet( set ) : set ;
return search.contains( target ) ;
}
我想我是在问,“为什么番石榴中没有'更容易'”,我想答案是,“好吧,总是把它返回的东西转储到一个新的收藏中,或者写你自己的转换来做到这一点”。transform
但是,如果我需要这样做,番石榴图书馆的其他客户可能不可以吗?也许在番石榴中有更好的方式,我不知道?