简体   繁体   中英

Best-Practices: action enum usage for events

I find my self hard to design action enums for events.

f.ex making calculation processor.

so I should have enum like this ? :

public enum CalculatorCoreActions
{
    ProcessStarted,
    ProcessFinished,
    ProcessFailure,
    ProcessFailed,
    SubstractionStarded,
    SubstractionFinished,
    SubstractionFailure,
    SubstractionFailed,
    <etc.>...
}

Or I should make two enums ?, f.ex:

public enum CalculatorAction
{
    Process,
    Substraction,
    Division
}

public enum CalculationActionResult
{
   Started,
   Finished,
   Failure,
   Failed
}

Or even I should create an new classes ? :

public class CalculatorActionEventArgs : EventArgs {<...>}
public class CalculatorActionFailedEventArgs : EventArgs {<...>}
public class etc... : EventArgs {<...>}

Which method is the best in your opinion?

What are you trying to do? What are you going to use the enums for? Your first example may be OK for very few combinations, whereas the second will be more complex but much cleaner and easier to extend.

My guess is that you want to be able to display the state of calculation, and perhaps act on the state in eg error handling. You might consider the State or State Machine patterns rather than enums, in order to avoid huge switch statements on your enums.

Of the two choices for enumerations that you presented I would go with the second set of enumerations.

Why, well when you cross (literaly multiply) the states with the actions you come up with a large growth pattern. When you want to add either a state or a feature in the future you no longer add one item but 1xM or Nx1 items. For other references to this style of problem see Martin Fowler's book Refactoring and object hierachy entanglement.

Now for the event args, use the generic EventArgs and give it the action and state in an object. Don't create more things than you have to and it will minimize the number of headaches you create.

it depends how you are designing your structure... to me events should be different but one should try not to use more EventArgs eg like you are using one for failed one for Action etc.... instead try to go for bare minimum amount of event arguments as its only your data passing mechanism...

now regarding enumeration part i am not exactly able to pick up your scenario.... why you want so much different enumerations?

if you meant to use it as replacement for multiple events than... if i were you than i will go for events... but if your structure requires a huge amount of events say 10 or more than go for a mix blend of events with enum as minimum event args... say in case of 10 reduce events to 3 with 4 or 5 enums

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