Return error from models - c#

I have the following model:
internal static List<Contracts.DataContracts.Report> GetReportsForSearch(string searchVal, string searchParam)
{
var param1 = new SqlParameter("#SearchVal", searchVal);
var ctx = new StradaDataReviewContext2();
var reports = new List<Contracts.DataContracts.Report>();
try
{
//Validate param1 here and return false if the requirment are not met
}
catch(Exception e)
{
//Throw
}
}
param1 here Is a value entered by a user and I want to validate It here, and If the requirements are not met, I want to return an error.
But how can I return an error here from the model? The method Is of the type List, and I can't not just write return false in this method.
Any suggestion how to do It?

It is good that you didn't thought about throwing an exception, when requirements are not met. We shouldn't use exceptions for controlling program flow.
I have two options in my mind :
1. Use objects
Modify your GetReportsForSearch method to following signature:
internal static List<Contracts.DataContracts.Report> GetReportsForSearch(string searchVal,
string searchParam, ReportRequestor requestor)
{
var param1 = new SqlParameter("#SearchVal", searchVal);
var ctx = new StradaDataReviewContext2();
var reports = new List<Contracts.DataContracts.Report>();
try
{
//Validate param1 here and call RequirementsAreNotMet method if the requirements are not met
requestor.RequirementsAreNotMet();
}
catch(Exception e)
{
//Throw
}
}
And then you can implement code responsible for handling this situation in ReportRequestor class
public class ReportRequestor
{
public void RequiremenrsAreNotMet()
{
//code which handle situation when requiremenets are not met
}
}
2. Use return type as indicator of status
In this way, when requirements are not met you should create ReportGenerationStatus object with HasResult flag set to false.
In other case just set HasResult to true and also set results accordingly. This somewhat mimics Option type known from functional languages
internal static ReportGenerationStatus GetReportsForSearch(string searchVal, string searchParam)
{
//code for your method
}
public class ReportGenerationStatus
{
public List<Contracts.DataContracts.Report> Result { get; set; }
public bool HasResult { get; set; }
}

Related

How do I refactor similar methods to eliminate duplicate setup and exception handling?

