Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send needed variables to subclass method - as method attributes or as protected class attributes


So my issue is that I don't know the best practice for this. I have an abstract superclass that has the following content:

protected ArrayList<Item> itemList; 
protected abstract ArrayList<Item> getSpecificObjects(SQLiteStatement st);
public ArrayList<Item> getItems() {
            itemList= new ArrayList<Item>();
            SQLiteStatement st = generateStatement();
            getSpecificObjects(st);
            return itemList;
        }

The getSpecificObjects(st) is an abstract method declared in this class, and its implementation is in the abstract class subclasses. It receives a SQLiteStatement local variable as a method variable, and writes the needed data in the instance protected variable itemList.

Should I send itemList as a local variable as well instead of making it an instance variable? Or better should I make the SQLiteStatement as well a instance protected variable?

The code works either way, but I just don't know what is best.
Any help is appreciated!

like image 322
Vlad Ilie Avatar asked Mar 06 '26 18:03

Vlad Ilie


1 Answers

Should I send itemList as a local variable as well instead of making it an instance variable? Or better should I make the SQLiteStatement as well a instance protected variable?

It's really a case of life span. If those values need to persist after the method call has been made, then you should make them instance values. If they do not, and should just be discarded after the method finishes, then declare them in the method header so the GC can deal with them.

like image 174
christopher Avatar answered Mar 09 '26 08:03

christopher



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!