Where Do I Put The Logon Code?
Given that you have a dialog that is used to collect user
credentials, where should the code that actually checks the
credentials go? I have been given answers such as:
-
In the OnClick of the OK button
-
A private method of the dialog
-
In the code that opened the dialog
-
In a separate class that is neither the dialog nor the
code that opened the dialog.
Lets look at each of these options.
Option 1: In the OnClick of the OK button
This is probably the most common place to find the
credential check logic. Unless you are writing throw away
code this is also one of the worst places to put it. Most
likely the code shows up here because our visual IDEs make
it easy for us to put it there. And until you run into
problems you don't have anything to worry about. What kind
of problems? How about testing? With the code located in the
event handler you have to either test manually or simulate
the event with some kind of GUI test package such as
Rational Robot. Also you've mixed your UI validation logic with your
credential check logic. A better approach would be to
separate the two.
Option 2: A private method of the dialog
This is a little better, but not much. You've separated out
the credential check logic, but it is still hard to test.
Maybe we should just let the dialog be responsible for the
user interaction.
Option 3: In the code that opened the dialog
So now we've moved the code out of the UI and into the
workflow. This is getting better, but how are we going to
test the credential check logic without testing all of the
workflow logic as well?
Option 4: In a separate class that is neither the
dialog nor the code that opened the dialog
Now we're cooking with gas! I can test the credential check
logic by itself without having any other code running. The
code is
highly cohesive and loosely coupled. Even better would be to provide the workflow component
with parameters that are the components for obtaining the
credentials and validating the credentials. An even further
refinement would be to create interfaces that represented
these services so that your workflow would still be valid
even if the credential store is moved from SQL to Active
Directory, or the credentials are provided as command line
parameters, in a config file or come from the Windows
identity.
Anyone have any other options that would be better?