简体   繁体   中英

Avoid passing null to constructor as param

I have an AsyncTask in a separate file as DownloadImageAsyncTask .java and I'm passing, along with context , an ImageView as an argument to the constructor. When AsyncTask enters onPostExecute() method it assigns the image to the ImageView .

Later I realized I need to use the same code to another part of my app but instead of assigning the image to an ImageView I need to assign it as a background image to a FrameLayout .

Since duplication is the root of a lot of errors in Programming how can I re-use the AsyncTask so it can handle both cases and avoid copy/paste code ?

I tried with a constructor like :

public DownloadImageAsyncTask(Context context, ImageView ivCover, FrameLayout flCover) {
    this.context = context;
    this.ivCover = ivCover;
    this.flCover = flCover;
}

where I set either ImageView or FrameLayout as null but that doesn't feels right to me. (since I know that we should avoid passing null as a param)

Any ideas?

You can use what is called an overloaded constructor inside the DownloadImageAsyncTask class. It is very similar to how you can have several methods with the same name that take different parameters.

public DownloadImageAsyncTask(Context context, ImageView ivCover) 
{
    this.context = context;
    this.ivCover = ivCover;
}

public DownloadImageAsyncTask(Context context, FrameLayout flCover) 
{
    this.context = context;
    this.flCover = flCover;
}

To check the running instance of your result variable, you can do the following, although you may want to sprinkle in some null checks as well

if(result instanceOf ImageView)
{
    // do stuff
}
else if(result instanceOf FrameLayout)
{
    // do stuff
}
else
{
    // do other stuff
}

I would do with constructor override for seperate ImageView and FrameLayout . Then inside AsyncTask methods use Object as param and in onPostExecute(Object result) just check if(result instanceOf ImageView) else

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM