Should I do such things?

I just started to learn guava. Therefore, I do not know the best practices, etc. This is the code (it binds some classes and places it in Order by collection):

public ImmutableList<ModelBean> toBean(Collection<Shape> model) {
    return ImmutableList.copyOf(Collections2.transform(Ordering.from(new Comparator<Shape>() {
        @Override
        public int compare(Shape o1, Shape o2) {
            return 0; //here placed some one line logic
        }
    }).sortedCopy(model), new Function<Shape, ModelBean>() {
        final ModelBeanCreator binder = new ModelBeanCreator();

        @Override
        public ModelBean apply(Shape input) {
            return binder.createModelBean(input);
        }
    }));
}

So, should it be divided into several operations?

upd What does it do? A collection is required. Sorts it. Matches each object with another. Creates a new ImmutableList and returns it.

+3
source share
3 answers

, ( , Java , ), . .

, , .. :

private static Function<Shape, ModelBean> MODEL_BEAN_PROJECTION =
    new Function<Shape, ModelBean>() {
    final ModelBeanCreator binder = new ModelBeanCreator();

    @Override
    public ModelBean apply(Shape input) {
        return binder.createModelBean(input);
    }
};

MODEL_BEAN_PROJECTION . , , , .

, , , . - , , - . - , , .

+5

, . , , , .

public ImmutableList<ModelBean> toBean(Collection<Shape> model) {
    // I pulled out the first anonymous class object into a method scoped
    // reference and gave it some meaningful name based on what it does.
    final Comparator<Shape> shapeComparator = new Comparator<Shape>() {
        @Override
        public int compare(Shape o1, Shape o2) {
            return 0; //here placed some one line logic
        };

    // Also pulled out the second anonymous object into a method scoped
    // reference with meaningful name.
    final Function<Shape, ModelBean> sortFunc = new Function<Shape, ModelBean>() {
        final ModelBeanCreator binder = new ModelBeanCreator();

        @Override
        public ModelBean apply(Shape input) {
            return binder.createModelBean(input);
        }
    }; 

    // Now the transformation is much simpler without much work.
    return ImmutableList.copyOf(Collections2.transform(Ordering.from( shapeComparator ).sortedCopy(model), sortFunc ));
}
+2

, , Collections2.transform().

ImmutableList.Builder<ModelBean> builder = ImmutableList.builder();
for (Shape shape : sortedShapes) {
  builder.add(binder.createModelBean(shape));
}
return builder.build();

, , .

+1

Source: https://habr.com/ru/post/1779775/


All Articles