简体   繁体   中英

Is this the good class design practice in Java?

public class OneClass {
        private AnotherClass anotherClass = new AnotherClass();

        private void doOneJob(){
            anotherClass.doOtherJob();
        }
    }

In the above code, AnotherClass is instantiated and held as a class variable of OneClass.

  • What are the consequences of this design?
  • Is it a good practice?
  • Will this support unit testing?

This is called composition and is a fundamental part of Java language. There is nothing wrong with it, and might be essential in a lot of cases.

The only change I would do is use dependency injection to make it easier for testing, ie you'll be able to supply a mock AnotherClass object this way:-

public class OneClass {
    private AnotherClass anotherClass;

    public OneClass(AnotherClass anotherClass){
        this.anotherClass = anotherClass;
    }

    private void doOneJob() {
        anotherClass.doOtherJob();
    }
}

It is hard to "unit" testing because you cant mock the "external" dependency in a normal way. (With groovy tests for example you can override private fields with a mock)

I think it would be better that you have a constructor that accepts a AnotherClass than you can mock it in a unit test via constructor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM