检查断言

时间:2016-10-16 23:28:22

标签: java assert

setDates和setTimes方法的前提条件是它们的参数都不为null。这是通过断言来检查的。 (这意味着如果不满足前提条件,程序将在断言时失败,并且将抛出AssertionError。)

这是我的代码:

public class Section
{
/**
 * Default section number.
 */
private static final String DEFAULT_SECTION_NUMBER = "";

/**
 * Constant for building Strings with newline characters within them.
 */
private static final String LINE_SEPARATOR = System.
        getProperty("line.separator");

/**
 * The maximum number of students permitted into a section.
 */
private static final int MAXIMUM_STUDENTS_PER_SECTION = 30;

/**
 * Valid length for a sectionNumber string.
 */
private static final int SECTION_NUMBER_LENGTH = 3;

/**
 * Shared variable for keeping count of the number of section objects in
 * existence.
 */
private static int count = 0;

/**
 * The date at which the section is finished.
 */
private Date endDate;

/**
 * The end time for the meeting of the section.
 */
private Time2 endTime;

/**
 * The list of students in the class. This declaration uses the Java 7 facility
 * of not repeating the generic type if that type can be inferred by the
 * compiler.
 */
private final List<Student> roster = new ArrayList<>();

/**
 * The three-character designation of the section (called a
 * &ldquo;number&rdquo;).
 */
private String sectionNumber = DEFAULT_SECTION_NUMBER;

/**
 * The date on which the section starts to meet.
 */
private Date startDate;

/**
 * The time of day at which the section meets.
 */
private Time2 startTime;

/**
 * The course of which this is a section.
 */
private final Course thisCourse;

/**
 * Constructor.
 * 
 * @param course        the course of which this is a section
 * @param sectionNumber the section number (within the course) of this section
 * @throws SectionException
 */
public Section(Course course, String sectionNumber) throws SectionException
{
    /* Increment the collective count of all Section objects that have been
       created. Do this first as the object already exists. */
            ++count;

                this.thisCourse = course;
            try
            {
                if( isValidSectionNumber(sectionNumber) )
                this.sectionNumber = sectionNumber;
            }
            catch (Exception ex)
            {
                throw new SectionException("Error in constructor", ex);
            }
}

/**
 * Add a student to the course.
 *
 * @param student   the student object to be added. If the course is full, the
 *                  student is not added
 */
public void addStudent(Student student)
{
    if( roster.size() != MAXIMUM_STUDENTS_PER_SECTION )
        roster.add(student);
}

/**
 * Get details about the current state of this section, including the course of
 * which it is part, the dates it starts and ends, times, etc., and the current
 * count of the enrollment.
 *
 * @return  the section details
 */
public String getDetails()
{
    return String.join(LINE_SEPARATOR,
            "Section: " + this.toString(),
            "Course: " + thisCourse.getDetails(),
            "Dates: " + startDate + " to " + endDate,
            "Times: " + startTime + " to " + endTime,
            "Enrollment: " + roster.size());
}

/**
 * Create a string that represents the information about the students in the
 * course.
 *
 * @return      a string that represents the information about the students in the
 *              course
 */
public String getRoster()
{
    /* The following commented-out code is the obvious way to do this, using
       String concatenation (and this is acceptable). However, the recommended
       Java approach to this kind of operation is to use a StringJoiner (new
       class in Java 8), as this uses less garbage collection resources. */
//  String result = "";
//  for( Student student : roster )
//  {
//      result += ( result.isEmpty() ? "" : LINE_SEPARATOR) + student;
//  }
//  return result;

    StringJoiner stringJoiner = new StringJoiner(LINE_SEPARATOR);
    for( Student student : roster )
        stringJoiner.add(student.toString());
    return stringJoiner.toString();
}

/**
 * Get a count of the number of students registered (on the roster) for this course.
 *
 * @return  a count of the number of students registered for this course
 */
public int getRosterCount()
{
    return roster.size();
}

/**
 * Get the section number for this course.
 *
 * @return  the section number for this course
 */
public String getSectionNumber()
{
    return sectionNumber;
}

/**
 * Set the start and end dates for the section.
 *
 * @param startDate     the start date
 * @param endDate       the end date
 */
public void setDates(Date startDate, Date endDate)
{
    /* There is no requirement to validate these. */
    this.startDate = startDate;
    this.endDate = endDate;
}

/**
 * Set the start time and the end time for the meetings of the section.
 *
 * @param startTime     the start time for meetings of the section
 * @param endTime       the end time for the meetings of the section
 */
public void setTimes(Time2 startTime, Time2 endTime)
{
    /* There is no requirement to validate these. */
    this.startTime = startTime;
    this.endTime = endTime;
}

/**
 * Section number (prefixed)
 *
 * @return  Section number (prefixed)
 */
@Override
public String toString()
{
    return thisCourse.toString() + "-" + sectionNumber;
}

/**
 * Finalization. Reduce the instance count by 1.
 *
 * @throws Throwable    standard interface.
 */
@SuppressWarnings("FinalizeDeclaration")
@Override
protected void finalize() throws Throwable
{
    /* Decrement the count of the collective total of all Section objects. */
    --count;
    super.finalize();
}

/**
 * Get a count of how many total Section objects are currently in existence.
 *
 * @return  a count of how many Section objects are currently in existence
 */
public static int getSectionCount()
{
    return count;
}

/**
 * Validate the sectionNumber string. It must be of the correct length.
 *
 * @param sectionNumber the sectionNumber string
 * @return              true if the string if valid, otherwise false
 */
private static boolean isValidSectionNumber(String sectionNumber)
{
    return sectionNumber != null &&
            sectionNumber.length() == SECTION_NUMBER_LENGTH;
}
}

我只是简单地断言&#39;在this.startDate = startDate之前;等等???我的书只有一个例子,它是为了确保一个值在0到10之间。

这是我的书中使用的例子:

public class AssertTest
{
public static void main(string[] args)
{
Scanner input = new Scanner(System.in);

System.out.print("Enter a number between 0 and 10: ");
int number = input.nextInt();

//assert that the value is >= 0 and <= 10
assert (number >= 0 && number <= 10) : "bad number: " + number;

System.out.printf("You entered %d%n", number);
}
}

所以我可以说

assert this.startDate = startDate
assert this.endDate = endDate

等等?

1 个答案:

答案 0 :(得分:0)

首先,方法setTime和setDates是公开的,这表明它们可以在包之外使用。鉴于您无法控制参数 - 使用assert不会被视为最佳实践。当值可以在外部提供时(并且您无法控制它),您应该使用运行时异常,例如IllegalArgumentException:

if (startDate == null || endDate == null)
   throw new IllegalArgumentException("Non-null arguments are required");

Assert的语法如下:

assert startDate != null;
assert endDate != null;

您还可以使用以下语法在断言失败时输出其他信息:

assert startDate != null : "startDate was set to null"
assert endDate != null : "endDate was set to null"