<p>Say you have an application divided into 3-tiers: GUI, business logic, and data access. In your business logic layer you have described your business objects: getters, setters, accessors, and so on... you get the idea. The interface to the business logic layer guarantees safe usage of the business logic, so all the methods and accessors you call will validate input. </p>

<p>This great when you first write the UI code, because you have a neatly defined interface that you can trust.</p>

<p>But here comes the tricky part, when you start writing the data access layer, the interface to the business logic does not accommodate your needs. You need to have more accessors and getters to set fields which are/used to be hidden. Now you are forced to erode the interface of your business logic; now it is possible set fields from the UI layer, which the UI layer has no business setting. </p>

<p>Because of the changes needed for the data access layer, the interface to the business logic has eroded to the point where it is possible to even set the business logic with invalid data. Thus, the interface does not guarantee safe usage anymore.</p>

<p>I hope I explained the problem clearly enough. How do you prevent interface eroding, maintain information hiding and encapsulation, and yet still accommodate different interface needs among different layers? </p>

[{'answer_id': 9250, 'author': 'Lars Mæhlum', 'author_id': 960, 'author_profile': 'https://Stackoverflow.com/users/960', 'pm_score': 0, 'selected': False, 'text': '<p>I always create a separate assembly that contains:  </p>\n\n<ul>\n<li>A lot of small Interfaces (think ICreateRepository, IReadRepository, IReadListRepsitory.. the list goes on and most of them relies heavily on generics)  </li>\n<li>A lot of concrete Interfaces, like an IPersonRepository, that inherits from IReadRepository, you get the point..<br>\nAnything you cannot describe with just the smaller interfaces, you put into the concrete interface.<br>\nAs long as you use the IPersonRepository to declare your object, you get a clean, consistent interface to work with. But the kicker is, you can also make a class that takes f.x. a ICreateRepository in its constructor, so the code will end up being very easy to do some really funky stuff with. There are also interfaces for the Services in the business tier here.</li>\n<li>At last i stick all the domain objects into the extra assembly, just to make the code base itself a bit cleaner and more loosely coupled. These objects dont have any logic, they are just a common way to describe the data for all 3+ layers.</li>\n</ul>\n\n<p>Btw. Why would you define methods in the business logic tier to accommodate the data tier?<br>\nThe data tier should have no reason to even know there is a business tier..</p>\n'}, {'answer_id': 9251, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>It could be a solution, as it would not erode the interface. I guess you could have a class like this:</p>\n\n<pre><code>public class BusinessObjectRecord : BusinessObject\n{\n}\n</code></pre>\n'}, {'answer_id': 9257, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>What do you mean by that the data tier should not be aware of the business logic tier? How would you fill an business object with data?</p>\n\n<p>I often do this:</p>\n\n<pre><code>namespace Data\n{\n    public class BusinessObjectDataManager\n    {\n         public void SaveObject(BusinessObject object)\n         {\n                // Exec stored procedure\n         {\n    }\n}\n</code></pre>\n'}, {'answer_id': 9258, 'author': 'Dan', 'author_id': 230, 'author_profile': 'https://Stackoverflow.com/users/230', 'pm_score': 3, 'selected': False, 'text': '<p>This is a classic problem - separating your domain model from your database model. There are several ways to attack it, it really depends on the size of your project in my opinion. You could use the repository pattern as others have said. If you are using .net or java you could use <a href="http://www.hibernate.org/343.html" rel="nofollow noreferrer">NHibernate</a> or <a href="http://www.hibernate.org/" rel="nofollow noreferrer">Hibernate</a>. </p>\n\n<p>What I do is use <a href="http://en.wikipedia.org/wiki/Test-driven_development" rel="nofollow noreferrer">Test Driven Development</a> so I write my UI and Model layers first and the Data layer is mocked, so the UI and model is build around domain specific objects, then later I map these object to what ever technology I\'m using the the Data Layer. Is a very bad idea to let the database determine the design of your app, write the app first and think about the data later.</p>\n\n<p>ps the title of the question is a little mis-leading</p>\n'}, {'answer_id': 9264, 'author': 'Lars Mæhlum', 'author_id': 960, 'author_profile': 'https://Stackoverflow.com/users/960', 'pm_score': 1, 'selected': False, 'text': '<p>@Ice^^Heat:</p>\n\n<blockquote>\n  <p>What do you mean by that the data tier should not be aware of the business logic tier? How would you fill an business object with data?</p>\n</blockquote>\n\n<p>The UI asks the ServiceClass in the business tier for a service, namely getting a list of objects filtered by an object with the needed parameter data.<br>\nThen the ServiceClass creates an instance of one of the repository classes in the data tier, and calls the GetList(ParameterType filters).<br>\nThen the data tier accesses the database, pulls up the data, and maps it to the common format defined in the "domain" assembly.<br>\nThe BL has no more work to do with this data, so it outputs it to the UI.</p>\n\n<p>Then the UI wants to edit Item X. It sends the item (or business object) to the service in the Business Tier. The business tier validates the object, and if it is OK, it sends it to the data tier for storage.</p>\n\n<p>The UI knows the service in the business tier which again knows about the data tier.</p>\n\n<p>The UI is responsible for mapping the users data input to and from the objects, and the data tier is responsible for mapping the data in the db to and from the objects. The Business tier stays purely business. :)</p>\n'}, {'answer_id': 9277, 'author': 'Derek Park', 'author_id': 872, 'author_profile': 'https://Stackoverflow.com/users/872', 'pm_score': 0, 'selected': False, 'text': "<p>So the problem is that the business layer needs to expose more functionality to the data layer, and adding this functionality means exposing too much to the UI layer?  If I'm understanding your problem correctly, it sounds like you're trying to satisfy too much with a single interface, and that's just causing it to become cluttered.  Why not have two interfaces into the business layer?  One would be a simple, safe interface for the UI layer.  The other would be a lower-level interface for the data layer.</p>\n\n<p>You can apply this two-interface approach to any objects which need to be passed to both the UI and the data layers, too.</p>\n\n<pre><code>public class BusinessLayer : ISimpleBusiness\n{}\n\npublic class Some3LayerObject : ISimpleSome3LayerObject\n{}\n</code></pre>\n"}, {'answer_id': 9369, 'author': 'Jon Limjap', 'author_id': 372, 'author_profile': 'https://Stackoverflow.com/users/372', 'pm_score': 0, 'selected': False, 'text': '<p>You may want to split your interfaces into two types, namely:</p>\n\n<ul>\n<li>View interfaces -- which are interfaces that specify your interactions with your UI, and</li>\n<li>Data interfaces -- which are interfaces that will allow you to specify interactions with your data</li>\n</ul>\n\n<p>It is possible to inherit and implement both set of interfaces such that:</p>\n\n<pre><code>public class BusinessObject : IView, IData\n</code></pre>\n\n<p>This way, in your data layer you only need to see the interface implementation of IData, while in your UI you only need to see the interface implementation of IView.</p>\n\n<p>Another strategy you might want to use is to compose your objects in the UI or Data layers such that they are merely consumed by these layers, e.g.,</p>\n\n<pre><code>public class BusinessObject : DomainObject\n\npublic class ViewManager&lt;T&gt; where T : DomainObject\n\npublic class DataManager&lt;T&gt; where T : DomainObject\n</code></pre>\n\n<p>This in turn allows your business object to remain ignorant of both the UI/View layer and the data layer.</p>\n'}, {'answer_id': 9502, 'author': 'Wheelie', 'author_id': 1131, 'author_profile': 'https://Stackoverflow.com/users/1131', 'pm_score': 4, 'selected': True, 'text': '<p>If I understand the question correctly, you\'ve created a domain model and you would like to write an object-relational mapper to map between records in your database and your domain objects. However, you\'re concerned about polluting your domain model with the \'plumbing\' code that would be necessary to read and write to your object\'s fields.</p>\n\n<p>Taking a step back, you essentially have two choices of where to put your data mapping code - within the domain class itself or in an external mapping class.\nThe first option is often called the Active Record pattern and has the advantage that each object knows how to persist itself and has sufficient access to its internal structure to allow it to perform the mapping without needing to expose non-business related fields.</p>\n\n<p>E.g</p>\n\n<pre><code>public class User\n{\n    private string name;\n    private AccountStatus status;\n\n    private User()\n    {\n    }\n\n    public string Name\n    {\n        get { return name; }\n        set { name = value; }\n    }\n\n    public AccountStatus Status\n    {\n        get { return status; }\n    }\n\n    public void Activate()\n    {\n        status = AccountStatus.Active;\n    }\n\n    public void Suspend()\n    {\n        status = AccountStatus.Suspended;\n    }\n\n    public static User GetById(int id)\n    {\n        User fetchedUser = new User();\n\n        // Lots of database and error-checking code\n        // omitted for clarity\n        // ...\n\n        fetchedUser.name = (string) reader["Name"];\n        fetchedUser.status = (int)reader["statusCode"] == 0 ? AccountStatus.Suspended : AccountStatus.Active;\n\n        return fetchedUser;\n    }\n\n    public static void Save(User user)\n    {\n        // Code to save User\'s internal structure to database\n        // ...\n    }\n}\n</code></pre>\n\n<p>In this example, we have an object that represents a User with a Name and an AccountStatus. We don\'t want to allow the Status to be set directly, perhaps because we want to check that the change is a valid status transition, so we don\'t have a setter. Fortunately, the mapping code in the GetById and Save static methods have full access to the object\'s name and status fields.</p>\n\n<p>The second option is to have a second class that is responsible for the mapping. This has the advantage of seperating out the different concerns of business logic and persistence which can allow your design to be more testable and flexible. The challenge with this method is how to expose the name and status fields to the external class. Some options are:\n  1. Use reflection (which has no qualms about digging deep into your object\'s private parts)\n  2. Provide specially-named, public setters (e.g. prefix them with the word \'Private\') and hope no one uses them accidentally\n  3. If your language suports it, make the setters internal but grant your data mapper module access. E.g. use the InternalsVisibleToAttribute in .NET 2.0 onwards or friend functions in C++</p>\n\n<p>For more information, I\'d recommend Martin Fowler\'s classic book \'Patterns of Enterprise Architecture\'</p>\n\n<p>However, as a word of warning, before going down the path of writing your own mappers I\'d strongly recommend looking at using a 3rd-party object relational mapper (ORM) tool such as nHibernate or Microsoft\'s Entity Framework. I\'ve worked on four different projects where, for various reasons, we wrote our own mapper and it is very easy to waste a lot of time maintaining and extending the mapper instead of writing code that provides end user value. I\'ve used nHibernate on one project so far and, although it has quite a steep learning curve initially, the investment you put in early on pays off considerably.</p>\n'}, {'answer_id': 10448, 'author': 'Eric Z Beard', 'author_id': 1219, 'author_profile': 'https://Stackoverflow.com/users/1219', 'pm_score': 0, 'selected': False, 'text': '<p>I\'m going to continue my habit of going against the grain and say that you should question why you are building all these horribly complex object layers.</p>\n\n<p>I think many developers think of the database as a simple persistence layer for their objects, and are only concerned with the CRUD operations that those objects need.  Too much effort is being put into the "impedence mismatch" between object and relational models.  Here\'s an idea: stop trying.</p>\n\n<p>Write stored procedures to encapsulate your data.  Use results sets, DataSet, DataTable, SqlCommand (or the java/php/whatever equivalent) as needed from code to interact with the database.  You don\'t need those objects.  An excellent example is embedding a SqlDataSource into a .ASPX page.</p>\n\n<p>You shouldn\'t try to hide your data from anyone.  Developers need to understand exactly how and when they are interacting with the physical data store.</p>\n\n<p>Object-relational mappers are the devil.  Stop using them.</p>\n\n<p>Building enterprise applications is often an exercise in managing complexity.  You have to keep things as simple as possible, or you will have an absolutely un-maintainable system.  If you are willing to allow some coupling (which is inherent in any application anyway), you can do away with both your business logic layer and your data access layer (replacing them with stored procedures), and you won\'t need any of those interfaces.</p>\n'}]
['https://Stackoverflow.com/questions/9240', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']