简体   繁体   中英

Preferred techniques for passing objects which clients may invalidate

I have adopted a technique where I pass existing objects to forms so that they can display the object's content and allow the user to alter it if necessary. The form is not bound to the object, so when it comes time to act, the form sweeps up the content of its controls and puts them into the object. The object is then validated and any issues reported to the user. If the object is valid, it may be handed back to the caller so the caller can refresh a view/list/etc.

So far, so good. However, if the form's content, or lack of, creates an invalid object and the user does not correct it, maybe cancelling the form, there's a chance the form will hand an invalid object back to the caller. This is not good.

Essentially I'm looking for an elegant and efficient way of either leaving the object as it was or rolling back if the user cancels the form/action.

I have considered a range of techniques, each with many pros and cons. I'm keen to consider some other views.

My methodology has always been:

Validate the entire ViewModel. If it validates, commit the changes. If it doesn't validate:

  • For an entry in the form that is valid, leave it as the user entered it
  • For an entry in the form that is invalid, if it matches the proper format (eg it's a birthdate field, but the user entered a date from 1788), give the value back but flag it as invalid
  • For an entry in the form that is invalid, if it doesn't match the proper format (eg it's an age field, but the user has entered X), give no value back (make it blank) and flag it as invalid.

Hope that helps some

You can do for example

  • add IsValid() method to your object and when the form closes, check containing object on validity

  • add some state property to the form, which becomes (say it's boolean ) false , and when the form closes you can check that form's state.

Just examples.

In the past, I have solved this by making a shallow copy of the object when passing it out to your form. Then, when the copy comes back you validate it. If it checks out, you simply overwrite the original object with the copy.

  private static void PassTheObj()
  {
     MethodThatAcceptsObj(realObject.Copy());  
  }

  private static void ValidateObj(customObject objCopy)
  {
     if (objCopy.IsValid()) realObject = objCopy;
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM