Reasons for and against objects handling their own persistence [closed] - c#

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 10 months ago.
Improve this question
I am looking at different options for persistence modelling in Windows Phone using Isolated Storage. One of the ideas I have come up with was the concept of each object handling its own (were it makes sense of course) persistence, rather than making a repository or other such entity for the purpose of saving objects.
I can't seem to find any good information on this method of persistence which leads me to believe I may have stumbled onto an anti pattern of sorts.
Has anyone approached persistence in this manner? If so what are your for's or against's in relation to this approach.

There are several undeniable truths in software development:
A prototype becomes a product before you know it.
An app targetted "just for platform-x" will soon be ported to platform-y.
The data-store will change. Probably as a result of #2.
There are more ( :) ) but these are enough for to answer your question:
Go with a respository so your objects can be tested, know nothing about persistence, and you can swap out data stores (even go over the wire!) Might as well plan for that up-front.

Sounds like you're talking about the Active Record pattern? It works for some folks but there are criticisms against it (mostly from a testability / separation of concerns standpoint).
The biggest issue is that you end up with persistence logic spread out across all your classes. That can quickly lead to bloat, and it also embeds assumptions about your persistence technology all over your codebase. That gets messy if you need to change where or how you store your objects.
Those assumptions also make automated testing more difficult because now you have a persistence layer dependency to work around. You could inject a repository into the object to counteract some of this stuff, but then you're implementing a repository anyway. :) Better to just keep the core classes entirely peristence-ignorant if you can...
On the plus side, it's a simpler pattern for people to grasp and is a quick way to get things done on a lightweight project. If the number of classes is small it could be the quickest way to get from A to B. I still find myself building out separate repositories on small projects however, I just can't stand having persistence stuff mixed in with my business logic.

Cons:
Violates Single Responsibility Principle (SRP)
Hampers testability
Tightly couples you business logic to your database
Pros:
Is simple to implement
Basically, if your data model is flat and simple, and your application requirements are modest, Active Record might be a good choice; however, it starts to break down when your mapping requirements get a bit more complex. More robust ORM patterns like Data Mapper become appropriate in cases like these.

Pros
simplicity
Cons
breaks separation of concerns
tight coupling of business logic with database
makes testing much more difficult
This pretty much boils down to testing becoming much harder, and decreasing the time before you have to do a major refactor in your project.
At the end of the day you need to weigh your goals and concerns for the project and decide if the loss of testing/verifiability/cleaness is worth it to gain a simpler system.
If it's a simple application, you're probably fine to drop the DAL layer, and go for the simpler model. Though if you application has lots of moving parts and is of considerable complexity, I would avoid removing the DAL as you will want to be able to test and verify your code well.

It flies in the face of using a Data Access Layer...not that there's anything wrong with that.

Related

Writing a small C# application for bachelor thesis - Should I use MVC-Pattern? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I am currently writing my bachelor thesis about process optimization for creation of XML rendering Stylesheets for another application.
Therefore I am writing a very small and super basic software tool which displays XML structures in tree views. It enables the user to change those (add and delete nodes) and to do some simple application specific stuff.
For doing that, I use Windows Forms.
My question is if I should use a specific architecture or design pattern like MVC or if it would be sufficient to only stick to basic patterns like factory method, command, observer etc.
I am afraid that MVC would be overkill. But on the other hand I am afraid that I should make use of it as it is for a thesis...
The tool should only run on desktop. I don't think there will be any update after initial development.
Hoping for some toughs...
Most answers here will involve opinion. I lean towards suggesting you don't worry too much, but rather try writing it in a way that makes sense to you then once you've got it working, take a look at whether there are any patterns out there that would improve your implementation.
Many of these patterns only make sense once you hit a certain scale with your program.
I'll add that WinForms has its own way of working that pre-dates much of modern MVC. You can shoe-horn it in, but it's not going to feel totally natural. This also factors into my suggestion that you first get your solution working, then explore options to tidy it up.
WPF might be a better fit for the kind of application you're building (HierarchicalDataTemplate), but the learning curve for WPF is very steep.
Of course if the people grading your work are looking for usage of patterns, then that's a different thing.
Good luck!
There are arguably two primary reasons for using a specific design pattern in this context:
You feel it it makes it easier for you to develop and maintain the code base (this is the main reason for using a design pattern in any context).
You feel it would reflect well on you and potentially improve your grade.
Regarding the first point, I assume the code you are writing is not a long term project. There are some exceptions to this rule (for example this one), but in general most thesis project codebases aren't maintained as long term software projects, even if concepts from them are re-used.
Regarding the second point, if you feel you can easily integrate the design pattern without writing more plumbing code for it than the code you are writing for your thesis, then it may help you express your concepts more clearly. However, if you feel it will be a larger distraction, and that you can build a high quality codebase without it, I would avoid being so opinionated, especially on a research project where the concept between inception and completion could change so drastically, and your professor may not care for "over-engineering".
If you have time, I would say the best thing to do is get the thing working first, and then decide if you could get value out of refactoring it into a specific design pattern.

Repository Pattern or not? ORM needed? MVC Web api REST [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am pretty new to building restful web api's but I have been doing a lot of studying and have a strong understanding of the basics. I have built a service for my company using the latest best practices of web api 2. Attribute routing and route prefixes, dependency injection, and more. I think my service is pretty solid, but there is a possible need of a refactor.
My company is considering moving away from MS SQL to PostGreSql or possibly a different database solution. Also, I should mention that we do not use EF or any other ORM. The reason for us not using EF is because our DB schema is constantly changing and we have numerous environments that are often different from each other(dev, qa, prod, etc). So we have developed our own framework to handle our queries to the databases. We use stored procedures pretty regularly to retrieve data.
So, changing my service to accommodate a different DB, it seems that a repository pattern would be the solution. However, when I start researching into it, it feels like we are adding a lot of overhead code when in fact, it might be less code to write to just go back and refactor the service if the DB change actually happens. For each of my controllers I would need to write a IModelRepository and ModelRepository class at the least.
Can anyone provide any guidance on this?
Edit:
I'm not really sure how to make this question less broad. I don't know enough about repository patterns to be more detailed in my question. I basically, just wanted to know if repository pattern is the solution to the issue of possibly changing DB solutions in the future in a web api MVC service even if I am not using an ORM like entity framework?
I ask because every example I find online seems to use EF which makes it hard to relate to my current issue. However, the top answer gives a really good explanation and I think my question is answered. I just need to find a good resource to learn the pattern from. Thanks.
Repository pattern tries to avoid tight coupling of your domain with data-mapping layer (or just call it data layer), which is occasionally dependent to underlying data technology of choice.
While you might feel that's useless in your concrete use case, I'll try to convince you with a very simple argument: data-access details will be enforced in your repositories and this means that your data strategy will be self-contained there. In other words: your domain will remain agnostic to data-access approach, and you won't need to change thousands and thousands of code lines if you need to change this in the future.
Conclusion: even in your scenario repository pattern is useful. Leave your domain code to just solve domain issues rather than mixing everything in a true spaguetti code!
The inversion of control story...
When repository pattern meets inversion of control everything gets more powerful, since you can switch how your domain translate to data by configuration, and you enforce even more loose coupling and and separation of concerns.
Beat this ;)
Not using EF seems to be the mistake. EF would be the repository that abstracts away the database to a large extent. You want to be able to target different database products. EF is good at that.
Introduce Entity Framework to solve the problem.

approaches to organise event handling with increasing software complexity

I am trying to use the Model View Presenter (MVP) pattern for a software that I am writing. I am using C# and Windows Forms, althought that should not matter for answering my question.
I have multiple "MVP-structures". One, for example, is handling retained mode graphics where I can draw geometric shapes on a canvas. Another one is taking these shapes, doing some analysis on them and putting the result somewhere else. There are potentially many events that cause controllers to manipulate data somewhere which then causes cascading manipulation of data in yet another place and so forth.
My fear is that I will eventually loose track of what is changing what if I do not organise my software properly. I can think of two ways to organise the interactions between programm parts occuring in my software: either hierarchical or switch board-like.
My question is: Are there any well known approaches or patterns, that I should look up to organise my software? I would need a starting point for my web search.
I think your intuition is right. If you create many events that cascade you are going to end in trouble. I've seen many times over-complex applications due to out of control eventing. This makes the code very difficult to debug and improve.
First thing it came to my mind was the mediator pattern. Elaborating a bit more I would have central classes that manage parts of the business logic. I would have the model in each of the MVP lightweight , basically being a client that asks the server (one of this controller classes) for more complicated business logic. The idea is to have every model of the MVP classes interacting with as few classes as possible (core business logic) and avoid interacting with other MVPs (which will have more specific business logic)
In any case I would limit as much as possible the classes that throw and listen to events and would centralize this in as few places as possible. The observer pattern can help here. Also having a client-server architecture with a service layer containing the heavy business logic can help making this decoupled and maintanable in the future.
The pattern service layer from the fowler classic "patterns of enterprise application architecture" could be good reading too.