Context:
I consume a ERP WebService exposing N methods like:
FunctionNameResponse FunctionName(FunctionNameQuery query)
I made a functional wrapper in order to:
Get rid off wrapper object FunctionNameResponse and FunctionNameQuery, that every method has.
One instance of the WebService for all the program.
Investigate and log error in the wrapper.
Investigate Slow running and Soap envelope with IClientMessageInspector
Duplicated code:
For each of the methods of the WebService I end up with around thirty lines of code with only 3 distinct words. Type response, type query, method name.
public FooResponse Foo(FooQuery query)
{
// CheckWebServiceState();
FooResponse result = null;
try
{
result =
WSClient
.Foo(query)
.response;
}
catch (Exception e)
{
// SimpleTrace();
// SoapEnvelopeInterceptorTrace();
// TimeWatch_PerformanceIEndpointBehaviorTrace();
}
return result;
}
I would like to reduce those repetition. In order to :
Make it easier to add a Method;
Avoid copy pasting programming with no need to understand what you are doing.
Easier to add specific catch and new test without the need to copy past in every method.
The following code work and exist only in the imaginary realm. It's a not functional sketch of my solution using my limited understanding.
public class Demo
{
public enum WS_Method
{
Foo,Bar,FooBar
}
public class temp
{
public Type Query { get; set; }
public Type Response { get; set; }
public WS_Method MethodName { get; set; }
}
public static IEnumerable<temp> TestFunctions =>
new List<temp>
{
new temp{Query=typeof(FooQuery), Response=typeof(FooResponse), MethodName=WS_Method.Foo },
new temp{Query=typeof(BarQuery), Response=typeof(BarResponse), MethodName=WS_Method.Bar },
new temp{Query=typeof(FooBarQuery), Response=typeof(FooBarResponse), MethodName=WS_Method.FooBar },
};
public static void Run()
{ // Exemple of consuming the method
var input = new BarQuery { Bar_Label = "user input", Bar_Ig = 42 };
BarResponse result = Execute<BarQuery, BarResponse>(input);
}
public static T2 Execute<T1,T2>(T1 param) {
//Get temp line where Query type match Param Type.
var temp = TestFunctions.Single(x => x.Query == typeof(T1));
var method = typeof(DemoWrapper).GetMethod(temp.MethodName.ToString(), new Type[] { typeof(T1) });
var wsClient = new DemoWrapper();
T2 result = default(T2);
try
{
result =
method
.Invoke(wsClient, new object[] { param })
.response;
}
catch (Exception e)
{
// SimpleTrace();
// SoapEnvelopeInterceptorTrace();
// TimeWatch_PerformanceIEndpointBehaviorTrace();
}
return result;
}
}
I know the reflection is heavy and perhaps it's not the right way to achieve this refactoring. So the question is:
How do I refactor those function?
attachment : Live demo https://dotnetfiddle.net/aUfqNp.
In this scenario:
You have a larger block of code which is mostly repeated
The only difference is a smaller unit of code that's called inside the larger block
You can refactor this by passing the smaller unit of code as a Func or Action as a parameter to the larger function.
In that case your larger function looks like this:
public TResponse GetResponse<TResponse>(Func<TResponse> responseFunction)
{
var result = default(TResponse);
try
{
result = responseFunction();
}
catch (Exception e)
{
// SimpleTrace();
// SoapEnvelopeInterceptorTrace();
// TimeWatch_PerformanceIEndpointBehaviorTrace();
}
return result;
}
The individual functions which call it look like this, without all the repeated code:
public FooResponse Foo(FooQuery query)
{
return GetResponse(() => WSClient.Foo(query));
}
Here's another approach where you keep the methods but have them all call a method that handles the duplication.
public class Demo
{
private _wsClient = new DemoWrapper();
public static void Run()
{ // Exemple of consuming the method
var input = new BarQuery { Bar_Label = "user input", Bar_Ig = 42 };
BarResponse result = Bar(input);
}
public FooResponse Foo(FooQuery foo) =>
Execute(foo, query => _wsClient.Foo(query));
public BarResponse Bar(BarQuery bar) =>
Execute(bar, query => _wsClient.Bar(query));
public FooBarResponse FooBar(FooBarQuery fooBar) =>
Execute(fooBar, query => _wsClient.FooBar(query));
private static TResponse Execute<TQuery ,TResponse>(
TQuery param, Func<TQuery, TResponse> getResponse)
{
//Get temp line where Query type match Param Type.
var result = default(TResponse);
try
{
result = getResponse(query);
}
catch (Exception e)
{
// SimpleTrace();
// SoapEnvelopeInterceptorTrace();
// TimeWatch_PerformanceIEndpointBehaviorTrace();
}
return result;
}
}

how can i set return so it accepts class1 or class2?

