public string GetStatusDescription(Model model) { if(model.HasProblemReports) { return "Errors"; } if(model.SystemState.WorkingMode == WorkingMode.NotManaged) { return "Manual"; } if(model.SystemState.IsInitializing) { return "Initialize"; } if(!model.SystemState.InService) { return "Not in service"; } if(model.SystemState.WorkingMode == WorkingMode.Paused) { return "Paused"; } if(model.Storage.Objects.Any(obj => obj.IsMoving)) { return "Movement in storage"; } return string.Empty; }
class ModelToMessage { private Func<Model, bool> _predicate; public ModelToMessage(Func<model ,="" bool=""> predicate, string message) { _predicate = predicate; Message = message; } public bool IsValid(Model model) { return _predicate(model); } public string Message{get; private set;} }
private List<modeltomessage> _messageCreators = new List<modeltomessage> { new ModelToMessage(model => model.HasProblemReports, "Errors"), new ModelToMessage(model => model.SystemState.WorkingMode == WorkingMode.NotManaged, "Manual"), new ModelToMessage(model => model.SystemState.IsInitializing, "Initialize"), new ModelToMessage(model => !model.SystemState.InService, "Not in service"), new ModelToMessage(model => model.SystemState.WorkingMode == WorkingMode.Paused, "Paused"), new ModelToMessage(model => model.Storage.Objects.Any(obj => obj.IsMoving), "Movement in storage"), new ModelToMessage(model => true, string.Empty), }; public string GetStatusDescription(Model model) { var messageCreator = _messageCreators.First(mc => mc.IsValid(model)); return messageCreator.Message; }
Labels: .NET, C#, Refactoring, Tips and Tricks