Search code examples
javac#collectionsinterfacedata-access-layer

Is it good practice to return a Collection or a Collection's Interface even if it's a single student or single class? If yes, why?


Let's say I'm implementing an E-Learning application for a University.

Let's say we have methods in our Data Access Layer for retrieving a single student, a single Class, etc.

  1. getStudent
  2. getClass

Event if it's just a single student or a Single Class, is it good practice to always return a Single Collection or Collection's interface that would contain the single student or Single class? If yes, why?

  • IEnumerable< Student > getStudent(int StudentId)
  • IEnumerable< Class > getClass(int ClassId)

Solution

  • Since your method names are singular, it implies that a single instance of a class will be returned. If the method names were plural, it would imply returning a collection.

    Eg.

    Student getStudent(int StudentId);
    Class getClass(int classId);
    IEnumerable<Student> getAllStudents();
    IEnumerable<Class> getAllClasses();
    

    Doing it this way means that anyone using the methods has a pretty good idea what kind of object is going to be returned and means you don't need any additional code to get the first object in a collection that will always return 1 item.