how can i, in my function start to fill the parameters for the class it is supposed to return, but if an exception occurs i'll return my error class instead?
public **** function()
{
try
{
Articles articles = new Articles();
articles.articleid = 234;
articles.articlename = "Milk";
articles.deleted = 0;
//continue fill Articles
//and an exception occurs
return articles;
}
catch (Exception e)
{
Errors Error = new Errors();
Error.exceptionmessage = e.Message;
Error.exceptionname = e.ToString();
Error.httpcode = 500;
return Error;
}
}
is this possible and a good thing to do? or should i just extend all return classes with my error class, even though i will return much info with allot of null values.
i would like to send as little data as possible and if my function fails i'll just send back the error.
UPDATE
sorry for not giving enough inforamtion about my situation this is a function that i want to use in a webservice
[OperationContract]
[WebGet(
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json)]
**** Function();
so i dont think i can just throw an exception. i would like to return a class of articles if all is well so i dont have to convert my data to JSON but if something goes wrong i would like to send http code 500 Internal Server Error to the client.
i have not yet read all answers but i think i'll have to include my error class in all my other return classes so the client can now when something went wrong?
UPDATE:
That gives more insight on what you want to do. Since you can't throw exceptions, you should have a base result class. I usually do this for WCF methods I call through javascript, since it can't handle the exceptions nicely.
So you'll want a base class like:
[DataContract]
public class AjaxResult
{
public static AjaxResult GetSuccessResult()
{
return new AjaxResult();
}
[DataMember]
public int Status { get; set; }
[DataMember]
public string Error { get; set; }
}
Then you can inherit this, adding any data you would want to return. This example returns a single product object and a list of validation errors.
[DataContract]
public class SingleProductResult : AjaxResult
{
[DataMember]
public Product Data { get; set; }
[DataMember]
public IList<int> ValidationErrors { get; set; }
}
You can also opt to create a generic wrapper so you don't have to write to much code in your methods. I usually put this in a base class and let all WCF services inherit from that class.
protected T PerformAjaxOperation<T>(Func<T> action) where T : AjaxResult, new()
{
try
{
return action();
}
catch (AccessDeniedException ade)
{
// -- user tried to perform an invalid action
return new T()
{
Status = AjaxErrorCodes.AccessDenied,
Error = ade.ToString()
};
}
catch (Exception ex)
{
return new T()
{
Error = ex.ToString(),
Status = 1
};
}
}
Then just use it like so:
public SingleProductResult GetProduct(int productId)
{
return PerformAjaxOperation(() =>
{
return retval = new SingleProductResult()
{
Data = ProductServiceInstance.GetProduct(productId)
};
});
}
public AjaxResult DeleteProduct(int productId)
{
return PerformAjaxOperation(() => {
ProductServiceInstance.DeleteProduct(productId);
return AjaxResult.GetSuccessResult();
});
}
So, if everything proceeds smoothly, error will be 0 and message will be null. If an exception is thrown, then it will be caught by the PerformAjaxOperation() function and stuffed inside the AjaxResult object (or a derivative of it) and return to the client.
Previous answer:
I don't think this is a good idea. What you can do is create a custom exception by creating a class that inherits from Exception and add properties there that you want to save. Then when an exception occurs, you just catch it and stuff it inside this new exception along with other details. Then throw this exception instead. You can then catch this exception in the higher levels and display the proper message.
an example:
public IList<Articles> GetArticles()
{
try
{
return GetSomeArticlesFromDatabase();
}
catch (Exception innerException)
{
throw new MyCustomException("some data", 500, innerException);
}
}
public class MyCustomException : Exception
{
public int HttpCode { get; set; }
public MyCustomException(string errorMessage, int httpCode, Exception innerException)
: base(errorMessage, innerException) {
HttpCode = httpCode;
}
}
public void EntryPoint()
{
try
{
DoSomething();
var result = GetArticles();
DoSomething();
DisplayResult(result);
}
catch (MyCustomException ex)
{
ReturnHttpError(ex.Message, ex.HttpCode);
}
}
I would honestly advise against doing what you suggest. Instead, either use an existing Exception type or create a new subclass of Exception and throw it. You can even retain the causing exception information in the new exception's InnerException if so desired.
If the situation does not warrant an exception, however (you have not given enough details about what you are doing), you can create a Result class that contains error/warning information. This kind of thing would be better suited for warnings, though. That is, it is not an error condition that prevents things from continuing (exception), but instead a message that the calling code could choose to ignore without drastic side-effects.
For example:
class Result<T>
{
public Result(T Value, Errors Errors = null)
{
this.Value = Value;
this.Errors = Errors;
}
public T Value {get; private set;}
public Errors Errors {get; private set;}
}
Usage (as per your example code):
public Result<Articles> function()
{
try
{
Articles articles = new Articles();
articles.articleid = 234;
articles.articlename = "Milk";
articles.deleted = 0;
//continue fill Articles
//and an exception occurs
return new Result(articles);
}
catch (Exception e)
{
Errors Error = new Errors();
Error.exceptionmessage = e.Message;
Error.exceptionname = e.ToString();
Error.httpcode = 500;
return new Result<Articles>(null, Error);
}
}
If class1 and class2 have a common base type or common interface, use that. But in this case, you could create a wrapper class to encapsulate both result types, like this:
class MethodResult<T>
{
public T Result { get; private set; }
public Errors Errors { get; private set; }
public MethodResult(T result) { this.Result = result; }
public MethodResult(Errors errors) { this.Errors = errors; }
}
public MethodResult<Articles> MyMethod()
{
try
{
...
return new MethodResult<Articles>(articles);
}
catch(Exception e)
{
...
return new MethodResult<Articles>(errors);
}
}
In light of additional information in the question, since this is a WCF service, you could throw a WebFaultException:
public Articles function()
{
try
{
Articles articles = new Articles();
articles.articleid = 234;
articles.articlename = "Milk";
articles.deleted = 0;
//continue fill Articles
//and an exception occurs
return articles;
}
catch (Exception e)
{
throw new WebFaultException(System.Net.HttpStatusCode.InternalServerError)
{
Message = e.Message
};
}
}
The ways that other answers have handled this involve technical methods of how to define the two classes, using interfaces and subclassing.
However, fundamentally you're actually solving the wrong problem. You will still need to write code in the caller that distinguishes between the two types of object, as well as documenting the way in which your function works.
Personally, I would create a new Exception class for the type of error you may be handling, and throw that instead, for example:
public class InvalidArticleException: Exception {
public string ExceptionMessage { get; set; }
public string ExceptionName { get; set; }
public int HttpCode { get; set; }
}
public **** function()
{
try
{
// DO STUFF
return articles;
}
catch (InvalidArgumentException e)
{
throw new InvalidArticleException() {
ExceptionMessage = e.Message,
ExceptionName = e.ToString(),
HttpCode = 500
}
}
catch (Exception ex) { // Not actually required; left in for future debugging
throw ex;
}
}
Callers would then be able to catch the exception and examine it for the error details, with code that is kept separated from that which processes the returned articles.
You can try out keyword,
public Articles function(out Error err)
{
Articles articles = null;
err = null;
try
{
articles = new Articles();
articles.articleid = 234;
articles.articlename = "Milk";
articles.deleted = 0;
// Set your article values
}
catch (Exception e)
{
Errors ex = new Errors();
ex.exceptionmessage = e.Message;
ex.exceptionname = e.ToString();
ex.httpcode = 500;
err = ex;
}
return articles;
}
I'm not sure why would you want swallowing the exeptions, but if you do whatn this behgaviour make a return type common for both type. The both classes inherit from object so you can change the method signature to public object function()

