Skip to main content
Ben Nadel at CFCamp 2023 (Freising, Germany) with: Randy Brown and Sebastian Zartner
Ben Nadel at CFCamp 2023 (Freising, Germany) with: Randy Brown Sebastian Zartner

What The Heck Is Business Logic Anyway?

By
Published in Comments (51)

For the last year, I've been trying hard to become a better programmer. This journey has involved both writing a ton of code as well as constantly evaluating and re-evaluating the way I think about software application architecture. Of course, I can only do so much on my own; which is why I turn - daily - to the blogosphere to see what people are saying about software development. From everything that I've read / watched so far, the consistent message seems to be:

Put your "business logic" in your domain model and your "application logic" in your application layer. Further breaking down the domain model, most things should live in your domain entities; and, whatever doesn't make sense in a single entity can (and only if necessary) be moved into a domain service.

This sounds really good, and makes for fancy diagrams; but, the problem that I keep running into is that nobody seems to be good as actually defining what in the heck "business logic" is; and, more importantly, how it's different from "application logic".

Imagine, if you will, that I am building a Forum / Discussion site that has discussion threads, users, and moderators. Now, let's say that I have a feature that allows a discussion thread to be renamed. In order to carry out this action, I have to take a number of steps:

If the user (performing the rename) is a Moderator:

  • Make sure the user is logged-in.
  • Make sure the user is a moderator.
  • Make sure the name isn't empty.
  • Make sure the name length abides by the rules of the persistence engine (ie. DB column).
  • Make sure the name it's blacklisted.
  • Rename the discussion thread.
  • Persist the change.
  • Email the owner (ie. user who created the thread), notifying them of the change.

If the user (performing the rename) is the thread owner:

  • Make sure the user is logged-in.
  • Make sure the user is the one who started the thread.
  • Make sure there are no existing responses within the thread by other users.
  • Make sure the thread is not more than 3 days old.
  • Make sure the name isn't empty.
  • Make sure the name length abides by the rules of the persistence engine (ie. DB column).
  • Make sure the name it's blacklisted.
  • Rename the discussion thread.
  • Persist the change.
  • Email the moderators, notifying them of the change.

Now, if my "business" were to be building and running a Forum / Discussion site, then all of this could feel like "business logic" - heck, it's my business! However, I am sure that there are people who would look at this list say that there's absolutely no business logic here whatsoever - that this is all purely application logic. And, of course, I'm sure there are people somewhere in the middle.

What makes this conversation even more interesting is when people further define the software application layering by stipulating that the "application layer" should be very "thin", and that the "domain model" layer should be very "thick."

This creates an odd dilema. By using the relative-size definition, it requires the above list of steps to be part of the "business logic." If it were not, it would leave us with an application layer that was far thicker than our domain model layer... which, apparently, it cannot / should not be.

However, if we consider the list to be mostly "business logic", then it means that this list of steps - or, at least, many of them - should reside within a domain entity. This leaves me with the gut feeling that we're creating "God Objects," which do far more than they aught to.

A third option is put some of the steps in the application layer, some of the steps into a "domain service," and then leave little more than a name-setter with length validation in the discussion thread, "domain entity." Of course, if we do this, people will condemn you for creating an "anemic domain model," but give you little-to-no insight as to what you should have done better.

Oh, and if none of this fits the bill, people will simply tell you that your site simply doesn't require a "domain model" at all - that is has no "behavior;" which, is frustrating when you think to yourself, "but my site does a lot of stuff!"


 
 
 

 
What the heck is business logic anyway?!  
 
 
 

As you can probably tell, this is a topic that frustrates me greatly. I feel completely ignorant; and I feel that my research leads me nowhere. If anything, I'd say that the more I read, think, and experiment, the more I tend to believe that having domain entities is hardly worth-while. It seems like I'd get the same amount of DRY'ness and encapsulation if my "domain model" had little more than domain services (ie. an anemic domain model without the overhead of entities).

I think this is what people call a "Transaction Script" approach? (maybe).

If anyone can give me any clarity on the topic, I would be forever indebted to you and would probably shower you with all kinds of awesome praise.

Reader Comments

3 Comments

Hi Ben,
It's none of my business to comment on your programmer frustration since I know very, very little about programming. (Though, I'm much interested in it). However, I started following you a while ago on Facebook after reading your blog. I like your writings.
But, to return to why I respond here in the first place, besides telling you that I like reading your blog and that the title of this one caught my eye tonight on FBs startpage, next to the phrase that you're posting for the first time in months (I'm a blogger as well and didn't post new blogs for months either, which I miss actually a lot)is that you made me curious about the phrase "business logic".
The first thing I thought (as being a non-programmer) was that it must have had something to do with business-like manners. Meaning short, to-the-point, and profitable. The second thing was, let's see what google say about it. Maybe Dutch google would pop up the answer you're looking for. And pro's probably skip the results google returns which seem to obvious. To be honest, the idea to be showered with all kinds of awesome praises was partly why I did that :)
Business-logic is defined on Wiki and there was a link to Business-rule-management system. Then I was lost already. I have not the slightest bit of hope that you don't already know what's written there. So much for the awesome praises.
However, I do hope that someone will seriously help you to tackle this question and that you won't be frustrated any further by my reply. Frustrations in general are not very helpful to find the answers you're looking for. But hey, that's my topic, as being a psychology student ;)

Best wishes,
Debby

5 Comments

Ben, I found the accepted answer to this SO question to be a concise answer to your question:

http://stackoverflow.com/questions/2630758/whats-the-difference-between-application-layer-and-business-logic-layer

My understanding of the answer, from an MVC perspective, is that the "Model" is the layer that contains the business logic. In a perfect world (i.e., never), the model could be plugged into any framework and it would just work because it doesn't care about the way it's being used in the application. In this case, the application logic would be contained in the "Controller" layer of our application. The business logic doesn't need to know how it's being used by the application, and the application logic doesn't need to know what the business logic is doing.

I don't think this necessarily lends itself to a "God Object," unless you would consider the controller itself to be that object. The application layer knows all the rules and how these rules interact (user must be logged in, name cannot be empty), but it doesn't know how to determine if the rules are being broken - it only knows who to ask to find out if they are being broken. On the other hand, the business layer is there to tell you if a rule is being broken, but it doesn't need to know the overarching goal of evaluating that single rule - it just checks if the user is logged in, but it doesn't know that that is one of a dozen rules that has to be run before a post can successfully be renamed.

I feel like I rambled a bit there, so (anyone) please feel free to poke holes in it. Also, I may be 100% wrong in which case I would love to hear any rebuttals. :)

68 Comments

In my head, the divide between Business and Application logic is this: Business logic manages data, Application logic manages users. If your system was never touched by users (such as an automated system, like an ETL process) there would be little or no Application logic. If your data had no structure and no rules (think JSON data store) there would be little to no Business logic.[1]

Sure, there will sometimes be overlap, but the key is to figure out if you're trying to keep the user from doing something dumb/unauthorized, or if you're trying to ensure your data doesn't degenerate into useless entropy.

I also find that Application logic may involve state ("the user must be logged-in and an admin", "this request should be cached") whereas Business logic usually doesn't. (Unless you want to be pedantic and call setters "state mutators", but that's just being obtuse.)

I remember an argument years back in which someone (maybe Hal Helms or Sean Corfield) very smartly asserted that objects (and by extension data) should never be able to exist in an invalid state. The stuff that ensures that is the case is Business logic.

--
1. Yes, a JSON data store still has Business logic in the form of validating that incoming data is correctly-formatted JSON, but you get my point.

55 Comments

Here are what would go through my mind for deciding where to implement the business logic.

Purely manipulating properties of the object itself?
> Implement in a method of the object class.

Front-end dependent?
> Implement in the handler layer of your MVC framework.

Complex task that needs other services to complete?
> Implement in a service where it is easy to hook up to other services through dependency injection. Make sure the sub-tasks are implemented in the appropriate services. Aim for readability over everything. You may also consider inject the service back to the object through a factory if the task makes sense to be exposed as obj.doTaskX(). Once things are working, spend the time to re-factoring until the code is easily readable and the flow of sub-task can be traced clearly.

1 Comments

Thanks for a thought provoking post-- takes me back to early VB days when "n-tier" programming with Microsoft products was all the rage. Funny part is, I don't recall hearing anyone use the phrase "business logic" in the entire time I've done web programming.

If you'd asked me to explain "business logic" back then, I'd have said something like "it's where you capture requirements that are unique to this client/department to keep them separate from the parts that can be reused in other projects." So, for example, all applications have user accounts that require passwords to authenticate-- but the password policies for a valid/strong password will be different from one department to the next, so that's a "business rule" you would capture in your middle tier. This leaves your first tier free for reuse with different "business rules" in other applications.

I could be full of nonsense, of course, but that's my recollection of how it was explained to me.

4 Comments

Ben -- I can definitely understand your frustration! With things like overloaded terms, misused terms, differing experiences, and changing technology, it sure gets confusing out there. Thanks for providing a concrete example for discussion. Here's how I've often seen the division of responsibilities between the application and business layers decided.

Looking at the individual steps that you've identified, we can group the specific lines into these broader categories.

1. Make sure the user is authorized to rename this thread
2. Make sure that the thread is able to be renamed
3. Make sure that the new thread name is valid
4. Change the name
5. Send notifications

This high-level list hopefully conceptually includes everything you've got in your lists above, just with a little less detail. If I were writing an application layer, I'd start by putting these five statements into it. In other words, each of these five steps would be (roughly) a single call to some domain object, or maybe to another service.

Then, the actual implementation of each of these five steps would go into the business layer. That way, the application layer is orchestrating the domain model (i.e., making the calls into it) but not doing the actual work.

From there, you might choose to move small bits of code up into the app layer or down into the domain. For example, it'd probably make sense to have the name validation done as part of the call to thread.rename().

Naturally, you can slice up the code in all sorts of different ways and still get the same functionality. A good design is defined by how well it serves you as the programmer, today and in the future. So if using a domain model isn't a natural fit for the app, I wouldn't force it.

Does that help at all?

1 Comments

Hey Ben,

This is a very very interesting question you ask. What is "Business Logic". Well within the last year working in my company I got to know what business logic is (at least for the company I work for)

So before I started working at Pepsi I had no concept of what business logic was. But the way it was explain to me by our senior analyst is that "Business Logic" is the way the Business manages, calculates, or uses data. This "logic" is presented to the Developer {me} in a set of requirements. The Developer {me} takes the requirements and implements them in the application.

So for example for the last year Pepsi has created several metrics for measuring efficiency for all their plants that manufacturer and bottle soda and water.

So the business creates different metrics that measures the rate of the machines, the people on staff, any stoppage of production given specific reasons which helps them determine how efficient that plant is running.
Now as a developer that has not been in the plant, I have no way of knowing what those measures are for calculating efficiency and what I should be looking for. I depend on the Business team (which are business analyst that already track these things in Excel Spreadsheets) to give me that information so I can correctly implement it into the application that I will be updating.

So in my case "Business Logic" are a set of requirements that reflect the current business practices.

My example is different from yours and I imagine others who are in a different line of business. Your business is programming and is where I'm assuming it makes its money from, I work for a company who sells a product and the IT department is just a part of it, but not the main part.

But Like Sean Walsh mention in the comments about MVC which is a framework my company uses. We will implement the business logic in the "Model". Currently I'm doing that through the use of Stored Procedures that generate reports for the user through and desktop application.

http://www.jcorporate.com/expresso/doc/edg/edg_WhatIsMVC.html

Hope that Helps
Cris

"Hope you still working out - I miss Equinox"

11 Comments

Hi Ben,

I wouldn't worry about it to much 'People' say a lot of stuff. The vast majority of people are just muddling through in the best way they can. If you build it in the way that makes it simpler to maintain and easier for other people on your team to understand then surely your doing the right thing.

Theories fine but doing or having done it is better. You can always rejig it later.

5 Comments

Hi Ben,
I read first article of MVC from your blog. Digging deep through the meaning of MVC I found this article which said
... Business logic is the process, formula, algorithm, decision tree, methodology, query, or any other means used to perform a piece of work that is specific to an application...

So I believe that the methodology used to get any relevant information with respect to the request from application is "Business logic"

You can find the full article here - http://www.dougboude.com/blog/1/2008/03/What-IS-Business-Logic-Anyway.cfm

15,902 Comments

@Sean,

Thanks for that SO link. I actually have read that articles like 2-3 times in the last few weeks. Inevitably it comes up on Google searches when looking at Application/Business logic.

You bring up another point of confusion that I have from reading all the articles / blogs / tutorials, and that is "How much to do I put in the Controller layer?"

It seems that everything I read says that the Controller should do *almost* nothing more than taking requests and handing those requests off to the "core" application. Currently, I do handle some of the security of the application in the Controller workflow - namely, is user XYZ logged-in or not.

Beyond that, however, I have been (as of lately) deferring more localized permissions (ie. can edit? can delete?) to the service / model layer. The seemingly-nice thing about this is that I can use the same, simple application API when a user is accessing the site through two different access points (such as website vs. RESTful API). It's nice to not have to duplicate the access logic in two different controllers.... though, clearly both "applications" (in the web server sense) have to handle their own authentication approaches (ex. cookies vs Basic Auth vs. oAuth).

15,902 Comments

@Rick,

One thing that you said really connected with some of the thoughts I've been mulling over:

" If your system was never touched by users (such as an automated system, like an ETL process) there would be little or no Application logic."

The other day, I started to think about Scheduled Tasks in ColdFusion, and I had a moment of clarity - with a scheduled task, there is no user! If there is no user, I can't use a pathway into the domain model that requires user-authentication and permissions.

Granted, my access point for the scheduled task (an HTTP entry point) will have to have some security, like Basic Authentication of HTTPS; but, after that, the request has been "fully authenticated." By fact of it's *my* code, it's already authorized to do whatever my code tells it to do (except for, as you say, violating data rules).

This access-duality was what really got my machinery firing. If an authenticated user can call method XYZ(); and, a scheduled task can call method XYZ(); THEN, there better be no user-based permissions checking encapsulated within method XYZ(). As such, one can only conclude that user-based permissions must be executed in a higher layer, prior to the invocation of method XYZ().

As far as objects and valid state, I know I've heard Hal Helms talk about that:

www.bennadel.com/blog/1382-Hal-Helms-On-Object-Oriented-Programming-Day-Four.htm

15,902 Comments

@Henry,

I've become a big fan of Dependency Injection (DI). In my recent project, we've been using Sean Corfield's DI/1.

When you say, "Implement in the handler layer of your MVC framework," what do you mean by "handler layer"? Do you mean the Controller of the MVC paradigm? Or do you mean the next layer that the Controller talks to?

15,902 Comments

@Andrew,

It's funny that you talk about code reuse across applications. I think this is one of those things that's incredibly hard [for me] to think about. Since the extent of my cross-application re-use has been, "I like the way I did that in the other app, let me copy-paste the objects into this project," it's hard for me to think about actually sharing components in a meaningful way.

While I do "borrow" from other apps, all of the applications that I have built in the last 10 years exist as islands unto themselves. The don't share libraries with other applications; and when I build them, I don't have the foresight to create components intended for cross-app reuse.

Maybe if I started to perform more "reuse analysis," it would actually help me figure out where things should be put?

15,902 Comments

@Dave,

What you just said is so on-target with so many of the thoughts that I've been having. If I can just add one more thing to it, I'd say "transaction management" would be the thing that ties all of that together:

transaction action = "begin" {
 
	1. Make sure the user is authorized to rename this thread
	2. Make sure that the thread is able to be renamed
	3. Make sure that the new thread name is valid
	4. Change the name
	5. Send notifications
 
}

This way, going back to what I was saying to @Rick, if I had a scheduled task that had to so the same operation, I could simply use the following steps:

transaction action = "begin" {
 
	1. --- not needed.
	2. Make sure that the thread is able to be renamed
	3. Make sure that the new thread name is valid
	4. Change the name
	5. Send notifications
 
}

Clearly, with a scheduled task, the authentication cannot be used (since there is no user).

15,902 Comments

@Cris,

Admittedly, the software that I build very rarely has highly complex calculations. Most of what I deal with involves permissions, data entry, and data aggregation (and maybe some scheduled tasks to clean up old data / expired data). Maybe this is part of why the journey has been difficult - the underyling code is not terribly complex, so it doesn't have an overwhelming "smell" as to where it should be.

I think I'm getting closer though - these conversations are really helping.

15,902 Comments

@Cris,

On a workout-tangent, I haven't worked out in MONTHS :( This current project has dominated every aspect of my life (unfortunately) and I cannot express in words how excited I am to get my life back on track (soon).

15,902 Comments

@Adam,

I guess, what I know now is that the my approaches in the past have not been the easiest things to maintain. This is why I am itching to improve the way I architect my software.

15,902 Comments

@Madhu,

That's really funny that Doug has an articles (5 years ago) with almost the same exact title :) I know Doug - he's a very bright guy.

290 Comments

Welcome back, @Ben!

To avoid confounding the topic with software engineering jargon: Business logic constitutes the rules the business wants the software to obey. If you're a contractor/employee, the business is your customer/employer. If you're the boss who commissioned the software to be written, the business is you; you say what the business rules are.

Those who work on the software define application logic as a way to instantiate the business rules. But software environments change and it's possible to define an instance of the business rules for HTML using one kind of application logic, and a completely different instance for XML / web services using completely different application logic.

Like it or not, our industry is subject to trends and fashion. You get something working perfectly, so you want to just let it be. If it ain't broke, don't fix it. But then along comes some new UI, or some new platform, and even though there's nothing wrong with it, you have to rearchitect the whole damn thing to be cool and keep your customers.

Yet all instances have to obey the same business rules.

I wrote and maintain a 15 year old search engine that has really kept up with the times: It allows you to view results tabularly, as a detail report, as a summary report, as csv, as another spreadsheet import format different from csv, for desktop browsers, for mobile devices, as web services, etc. I haven't been asked to generate charts and graphs yet, but you know from some SVG/Canvas code I showed you once (for a different search engine) that that's possible too.

Yet all of these different instantiations of the same search obey the same business rules (sorry that some have to be cryptic):
(1) We can't let searchers retrieve ridiculously large result sets and slow the servers down for everybody else. So insufficient search criteria has to be regarded as an error.
(2) Privacy-protected data is never divulged without https, login and sufficient privilege.
(3) Certain kinds of data are not retrieved unless certain search criteria are entered.
(4) Consistent search behavior. Specifically, adding a new category of search criteria (e.g.: state code) narrows a search, but entering multiple values for that category (e.g.: NY, NJ, CT, MA) broadens it.

All of those business rules derived from what my customer wanted the search engine to be. All instantiations (faces, views) obey those business rules. But only web views provide accessibility enhancements for blind users with screen reading browsers, which implies structuring HTML, JS and CSS in a particular way. That's application logic.

In the long run, to achieve this kind of flexibility, you have to segregate business rules from application rules. Business rules reside nearer to the data. Application rules reside nearer to the user, or the platform/middleware through which you talk to the user.

One last observation and I'll leave you to your holiday shopping:

Stored procedures are a good place for business rules, if that option is available. If all developers have to funnel their updates through stored procedures, the rules will be consistently enforced across all applications. Of course, you have to write the procedures intelligently to avoid inefficiencies, deadlocks, etc, but stored procedures are pretty darned close to the data. If a rule doesn't seem like it belongs in the procedure, if it seems to specific to user interface, it's probably an application rule.

290 Comments

Don'tcha just hate it when you write something long and thoughtful, but your proofreading breaks down in the very last sentence?

Not enough coffee, apparently.

15,902 Comments

@WebManWalking,

Thinking of business logic as the stuff your client asks for in order to build the software, is typically how I have been thinking about it. But, I think the problem with that is that [from my point of view] is that it doesn't allow the "application layer" to orchestrate business logic.

If the requirements of the software say that for some actions, steps 1, 2, 3, and 4 have to take place, then it seems that in order to "enforce" that all of that happens, all of that orchestration has to be inside the "domain model", not inside the application layer (since it's business logic).

But, I think using the application layer as a place to orchestrate business logic has value (even if it requires a workflow to be enforced outside of the domain model).

... too hungry to think more deeply at this moment :)

290 Comments

Redundancy's okay.

In one of my banking applications, fixed interest rate loans require initial interest rate but not spread over prime. Variable interest loans require spread over prime, but not initial interest rate.

In the web pages, users have come to expect immediate feedback. Clicking the Fixed radio button results in initial interest rate being marked mandatory and spread over prime being marked optional, in our case, via JS that adds or removes classes. Clicking Variable results in the opposite.

Yeah, that's in the application logic. But that's okay. In fact, accessibility for cognitively disabled users pretty much requires that kind of implications-revealing feedback.

In a web service, you wouldn't have that sort of bleed-over of business logic into application logic. That's okay too.

It's not like rigorously normalizing a database, where you're trying to make sure each data element appears in only one place on the database. A rule doesn't have to reside only in business logic or application logic, never both.

The important thing is, in the absence of upfront application logic, business logic catches and prevents violations of business rules.

My $0.02.

96 Comments

Checkout the 'Service Layer' example for Overview of Application Layers

Pg53 @ Pro Spring MVC w Web Flow ...

Application Layering ...

"Layers should be thought of as conceptual boundaries"

Presentation =

This is most likely to be a web-based solution. The presentation layer should be as thin as
possible. It should also be possible to provide alternative presentation layers like a web
front-end or maybe even a web service façade. This should all operate on a well-designed
service layer.

Service =

The entry point to the actual system containing the business logic. It provides a coarse grained
interface that enables use of the system. This is also the layer that should be the
transactional boundary of the system (and probably security, too). This layer shouldn't
know anything (or as little as possible) about persistence or the view technology used.

Data Access =

An interface-based layer that provides access to the underlying data access technology,
but without exposing it to the upper layers. This layer abstracts the actual persistence
framework (e.g., JDBC, JDO, or JPA). Note that this layer should not contain business
logic.

"Communication between the layers is from top to bottom. The service layer can access the data
access layer, but the data access layer cannot access the service layer. If you see these kinds of circular
dependencies creep into your application, take a few steps back and reconsider your design. Circular
dependencies (or bottom to top dependencies) are almost always a sign of bad design and lead to
increased complexity and a harder-to-maintain application."

http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/mvc.html#mvc-servlet

15,902 Comments

@Edward,

I've definitely been thinking of the service layer as my conceptual boundary to my core application. I'm exactly pleased with some of the choices I've made (hence this post), but I have been using a consistent approach with passing the authenticated user ID through to the service layer on all the calls. For example:

function doSomething(
	required numeric authenticatedUserID,
	required .... other args,
	required .... other args
) {
	// ... orchestration logic
}

My controller layer handles the authentication (using calls to the security layer to check for username / password or whatever); then, subsequent calls back into the service layer will always pass the auth user ID as the first argument.

That said, I would like to extract all of that stuff UP into the "application layer", which I currently don't really have. My service layer is a bit of a hodgepodge of responsibilities... something to be refactored soon.

20 Comments

I like webmanwalking's notion that business logic implements business rules, and business rules are basically requirements. At implementation time you then get application logic and domain logic, and the business rules could be implemented in either or both depending on the degree of generality desired.

To me domain logic is all about generality. What *is* a thread? What are it's properties, and what can it do? Come up with a definition that you're happy to run with across all the applications of this kind that you might want to write, and that's domain stuff. This is why really rich domain models are rare - because most domains have very few truly general rules - and complicated - because a lot of the rules have be parameterized to make them general.

So if all discussion threads in the universe of applications you might want to write have to be less than three days old to be renamed - that's domain logic. If only this particular application cares about thread age and renaming - that's application logic. If thread age has a bearing on renaming in all applications, but different applications might allow different ages - that's a mix. The "care about thread age when renaming" is domain logic, and "make the threshold three days" is application logic.

15,902 Comments

@Edward,

On the "framework" side of things, I feel mostly comfortable. I have not, traditionally, been a "framework" person; and, getting requests to responses has been a matter of converting URLs to actions, to content, to rendering. It's not always pretty, but that part of the web-development world has been one of the kinder aspects. Though, I have stressed over rendering complex layouts and how that's done properly; but, I get something working.

The part of this whole process that comes back to bite me is often the gathering of data for display - the point where the controller needs to prepare the view-model (or what ever you want to call it). That's the part, for me, that gets unwieldy over time.

As far as Bob Martin, I definitely gobble up all the articles and presentations and interviews of his that I can find :)

15,902 Comments

@Jaime,

I think what makes that mindset so difficult, at least for me, is that I rarely build two applications that are a like. In my job at Epicenter Consulting (~last 4 years), I never built two sites that were similar. Ok, maybe a few e-commerce sites; but other than that, we build line-of-business web-apps for all kinds of different types of businesses.

Now, at InVision, we build a single product.

As such, the thought of using a component in a non-application-specific way seems incredibly foreign. Since I am so heavily influenced by the current project and all of its constraints, it's hard to think about the aspects of it that could exist in other apps. I fear it would leave me with just a set of vanilla data-structures.

96 Comments

@Ben "The part of this whole process that comes back to bite me is often the gathering of data for display "

I feel your pain ... Systems architecture is complex. In my bootstrap description ... model layer 'data-structures' are transitive and dynamic by nature - handling attributes and behaviors responsible for their effective transport is 'The Rub'

I think we can only hope to make good progress in this area ... as perfection is quite illusive ...

96 Comments

Back again ...

Sorry for all the responses ... Got my attention here ... I'd say @Rick and @WMW's view are accurate ...

