Where to throw an exception in layered architecture? - wcf

I've an application that offers its Business Layer through a Service Layer developed with WCF.
What I'm thinking about is: this service layer offers operational method like Create, Update and so on. These operation then reroute these calls to the Business Layer. The question is: suppose that one of these call doesn't accept a null input value (like: Create a null object), where is the best place to perform the check? My personal answer is in both the places (service and business) as I can guarantee the reuse of the Business Layer without using the Service Layer and viceversa.
Am I right?
Thanks
Marco

Your library code or the code that is
used by higher-layers in your
application must always only throw
exceptions and never worry about how
to deal with them.
This is important because you may use this library at many places for different purposes.
In your application presentation layer, if you're consuming a library code and you're aware about the possible exceptions then do catch them with try/catch.

if you dont handle the error in the DAL or BLL, then it bubbles up until you catch it.
Exceptions do not get "overwritten".
If you handled it in the DAL then you no longer have an exception.
If you didnt fully handle it, then the BLL could still throw another exception because of an improperly handled error in the DAL.
The general rule goes like this:
Handle Specific errors and dont use a generic catch-all. Allow any unanticipated exceptions to bubble further up the stack.
Try running FxCop on your project to see where you are violating best practices.
http://www.gotdotnet.com/team/fxcop

Related

When and how to use Result in Kotlin?

I love the idea of Result.
I love having encapsulated try/catch.
But I’m a little confused about how and when to use Result.
I currently use it like this:
My adapters and services return a Result. Failures and stacktraces are logged but do nothing else
runCatching{
.... // do something cool
}.onFailure {
logger.error("Something bad happened ", it)
}
My Resource classes fold and handle the Result
return service.method().fold(
onFailure = {
Response.serverError().entity("Oops").build()
},
onSuccess = {
Response.ok().entity(doSomethingWith(it)).build()
}
)
Is this really the correct way to use a Result? Or is there a more idiomatic way to code in Kotlin?
TL;DR: never in business code (prefer custom sealed classes), but you can consider Result if you build a framework that must relay all kinds of errors through a different way than the exception mechanism (e.g. kotlin coroutines).
First, there is actually a list of use cases for the motivation of the initial introduction of Result, if you find it interesting. Also in the same document:
The Result class is designed to capture generic failures of Kotlin functions for their latter processing and should be used in general-purpose API like futures, etc, that deal with invocation of Kotlin code blocks and must be able to represent both a successful and a failed result of execution. The Result class is not designed to represent domain-specific error conditions.
Also, here is a very nice article by the lead Kotlin designer about exceptions in Kotlin and more specifically when to use the type system instead of exceptions.
Most of what follows is my personal opinion. It's built from facts, but is still just an opinion, so take it with a grain of salt.
Do not use runCatching or catch Throwable in business code
Note that runCatching catches all sorts of Throwable, including JVM Errors like NoClassDefFoundError, ThreadDeath, OutOfMemoryError, or StackOverflowError. There is usually almost nothing you can do with such JVM errors (even reporting them might be impossible, for instance in case of OOME).
According to the Java documentation, the Error class "indicates serious problems that a reasonable application should not try to catch". There are some very special cases where you might want to try to recover from error, but that is quite exceptional (pun intended).
Catch-all mechanisms like this (even catch(Exception)) are usually not recommended unless you're implementing some kind of framework that needs to attempt to report errors in some way.
So, if we don't catch errors (and instead let them bubble up naturally), Result isn't part of the picture here.
Do not catch programming exceptions in business code
Apart from JVM errors, I believe exceptions due to programming errors shouldn't really be handled in a way that bloats the business code either. Using error(), check(), require() in the right places will make use of exceptions to detect bugs that cannot be caught by the compiler (IllegalStateException, IllegalArgumentException). It often doesn't make sense to catch these exceptions in business code, because they appear when the programmer made a mistake and the logic of the code is broken. You should instead fix the code's logic.
Sometimes it might still be useful to catch all exceptions (including these ones) around an area of code, and recover with a high level replacement for the whole failed operation (usually in framework code, but sometimes in business code too). This will probably be done with some try-catch(Exception), though, but Result will not be involved here because the point of such code would be to delimit with try-catch the high-level operation that can be replaced. Low-level code will not return Result because it doesn't know whether there are higher level operations that can be replaced with something in case of programming errors, or if it should just bubble up.
Modeling business errors
That leaves business errors for result-like types. By business errors, I mean things like missing entities, unknown values from external systems, bad user input, etc. However, I usually find better ways to model them than using kotlin.Result (it's not meant for this, as the design document stipulates). Modelling the absence of value is usually easy enough with a nullable type fun find(username: String): User?. Modelling a set of outcomes can be done with a custom sealed class that cover different cases, like a result type but with specific error subtypes (and more interesting business data about the error than just Throwable).
So in short, in the end, I never use kotlin.Result myself in business code (I could consider it for generic framework code that needs to report all errors).
My adapters and services return a Result. Failures and stacktraces are logged but do nothing else
A side note on that. As you can see, you're logging errors in the service itself, but it's unclear from the service consumer's perspective. The consumer receives a Result, so who's reponsible with dealing with the error here? If it's a recoverable error then it may or may not be appropriate to log it as an error, and maybe it's better as a warning or not at all. Maybe the consumer knows better the severity of the problem than the service. Also, the service makes no difference between JVM errors, programming errors (IAE, ISE, etc.), and business errors in the way it logs them.

is there a proper way to handle multiple errors/exceptions?

in OO programming, is there some conceptual pattern, ideas, about handling multiple errors?
for example, i have a method that performs some checks and should return an error message for each error found
['name is too short', 'name contains invalid unicode sequences', 'name is too long']
now, should i use an array of exceptions (not thrown exceptions)?
or something like this is better:
class MyExceptionList extends Exception{
public Void addException(Exception e){}
public Array getExceptions(){}
}
any theory behind this argument will be appreciated!
(this isn't a request about a specific programming language, but a pure theoretical one)
thank you in advance
Unfortunately, many languages and frameworks (including C++, Java, and .net) use an exception-handling mechanism which requires the type of an an exception object to simultaneously answer many questions, including:
What happened
What actions need to be taken beyond stack unwinding
At what point should the system be considered to be in a "known" state, at least with regard to the problems indicated by the exception.
Unfortunately, while the answers to those questions are somewhat related, they are in reality far from 100% correlated. Unfortunately, the assumption that the type of an exception will be sufficient to answer all of those questions makes it difficult to deal sensibly with many situations.
If you have control over all the exceptions that can be thrown, it may be helpful to use an exception-handling paradigm where the exception-handling object includes a virtual IsResolved property or method along with a ShouldCatchAs<T> property or method that returns a T if the exception needs to be handled as a T. Such a paradigm would be able to smoothly handle situations where an exception occurs while unwinding the stack from an earlier exception (the existing exception and new one would be wrapped into a composite exception object, whose ShouldCatchAs property would combine those of the original exceptions, and whose IsResolved property should only return true when both of the original exceptions' IsResolved properties do likewise).
I don't know any way to integrate such behavior into the existing frameworks unless one catches and wraps all exceptions that don't fit the paradigm, but perhaps future frameworks can facilitate such things.
From my years of experience, dealing with errors is best done via logging them at all levels, and return true/false from functions, indicating success/fail.
Logging is implementation dependant. It could be to a file, to memory, and you can log messages, unique numbers, whatever, as long as the log will enable you to pinpoint the exact place of the error.
I sometimes use exceptions, in cases where I perform many operations, each one depending on the success of its predecessor. This makes the code cleaner, with no ifs for error checking. Nevertheless, this is not the main thing to care about. The main thing is log the errors, and return success/fail. Success/fail is needed so that you can decide whether to continue the normal way or not (such as not doing the indended operation because the read size may overrun the memory).
Two more important notes:
1) You must construct a super easy API to report (log) your messages, otherwise you will find yourself postponing this crucial thing, eventually not doing it.
2) It's essential for the log or report to be easily viewed and inform you about the problems as they accure. Otherwise you might find yourself not using the error report mechansim at all.
This is a very important subject to me, and I believe it to be one of the most important issues in software engineering. You can read more about it on my website
You shouldn't be throwing Exceptions then.
An Exception is meant for an exceptional case. Errors found on a validation method isn't considered "Exceptional", it's rather obvious that validation errors would occur.
An exceptional situation is when your attempt to connect to a database failed, for example.
You should log all validation errors to an array, and then format it and display it as you like.
Exceptions are not intended for validation, they are intended to be created when something that is different from what was expected happens during the execution. This is why you can't create many exceptions at once, but exceptions can be caused because some other exception happened, this is why they can have a parent exception named case.

Is Fetching and updating in same web service operation symantically correct

I know that WCF or any web service platform does not prevent the developers from mixing fetch and update in same operation. What I mean is mentioned below
List UpdateDate( SomeType Datacontract)
Syntactically this is correct format an is supported in WCF. But is it ok to do this in service oriented world, also is industry wide standard to support this.
One problem I see right away is we violate the very first law of SOA which is atomicity but are there any other issues associated?
It's wider than just WCF: any method that appears to be a Get/Fetch (i.e. by its name) should ideally not perform updates.
The classic Bad example is a Property Getter than alters the state of objects, thus introducing the possibility of unwanted side effects.

Validating Class Data

In my app, I am creating a series of validation classes to check, for example, that a user entered Name property of the class (from a WinForm) doesn't exceed the size of the varchar() in the database.
Currently, the validation code will throw a custom Exception if the Name field is too large. (The custom exception, when caught by the UI, will show the custom exception message in a MessageBox as opposed to my generic error form for regular exceptions.) Validation classes are in the app's class library, and are scoped as Friend. The flow looks like this:
The DLL's Public Service Layer used by the WinForms --(calls)--> Friend Validation Layer
The DLL's Public Service Layer used by the WinForms --(calls)--> Friend Data Access Layer if validation succeeds.
Simplified example:
Public Shared Sub CreateCustomer(cust as Customer)
Validation.Customer.ValidateForCreate(cust) ' scoped as Friend
Dal.Customer.Create(cust) ' scoped as Friend
End Sub
Is it "smart" design to have the Validation Layer throw custom exceptions back to the UI when validation fails?
Is it better design to just return True/False from the Validation Layer along with a String message of what failed, and have the Service Layer handle throwing exceptions?
Is it better design to just return True/False from the Validation Layer, and have the Services Layer bubble up the True/False to the UI along with a String message of what failed?
I'm trying to keep an object oriented approach. My opinion is that throwing custom exceptions doesn't break OOP principles, but I'd like other opinions :)
AFAIK the exception mechanism is in fact at the core of OOP methodology, and is actually encouraged where it is built into the programming language. I'd say having your validation throw a custom exception is very much a good thing, especially if you have several custom exceptions (NameTooLongException, NameIncludesNonStandardCharactersException...) that are self-documenting and easily readable to future maintainers of the code.
Once your exception reaches your service layer, you can decide whether to catch and handle it (this depends on your business logic) or let it go all the way to the UI. If the exception carries a meaningful error message that is always appropriate, perhaps letting the UI present it to the user is not a bad idea. (Bare in mind though that you may want to internationalize your application at some point, in which case the message will need to be in the correct language.)
My opinion is that layer separation, while sometimes purely logical, has its reasons, and exceptions should not be thrown from the back-end to the front-end, but this is more of a guideline than a rule. Bottom line, do what needs to be done, don't overthink the design.
Hope this helps somehow...
Yuval =8-)

Lazy Loading with a WCF Service Domain Model?

I'm looking to push my domain model into a WCF Service API and wanted to get some thoughts on lazy loading techniques with this type of setup.
Any suggestions when taking this approach?
when I implemented this technique and step into my app, just before the server returns my list it hits the get of each property that is supposed to be lazy loaded ... Thus eager loading. Could you explain this issue or suggest a resolution?
Edit: It appears you can use the XMLIgnore attribute so it doesn’t get looked at during serialization .. still reading up on this though
Don't do lazy loading over a service interface. Define explicit DTO's and consume those as your data contracts in WCF.
You can use NHibernate (or other ORMs) to properly fetch the objects you need to construct the DTOs.
As for any remoting architecture, you'll want to avoid loading a full object graph "down the wire" in an uncontrolled way (unless you have a trivially small number of objects).
The Wikipedia article has the standard techniques pretty much summarised (and in C#. too!). I've used both ghosts and value holders and they work pretty well.
To implement this kind of technique, make sure that you separate concerns strictly. On the server, your service contract implementation classes should be the only bits of the code that work with data contracts. On the client, the service access layer should be the only code that works with the proxies.
Layering like this lets you adjust the way that the service is implemented relatively independently of the UI layers calling the service and the business tier that's being called. It also gives you half a chance of unit testing!
You could try to use something REST based (e.g. ADO.NET Data Services) and wrap it transpariently into your client code.