Book Image

Learning Apex Programming

5 (1)
Book Image

Learning Apex Programming

5 (1)

Overview of this book

Table of Contents (17 chapters)
Learning Apex Programming
Credits
Foreword
About the Authors
About the Reviewers
www.PacktPub.com
Preface
Index

Dyna batch


Sometimes, after you write your code, you realize that you need to execute it slightly differently now and then. You could make a second version of your class, but what if there were three or four different situations? Remember, we don't like to write the same code twice; that's inefficient. If the only difference between your use cases are the records that need to be queried but the actual logic is the same, then you can easily add some flair to your implementation of the Database.Batchable interface and make it more dynamic!

//Apex Class that implements the Batchable interface
global class dynaBatch implements Database.Batchable<SObject> {
  
  String queryString;

  global dynaBatch (String otherQueryString){
    queryString = 'Select Id from Contact';
    if ( string.isNotBlank(otherQueryString) ){
      //override the default queryString with one passed in to
      //the constructor  
      queryString = otherQueryString;
    }
  }

  global Database.QueryLocator start...