In this case ... attempting to define both coarse and fine-grained logic and maintaining a separations of concerns is where JPA / Hibernate really shines By designing interfaces that work with data mappers and repositories ... we can define abstract DTO interfaces for both the UI layer and the DA layer without most of the negative issues associated with coupling and design scale.

I'm just getting my feet wet with full-scale application architecture but the benefits of designing model and views through JPA are huge.

15,902 Comments

@Edward,

Hopefully, I'm getting better at it. My understanding is much better than it was even a few months ago, thanks to the current project (letting me experiment and learn and feel pain).

One of the biggest mental hurdles left is understanding / figuring out how to deal with collections and aggregates. For example, going back to the forum type example, imagine that I had to get a list of discussion threads along with the count of new comments available for the currently authenticated user. In SQL, this is a moderately easy query with GROUP'ing or some sort of intermediary table.

BUT, what happens when I have a number of those kinds of queries required by many, slightly different User Interfaces? How do I build that kind variety, with good performance, on top of a domain model.

I've been reading up on CQRS - Command Query Responsibility Separation. From what I've read, this consists of a different database for reading / writing; however, even with a single database, I definitely see very different needs in an application for reading vs. maintaining data integrity. The question is, how to organize those kinds of queries in the set of components in the application.

... still trying to think that one through.

6 Comments

Let's say you want to develop a forum application and sell it. This may be redefining "business logic" but you could go about it like this for pragmatic reasons:

"Business logic should be that which consumers of your application can change and application logic is the fixed part. The controller has to mediate between the two."

Business Logic:
Do new users need to click an activation link to validate their email?

Application Logic:
When you click on an activation link unlock the user and allow logins.

Business Logic 2:
When a user logs in x times incorrectly, lock their account.

Application Logic 2:
Call business logic on failed login. If it returns 'L' then lock the account.
Provide unlocking mechanism.

Business Logic would then be that part of the App which can be customized/overwritten and will (somehow) survive an upgrade.

19 Comments

I often take the approach of business logic typically being objects that are unaware of their surroundings.

Example, I create an object, set some properties for it, and call the doYourThing() method and check for output.

It wouldn't know anything about the UI, or how the data itself is gathered, nor what to do with the data, how to store, etc. It just processes the information according to the business rules requirements.

This way, I can manually test the object however I wished using things like test cases and such to verify the business rules are operating correctly.

Afterwards, I start wrapping/extending the object with application and storage specific code, maybe a layer of validation before the data goes in to the core and as it comes out.

This is all decoupled from the core logic and is theoretically interchangeable.

In coldfusion, I typically do this with a cfc, and then create cfc wrappers that instantiate (or directly call from persistent scope) the object. These wrappers would handle remote webservice calls or ExtJS Direct invocations. They take care of validating the webservice call, validating the incoming xml against schemas before the data makes it to the core, building success and error responses, parsing and creating json responses, etc.

Most often with coldfusion code, I leave DB specific code inside the core as I know what system I'm writing for, otherwise, this is where the ORM stuff would come into play inside the core.

I typically have something like:

/Components/Something/widget.cfc
/Webservices/Something/widget.cfc

The latter processes remote calls, validates against messaging schema, build error response if bad input, calls the former, builds response, validates response against messaging schema, returns response.

A little bit different with my ExtJS Direct stack, but similar idea.

19 Comments

For business logic specific to UI, it can be similar.

Your click button press event wouldn't perform much. I like to have them create pointers to the elements I need to check and pass those in to an object. This way, the dom locations or names can change, but the core business logic doesn't need to.

onChange=doThing();

doThing(){
var in1 = document.getElementById('text1');
var in2 = document.getElementById('text2');

var v = new Validator(in1, in2);
v.validate();
if(!v.success)
{
alert(v.errorMessage);
}
}

15,902 Comments

@Edward,

At first glance, it looks very interesting. I'll have to carve out some more time to go through it and really try to understand it. One thing that I do have a particular interest in is how you organize files. I see in you Java folder, you are making good use of namespaces. This is something that I don't have very much experience with... especially when using Dependency Injection that seems to be powered by component names (without name spaces).

I really appreciate you putting that together! You rock!

15,902 Comments

@Marc,

I think my current understanding of Business Logic is a little bit of the opposite - it's the stuff that *wouldn't* need to be changed from application to application? Not saying I'm right - that's just the way I've been leaning lately.

15,902 Comments

@Jim,

What you're describing sounds a bit like the "Onion Architecture" that I have been reading up on:

http://jeffreypalermo.com/blog/the-onion-architecture-part-1/

