I have a function that draw an image on graphics:
private void DrawSmallImage(Graphics g)
{
if (this.SmallImage == null) return;
var smallPicHeight = this.Height / 5;
var x = this.ClientSize.Width - smallPicHeight;
var y = this.ClientSize.Height - smallPicHeight;
g.DrawImage(this.SmallImage, x, y, smallPicHeight, smallPicHeight);
}
the check if (this.SmallImage == null) return;
should be in the func开发者_StackOverflowtion DrawSmallImage or should be in the caller? which is better?
The best place to put the check logic would be in the calling method.
It is generally considered best to design a method for a single, specific purpose. Not only does this keep your design cleaner, it will decrease the coupling on the method and make it reusable.
I would put it in the caller. The method DrawSmallImage shouldn't know anything about the state of the class. It's purpose is to DrawSmallImage.
I would leave the check there, and pass SmallImage
as a parameter to the DrawSmallImage
method.
This way it can be reused for any image.
Something like
private void DrawSmallImage(Graphics g, Image smallImage)
{
if (smallImage == null) return;
var smallPicHeight = this.Height / 5;
var x = this.ClientSize.Width - smallPicHeight;
var y = this.ClientSize.Height - smallPicHeight;
g.DrawImage(smallImage, x, y, smallPicHeight, smallPicHeight);
}
You might want to throw an Exception when this happens:
if (this.SmallImage == null)
throw new NullReferenceException("Small image can't be null");
Then expect the caller to check a property like:
bool HasSmallImage
{
get { return this.SmallImage!=null; }
}
SmallImage is a member field. The best design, in my view, is the one that prevents it from ever being null (e.g. have it initialized in every constructor, and throw an ArgumentException if it's about to be set to null). Of course, you haven't given much background, so this may not be possible. But it's definitely something to consider.
Either way, you can definitely specify that it must be non-null when this method is called. This is a type of pre-condition.
精彩评论