Java (anonymous or not) inner classes: is it good to use them?

后端 未结 15 2333
鱼传尺愫
鱼传尺愫 2020-12-01 06:48

In some of my projects and in some books was said to not use inner class (anonymous or not, static or not) - except in some restricted conditions, like

15条回答
  •  忘掉有多难
    2020-12-01 07:17

    I tend to avoid non-static inner classes for the reasons given by other posters. However I have a particularly favourite pattern where a non-static inner class works very effectively: Lazy loading stateful classes.

    A typical lazy loading stateful class is constructed with an entity ID and then on demand can lazily load additional entity information. Typically to lazily load the additional information we will require dependencies. But dependencies + state == anti pattern!

    Non-static inner classes provide a way to avoid this anti-pattern. Hopefully the following simple example illustrates this better than words can:

    /*
     * Stateless outer class holding dependencies
     */
    public class DataAssembler {
      private final LoadingService loadingService;
    
      @Inject
      DataAssembler(LoadingService loadingService) {
        this.loadingService = loadingService;
      }
    
      public LazyData assemble(long id) {
        return new LazyData(id);
      }
    
      /*
       * Stateful non-static inner class that has access to the outer
       * class' dependencies in order to lazily load data.
       */
      public class LazyData {
        private final long id;
    
        private LazyData(long id) {
          this.id = id;
        }
    
        public long id() {
          return id;
        }
    
        public String expensiveData() {
          return loadingService.buildExpensiveDate(id);
        }
      }
    }
    

    Worth noting that there are many other patterns beyond the above example where inner classes are useful; inner classes are like any other Java feature - there are appropriate times where they can be used and inappropriate times!

提交回复
热议问题