简体   繁体   English

避免将null传递给构造函数作为参数

[英]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. 我在一个单独的文件中有一个AsyncTask作为DownloadImageAsyncTask .java,并且我将contextImageView传递给构造函数作为参数。 When AsyncTask enters onPostExecute() method it assigns the image to the ImageView . 当AsyncTask进入onPostExecute()方法时,它将图像分配给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 . 后来我意识到我需要对应用程序的另一部分使用相同的代码,但是除了将图像分配给ImageView我还需要将其作为背景图像分配给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 ? 由于重复是编程中许多错误的根源,我如何重用AsyncTask使其能够处理两种情况并避免复制/粘贴代码?

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. 我将ImageViewFrameLayout设置为null,但我觉得FrameLayout (since I know that we should avoid passing null as a param) (因为我知道我们应该避免将null作为参数传递)

Any ideas? 有任何想法吗?

You can use what is called an overloaded constructor inside the DownloadImageAsyncTask class. 您可以在DownloadImageAsyncTask类中使用所谓的重载构造函数。 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 要检查结果变量的运行实例,可以执行以下操作,尽管您可能还希望进行一些null检查

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 . 我将对单独的ImageViewFrameLayout进行构造函数重写。 Then inside AsyncTask methods use Object as param and in onPostExecute(Object result) just check if(result instanceOf ImageView) else 然后在AsyncTask方法内部使用Object作为参数,然后在onPostExecute(Object result)检查if(result instanceOf ImageView) else

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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