Test Driven Design and Layered architecture [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
How to apply TDD over enterprise application that has layered architecture?
I want to know how to apply TDD to an application that has following
WPF application (6-7 screens)
3-4 Modules (Prism modules)
Some application services (Logging, Exception Handling, Security, Authorization, Core Business services library)
Data Access Layer (using Entity Framework)
A bunch of WCF services
As I understand, first thing is to get the architecture right. As a result, Components are identified.
Next is to develop the components independently, where I stuck.
With TDD, design (of a component) evolves with time. For a component following is the way (I perceive) to go with TDD
Identify all use cases
Identify all test cases
For each test case, write all scenario, and for each scenario, write a failing test case. Make little code, so that test case is passed. Add to list, if new scenario is found
Follow Red-Green-Refactor until all the test cases (corresponding to all scenario) are passed
In the refactoring, dont forget DRY, YAGNI, Mocking, DI, etc,etc.
End result is well designed Component (how much well designed depends on experience and skills of developer).
Problem i face is, For a component, until i reach to Step 6 of TDD process, i donot know the interfaces. Since there are multiple components, multiple teams, No body is sure what they will come up with.
Now the summary Questions based on above scenario
Is there some basics that I am missing? Please point me to appropriate resources if yes.
How to apply TDD over layered architecture?
How to do parallel development of multiple components
Best practices for TDD with WPF UI (PRISM)
Best practices for TDD with Database (using Entity Framework)
How to decide WCF service contract, when using TDD?
I think you have the order wrong. You're choosing the architecture, then trying to get there with TDD. The idea behind TDD is to start w/ nothing, and arrive at an layered architecture if it's needed.
Of course, that probably doesn't help when you're looking at a very large project, because there has to be some organization to it all. My usual approach is to try to divide the work into something that makes sense to real people (not programmers). And no, I'm not really talking full Domain Driven Design. I'm referring to just thinking of the different pieces as an outsider would.
For example, if I want to make a program that represents a cash register (something that can hold money and figure totals).
What's the first thing I want it to do? Hold and dispense money. So, I need a drawer (first component, give it to a team). I need a button to open it (second component, second team), etc... The key is to focus on what it should do, not how it should do it.
Yes, there's a lot of contract/protocol talks that have to happen. Those are things the teams involved will have to work out as they hit the problem. The key is to focus on what you want it to do. Solve the now problem. Don't pre-optimize. You'll probably find that not all of the components require all of the layers.
The short answer to the best practices questions is "it depends." (The cheesy, common, and overused IT answer.) The general rules are you want to focus on behavior, not implementation. Ensure you can trust the tests (they produces the correct results all the time). Make sure you test as much as is possible... Or, numbered...
Start with tests, not design. Roy Osherove and others have a tons of writings on the subject. His book, along w/ Micheal Feathers are the best place to start.
If you start w/ tests, and the layers evolve as you fulfill more tests, you wind up with TDD over a layered architecture.
Divide them in a way that makes sense. My rule is to stick to what makes sense in the real world. Engine team gets the engine, tire team gets the tire. Make sure people communicate.
I don't use PRISM.
I don't use EF, but can say that database testing is a whole can of worms. Integration testing involves a lot of environmental configuration and such. Ayende has quite a few blog posts on this.
Danger Will Robinson. What makes you so sure you need a WCF service contract?
Sorry if this was really vague. Google the names I dropped, they're good places to start. If you want a leg up on TDD, hire a couple experienced coders and use pair programming. If you can't afford that, hire someone to come in and do some training, then do pair programming. Can't do that? Get some books and use pair programming.
Then, beat the pairs to ensure they're writing tests first.
At the end of the day, it's about deciding what you want something to do, then letting the tests evolve the architecture. Not the other way around.
I think that you are going in the right direction with all of your plans so far. What I advise is that you spend just enough time on upfront design so that you DO have the interfaces between each layer defined. It's simply impractical to start doing any development (let alone TDD) without it. Once the interfaces are agreed upon by all teams, you can then easily transition to TDD by using mock objects to implement the interfaces. There are many well established mocking frameworks available, such as Rhino Mocks. The idea of creating the interfaces upfront may be easier said than done, and you will undoubtedly end up having to make changes along the way. But you need to have a starting point. This is sort of challenge is exactly where a Component Model Diagram becomes useful. By having the teams work together to create this upfront, you won't be able to predict the final interfaces exactly, but you will get the high level details hammered out which will help avoid earth-shattering refactorings later in the project.
Also, I would give special consideration to your database layer. This is a debatable topic worthy of it's own separate discussion. Using EF you will find that you cannot simply "mock out" the entire layer. You would have to create a whole separate abstraction on TOP of EF to do so. Doing so may add unnecessary complexity to your application. You should consider very carefully if this is required - if you can just populate a test database with test data, there's no reason not to let your automated tests directly call the database.

Linq to SQL ORM 3-layer question

I am designing this HR System (desktop-based) for a mid-size organization. The thing is I have all the tables designed and was planning on using the O/RM in VS2008 to generate the entity classes (this is the first time I work with OR/M; in fact, this is my first "big" project.) I wanted to make the app with 3 layers (one of the programmers of the company suggested not 3 but 4 or 5 layers) but after reading quite a lot of blog entries and a lot of questions here I've realized that is not quite easy to do that with LINQ to SQL because of how the datacontext works and how difficult it is to pass objects between layers using LINQ to SQL.
Probably I'll just use the entity classes generated by the VS2008 ORM and add any validation and bussines logic in partial classes. But that would be 2 layers, or not? The app will be used by like 10 users, so I don't think the 2 layer approach is a big issue for now.
In the future, a web-based front-end will be developed so candidates can apply to jobs online. I want to develop it as scalable as possible. But the truth is I don't have a lot of time to waste to make a decision, times running up hehe.
Having said all that, should I just use the entities generated by the VS2008 ORM?
So any suggestion or idea would be greatly appreciated. Thanks.
You're chewing over quite a lot with your line of questioning here. (Is there a concrete question hidden in there somewhere?)
With layers, I assume you mean physical boundaries, i.e. application, app/SOA/WCF server, data layer that lives on the SOA server, and a database somewhere.
Designing for the future might seem like a good idea, but DO make sure that there WILL be a need for all those layers somewhere down the line. Essentially, you do not need a WCF/SOA based approach if you're not exposing your application over the internet at some point. A web frontend can solve the same problem in many cases.
I'm not saying you will not need those layers at all, but you might not. If you really do, seams are your friend. You need to make "cut points" where you can define your boundaries. I commonly use the repository pattern to diversify data access methodologies, and use plain objects (POCO) and interfaces that are persisted via technologies such as NHibernate. Using POCOs also makes it MUCH easier to transfer those objects over the wire at a later point, either standalone or part of messages.
Creating service interfaces that are called can solidify your boundaries. When you are ready to move cross-machine/physical boundaries, you simply create your boundaries in the service implementations.
It sure sounds like a dangerous way to go - creating the tables first, then domain and finally GUI.
I must admit I am no expert on ORM expert but the generated classes I´ve seen looks more like dataobjects than classes. I would say you need another layer to stop all logic to end up in the GUI ).

Categories

Resources