It has the "domain core" in the middle; and, then a set of layers that wrap around it. Actually, the Onion Architecture is, in big part, how I finally got to writing this post - the Onion Architecture makes use of "Application Services" and "Domain Services", which sounded good. BUT, I had no idea how to define the type of information that when in each... hence, what the heck is Business Logic :D

I think I'm getting closer.

1 Comments

@Sean,

I found your comment to be very concise and has cleared up some confusion on my own projects. Just this morning I asked myself; is my business logic in the correct place, then I asked myself; what is business logic?

According to your comment ive got all the pieces in the places they should be.

2 Comments

My 2 cents.

Application Logic consumable logic. Change aspects, behavior, input, etc.

In a console application, the application logic is the input params and the output response. In a schedule task, it's the same. The trigger that make the application start and the output, both are Application Logic.

Please note, Consumer does NOT have to be a User.

In a webapi, Application Logic refers to request, response, INPUT validation.

Side note: Validation can and happens at multiple levels of an Application. Some at Application Logic and other not!

So now, what is business logic ? Business Logic is the process that happen under the scene, without notifying a consumer, but the application logic and without getting input from the consumer but the application logic.

That's why business logic can have be shared in multiple applications, and applications shared with multiple consumers. business logic cannot be shared by consumers, because are not consumables.

So, WHERE should business logic be ? That's sounds as a good question. and the answer as I see it is very simple: Anywhere that makes sense.
Spa application can have heavy business logic on the client 'layer' while standard web apps have less.

If you want to do heavy business logic on your client side, you can have SQL-like queries in your Javascript. (see breeze.js for example).

In an application like Entity Framework ORM, the lambda expression like .Where() .Select(), etc are all EF application logic. The actual implementation on how that translates that to a query is EF business logic, because the only consumer is the Application Logic while the Application Logic can have many consumers.

Last words:
If a consumer interacts with an application logic, the application logic *may* call the business logic and interpret the response (if any) from the business logic and then the application logic interacts with the consumer again. It doesn't matter if that 'business logic' is a DLL behind 213432 layers, the same in page Javascript or a store procedure in a DB.

TL;DR;
Business Logic is code that has no consumer but Application Logic.
Application Logic is code that has n consumer(s).

1 Comments

Together with my coleages I had this frustration too. A few years ago we were working on a language (XML) that would be able to describe a domain fully and completely to be able to but all business logic into the domain model.

The idea was to generate UI automatically from the domain model and to reduce the code for the controller as much as possible. Martin F"owler's Patterns of Enterprise Architecture" ans Eric Evan's "Domain Driven Design" were our most important inspirations. I also recommend Vaughn Vernon's "Implementing Domain Driven Design" very highly.

Today we are able to do just that. Have a look at http://sclable.com and if you have any questions I am happy to share our ideas!

all the best,
Roland

1 Comments

There is no spoon. I think this question could be paralleled with similar ideological dualistic conundrums such as where do I end and you begin? Everything bleeds into everything. I don't think there is a finite line to be drawn in the sand that will be universally agreed upon that separates the two in a quantifiable way. The useful function of programming paradigms is what is most important in my opinion. Adopting it should help you not frustrate you.

In this case for me it is useful to think about the data sets I will be working with and how they tie into the real world as business logic. For instance a fulfillment center needs to track orders among many things.

There are many operations on orders but when an order changes there are finite things that occur if its line items change in quantity then the corresponding inventory of its product will decrease. There is no application in the fulfillment industry that would say otherwise.

The result of this business logic is useful to different people in different ways. A customer service representative will be most interested in being able to quickly access order details to answer a clients questions. The owner will want to see profit and loss based on inventory and sales. So that to me is application logic. People can say I am wrong but if it helps me code better than that was the purpose of the contemplation of the ideology from the get go. But is someone had a more useful understanding then it would be worth looking back into it.

My main point is how useful is your definition not how authoritative is its speaker in their tone. That and there is no spoon or right answer. I very much appreciate the conversation your humble and honest tone brought. It is especially impressive coming from a CTO.

I believe in love. I believe in compassion. I believe in human rights. I believe that we can afford to give more of these gifts to the world around us because it costs us nothing to be decent and kind and understanding. And, I want you to know that when you land on this site, you are accepted for who you are, no matter how you identify, what truths you live, or whatever kind of goofy shit makes you feel alive! Rock on with your bad self!
Ben Nadel