vendredi 22 octobre 2021

Can I override a method in Java to let in do nothing?

I have some code to refactor, this is how it looks right now:

   class A {
        public void foo() {
            //do A

            //perform validation

            //do B
        }
    }

I need to implement a new method bar that does exactly what foo does, and skip the validation step:

    public void bar() {
        //do A

        //do B
    }

In order to reuse the code block "do A" and "do B", this is now I did. I created a protected method in class A, and moved the validation logic into this method:

   class A {
        public void foo() {
            //do A

            validate();

            //do B
        }


        protected void validate() {
            // perform validation
        }
    }

Then I created another class B that extends class A. It overrides the validate method and do nothing instead.

    class B extends A {
        @Override
        protected void validate() {
            //do nothing
        }
    }

However, I'm still not sure if this is a clean and elegant code design. Please let me know if there's anyway I can improve it. Thanks!

Aucun commentaire:

Enregistrer un commentaire