C# delegates functions being defined in an array declaration?

I am making an IRC Chat bot for my stream. I found a few basic connectivity examples using C# so I decided to give it a try.
So far I love it
But i am stuck on this one part.
I want to store the bot commands inside an array of a structure type.
public delegate void cmdHandler(string[]);
struct botCommand
{
string name;
cmdHandler chandler;
bool isAdmin = false;
string help = "Nothing here.";
}
Is currently what I have, and then I want to beable to do this:
botCommand[]commands =
{
{ "TestCommand", testCommand(), 0, "Help for this" },
{ "TestCommand2", testCommand2(), 0 "..." },
......
};
So how do I link a generic function in that array?
or am I going about this all the wrong way?
Basically instead of having a giant Switch() statement to check for which command was used I want to loop through an array and see if the command is in there. If it is then call the function associated with that command.
EDIT:
This is exactly what I have now so you can see what I am trying to do
public delegate void cmdHandler(string[] ex);
struct botCommand
{
string name;
cmdHandler chandler;
bool isAdmin = false;
string help = "Nothing here.";
}
botCommand[] commands =
{
{"test", new cmdHandler(testf), 0, "" }
};
public void testf(string[] ex) {
return;
}
Steps of logic:
user enters the test command
Loop through all botCommands to see if we find the test command
Test command is found
Call the function associated with the test command and pass on an argument (the rest of the command)
To me it seems like you're mixing C/C++ concepts with C# (using struct instead of class, 0 for false, object initializers, etc...).
To solve your individual problem, you must instantiate your struct differently.
botCommand[] commands = new []
{
new botCommand {
name = "Test",
chandler = new cmdHandler(MyMethod),
isAdmin = false,
help = "No help for you..."
}
};
where MyMethod is defined as.
public static void MyMethod(string[] myArgs)
{
//... do something ...
}
However, I think a better approach would be to have an abstract class / interface for an individual command, list or dictionary of your commands.
public interface IBotCommand
{
string Name { get; }
bool IsAdmin { get; }
void Process(string[] args);
string HelpText { get; }
}
public class MyCommand : IBotCommand
{
string Name
{
get
{
return "NameOfTheCommand";
}
}
bool IsAdmin
{
get
{
return false;
}
}
void Process(string[] args)
{
// bla bla, im processing stuff
}
string HelpText
{
get
{
return "This is the help text";
}
}
}
And then using it.
List<IBotCommand> commands = new List<IBotCommand>();
commands.Add(new MyCommand());
// to find a command and execute it
IBotCommand cmdToExecute = commands.SingleOrDefault(c => c.Name == "NameOfTheCommand");
if (cmdToExecute != null)
{
cmdToExecute.Process(args); // where-ever args comes from
}
else
{
// unknown command "NameOfTheCommand"
}

Error Reporting

I have a class that follows the Command Pattern.
It has 2 methods which are Execute, and CanExecute which checks whether to invoke Execute or not (they derive from ICommand).
CanExecute invokes a few methods that check that all required services are running, the version is correct, etc.
After CanExecute is invoked, it may fail and return false and I need to know why. Is it because of a bad version, services, missing file, etc.
What is the best strategy to know what is the problem
One option is whenever a required condition fails I can throw an exception that will describe the error in the message field. However the possibility that it will fail is expected and you shouldn't use exceptions for regular flow of control. So I'm really not sure.
Thank you.
You can use a collection of "reasons" that will tell the users of the class why CanExecute returned false. The reasons can be a simple IEnumerable<string>.
public bool CanExecute() {
var messages = new List<string>();
if (!Condition1) {
messages.Add("Missing Condition1");
}
...
Messages = messages;
return messages.Count == 0;
}
public IEnumerable<string> Messages { get; private set; }
Then, client code can show the collection of messages to end-users.
UPDATE:
You can also associate new commands with the messages to give the users ways to fix the problems found. In this case, instead of an IEnumerable<string>, you can create your own class that encapsulates that information:
public class Message {
public string Text { get; set; }
public ICommand Command { get; set; }
}
...
public bool CanExecute() {
var messages = new List<Message>();
if (!Condition1) {
messages.Add(
new Message {
Text = "Missing Condition1",
Command = new FixCondition1Command()
}
);
}
...
Messages = messages;
return messages.Count == 0;
}
public IEnumerable<Message> Messages { get; private set; }
UPDATE: Reworked based on feedback.
Since the UI needs the reasons CanExecute() returns false, two things come to mind:
Option 1: Add an enumerable message property to the command interface and populate it as needed during the call to CanExecute(). The UI could then interrogate the property as needed. If you go this route, make sure you clear out the contents of the property each call to CanExecute() so you don't lose track of state.
public interface ICommand
{
IEnumerable<string> Messages { get; }
bool CanExecute();
void Execute();
}
public class SomeCommand : ICommand
{
public IEnumerable<string> Messages { get; private set; }
public bool CanExecute()
{
var messages = new List<string>();
var canExecute = true;
if (SomeCondition)
{
canExecute = false;
messages.Add("Some reason");
}
if (AnotherCondition)
{
canExecute = false;
messages.Add("Another reason");
}
Messages = messages;
return canExecute;
}
public void Execute() { }
}
Option 2: Have CanExecute() return an object which contains the bool as well as an enumerable messages property. This makes it obvious that the messages only apply to that call of CanExecute(). However, depending on where/how you're implementing (e.g. data binding), this could complicate other scenarios more than you're looking for.
public class CanExecuteResult
{
public bool CanExecute { get; set; }
public IEnumerable<string> Messages { get; set; }
}
public interface ICommand
{
CanExecuteResult CanExecute();
void Execute();
}
public class SomeCommand : ICommand
{
public CanExecuteResult CanExecute()
{
var result = new CanExecuteResult { CanExecute = true };
var messages = new List<string>();
if (SomeCondition)
{
result.CanExecute = false;
messages.Add("Some reason");
}
if (AnotherCondition)
{
result.CanExecute = false;
messages.Add("Another reason");
}
result.Messages = messages;
return result;
}
public void Execute() { }
}
Obviously, the specifics of how you want to handle the interfaces, enumerable types, etc. is up to you. The code is just a representation of the idea.
Bool CanExecute()
{
if(!CheckXXX)
throw new Exception("CheckXXX function throws an exception")
if(!CheckYYY)
throw new Exception("CheckYYY function throws an exception")
if(!CheckZZZ)
throw new Exception("CheckZZZ function throws an exception")
return true; //everything is working fine
}

How to evaluate why a method returns what it returns

What strategy do you use to give to the user the reason why a certain method "failed"
Exemple:
public List<Balance> GetBalanceFinale(Periode periode)
{
if (periode == null || periode.DateStart >= DateTime.Now || isBalanceFinished(periode.PeriodeID))
return null;
//My other code...
}
I want to tell the user which of the steps went wrong. I don't want to use a messagebox in such class. I can't return the description of the failure because I already return something.
What do you usally do? Any advice? Thanks!
You can throw an exception with a descriptive message.
Consider throwing exceptions instead of returning null.
In this case you will be able to provide descriptive information with each exception, which later can be properly handled and presented to the caller.
I am assuming you don't want to throw an exception otherwise you would've already done that. Something like an alert / warning without stopping execution of the program. In that case, you can still use an exception, just don't throw it, instead pass it as an out parameter or put it somewhere where the user can access it if desired. If that seems over the top then just use a message instead.
Also framing it as a 'Try' method might be a good idea. It makes it very clear that the method is prone to failure under certain conditions.
These are all different options:
public bool TryGetBalanceFinale(Periode periode, out List<Balance> list, out string msg)
{
// return false if anything is wrong, and have an out parameter for the result & msg
}
public bool TryGetBalanceFinale(Periode periode, out List<Balance> list, out Exception ex)
{
// return false if anything is wrong, and have an out parameter for the exception
}
These first two above are my two preferred approaches. The following are possibilities as well, however they are somewhat non-standard:
public Tuple<string, bool> TryGetBalanceFinale(Periode periode, out List<Balance> list)
{
// return false if anything is wrong, and include message in the returned Tuple
}
// an anonymous type approach
public object TryGetBalanceFinale(Periode periode, out List<Balance> list)
{
return new {
Successful = false,
Message = // reason why here
};
}
// a functional approach
public List<Balance> list GetBalanceFinale(Periode periode, Action<String> messageAct)
{
// when something is wrong, do:
messageAct("Something went wrong...");
}
I think the 'Try' strategy makes the most sense when you consider how it will be used:
string message;
List<Balance> result;
if (!TryGetBalanceFinale(periode, out result, out message))
{
// examine the msg because you know the method failed
Console.WriteLine(message);
}
else
{
// you know the method succeeded, so use the result
Console.WriteLine("The result is: " + result.ToString());
}
I like to wrap my results in a ResultState<T> object (usually for Json or Xml serialization). Might be helpful if you are building a framework for someone else to consume as each result can be handled the same way by the consumer.
public class ResultState<T>
{
public T ResultValue { get; set; }
public Exception ExceptionThrown { get; set; }
public bool IsValid { get; set; }
public string FriendlySummary { get; set; }
// whatever else properties you think are needed
}
public interface IResultState<T>
{
public T ResultValue { get; }
public Exception ExceptionThrown { get; }
public bool IsValid { get; }
public string FriendlySummary { get; }
// whatever else properties you think are needed
}
public IResultState<List<Balance>> GetBalanceFinale(Periode periode)
{
ResultState<List<Balance>> result = new ResultState<List<Balance>>();
try
{
if (periode == null
|| periode.DateStart >= DateTime.Now
|| isBalanceFinished(periode.PeriodeID))
{
result.IsValid = false;
result.FriendlySummary = "Periode is in an invalid state.";
}
//My other code...
result.ResultValue = new List<Balance>();
result.ResultValue.Add(...);
}
catch(Exception ex)
{
result.IsValid = false;
result.Exception = ex;
// Ambigious is bad.. so for bad example..
result.FriendlySummary = "An unknown exception happened.";
}
}
An alternative that has worked for me in the past is the Notification pattern.
This is a way of getting information out of your domain layer and up into the presentation. For example, create something like this:
public class Notification
{
public List<Message> Messages;
public bool HasMessages;
// etc
}
and use an instance of it as a property on your domain.
You can then do something like this:
myDomain.GetBalanceFinale(periode);
if(myDomain.Notification.HasMessages)
// get the messages and do something with them
You need to re-factor your code first. before calling GetBalanceFinale you can validate it and show proper message if validation failed. if validation pass you can call GetBalanceFinale method.
Sometimes you may not able to do all the validation before calling the method. in that case you can throw exception with proper message or use out parameters.
If I need to return a value and a message, I just use an out parameter.
public List<Balance> GetBalanceFinale(Periode periode, out string errorMessage)
{
if (periode == null)
{
errorMessage = "Periode is null";
return null;
}
// Other checks
}
Then just call it like
string errorMessage;
var value = GetBalanceFinale(periode, out errorMessage);
if(value == null)
// Do whatever with errorMessage
You can decompose your logic into 3 separate tests, and then define an 'out' argument to return the "reason"
public List<Balance> GetBalanceFinale(Periode periode, out string reasonFailed)
{
reasonFailed = false;
if (periode == null)
{
reasonFailed = "preiod is null";
return null;
}
// etc.....
//periode.DateStart >= DateTime.Now || isBalanceFinished(periode.PeriodeID))
//My other code...
}

Categories

Resources