Where to place an assert statement for a collection member property value : at the start of a method or just before using it?

StackOverflow https://stackoverflow.com/questions/18655381

Question

Consider a class Device as follows. Consider a method filterByType that accepts a collection of Devices as input parameter and returns devices of the specified type:

class Device
{
  String barcode;
  String name;
  String type; // values like 'Laptop', 'Desktop', 'Tablet' etc.

// other methods
.
.
.
}

class DeviceManager {

/**
* @param devices is a list of Device type objects
* @param requiredType filter
*/
List<Device> filterByType(List<Device> devices, String requiredType)
{
 // Assert that the input list is neither null or empty
 // Assert that the requiredType parameter is valid

 // Do I assert type member here? i.e. Iterate through all collection members to check that type  member is non-empty
 .
 // Filter based on type member value
 .
 .
 // throw an exception if type is empty
}
.
.

}

Queries:

  1. Do we add an assertion at the start of the method itself that each instance has the required info OR Is it better to start filtering while iterating through the collection and throw an exception if type is indeed empty

  2. Is it good practice to add a note in method level javadoc that Device 'type' member must be provided (i.e. as non-empty) or is this providing too much of (internal) implementation details

Was it helpful?

Solution

If you make DeviceType an enum, then you only need to check for null. If Devices require a type, the time to check that is when Device gets constructed. In the unlikely event that type is an optional property for a Device, you can either (a) claim that untyped devices do not match the requiredType, and so you don't return them, or (b) check as you go through and handle the failure. If you do (b), you should only use an assertion if this method is internal-facing (private). If it's public, you need to throw an exception, either runtime or checked.

It is reasonable and expected for documentation to list preconditions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top