Is Belt and Braces programming good practice or just introducing needless complexity?

拜拜、爱过 提交于 2019-11-30 13:13:10

问题


I was wondering whether using a Belt and Braces (Suspenders) approach to programming - and to data validation in particular - was good practice or not. This came about from the following example.

I was creating a form and I added Listeners to all the fields which should mean that the OK button is only enabled if all the fields in the form have valid values. I was then writing the code which was run when the OK button is clicked.

The pessimistic side of me decided that Belt and Braces never hurt anyone and it couldn't hurt to validate the form again in case there's a bug in my form logic.

But then I didn't know what to put in if the validation fails. If I do something like this:

if (! form.isValid()) {
  displayErrorMessage();
}

then I have to create code to display an error message which should never be shown. Anyone maintaining this code in future is then going to worry about and possibly be confused by this in theory needless dialog. The last thing I want is someone wondering why this particular dialog is never displayed.

An option at the other end of the scale is:

if (! form.isValid()) {
  throw new RuntimeException("This should never happen!");
}

Frankly, I feel dirty even typing that but perhaps there's a good reason to use it which I have missed.

So finally I ended up with:

assert form.isValid();

However, the downside of that is that it's not really belt and braces since the braces aren't there at run-time so if there is a bug in the code my form's trousers are still going to fall down as it were.

So maybe I shouldn't have the extra validation at all, but there's still a part of me which thinks it couldn't hurt.

I'd be interested to hear what you do in similar situations.

(Edit: the question is asking what is the best way to ensure the form returns valid data. Assume that the output of the form is validated again before it ends up in the database and so on.)


回答1:


I don't do much UI work, but recently I found myself doing something very similar. I left in both the belt (validate each control as it changes) and the braces (check is valid again on OK_Click).

I left both in on the basis that if some future change missed validation on the control, it would be caught when the OK button is clicked.

In my head the check on OK is the real validation, and the per control validation is sugar that just enhances the users experience.

That said I haven't thought about it too much, and I don't often do UI work.




回答2:


From my experience, "just in case" code is sometimes a symptom of lazy programming. I.e., I've found a solution that basically works, I'm not sure it will always work, so I'll throw in some double-checking code "just in case." If you're not sending rocket ships to the moon, this type of thing is relatively harmless, but can be very bad practice nonetheless.

For my (non-rocket-ship) business applications, I always put in error logging and a friendly message, and try to think the problem all the way through so that the users see the friendly message as infrequently as possible. If there is a problem, I'm better able to fix it because my code isn't cluttered up with all kinds of unnecessarily checks.




回答3:


My coworkers generally do double-validate inputs, "just in case." I think it would depend largely on the people you work with or who will have to maintain your code. If you always double-validate, they will quickly catch on as to what you're doing. If you only sometimes double-validate, they will likely be confused. Perhaps you should consult with coworkers as to their habits? If you work alone or in a very small group, it would probably be okay to double-validate your inputs.

If I were to take over your code, I think the important thing is probably following a convention, either always or never put validation in both places. At least that way I wouldn't get confused.

Edit: As far as web programming goes, javascript is generally used to validate before inputs are sent to the server. Obviously, this isn't enough as users can turn off javascript and circumvent that validation, so server-side validation is necessary in that case. In any case where a user could maliciously or accidentally circumvent the first line of validation, it's imperative to also double-check on the back-end. I imagine this is less of a problem in Java, C#, etc.




回答4:


I would also say that double validation never hurt anyone, and can only increase security.

I'd also like to bring up a point about your business logic. I assume this is a Winforms application, but the principle applies to the web as well. The UI should not be enforcing business logic. It's fine to put validation there, but it also needs to be in the business logic.




回答5:


Whatever else you decide to do, just make sure you log the unexpected state and make the program fail somehow to prevent data corruption. Personally I think that is required and sufficient for a case where I'm not expecting an error.




回答6:


In web (no pun intended) programming one would always take this approach because you can't depend on the client-side validation actually running; a crafty user can construct a form post or URL that simulates your client and sends data back to the server.

In a standalone app, it is less clear. I would suggest that it depends on where the validation is occurring. For example, if your validation runs in your business logic, not in your UI, then your validation ought to run every time. Using separation of concerns, the business logic shouldn't depend on the UI to do validation. After all, the business logic may be called from a typical GUI, a web app, or even an API.

One thing that I would suggest is that doubling up the validation logic in the UI, is probably overkill -- but you ought to be able to handle errors arising from the underlying layers. In this case, the errors might arise from validation.




回答7:


I'd recommend looking at this from a purely usability perspective. How are your users supposed to work while filling in forms? Most of the time, doing validation on both the control and the form level is what I'd recommend. Of course, there are many user interaction styles you can use:

  1. Let the users do what they please, and then check on their results on OK. This can be excellent for expert users, allowing them to input things quickly and incrementally, but leaves newbies and infrequent users rather at a loss.
  2. Validate each control as it's entered or on leaving. This can be good, especially for complex forms (which of course we shouldn't design, ever, really, but...!); but done poorly can prevent people from filling in forms incrementally in their own order. I prefer a visual indication that something's amiss if I do this.
  3. Make it impossible to enter anything wrong. This can (almost) be achieved through e.g. sliders for numbers, combo boxes for restricted scalars, auto-validated edit boxes which prevent bad entries.

However, even in case 3, there are some cases where you have to check whether combinations of values are valid. I've worked with some cases where the values in some subsets of controls are dependent on each other (governed by an equation). It's not always feasible or worth the effort to provide the user with immediate feedback in these cases, so a case can always be made for validating on OK.

I'd agree with Binary Worrier that the OK check is the main one. If you're sure it should never fail, be sure to log a warning if it triggers, and sniff such events through your support channels if possible, but don't make the end user pay for programming errors.




回答8:


I'm going to give an incredibly unpopular answer.

My answer is: it depends.

Before people start rising up from their chairs in indignation and add extra froth to their latte' from venting their rage, hear me out.

I modify an ERP package that uses shared files. Don't laugh, it's the day job. Anyways, the system has a single flaw in the design - it validates the data upon input, and then always assumes it is correct due to that one-time validation, once it writes records out.

This sounds like a reasonable approach until you run into missing data fields, crashed sessions, machines with bad RAM that you can't see, machines with spotty LAN connections that go undetected, and occasionally a bug (or two) in the programming language itself. Records are half-written, fields may go missing data, indexes occasionally just implode for no reason...the list goes on.

Now, the vendor that provides the software very much runs against belt-and-suspenders because, hey, time is money, and they're in business to sell their product (software). Every 15 minutes of time writing additional sanity checks is 15 minutes that could be spent generating revenue. But they don't get paged at 3am to fix crashed sessions or release nasty deadlocks. I do.

So I add the rough equivilent of asserts into the procedures, functions, and methods that I write. I do sanity checks on the data types passed (it makes all variables variants), I attempt to cross-reference data when possible, and I look for other signs of "insanity" in the code. When a routine finds something that resembles the twilight zone, it gives a diagnostic dialog (which the user typically screen-shots and forwards to me) and then attempts to gracefully fail; if it can't gracefully fail, the user usually sees instructions to save what progress they have and log out.

Is this belt-and-suspenders? Yes. Do I like having to do this? No. Has it saved my sanity, sleep time, and bacon on many many occasions?

Yes. Oh, yes...

So, if you have a "hostile" programming environment where you can't always trust the data that's being fed to your code, it's reasonable to embed all kinds of sanity checks...go full belt-and-suspenders, all the way.

Otherwise, it's not needed.




回答9:


I think that belt and braces is not a good practice.

If extreme reliability is required, as the case is for example with spaceship software, then the way to guarantee it is by providing multiple different implementations that run in parallel, are all provided the same input, and are all expected to provide the same output. Clearly, that's not belt and braces, it is something else.

If extreme reliability is not an issue, then belt and braces really only complicates things precisely in the ways that you discovered by yourself.

The assertion that you ended up with is the best thing to do, because assertions are meant to catch bugs and to document the code, and that's precisely what is happening in the situation at hand: if the form is not valid at the point of your assertion, then you have a bug elsewhere in your form, and the assertion is essentially documenting the fact that at this point in your code you expect that the validity of the form has already been taken care of. Also, the possibility of this bug happening should be eliminated during the testing phase of your application, so it should never happen in production, which is again in par with the purpose and intended use of assertions.

If you really like the belt and braces paradigm, then you can still consider the assertion as part of a belt and braces scheme, but in the right context: testing. This assertion is belt and braces during testing, because it guarantees that you have done all the right tests elsewhere in your code.



来源:https://stackoverflow.com/questions/767952/is-belt-and-braces-programming-good-practice-or-just-introducing-needless-comple

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!