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 9 years ago.
Improve this question
I am designing a C# ASP.Net web application that uses a lot of common functionality and the right way to deal with that seems to be through inheritence. I plan to make a base class (Person) and the inherit it in other classes like Employee and Vendor, and then in turn inherit Employee with Manager, etc. That way I don't have to define common properties such as FirstName, LastName, PhoneNumber, etc. on each one of them.
The second part of the questions is this: If I use inheritence and use Entity Framework's CodeFirst entities, will they understand the inheritence? How will the data be stored in the tables? Will each table have a FirstName and LastName column, or is EF smart enough to make them a common table?
I am really hoping someone who is a REAL object oriented programmer out there can help me clear this up. I have gotten a lot of conficting information and I need someone with actual experience on EF projects to give me some guidance. Am I understanding inheritence right? If not, what am I getting wrong? Any help is appreciated.
Thanks,
Bert
This is not an easy question, but for most cases it's better to choose composition instead of inheritance. You should not derive cash dispenser from calculator just because calculator has display and keyboard properties. It's ridiculous.
But sometimes inheritance makes sense. Ask yourself, should those classes have 'is a' relationship? As I see your task, it's better to make Vendor and Employee to be independent classes, both have Person property. And derive Manager from Employee.
Nevertheless keep depth of inheritance as little as possible. Deep hierarchies are pain to debug and understand, especially if there are many method overrides.
For more inspiration about the topic have a look at Chad Myers blogpost.
From an object-oriented perspective, the problem with that approach is when a person becomes a manager, a employee, a vendor or all of them. In some latin languages we have to forms for the verb to be (ser/estar). The former refers to the nature of the being and later to the state. It is better to use isA for inheritances when refers to the nature of the being rather than its state. In your case, I would recommend using roles. A person has many roles. Manager is Role (Manager inherits from Role), Employee is Role, etc. This way, you can reuse your person attributes and you can add and remove roles of a person.
First 1: Sounds good. But make sure that an "is a"-relation is given. Do not derive Person from Address just to include the Address-specific properties - use EF complex types for this kind of reuse.
One issue that comes to my mind: Are you sure that Vendor is a sub type of Person?
More on that: make sure that you stay within "one domain" with your inheritance. As Vinny posted in another possible answer, if the same Person could be Manager AND CustomerContact and both inherit from Person you run into a problem. However, if managers and customer contacts are not within the same domain it is probably better to add the person data twice - maybe the same person wants to have you different contact data as manager than as customer contact.
Part 2: You can choose what EF generates:
http://www.entityframeworktutorial.net/code-first/inheritance-strategy-in-code-first.aspx
Related
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 6 days ago.
Improve this question
Context:
I am writing a web application using SQL server database, C# MVC API layer, Next (React) front end. The database is already created and populated and is in full Third Normal Form (3NF) and the base entity classes have been autogenerated from the database, so using a database-first modelling approach. This will seem like a bit of a rant, but I want to know if I am approacing this correctly because it feels like an awful lot of boiler plate code but this may just be because my project is not big enough to reap the benefits.
These aren't my tables but the relationship is the same; namely 1:many relationships with a primary key of ParentTable.id and foreign key of ChildTable.ParentTable_id
Consider a system with 4 tables: Store, Customer, Order, OrderLine. Each customer belongs to only one store and each order belongs to only 1 customer. The base models have their respective links (1 Parent => N Children) and Inverse Link (1 Child => 1 Parent). When you call the .../api/store it doesn't contain any customers by default. If you modify the controller
_context.Stores.Include("Customers").ToListAsync()
This throws an error when returning it as JSON because of the cyclic link so I need to create ViewModels for both the Customer (exluding the Stores model, but just keeping the storeID) and for the Store (including the collection of CustomerViewModel). This is fine while this is the only VM I need for customer or store but what if I also need a customer view model that includes the orders, or a viewmodel for the marketing team and a different one for the finance team. What options do I have? I am thinking either different model names within the same namespace
StoreCustomerViewModel
FinanceCustomerViewModel
MarketingCustomerViewModel
or using namespaces
using ...models.finance -> CustomerViewModel
using ...models.marketing -> CustomerViewModel
Or am I thinking about this the wrong way? If I need to combine models (e.g. where the main model contains a collection of other models - Customer.orders = List-OrdersViewModel) can these cut across namespaces and if so how and what are the caveats around that.
I'm not sure but once I stumbled upon a similar problem (Eager Loading).
Some advised to use [JsonIgnore] above the properties I don't want.
others advised to add UseLazyLoading() in my program.cs
But what really worked for me was creating DTOs and using AutoMapper.
So try out each option and see what works for your project.
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 3 years ago.
Improve this question
I have different product types that have different attributes. They cannot be stored in a single table as the attributes are too distinct. There's a couple of options I'm currently looking at: EAV and a table for each type.
My situation is, at the moment, there are only a number of types (lets say 8) but in the near future with almost 100% certainty, this can grow. But the growth is controlled by me, its not defined by users. It will be up to me to grow the product type.
I'm currently inclined to use EAV (for the reason that I can cover the growth easily - I think) but I am not sure as I'm concerned with the performance as well as modeling them in my language of choice (C#). My question is, given the scenario above, is it better for me to create a single table for each product type and add as necessary, or would this be a good case (or not even good, lets say acceptable) to use EAV?
There's no short good or bad answer to this concern, because it depends of many things.
Do you have a lot of product types ?
How do you think each of them will evolve (think to what will happen when you will add new fields to products) ?
Do you need to handle "variants" of the products ?
Do you intend to add entirely new types of products ?
Etc.
EAV is probably a good way to go if you answer if you answer "yes" to some or all these questions.
Regarding C#, I have implemented in the past an EAV data catalog with it, and using Entity Framework over SQL Server (so a RDBMS).
It worked nice to me.
But if you need to handle a lot of products, performance can quickly become an issue. You could also look for a "NoSQL" solution, did you think about it ?
Just keep in mind that your model object does not have to match your data model.
For example you could perfectly have a stronly typed object for each type of product if you need so.
Much depends on the operations that will be performed on entities. If you will:
often add new attributes to products;
add a lot of products type;
implement full product type search (or other "full product type" feature);
I recommend you to use EAV.
I have implemented in the past EAV data structure with ADO.NET and MS SQL and don't have any problem with performance.
Also, Morten Bork above recommend use "sub types". But if you want implement some "full product type" features, I think it will be more difficult then use pure EAV model.
EAV doesn't really play well with a relational database. So if that is what you are doing. (IE connecting to SQL) Then I would say no. Take the hit in development time, and design a table pr type of product, or make a aggregate table that holds various properties for a product type, and then connect the properties to the relevant tables.
So if a product contains "Cogs" then you have a table with "teethcount", "radius" etc.
Another product type has "Scews" with properties "Length", "riling" etc.
And if a product type has both cogs and screws, it merely has relation to each of these subtypes.
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 9 years ago.
Improve this question
Before down-voting let me explain my question. I have a little experience in designing architectures and try to progress. Ones, when I was fixing a bug, I came up with a conclusion that we need to make our private method to be public and than use it. That was the fastest way to make my job done, and have a bug fixed. I went to my team-leader and said it. After I've got a grimace from him, I was explained that every public method is a very expensive pleasure. I was told that every public method should be supported throughout the lifetime of a project. And much more..
I was wondering. Indeed! Why it wasn't so clearly when I was looking in the code. It wasn't also so evidently when I designed my own architectures. I remember my thoughts about it:
Ahh, I will leave this method public, who knows, maybe it will come usefull when the system grows.
I was confused, and thought that I made scaleable systems, but in fact got tons of garbage in my interfaces.
My question:
How can you explain to yourself if a method is really important and worthy to be public? Are any counterexamples for checking it? How you get trained to make private/public choise without spending hours in astral?
I suggest you read up on YAGNI http://c2.com/cgi/wiki?YouArentGonnaNeedIt
You should write code to suit actual requirements because writing code to suit imagined requirements leads to bloated code which is harder to maintain.
My favourite quote
Perfection is achieved, not when there is nothing more to add, but
when there is nothing left to take away.
-- Antoine de Saint-Exupery French writer (1900 - 1944)
This question need a deep and thorough discussion on OOP design, but my simple answer is anything with public visibility can be used by other classes. Hence if you're not building method for others to use, do not make it public.
One pitfall of unecessarily making private method public is when other classes did use it, it makes it harder for you to refactor / change the method, you have to maintain the downstream (think if this happen to hundreds of classes)
But nevertheless maybe this discussion will never end. You should spend more time reading OOP design pattern books, it will give you heaps more idea
There are a few questions you can ask yourself about the domain in which the object exists:
Does this member (method, property, etc.) need to be accessed by other objects?
Do other objects have any business accessing this member?
Encapsulation is often referred to as "data hiding" or "hiding members" which I believe leads to a lot of confusion. Inexperienced developers would rightfully ask, "Why would I want to hide anything from the rest of my code? If it's there, I should be able to use it. It's my code after all."
And while I'm not really convinced with the way in which your team leader worded his response, he has a very good point. When you have too many connection points between your objects, you end up with too many connections. Objects become more and more tightly coupled and fuse into one big unsupportable mess.
Clearly and strictly maintaining a separation of concerns throughout the architecture can significantly help prevent this. When you design your objects, think in terms of what their public interfaces would look like. What kind of outwardly-visible attributes and functionality would they have? Anything which wouldn't reasonably be expected as part of that functionality shouldn't be public.
For example, consider an object called a Customer. You would reasonably expect some attributes which describe a Customer, such as:
Name
Address
Phone Number
List of orders processed
etc.
You might also expect some functionality available:
Process Payment
Hold all Orders
etc.
Suppose you also have some technical considerations within that Customer. For example, maybe the methods on the Customer object directly access the database via a class-level connection object. Should that connection object be public? Well, in the real world, a customer doesn't have a database connection associated with it. So, clearly, no it should not be public. It's an internal implementation concern which isn't part of the outwardly-visible interface for a Customer.
This is a pretty obvious example, of course, but illustrates the point. Whenever you expose a public member, you add to the outwardly-visible "contract" of functionality for that object. What if you need to replace that object with another one which satisfies the same contract? In the above example, suppose you wanted to create a version of the system which stores data in XML files instead of a database. If other objects outside of the Customer are using its public database connection, that's a problem. You'd have to change a lot more about the overall design than just the internal implementation of the Customer.
As a general rule it's usually best to prefer the strictest member visibilities first and open them up as needed. Combine that guideline with an approach of thinking of your objects in terms of what real-world entities they represent and what functionality would be visible on those entities and you should be able to determine the correct course of action for any given situation.
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 4 years ago.
Improve this question
I would like to build some sort of survey/ auditing software.
I am brainstorming how to build my classes and if there is a design pattern that could support me. Because ther must be something that makes life eaysier...
My application should have questions which contains a title and a description.
And then I have multiple types of answers.
So... one type could be a yes/no answer
Another type could be a value between 1 and 10.
Another type could free text answer
Another type could be a three given text choices where you can select one (The dinner was excellent, good, nod bad)
So on the survey planning site I would write down my questions and assign answer types.
And on executing the survey I want to tread it like a collection of questions with an answer...
Basically the question is how to unify all the different answer types and how to store them in the database?
I looked at composite and strategy pattern but I am not sure...
and I know there is not perfect solution and it always depends...
But it would be great if someone can share best practice on how they dealed with similar topics...
Thanks in advance...
What you seem to be asking here is what are the different entity mapping strategies that are available to you in the database? In short you can have:
a table per entity
a single table for all entities with a discriminator value to identify each one (values could be just a tokenized string for example) - essentially a big Map
a table per entity with 1:1 join for optional properties
Your ORM solution then reads the data back from the database and turns it into the appropriate type of object (the entity) populating the fields as it goes.
In terms of the middle tier, you will need the following classes:
AbstractQuestion
An abstract base class for questions. Containing title, description and abstract ask() and answer() methods. There will be a variety of subclasses for AbstractQuestion that provide different display messages depending on the type of question. For example, MultiChoiceQuestion will implement the ask() method in such a way that the title and description get displayed (you could pull this up into the AbstractQuestion ask() method) along with all the choices available (which is specific to each subclass). This could be generalised so that ask() takes a Map as a parameter which can be populated with anything you like. Or you could use varargs - whatever.
Answer
Just a simple class containing a Map with known keys representing the different aspects of the answer with a reference to the owning AbstractQuestion.
Questionaire
A collection of AbstractQuestions arranged in a list. For each AbstractQuestion call the ask() method, wait for user input, then call the answer() method with the provided data.
No need for complex design patterns, unless you count abstract base classes as a pattern. The above is not complete, but it should be enough to get you started.
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 5 years ago.
Improve this question
I'm wondering whether it's insane to (almost) always use custom data types in C# rather than relying on built in types such as System.Int32 and System.String.
For instance, to represent a persons First name, the idea is to use a data type called PersonFirstName rather than System.String (of course, the PersonFirstName data type would have to contain a System.String). Another example is to have a PersonID class which represents the database identifier for the person, rather than to have a System.Int32.
There would be some benefits here:
Today, if a function takes an int as parameter, it's easy to pass in an ID of a Company object rather than the ID of an Person object, because both are of types int. If the function took a CompanyID, I would get a compilation error if I tried to pass in a PersonID.
If I want to change the database column data type from int to uniqueidentifier for a Person, I would only have to make the change in the PersonID class. Today, I would have to make changes in all places which takes an Int and is supposed to represent a company.
It may be easier to implement validation in the right places. " " may never be a correct first name, which PersonFirstName can take care of.
Yes, I would have to write more constructors. I could implement implicit overloading in these to make them easy to work with though.
Is this madness?
Yes, utter madness - to sum up your idea, and to Paraphrase Blackadder
It's mad! It's mad. It's madder than Mad Jack McMad, the winner of this year's Mr Madman competition
I don't think that's madness. I think using business logic objects with strongly typed objects is a very good thing
No, you're not getting any real benefit of that. For some things it makes sense, perhaps an Email class or maybe, maybe an ID class. However, having a "PersonID" or "ClientID" class seems to go far. You could have a "typedef" or alias or whatever but I would not go too far with this in most circumstances. You can go overboard very quickly and end up with a lot of work for no benefit.
Yes... It is ! You will lose more than you gain.
Yes, madness AND OVERKILL...
It sounds like a maintenance nightmare to me. what would the CompanyID constructor take? An integer? Sooner or later - you are going to have to use native types whether you like it or not.
So what I see here at first glance is a question within a question. Basically:
How do I mitigate complexity and change in my code base?
I would say that you need to look at the problem you are trying to solve and first see what the best solution is going to be. If you are dealing with something that is potentially going to be pervasive throughout your code base then you might want to see if you are violating SOLID design principles. Chances are that if you have one type that is being used in A LOT of different places your design is way too coupled, and you have a poor separation of concerns.
On the other hand, if you know that this type is going to be used in a lot of places, and it also happens to be very volatile (changes is certain), then the approach you mention above is probably the right way to go.
Ask yourself "What problem am I trying to solve?" and then choose a solution based on that answer. Don't start with the answer.
As extracted from Code Complete by Steve McConnell:
The object-oriented design would ask, "Should an ID be treated as an object?" Depending on the project's coding standards, a "Yes" answer might mean that the programming has to write a constructor, comment it all; and place it under configuration control. Most programmers would decide, "No, it isn't worth creating a whole class just for an ID. I'll just use ints.
Note what just happened. A useful design alternative, that of simply hiding the ID's data type, was not even considered...
For me, this passage is a great answer to your question. I'm all for it.