I am creating a library for image loading and caching. I want the user programmer to select the file extension between .png and .jpeg that is want to it to be selected from this 2 only and if programmer types another extension then it must show error. How can I do so?
1 Answer
If i understood your question right, you want to create a library, where you handle images, and when the programmer, who uses your library wants to instantiate your image handling class/classes, you want him/her to choose between jpg and png?
If so, your best option is to create an enum:
public enum ImageType
{
TYPE_JPG, TYPE_PNG;
}
And in your actual image-manipulating class:
public class MyImageHandler
{
public MyImageHandler(ImageType type)
{
//You still need a nullcheck
if(type == null)
throw new NullPointerException("null is not accepted!");
if(type == ImageType.TYPE_JPG)
{
//JPG chosen
}
else if(type == ImageType.TYPE_PNG)
{
//PNG chosen
}
}
}
When the user-programmer uses it:
MyImageHandler handler = new MyImageHandler(ImageType.PNG); //correct
MyImageHandler handler = new MyImageHandler(ImageType.JPG); //correct
MyImageHandler handler = new MyImageHandler(null); //runtime error