Home > Back-end >  Follow DRY principle
Follow DRY principle

Time:04-03

I have an implementation of following kind-

int max_count = 10;

main() {

  Writer writer = //initialise writer;
  List records = new ArrayList();

  while(true) {

    // some functionality
    // some functionality

    if (records.size() >= max_count) {

      // xyz code
      // xyz code

      records = new ArrayList();
    }
  }

  if(records.size() != 0) {

    // xyz code
    // xyz code
  }

}

How can I follow the DRY principle here so that the code in while loop and in if block shortens?

CodePudding user response:

You simple have to create another function that contains yout "xyz code" and call it where needed. I hope this answer is what you wanted, if this is not or if you need anything else, feel free to ask !
Have a great day, Lukas.

CodePudding user response:

I guess the most simple way would be extracting the xyz code to one function and call it multiple times.

int max_count = 10;

void doXyz(){
      // xyz code
      // xyz code
}

main() {

  Writer writer = //initialise writer;
  List records = new ArrayList();

  while(true) {

    // some functionality
    // some functionality

    if (records.size() >= max_count) {

      doXyz()

      records = new ArrayList();
    }
  }

  if(records.size() != 0) {

    doXyz()
  }

}
  • Related