Question

Is having reference to System.Windows.Forms in a business class and using MessageBox.Show wrong?

Currently have a event processing decorator class decorating a service class. When certain events fired decorator would like to ask user if they want to proceed processing certain functionality.

Is it ok for this decorator class have these message boxes?

Was it helpful?

Solution

You should never have a UI in a business class.

The reason for this is you never know how your business class might be used down the road. Perhaps it will be used in a new website, a web service, a windows service, etc. In all of those cases a message box would be inappropriate.

The right way to handle this is to provide an event that your UI or any other consumer of your business class can subscribe to. Let the UI layer decide whether it will show a message box or not.

You certainly should also look at some of the logging frameworks out there and probably log this event.

OTHER TIPS

Message boxes are probably wrong everywhere. I can already tell you the result before you've shown them. Users will click Cancel. They always do. If you hit the same messagebox not a whole lot later, your users are going to click continue because "Cancel" didn't do what they wanted.

So, if you already know the answer, why bother asking the question?

In bussines class you should NEVER use any direct-UI communications.

Its because the UI can be winforms/webforms/console/smart_devices/etc... or no UI is used (in scripts for example).

If you need some user-decide in bussines process you can use several ways, how to that. In .NET is one of the simple way Events.

For example:

public class MyBussinesClass {
    public void DoSomeBussinesRelatedWork() {
        // ... some code and then you need a users decision
        var argWhichCurrencyToUse = new DecisionEventArgs {
           Title = "Currency selection",
           Text = "Which currency you want to use in bill?",
           Answer = "USD"
        };
        this.OnDecisionRequred( argWhichCurrencyToUse );
        // ... contine in work ...
    }

    protected void OnDecisionRequired( DecisionEventArgs e ) {
        // run the event
    }
    public event EventhHandler<DecisionEventArgs> DecisionRequired;
}

public class DecisionEventArgs {
    public string Title {get;set;}
    public string Text {get;set;}
    public object Answer {get;set;}
}

The UI then can hook the events and show the correct UI (messagebox, inputbox, webform, console read/write, etc....

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top