[SalesForce] Batch Class : how to get Scope size informations at constructor level

This is a philosophical question (maybe not properly) …
I'm wondering about being able to have informations about the scope size for every batch chunk. OK, it's possibible to get the scope size() within an execute call of the batch, but what if I'd like to have informations about this size at Batch class constructor level? So, when someone call

ID batchprocessid = Database.executeBatch(new myBatch(), x);

could I know, in the batch constructor, the value of x?




RECAP

1 – JEREMY NOTTINGHAM SOLUTION:

You can set up your constructor to take the batch size as an argument, and then have access to it later, as long as you implement Database.Stateful:

    global class myBatch implements Database.Batchable<sObject>, Database.Stateful
{
    private Integer batchSize;
    global myBatch(Integer batchSize)
    {
        this.batchSize = batchSize;
        system.debug('batch size: ' + this.batchSize);

        //other constructor stuff
    }
    ...
}

Then your call to run the batch looks like this:

ID batchprocessid = Database.executeBatch(new myBatch(x), x);

1 – MY ANSWER:

I just considered your solution, but my question was a bit harder, i.e. : your solutions works until I know I have to call the myBatch class constructor passing x as parameter, but this way someone else could always call the empty constructor, and I would not be able to catch the scope size.

I would like to be able to do it in any situation , even if someone else call my Batch class constructor (any constructor he wants to call)!

Best Answer

I don't believe that you can.

Instead, consider protecting access to your batcheable class and provide a service class that calls the constructor for you, passing in the batch size, and then you call

global static class myService {
    global static void RunMyBatch(Integer batchSize) {
        myBatch theBatch = new myBatch (batchSize); // Batch size in constructor
        Database.executeBatch(theBatch, batchSize);
    }
}