Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I have a set of items, and each item in the set must be unique. Item are compose

ID: 639402 • Letter: I

Question

I have a set of items, and each item in the set must be unique. Item are composed from multiple properties and each property of each item can be changed. But after each change every item in the set must still be unique.

Should I simply try to change the property:

int err = setOfItems.SetPropertyOfItem( item, property, newValue )
if ( err != 0 ) {
    MessageBox( "You cannot change property to this value" );    
    return;
}
// ( ...or similar exception based code )
Or should I first check if the property can be changed and only then change it:

if ( !setOfItems.CanBePropertyChanged( item, property, newValue ) ) {
    MessageBox( "You cannot change property to this value" );    
    return;
}
setOfItems.SetPropertyOfItem( item, property, newValue );
Which approach is better and why?

Explanation / Answer

As long as the SetPropertyOfItem method reliably doesn't change the property when it detects a conflict, I would always choose the first way of doing things. Separating checks from actions can work, but it's prone to misuse by callers who perform the action without performing the check. And folding the check into the action method can lead to wasted effort if you also have a separate check method that a confused caller might call without need.

One problem with returning error codes is that the caller might forget to check it, and falsely assume that a change has occurred when it hasn't. If this is likely to be a problem, raising exceptions instead of error codes is an option.

(There are also people who advocate that you should never return anything from a method with side effects. I consider that short-sighted extremism, like claiming that the 100% pure functional style is the right choice for everything. I think design decisions always have to be made considering the pressures and context in the current situation.)

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote