Is it worth it to write a bunch of 2 liner functions in BLL object just to re-route to DAL? - data-access-layer

It seems pretty silly to me. What don't I get?

I've run into cases like this where my app calls a business layer to select a list of values. The business layer then calls through to the Dal to do the data access. In a lot fo these cases, there is no apparent reason for the business layer method that does the pass through, but it does leave room to add business logic, processing of the data, etc in the future. It also helps keep your app decoupled, which will make testing much easier.
So, I say keep the one liners, but if your inserts, updates, etc are still one or two lines, you need to re-think where you are doing your validation and business level data processing.

If your BLL never does validation or implements any business logic and always remains 2 liners, then yes it is pretty silly. If you do this though, you've probably missed the point of having a business logic layer and you have probably been doing your validation in the UI, or adding business logic in your UI or your DAL. There are very few applications that require no validation and have no business logic.

While Rob and Bullines are often correct that the need to do this points to a deeper problem, there are legitimate instances in which going straight to the data access layer makes perfect sense. Writing a brainless method (or worse, entire object model) to wrap the data access layer is among the least useful things any programmer can ever do, so don't. You can feel good about not going through the business logic layer if there's a legitimate reason.

Business logic should be in your BLL. If you end up with "2 liner functions" in your BLL, did you accidentally put that business logic in your DAL or UI?

Related

Best practice for commitment control using RESTful APIs

We are currently designing an application using RESTful APIs to communicate with the DB. Our DB is a normalized structure, with upwards of 7 table representing a single application data point with an API for each DB entity.
What I am struggling with is how to institute commitment control over these tables. Ideally, I would like to call each API from my API controller, but that would make the commit scope to a table level, and make the application control rollbacks. This is not ideal as this would mean that we are in essence doing dirty writes.
What is the best practice to use RESTful APIs and still have teh DB perform commitment control?
The model that you expose as a group of RESTful resources need not be the same as the model that the database uses. For example, you can use RESTful manipulation to build up a “change description” resource (local to the user's session) that is then applied to the database in one commit. The change description is complex, but there are no problems with dirty writes because all the user is changing a private world until they choose that they're going to commit to it.
If you think of a web-based model (useful with REST!) then this is like filling out a complicated order form in multiple stages. The company from which you are buying happily lets you fill out the form, storing values as necessary, but doesn't commit to actually fulfilling the order and charging your credit card until you say that it is all ready to go. I'm sure you can apply the same principle to other complex modifications.
One key thing though; if the commitment is not idempotent (i.e., if you commit it twice, different things happen) it must be a POST. That's probably a good idea in your scenario anyway, since I'd guess you want to remove the “building up an action description” resource on successful POSTing. (Yes, we'd still be following the “web form” model.)
I do think you want to carefully consider the complexity of your models though. It's a useful exercise to make things as simple as possible (no simpler though) where “simple” involves keeping the number of concepts down. If you have lots of things, but they all work exactly the same way, they're actually pretty simple. (Increasing the number of address lines in a customer record doesn't really increase the complexity very much.) The good thing about REST is that it uses very few concepts, and they're concepts that lots of people are familiar with from the web.
Implement the controller you want for your RESTful services. The controller does little more than call through to a service layer where your transactions are managed. The service layer coordinates access to the various tables by whatever DAOs need to cooperate together--the DAOs do not need to be concerned with the transaction boundaries. If you happen to be a Spring user, this thread may be of help.

Layers on a WCF service

Okay, I've got this WCF service going. It has a public access, which is the main service itself (HydSQLService) which contains a DataContext for access to the database. This DataContext was generated by SQLMetal.exe, although I created a partial class to fill in the partial methods.
So this question is more about how to layer this application. At the moment, the service (i.e. the publically exposed bit) holds a reference to the DataContext object. It goes through this to access the SQL database.
I intend to add a layer between these for server side validation, but I'm not sure if I'm missing a layer or something (I'm somewhat new to all this).
So is this the right amount of layers? Is it structured correctly, or have I made some horrendous oversight? Suggestions would be welcome.
The answer is - as always - it depends.
To understand the pros and cons of your architecture as described, we would need to know a whole lot more about the requirements and environment that you're working with. However, the fact that you have layers is likely a good thing. The fact that you're thinking about this aspect of your application is definitely a good thing.
In general, we add layers to solve a few challenges:
Separation of concerns. Having a layer handle one aspect of the application (and handle it well) is seldom a bad thing. This allows you to rip out that layer and replace it without rewriting the rest of the application.
Testability - It's often beneficial to test the layers in isolation (e.g. automated unit tests) that ensure that piece is working correctly.
Abstract away common functions (data access, validation, etc). This can make the application easier to maintain. For example, not having to maintain a bunch of data access specific code in the middle of a business object layer is nice.
This sort of question is difficult to answer specifically in this context. You would a much more in depth review to get the kind of feedback / direction you're looking for.

How to design a business logic layer

To be perfectly clear, I do not expect a solution to this problem. A big part of figuring this out is obviously solving the problem. However, I don't have a lot of experience with well architected n-tier applications and I don't want to end up with an unruly BLL.
At the moment of writing this, our business logic is largely a intermingled ball of twine. An intergalactic mess of dependencies with the same identical business logic being replicated more than once. My focus right now is to pull the business logic out of the thing we refer to as a data access layer, so that I can define well known events that can be subscribed to. I think I want to support an event driven/reactive programming model.
My hope is that there's certain attainable goals that tell me how to design these collection of classes in a manner well suited for business logic. If there are things that differentiate a good BLL from a bad BLL I'd like to hear more about them.
As a seasoned programmer but fairly modest architect I ask my fellow community members for advice.
Edit 1:
So the validation logic goes into the business objects, but that means that the business objects need to communicate validation error/logic back to the GUI. That get's me thinking of implementing business operations as objects rather than objects to provide a lot more metadata about the necessities of an operation. I'm not a big fan of code cloning.
Kind of a broad question. Separate your DB from your business logic (horrible term) with ORM tech (NHibernate perhaps?). That let's you stay in OO land mostly (obviously) and you can mostly ignore the DB side of things from an architectural point of view.
Moving on, I find Domain Driven Design (DDD) to be the most successful method for breaking a complex system into manageable chunks, and although it gets no respect I genuinely find UML - especially action and class diagrams - to be critically useful in understanding and communicating system design.
General advice: Interface everything, build your unit tests from the start, and learn to recognise and separate the reusable service components that can exist as subsystems. FWIW if there's a bunch of you working on this I'd also agree on and aggressively use stylecop from the get go :)
I have found some o fthe practices of Domain Driven Design to be excellent when it comes to splitting up complex business logic into more managable/testable chunks.
Have a look through the sample code from the following link:
http://dddpds.codeplex.com/
DDD focuses on your Domain layer or BLL if you like, I hope it helps.
We're just talking about this from an architecture standpoint, and what remains as the gist of it is "abstraction, abstraction, abstraction".
You could use EBC to design top-down and pass the interface definitions to the programmer teams. Using a methology like this (or any other visualisation technique) visualizing the dependencies prevents you from duplicating business logic anywhere in your project.
Hmm, I can tell you the technique we used for a rather large database-centered application. We had one class which managed the datalayer as you suggested which had suffix DL. We had a program which automatically generated this source file (which was quite convenient), though it also meant if we wanted to extend functionality, you needed to derive the class since upon regeneration of the source you'd overwrite it.
We had another file end with OBJ which simply defined the actual database row handled by the datalayer.
And last but not least, with a well-formed base class there was a file ending in BS (standing for business logic) as the only file not generated automatically defining event methods such as "New" and "Save" such that by calling the base, the default action was done. Therefore, any deviation from the norm could be handled in this file (including complete rewrites of default functionality if necessary).
You should create a single group of such files for each table and its children (or grandchildren) tables which derive from that master table. You'll also need a factory which contains the full names of all objects so that any object can be created via reflection. So to patch the program, you'd merely have to derive from the base functionality and update a line in the database so that the factory creates that object rather than the default.
Hope that helps, though I'll leave this a community wiki response so perhaps you can get some more feedback on this suggestion.
Have a look in this thread. May give you some thoughts.
How should my business logic interact with my data layer?
This guide from Microsoft could also be helpful.
Regarding "Edit 1" - I've encountered exactly that problem many times. I agree with you completely: there are multiple places where the same validation must occur.
The way I've resolved it in the past is to encapsulate the validation rules somehow. Metadata/XML, separate objects, whatever. Just make sure it's something that can be requested from the business objects, taken somewhere else and executed there. That way, you're writing the validation code once, and it can be executed by your business objects or UI objects, or possibly even by third-party consumers of your code.
There is one caveat: some validation rules are easy to encapsulate/transport; "last name is a required field" for example. However, some of your validation rules may be too complex and involve far too many objects to be easily encapsulated or described in metadata: "user can include that coupon only if they aren't an employee, and the order is placed on labor day weekend, and they have between 2 and 5 items of this particular type in their cart, unless they also have these other items in their cart, but only if the color is one of our 'premiere sale' colors, except blah blah blah...." - you know how business 'logic' is! ;)
In those cases, I usually just accept the fact that there will be some additional validation done only at the business layer, and ensure there's a way for those errors to be propagated back to the UI layer when they occur (you're going to need that communication channel anyway, to report back persistence-layer errors anyway).

Should the data access layer contain business logic?

I've seen a trend to move business logic out of the data access layer (stored procedures, LINQ, etc.) and into a business logic component layer (like C# objects).
Is this considered the "right" way to do things these days? If so, does this mean that some database developer positions may be eliminated in favor of more middle-tier coding positions? (i.e. more c# code rather than more long stored procedures.)
If the applications is small with a short lifetime, then it's not worth putting time into abstracting the concerns in layers. In larger, long lived applications your logic/business rules should not be coupled to the data access. It creates a maintenance nightmare as the application grows.
Moving concerns to a common layer or also known as Separation of concerns, has been around for a while:
Wikipedia
The term separation of concerns was
probably coined by Edsger W. Dijkstra
in his 1974 paper "On the role of
scientific thought"1.
For Application Architecture a great book to start with is Domain Driven Design. Eric Evans breaks down the different layers of the application in detail. He also discusses the database impedance and what he calls a "Bounded Context"
Bounded Context
A blog is a system that displays posts from newest to oldest so that people can comment on. Some would view this as one system, or one "Bounded Context." If you subscribe to DDD, one would say there are two systems or two "Bounded Contexts" in a blog: A commenting system and a publication system. DDD argues that each system is independent (of course there will be interaction between the two) and should be modeled as such. DDD gives concrete guidance on how to separate the concerns into the appropriate layers.
Other resources that might interest you:
Domain Driven Design Quickly
Applying Domain Driven Design and
Patterns
Clean Code
Working Effectively with Legacy
Code
Refactor
Until I had a chance to experience The Big Ball of Mud or Spaghetti Code I had a hard time understanding why Application Architecture was so important...
The right way to do things will always to be dependent on the size, availability requirements and lifespan of your application. To use stored procs or not to use stored procs... Tools such as nHibrnate and Linq to SQL are great for small to mid-size projects. To make myself clear, I've never used nHibranate or Linq To Sql on a large application, but my gut feeling is an application will reach a size where optimizations will need to be done on the database server via views, Stored Procedures.. etc to keep the application performant. To do this work Developers with both Development and Database skills will be needed.
Data access logic belongs in the data access layer, business logic belongs in the business layer. I don't see how mixing the two could ever be considered a good idea from a design standpoint.
Separation of layers does not automatically mean not using stored procedures for business logic. This separation is equally possible:
Presentation Layer: .Net, PHP, whatever
Business Layer: Stored Procedures
Data Layer: Stored Procedures or DML
This works very well with Oracle, for example, where the business layer may be implemented in packages in a different schema from the data layer (to enforce proper separation of concerns).
What matters is the separation of concerns, not the language/technology used at each level.
(I expect to get roundly flamed for this heresy!)
The perfect world doesn't exist. It's about elegance versus what works better.
Executing complex SQL queries inside data access layers is much more performative than making a service to ask data many times and then merging and transforming them. When you make complex queries you are putting business logic in those queries.
It really depends on the requirements. Either way as long as it's NOT "behind the button" as it were. I think stored procedure are better for "classic" client server apps with changing needs. A strict middle "business logic" layer is better for apps that need to be very scalable, run on multiple database platforms, etc.
If you are building a layered architecture, and the architecture contains a dedicated business layer, then of course you should put business logic there. However, you can ask any five designers/architects/developers what 'business logic' actually is, and get six different answers. (Hey, I'm an architect myself, so I know all about 'on the one hand, but on the other'!). Is navigating an object graph part of the data layer or business layer? Depends on which EAA patterns you are using, and on exactly how complicated/clever your domain objects are. Or is it perhaps even part of your presentation?
But in more concrete terms: database development tools tend to lag behind Eclipse/Visual Studio/Netbeans/; and stored procedures have never been extremely comfortable for large-scale development. Yes, of course you can code everything in TSQL, PL/SQL &c, but there's a price to pay. What's more, the price of having several languages and platforms involved in one solution increases maintenance costs and delays. On the other hand, moving data access out of reach of DBA's can cause other headaches, especially with shared infrastructure environments with any kind of availability requirements. But overall, yes, modern tools and languages are currently moving logic from the data(base) layer into the application layer. We'll have to see how well it works out and scales.
The reason I've seen this trend is that LINQ and LINQ to SQL ORM give you a nice type-safe alternative to stored procedures.
What's "right" is whether you benefit from doing this personally.
Yes, business logic should be in the business logic layer. For me this is the biggest drawback of using store procedures for everything and thus moving some of the business rules to the db, I prefer to have that logic in the BLL in have the DLL only do communication with the db
It is ALWAYS a good idea to separate your layers. I can't tell you the number of times I've seen stored procedures that are VERY gnarly from lots of business logic written into the sproc. Also if you modify your complex stored procedure for whatever reason, you have the potential to break EVERYTHING that uses it.
Us devs at my company are moving to LINQ w/ the EF and dismissing the stored procedure unless we absolutely need it. LINQ and the EF make separating our layers a lot easier...when the EF is not being difficult. But that's another rant. :)
There will likely always be some level of business logic in the data layer. The data itself is a representation of some of that logic. For instance, primary keys are often created based on business logic rules.
For example, if your system won't allow an order to have more than one customer is part of the business logic, but it's also present (or should be) in the Data layer.
Further, some kinds of business rules are best done on the database itself for efficiency reasons. These are usually stored procedures, and thus exist in the data layer. An example might be a trigger that goes off if a customer has spent more than $X in a year, or if a ship-to is different from a bill-to.
Many of these rules might be handled in the business layer as well, but they also need a data layer component. It depends on where your error handling is.
Business logic in the data layer was common in client/server apps, as there really was no business logic layer per se (unless you could really, seriously prevent anyone from connecting to the database outside the application). Now that web apps are more common, you're seeing more 3- and 4-tier apps (client+web server+app server+database server), and more companies are following best practices and consolidating business logic in its own tier. I don't think there will be any less work for database developers, they'll probably just become the ones that write the business logic layer (and let an ORM tool write most of the database layer).
There are also technical reasons/limitations to be considered when planning where to author the business rules.
In most LOB applications centralization and performance pushes developers to use the database it self as the primary Business Layer, so in a sense, DAL and BL is mixed or unified.
A typical example would be the field that calculates the current location of a rental item, a piece of information that should be available for one or for many listed items, making an SQL view with a User Defined Function the most powerful candidate to hold the rule.
The above example is valid of course if a specific database design and processes implementation is preferred, but I just want to point out that in real world, we choose based on technical limitations and other principles, more often than we do for organizing our code.

I've never encountered a well written business layer. Any advice?

I look around and see some great snippets of code for defining rules, validation, business objects (entities) and the like, but I have to admit to having never seen a great and well-written business layer in its entirety.
I'm left knowing what I don't like, but not knowing what a great one is.
Can anyone point out some good OO business layers (or great business objects) or let me know how they judge a business layer and what makes one great?
Thanks
I’ve never encountered a well written business layer.
Here is Alex Papadimoulis's take on this:
[...] If you think about it, virtually every line of code in a software
application is business logic:
The Customers database table, with
its CustomerNumber (CHAR-13),
ApprovedDate (DATETIME), and
SalesRepName (VARCHAR-35) columns:
business logic. If it wasn’t, it’d
just be Table032 with Column01,
Column02, and Column03.
The
subroutine that extends a ten-percent
discount to first time customers:
definitely business logic. And
hopefully, not soft-coded.
And
the code that highlights past-due
invoices in red: that’s business
logic, too. Internet Explorer
certainly doesn’t look for the strings
“unpaid” and “30+ days” and go, hey,
that sure would look good with a #990000 background!
So how then is possible to encapsulate all of this business logic
in a single layer of code? With
terrible architecture and bad code of
course!
[...] By implying that a system’s architecture should include a layer dedicated to business logic, many developers employ all sorts of horribly clever techniques to achieve that goal. And it always ends up in a disaster.
I imagine this is because business logic, as a general rule, is arbitrary and nasty. Garbage in, garbage out.
Also, most of the really good business layers are most probably proprietary. ;-)
Good business layers have been designed after a thorough domain analysis. If you can capture the business' semantics and isolate it from any kind of implementation, whether that be in data storage or any specific application (including presentation), then the logic should be well-factored and reusable in different contexts.
Just as a good database schema design should capture business semantics and isolate itself from any application, a business layer should do the same and even if a database schema and a business layer describe the same entities and concepts, the two should be usable in separate contexts--a database schema shouldn't have to change even when the business logic changes unless the schema doesn't reflect the current business. A business layer should work with any storage schema provided that it's abstracted via an intermdiate layer. For example, the ADO.NET Entity framework lets you design a conceptual schema which maps to the business layer and has a separate mapping to the storage schema which can be changed without recompiling the business object layer or conceptual layer.
If a person from the business side of things can look at code written with the business layer and have a rough idea of what's going on then it might be a good indication that the objects were designed right--you've succesfully conveyed a solution in the problem domain without obfuscating it with artifacts from the solution domain.
I've always been stuck between a rock and a hard place. Ideally, your business logic wouldn't be at all concerned with database or UI-related issues.
Keys Cause Problems
Still, I find things like primary and foreign keys causing problems. Even tools like Entity Framework don't completely eliminate this creep. It can be extremely inefficient to convert IDs passed as POST data into their respective objects, only to pass this to the business layer, which then passes them to the data layer to just be stripped down again.
Even NoSQL databases come with problems. They tend to return full object models, but they usually return more than you need and can lead to problems because you're assuming that object model won't change. And keys are still found in NoSQL databases.
Reuse vs. Overhead
There's also the issue of code reuse. It's pretty common for data layers to return fully populated objects, including every column in that particular table or tables. However, often business logic only cares about a limited subset of this information. It lends itself to specialized data transfer objects that only carry with them the relavent data. Of course, you need to convert between representations, so you create a mapper class. Then, when you save, you need to somehow convert these lesser objects back into the full database representation or do a partial UPDATE (meaning a another SQL command).
So, I see a lot of business layer classes accepting objects mapping directly to database tables (data transfer objects). I also see a lot of business layers accepting raw UI values (presentation objects), as well. It's also not unusual to see business layers calling out to the database mid-computation to retrieve needed data. To try to grab it up-front would probably be inefficient (think about how and if-statement can affect the data that gets retrieved) and lazy loaded values result in a lot of magic or unintended calls out to the database.
Write Your Logic First
Recently, I've been trying to write the "core" code first. This is the code that performs the actual business logic. I don't know about you, but many times when going over someone else's code, I ask the question, "But, where does it do [business rule]?" Often, the business logic is so crowded with concerns about grabbing data, transforming it and whatnot that I can't even see it (needle in a hay stack). So, now I implement the logic first and as I figure out what data I need, I add it as a parameter or add it to a parameter object. Getting the rest of the code to fit this new interface usually falls on a mediator class of some kind.
Like I said, though, you have to keep a lot in mind when writing business layers, including performance. The approach above has been useful lately because I don't have rights to version control or the database schema yet. I am working in a dark room with just my understanding of the requirements so far.
Write with Testing in Mind
Utiltizing dependency injection can be useful for designing a good architecture up-front. Try to think about how you would test your code without hitting a database or other service. This also lends itself to small, reusable classes that can run in multiple contexts.
Conclusion
My conclusion is that there really is no such thing as a perfect business layer. Even in the same application, there can be times when one approach only works 90% of the time. The best we can do is try to write the simplest thing that works. For the longest time I avoided DTOs and wrapped ADO.NET DataRows with objects so updates were immediately recorded in the underlying DataTable. This was a HUGE mistake because I couldn't copy objects and constraints caused exceptions to be thrown at weird times. I only did it to avoid setting parameter values explicitly.
Martin Fowler has blogged extensively about DSLs. I would recommend starting there.
http://martinfowler.com/bliki/dsl.html
It was helpful to me to learn and play with CSLA.Net (if you are a MS guy). I've never implemented a "pure" CSLA application, but have used many of the ideas presented in the architecture.
Your best bet is keep looking for that elusive magic bullet and use the ideas that best fit the problem you are solving. Keep it simple.
One problem I find is that even when you have a nicely designed business layer it is hard to stop business logic leaking out, and development tools tend to encourage this. For example as soon as you add a validator control to an ASP.NET WebForm you have let business logic leak out into the view. The validation should occur in the business layer and only the results of it displayed in the view. And as soon as you add constraints to a database you then have business logic in your database as well. DBA types tend to disagree strongly with this last point though.
Neither have I. We don't create a business layer in our applications. Instead we use MVC-ARS. The business logic is embedded in the (S) state machine and the (A) action.
Possibly because in reality we are never able to fully decouple the business logic from the "process", the inputs, outputs, interface and that ultimately people find it hard to deal with the abstract let alone relating it back to reality.