Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7505321
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 29, 20262026-05-29T21:52:30+00:00 2026-05-29T21:52:30+00:00

Let’s assume we have a class Student with the following constructor: /** Initializes a

  • 0

Let’s assume we have a class Student with the following constructor:

/** Initializes a student instance.
 * @param matrNr    matriculation number (allowed range: 10000 to 99999)
 * @param firstName first name (at least 3 characters, no whitespace) 
 */
public Student(int matrNr, String firstName) {
    if (matrNr < 10000 || matrNr > 99999 || !firstName.matches("[^\\s]{3,}"))
        throw new IllegalArgumentException("Pre-conditions not fulfilled");
    // we're safe at this point.
}

Correct me if I’m wrong, but I think in this example, I followed the design by contract paradigm by simply specifiying the (rather static) constraints on the possible input values and raising a generic, unchecked exception if those are not fulfilled.

Now, there is a backend class that manages a list of students, indexed by their matriculation number. It holds a Map<Integer, Student> to save this mapping and provides access to it through an addStudent method:

public void addStudent(Student student) {
    students.put(student.getMatrNr(), student);
}

Now let’s assume there is a constraint on this method like “a student with the same matriculation number must not already exist in the database“.

I see two options of how this could be realized:

Option A

Define a custom UniquenessException class that is raise by addStudent if a student with the same matr. number already exists. Calling code will then look something like this:

try {
    campus.addStudent(new Student(...));
catch (UniquenessError) {
    printError("student already existing.");
}

Option B

State the requirement as a pre-condition and simply raise an IAE if it doesn’t hold. Additionally, provide a method canAddStudent(Student stud) that checks in advance whether addStudent will fail. Calling code would then look something like this:

Student stud = new Student(...);
if (campus.canAddStudent(stud))
    campus.addStudent(stud);
else
    printError("student already existing.");

I feel that option A is much cleaner from a software-engineering point of view, for at least the following reason:

  • It can easily be made thread-safe without modifying the calling code (Thanks to Voo for pointing me to TOCTTOU, which seems to describe that exact issue)

Thus I wonder:

  1. Is there a third option which is even better?
  2. Does option B have an advantage that I didn’t think of?
  3. Would it actually be allowed from a design by contract point of view to use option B and define the uniqueness as a pre-condition of the addStudent method?
  4. Is there a rule of thumb when to define pre-conditions and simply raise IAE and when to use “proper” exceptions? I think “make it a pre-condition unless it depends on the current state of the system” could be such a rule. Is there a better?

UPDATE: It seems like there is another good option, which is to provide a public boolean tryAddStudent(...) method that doesn’t throw an exception but instead signals error/failure using the return value.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-29T21:52:30+00:00Added an answer on May 29, 2026 at 9:52 pm

    (this is too long for a comment)

    In your option B, I wouldn’t use a Map<Integer,Student> and then do:

    if (campus.hasStudent(12000)) 
        printError("student already existing.");
    else
        campus.addStudent(new Student(...));
    

    The Map abstraction isn’t practical enough for your use case (you’re mentionning concurrency issues), I’d use instead a ConcurrentMap<Integer,Student> and do something like this:

    final Student candidate = new Student(...);
    final Student res = putIfAbsent(student.getMatrNr(), candidate)
    if ( res != null ) {
        throw new IllegalStateException("Class contract violation: \"student already exists!\", please read the doc");
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Let's say you have a class called Customer, which contains the following fields: UserName
Let's say I have the following models class Photo(models.Model): tags = models.ManyToManyField(Tag) class Tag(models.Model):
Let's say on a page I have alot of this repeated: <div class=entry> <h4>Magic:</h4>
Let's say I have the following text: (example) <table> <tr> <td> <span>col1</span> </td> <td>col2</td>
Let's say I have the following object: var VariableName = { firstProperty: 1, secondProperty:
Let say I have the following desire, to simplify the IConvertible's to allow me
Let's imagine I have a Java class of the type: public class MyClass {
Let's say I have the following function in C#: void ProcessResults() { using (FormProgress
Let's say for example i have URL containing the following percent encoded character :
Let's say for example, I have the following javascript function that returns a boolean:

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.