开发者

What name should have method which returns number of nested objects?

Suppose we have classes Gallery and Image. There can be many images in one gallery.

Gallery should have some method which returns number of nested images. My suggestions:

int getImagesCount ();

int countImages ();

int imagesCount ();

I saw examples of each of these 3 suggestions in different APIs (of course with another noun or even without it, like method size () in Collections API).

What would you prefer and why? (One of my thoughts against countImages () is that this name can make user think that this method does some com开发者_如何学运维plex calculations.)


My suggestion:

public interface Gallery {

    int getNumberOfImages();

    //...
}

I agree, that countXX() leads to the impression, that calling this method triggers some sort of calculation. So I wouldn't use it here as well.


I would rule out countImages () too, for the same reason.

Other than that, if there is a more or less consistent naming convention in the codebase Gallery belongs to, I would recommend adhering to it. In absence of a clear project convention, I personally would lean towards size().


If you are thinking of having one method that returns the size, and another one that returns the nth element, my recommendation in general: Don't do it! Use the power of the collections api!: create a method that returns a List<Image>. That way the user of the API can more easily do things like iterating over the images (using the enhanced for-loop instead of having to juggle with indices), sorting them, combining them in other collections,...

It is really easy to implement:

  • If the images are internally already represented as a list, you can just return that (optionally wrapped with Collections.unmodifiableList).
  • And even if you don't store them as a list, exposing them as List<Image> is as easy as writing a small subclass of AbstractList by just overriding size() and get(int), the two methods you were going to implement anyways.


The problem with size() is that it's not necessarily clear whether you're returning the number of elements (images in this case) or the size in bytes/kilobytes/megabytes of the collection. For the same reason, I tend to prefer getImageDimensions() to getImageSize(). In your case, I like countImages() because it's clear and concise, but it doesn't follow naming conventions if for example, there are methods like getImage(int). Therefore, I will have to go with int getImagesCount() or better, int getNumberOfImages() or int getNumImages()

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