Search Results

Search found 320 results on 13 pages for 'polymorphism'.

Page 8/13 | < Previous Page | 4 5 6 7 8 9 10 11 12 13  | Next Page >

  • join same rails models twice, eg people has_many clubs through membership AND people has_many clubs through committee

    - by Ben
    Models: * Person * Club Relationships * Membership * Committee People should be able to join a club (Membership) People should be able to be on the board of a club (Committee) For my application these involve vastly different features, so I would prefer not to use a flag to set (is_board_member) or similar. I find myself wanting to write: People has_many :clubs :through = :membership # :as = :member? :foreign_key = :member_id? has_many :clubs :through = :committee # as (above) but I'm not really sure how to stitch this together

    Read the article

  • Can I pass a pointer to a superclass, but create a copy of the child?

    - by Alex
    I have a function that takes a pointer to a superclass and performs operations on it. However, at some point, the function must make a deep copy of the inputted object. Is there any way I can perform such a copy? It occurred to me to make the function a template function and simply have the user pass the type, but I hold out hope that C++ offers a more elegant solution.

    Read the article

  • Force calling the derived class implementation within a generic function in C#?

    - by Adam Hardy
    Ok so I'm currently working with a set of classes that I don't have control over in some pretty generic functions using these objects. Instead of writing literally tens of functions that essentially do the same thing for each class I decided to use a generic function instead. Now the classes I'm dealing with are a little weird in that the derived classes share many of the same properties but the base class that they are derived from doesn't. One such property example is .Parent which exists on a huge number of derived classes but not on the base class and it is this property that I need to use. For ease of understanding I've created a small example as follows: class StandardBaseClass {} // These are simulating the SMO objects class StandardDerivedClass : StandardBaseClass { public object Parent { get; set; } } static class Extensions { public static object GetParent(this StandardDerivedClass sdc) { return sdc.Parent; } public static object GetParent(this StandardBaseClass sbc) { throw new NotImplementedException("StandardBaseClass does not contain a property Parent"); } // This is the Generic function I'm trying to write and need the Parent property. public static void DoSomething<T>(T foo) where T : StandardBaseClass { object Parent = ((T)foo).GetParent(); } } In the above example calling DoSomething() will throw the NotImplemented Exception in the base class's implementation of GetParent(), even though I'm forcing the cast to T which is a StandardDerivedClass. This is contrary to other casting behaviour where by downcasting will force the use of the base class's implementation. I see this behaviour as a bug. Has anyone else out there encountered this?

    Read the article

  • Objectify - Retrieve subclass instances with superclass query

    - by Deviling Master
    for a project i'm making, i'm using Objectify and Google AppEngine I'm quoting and old message from Google Groups, but the problem i have is the same: Here's the problem I'm trying to solve: I'd like to persist instances of several subclasses of one superclass to the datastore, and then retrieve them by querying for that superclass. (For example, a query for Game would return instances of Chess and Backgammon). Is there any way to accomplish this using Objectify? Because the thing i want is the same, but the topic does not provides yet an answer (it's 3 years old), I moved here with the same question. From 2010 to now, this question has been solved? Thanks Bye

    Read the article

  • how to avoid temporaries when copying weakly typed object

    - by Truncheon
    Hi. I'm writing a series classes that inherit from a base class using virtual. They are INT, FLOAT and STRING objects that I want to use in a scripting language. I'm trying to implement weak typing, but I don't want STRING objects to return copies of themselves when used in the following way (instead I would prefer to have a reference returned which can be used in copying): a = "hello "; b = "world"; c = a + b; I have written the following code as a mock example: #include <iostream> #include <string> #include <cstdio> #include <cstdlib> std::string dummy("<int object cannot return string reference>"); struct BaseImpl { virtual bool is_string() = 0; virtual int get_int() = 0; virtual std::string get_string_copy() = 0; virtual std::string const& get_string_ref() = 0; }; struct INT : BaseImpl { int value; INT(int i = 0) : value(i) { std::cout << "constructor called\n"; } INT(BaseImpl& that) : value(that.get_int()) { std::cout << "copy constructor called\n"; } bool is_string() { return false; } int get_int() { return value; } std::string get_string_copy() { char buf[33]; sprintf(buf, "%i", value); return buf; } std::string const& get_string_ref() { return dummy; } }; struct STRING : BaseImpl { std::string value; STRING(std::string s = "") : value(s) { std::cout << "constructor called\n"; } STRING(BaseImpl& that) { if (that.is_string()) value = that.get_string_ref(); else value = that.get_string_copy(); std::cout << "copy constructor called\n"; } bool is_string() { return true; } int get_int() { return atoi(value.c_str()); } std::string get_string_copy() { return value; } std::string const& get_string_ref() { return value; } }; struct Base { BaseImpl* impl; Base(BaseImpl* p = 0) : impl(p) {} ~Base() { delete impl; } }; int main() { Base b1(new INT(1)); Base b2(new STRING("Hello world")); Base b3(new INT(*b1.impl)); Base b4(new STRING(*b2.impl)); std::cout << "\n"; std::cout << b1.impl->get_int() << "\n"; std::cout << b2.impl->get_int() << "\n"; std::cout << b3.impl->get_int() << "\n"; std::cout << b4.impl->get_int() << "\n"; std::cout << "\n"; std::cout << b1.impl->get_string_ref() << "\n"; std::cout << b2.impl->get_string_ref() << "\n"; std::cout << b3.impl->get_string_ref() << "\n"; std::cout << b4.impl->get_string_ref() << "\n"; std::cout << "\n"; std::cout << b1.impl->get_string_copy() << "\n"; std::cout << b2.impl->get_string_copy() << "\n"; std::cout << b3.impl->get_string_copy() << "\n"; std::cout << b4.impl->get_string_copy() << "\n"; return 0; } It was necessary to add an if check in the STRING class to determine whether its safe to request a reference instead of a copy: Script code: a = "test"; b = a; c = 1; d = "" + c; /* not safe to request reference by standard */ C++ code: STRING(BaseImpl& that) { if (that.is_string()) value = that.get_string_ref(); else value = that.get_string_copy(); std::cout << "copy constructor called\n"; } If was hoping there's a way of moving that if check into compile time, rather than run time.

    Read the article

  • Passing derived objects in a constructure

    - by Clarence Klopfstein
    This is a bit of a convoluted question, hopefully I can make it clear. I am finding that this may not be possible, but am trying to see if anybody has a solution. I have four classes, two are core classes and two are those core classes extended: extUser Extends coreUser extSecurity Extends coreSecurity In the constructor for coreUser you have this: public coreUser(string id, ref coreSecurity cs) When trying to extend coreUser you would have this: public extUser(string id ref extSecurity es) : base(id, ref es) This fails because es is of type, extSecurity and the base class expects a type of coreSecurity. I've not found anyway to cast this to allow for me to override this base class in C#. In VB it works just fine. Ideas?

    Read the article

  • C++ Problem: Class Promotion using derived class

    - by Michael Fitzpatrick
    I have a class for Float32 that is derived from Float32_base class Float32_base { public: // Constructors Float32_base(float x) : value(x) {}; Float32_base(void) : value(0) {}; operator float32(void) {return value;}; Float32_base operator =(float x) {value = x; return *this;}; Float32_base operator +(float x) const { return value + x;}; protected: float value; } class Float32 : public Float32_base { public: float Tad() { return value + .01; } } int main() { Float32 x, y, z; x = 1; y = 2; // WILL NOT COMPILE! z = (x + y).Tad(); // COMPILES OK z = ((Float32)(x + y)).Tad(); } The issue is that the + operator returns a Float32_base and Tad() is not in that class. But 'x' and 'y' are Float32's. Is there a way that I can get the code in the first line to compile without having to resort to a typecast like I did on the next line?

    Read the article

  • How to inherit methods from a parent class in C++

    - by Pat
    When inheriting classes in C++ I understand members are inherited. But how does one inherit the methods as well? For example, in the below code, I'd like the method "getValues" to be accessible not through just CPoly, but also by any class that inherits it. So one can call "getValues" on CRect directly. class CPoly { private: int width, height; public: void getValues (int* a, int* b) { *a=width; *b=height;} }; class CRect: public CPoly { public: int area () { return (width * height); } }; In other words, is there any way to inherit methods for simple generic methods like getters and setters?

    Read the article

  • Is it possible to cancel function override in parent class and use function from top level parent

    - by Anatoliy Gusarov
    class TopParent { protected function foo() { $this->bar(); } private function bar() { echo 'Bar'; } } class MidParent extends TopParent { protected function foo() { $this->midMethod(); parent::foo(); } public function midMethod() { echo 'Mid'; } public function generalMethod() { echo 'General'; } } Now the question is if I have a class, that extends MidParent because I need to call class Target extends MidParent { //How to override this method to return TopParent::foo(); ? protected function foo() { } } So I need to do this: $mid = new MidParent(); $mid->foo(); // MidBar $taget = new Target(); $target->generalMethod(); // General $target->foo(); // Bar UPDATE Top parent is ActiveRecord class, mid is my model object. I want to use model in yii ConsoleApplication. I use 'user' module in this model, and console app doesn't support this module. So I need to override method afterFind, where user module is called. So the Target class is the class that overrides some methods from model which uses some modules that console application doesn't support.

    Read the article

  • Calling an Overridden Method from a Parent-Class Constructor

    - by Vaibhav Bajpai
    I tried calling an overridden method from a constructor of a parent class and noticed different behavior across languages. C++ - echoes A.foo() class A{ public: A(){foo();} virtual void foo(){cout<<"A.foo()";} }; class B : public A{ public: B(){} void foo(){cout<<"B.foo()";} }; int main(){ B *b = new B(); } Java - echoes B.foo() class A{ public A(){foo();} public void foo(){System.out.println("A.foo()");} } class B extends A{ public void foo(){System.out.println("B.foo()");} } class Demo{ public static void main(String args[]){ B b = new B(); } } C# - echoes B.foo() class A{ public A(){foo();} public virtual void foo(){Console.WriteLine("A.foo()");} } class B : A{ public override void foo(){Console.WriteLine("B.foo()");} } class MainClass { public static void Main (string[] args) { B b = new B(); } } I realize that in C++ objects are created from top-most parent going down the hierarchy, so when the constructor calls the overridden method, B does not even exist, so it calls the A' version of the method. However, I am not sure why I am getting different behavior in Java and C#.

    Read the article

  • (Java) Is there a type of object that can handle anything from primitives to arrays?

    - by Michael
    I'm pretty new to Java, so I'm hoping one of you guys knows how to do this. I'm having the user specify both the type and value of arguments, in any XML-like way, to be passed to methods that are external to my application. Example: javac myAppsName externalJavaClass methodofExternalClass [parameters] Of course, to find the proper method, we have to have the proper parameter types as the method may be overloaded and that's the only way to tell the difference between the different versions. Parameters are currently formatted in this manner: (type)value(/type), e.g. (int)71(/int) (string)This is my string that I'm passing as a parameter!(/string) I parse them, getting the constructor for whatever type is indicated, then execute that constructor by running its method, newInstance(<String value>), loading the new instance into an Object. This works fine and dandy, but as we all know, some methods take arrays, or even multi-dimensional arrays. I could handle the argument formatting like so: (array)(array)(int)0(/int)(int)1(/int)(/array)(array)(int)2(/int)(int)3(/int)(/array)(/array)... or perhaps even better... {{(int)0(/int)(int)1(/int)}{(int)2(/int)(int)3(/int)}}. The question is, how can this be implemented? Do I have to start wrapping everything in an Object[] array so I can handle primitives, etc. as argObj[0], but load an array as I normally would? (Unfortunately, I would have to make it an Object[][] array if I wanted to support two-dimensional arrays. This implementation wouldn't be very pretty.)

    Read the article

  • Should I use polymorphic association, just a has_one, or attribute in this case?

    - by Angela
    I have three Models: Contact_Email, Contact_Letter, and Contact_Call. These represent the unique pairing of a Contact with a template for each of the three. For all of these, I want to record at least a status and date for the status. For example, "declined" on 5/10/10 or "responded" on 5/10/10 or something like that. I may in the future want to extend that. I later do want to be able to see all the instances that have the same status, such as "responded" or "meeting requested." What is the best way to do this? To make the three Contacts statusable and create a polymorphic association on a model called Status. Or just each Object of Contact_Email has_one Status?

    Read the article

  • Rails - single ID for multiple models

    - by user352351
    I'm building an app which will allow a user to scan the barcode on a 'shelf', 'box' or 'product' which will then bring up that particular item or all the associated items. As these are all separate models with their own ID's, I need a global ID table. I was thinking of a polymorphic table called 'barcodes' barcodes id barcode_number barcodable Is there an easy way to do this? Or is polymorphic the best way?

    Read the article

  • what's the right way to do polymorphism with protocol buffers?

    - by user364003
    I'm trying to long-term serialize a bunch of objects related by a strong class hierarchy in java, and I'd like to use protocol buffers to do it due to their simplicity, performance, and ease of upgrade. However, they don't provide much support for polymorphism. Right now, the way I'm handling it is by having a "one message to rule them all" solution that has a required string uri field that allows me to instantiate the correct type via reflection, then a bunch of optional fields for all the other possible classes I could serialize, only one of which will be used (based on the value of the uri field). Is there a better way to handle polymorphism, or is this as good as I'm going to get?

    Read the article

  • Is return-type-(only)-polymorphism in Haskell a good thing?

    - by dainichi
    One thing that I've never quite come to terms with in Haskell is how you can have polymorphic constants and functions whose return type cannot be determined by their input type, like class Foo a where foo::Int -> a Some of the reasons that I do not like this: Referential transparency: "In Haskell, given the same input, a function will always return the same output", but is that really true? read "3" return 3 when used in an Int context, but throws an error when used in a, say, (Int,Int) context. Yes, you can argue that read is also taking a type parameter, but the implicitness of the type parameter makes it lose some of its beauty in my opinion. Monomorphism restriction: One of the most annoying things about Haskell. Correct me if I'm wrong, but the whole reason for the MR is that computation that looks shared might not be because the type parameter is implicit. Type defaulting: Again one of the most annoying things about Haskell. Happens e.g. if you pass the result of functions polymorphic in their output to functions polymorphic in their input. Again, correct me if I'm wrong, but this would not be necessary without functions whose return type cannot be determined by their input type (and polymorphic constants). So my question is (running the risk of being stamped as a "discussion quesion"): Would it be possible to create a Haskell-like language where the type checker disallows these kinds of definitions? If so, what would be the benefits/disadvantages of that restriction? I can see some immediate problems: If, say, 2 only had the type Integer, 2/3 wouldn't type check anymore with the current definition of /. But in this case, I think type classes with functional dependencies could come to the rescue (yes, I know that this is an extension). Furthermore, I think it is a lot more intuitive to have functions that can take different input types, than to have functions that are restricted in their input types, but we just pass polymorphic values to them. The typing of values like [] and Nothing seems to me like a tougher nut to crack. I haven't thought of a good way to handle them. I doubt I am the first person to have had thoughts like these. Does anybody have links to good discussions about this Haskell design decision and the pros/cons of it?

    Read the article

  • Are there any data-binding solution that works in C++ and GWT and supports structures polymorphism?

    - by user116854
    I expect it should share a common description, like XmlSchema or IDL and should generate classes for target language. I found Thrift and it's really nice solution, but it doesn't support structures polymorphism. I would like to have collections of base class objects, where I could place instances of subclasses, serialize this and deserialize at the opposite side. Some mechanism of polymorphic behavior support, like Visitor, would be a perfect. Does anybody know something suitable for these requirements?

    Read the article

  • First languages with generic programming support

    - by oluies
    Which was the first language with generic programming support, and what was the first major staticly typed language (widely used) with generics support. Generics implement the concept of parameterized types to allow for multiple types. The term generic means "pertaining to or appropriate to large groups of classes." I have seen the following mentions of "first": First-order parametric polymorphism is now a standard element of statically typed programming languages. Starting with System F [20,42] and functional programming lan- guages, the constructs have found their way into mainstream languages such as Java and C#. In these languages, first-order parametric polymorphism is usually called generics. From "Generics of a Higher Kind", Adriaan Moors, Frank Piessens, and Martin Odersky Generic programming is a style of computer programming in which algorithms are written in terms of to-be-specified-later types that are then instantiated when needed for specific types provided as parameters. This approach, pioneered by Ada in 1983 From Wikipedia Generic Programming

    Read the article

  • First languages with generic programming support

    - by oluies
    Which was the first language with generic programming support, and what was the first major staticly typed language (widely used) with generics support. Generics implement the concept of parameterized types to allow for multiple types. The term generic means "pertaining to or appropriate to large groups of classes." I have seen the following mentions of "first": First-order parametric polymorphism is now a standard element of statically typed programming languages. Starting with System F [20,42] and functional programming lan- guages, the constructs have found their way into mainstream languages such as Java and C#. In these languages, first-order parametric polymorphism is usually called generics. From "Generics of a Higher Kind", Adriaan Moors, Frank Piessens, and Martin Odersky Generic programming is a style of computer programming in which algorithms are written in terms of to-be-specified-later types that are then instantiated when needed for specific types provided as parameters. This approach, pioneered by Ada in 1983 From Wikipedia Generic Programming

    Read the article

  • Is OO-programming really as important as hiring companies place it?

    - by ale
    I am just finishing my masters degree (in computing) and applying for jobs.. I've noticed many companies specifically ask for an understanding of object orientation. Popular interview questions are about inheritance, polymorphism, accessors etc. Is OO really that crucial? I even had an interview for a programming job in C and half the interview was OO. In the real world, developing real applications, is object orientation nearly always used? Are key features like polymorphism used A LOT? I think my question comes from one of my weaknesses.. although I know about OO.. I don't seem to be able to incorporate it a great deal into my programs. I would be really interested to get peoples' thoughts on this!

    Read the article

  • Java overloading and overriding

    - by Padmanabh
    We always say that method overloading is static polymorphism and overriding is runtime polymorphism. What exactly do we mean by static here? Is the call to a method resolved on compiling the code? So whats the difference between normal method call and calling a final method? Which one is linked at compile time?

    Read the article

  • Inheritance Mapping Strategies with Entity Framework Code First CTP5 Part 1: Table per Hierarchy (TPH)

    - by mortezam
    A simple strategy for mapping classes to database tables might be “one table for every entity persistent class.” This approach sounds simple enough and, indeed, works well until we encounter inheritance. Inheritance is such a visible structural mismatch between the object-oriented and relational worlds because object-oriented systems model both “is a” and “has a” relationships. SQL-based models provide only "has a" relationships between entities; SQL database management systems don’t support type inheritance—and even when it’s available, it’s usually proprietary or incomplete. There are three different approaches to representing an inheritance hierarchy: Table per Hierarchy (TPH): Enable polymorphism by denormalizing the SQL schema, and utilize a type discriminator column that holds type information. Table per Type (TPT): Represent "is a" (inheritance) relationships as "has a" (foreign key) relationships. Table per Concrete class (TPC): Discard polymorphism and inheritance relationships completely from the SQL schema.I will explain each of these strategies in a series of posts and this one is dedicated to TPH. In this series we'll deeply dig into each of these strategies and will learn about "why" to choose them as well as "how" to implement them. Hopefully it will give you a better idea about which strategy to choose in a particular scenario. Inheritance Mapping with Entity Framework Code FirstAll of the inheritance mapping strategies that we discuss in this series will be implemented by EF Code First CTP5. The CTP5 build of the new EF Code First library has been released by ADO.NET team earlier this month. EF Code-First enables a pretty powerful code-centric development workflow for working with data. I’m a big fan of the EF Code First approach, and I’m pretty excited about a lot of productivity and power that it brings. When it comes to inheritance mapping, not only Code First fully supports all the strategies but also gives you ultimate flexibility to work with domain models that involves inheritance. The fluent API for inheritance mapping in CTP5 has been improved a lot and now it's more intuitive and concise in compare to CTP4. A Note For Those Who Follow Other Entity Framework ApproachesIf you are following EF's "Database First" or "Model First" approaches, I still recommend to read this series since although the implementation is Code First specific but the explanations around each of the strategies is perfectly applied to all approaches be it Code First or others. A Note For Those Who are New to Entity Framework and Code-FirstIf you choose to learn EF you've chosen well. If you choose to learn EF with Code First you've done even better. To get started, you can find a great walkthrough by Scott Guthrie here and another one by ADO.NET team here. In this post, I assume you already setup your machine to do Code First development and also that you are familiar with Code First fundamentals and basic concepts. You might also want to check out my other posts on EF Code First like Complex Types and Shared Primary Key Associations. A Top Down Development ScenarioThese posts take a top-down approach; it assumes that you’re starting with a domain model and trying to derive a new SQL schema. Therefore, we start with an existing domain model, implement it in C# and then let Code First create the database schema for us. However, the mapping strategies described are just as relevant if you’re working bottom up, starting with existing database tables. I’ll show some tricks along the way that help you dealing with nonperfect table layouts. Let’s start with the mapping of entity inheritance. -- The Domain ModelIn our domain model, we have a BillingDetail base class which is abstract (note the italic font on the UML class diagram below). We do allow various billing types and represent them as subclasses of BillingDetail class. As for now, we support CreditCard and BankAccount: Implement the Object Model with Code First As always, we start with the POCO classes. Note that in our DbContext, I only define one DbSet for the base class which is BillingDetail. Code First will find the other classes in the hierarchy based on Reachability Convention. public abstract class BillingDetail  {     public int BillingDetailId { get; set; }     public string Owner { get; set; }             public string Number { get; set; } } public class BankAccount : BillingDetail {     public string BankName { get; set; }     public string Swift { get; set; } } public class CreditCard : BillingDetail {     public int CardType { get; set; }                     public string ExpiryMonth { get; set; }     public string ExpiryYear { get; set; } } public class InheritanceMappingContext : DbContext {     public DbSet<BillingDetail> BillingDetails { get; set; } } This object model is all that is needed to enable inheritance with Code First. If you put this in your application you would be able to immediately start working with the database and do CRUD operations. Before going into details about how EF Code First maps this object model to the database, we need to learn about one of the core concepts of inheritance mapping: polymorphic and non-polymorphic queries. Polymorphic Queries LINQ to Entities and EntitySQL, as object-oriented query languages, both support polymorphic queries—that is, queries for instances of a class and all instances of its subclasses, respectively. For example, consider the following query: IQueryable<BillingDetail> linqQuery = from b in context.BillingDetails select b; List<BillingDetail> billingDetails = linqQuery.ToList(); Or the same query in EntitySQL: string eSqlQuery = @"SELECT VAlUE b FROM BillingDetails AS b"; ObjectQuery<BillingDetail> objectQuery = ((IObjectContextAdapter)context).ObjectContext                                                                          .CreateQuery<BillingDetail>(eSqlQuery); List<BillingDetail> billingDetails = objectQuery.ToList(); linqQuery and eSqlQuery are both polymorphic and return a list of objects of the type BillingDetail, which is an abstract class but the actual concrete objects in the list are of the subtypes of BillingDetail: CreditCard and BankAccount. Non-polymorphic QueriesAll LINQ to Entities and EntitySQL queries are polymorphic which return not only instances of the specific entity class to which it refers, but all subclasses of that class as well. On the other hand, Non-polymorphic queries are queries whose polymorphism is restricted and only returns instances of a particular subclass. In LINQ to Entities, this can be specified by using OfType<T>() Method. For example, the following query returns only instances of BankAccount: IQueryable<BankAccount> query = from b in context.BillingDetails.OfType<BankAccount>() select b; EntitySQL has OFTYPE operator that does the same thing: string eSqlQuery = @"SELECT VAlUE b FROM OFTYPE(BillingDetails, Model.BankAccount) AS b"; In fact, the above query with OFTYPE operator is a short form of the following query expression that uses TREAT and IS OF operators: string eSqlQuery = @"SELECT VAlUE TREAT(b as Model.BankAccount)                       FROM BillingDetails AS b                       WHERE b IS OF(Model.BankAccount)"; (Note that in the above query, Model.BankAccount is the fully qualified name for BankAccount class. You need to change "Model" with your own namespace name.) Table per Class Hierarchy (TPH)An entire class hierarchy can be mapped to a single table. This table includes columns for all properties of all classes in the hierarchy. The concrete subclass represented by a particular row is identified by the value of a type discriminator column. You don’t have to do anything special in Code First to enable TPH. It's the default inheritance mapping strategy: This mapping strategy is a winner in terms of both performance and simplicity. It’s the best-performing way to represent polymorphism—both polymorphic and nonpolymorphic queries perform well—and it’s even easy to implement by hand. Ad-hoc reporting is possible without complex joins or unions. Schema evolution is straightforward. Discriminator Column As you can see in the DB schema above, Code First has to add a special column to distinguish between persistent classes: the discriminator. This isn’t a property of the persistent class in our object model; it’s used internally by EF Code First. By default, the column name is "Discriminator", and its type is string. The values defaults to the persistent class names —in this case, “BankAccount” or “CreditCard”. EF Code First automatically sets and retrieves the discriminator values. TPH Requires Properties in SubClasses to be Nullable in the Database TPH has one major problem: Columns for properties declared by subclasses will be nullable in the database. For example, Code First created an (INT, NULL) column to map CardType property in CreditCard class. However, in a typical mapping scenario, Code First always creates an (INT, NOT NULL) column in the database for an int property in persistent class. But in this case, since BankAccount instance won’t have a CardType property, the CardType field must be NULL for that row so Code First creates an (INT, NULL) instead. If your subclasses each define several non-nullable properties, the loss of NOT NULL constraints may be a serious problem from the point of view of data integrity. TPH Violates the Third Normal FormAnother important issue is normalization. We’ve created functional dependencies between nonkey columns, violating the third normal form. Basically, the value of Discriminator column determines the corresponding values of the columns that belong to the subclasses (e.g. BankName) but Discriminator is not part of the primary key for the table. As always, denormalization for performance can be misleading, because it sacrifices long-term stability, maintainability, and the integrity of data for immediate gains that may be also achieved by proper optimization of the SQL execution plans (in other words, ask your DBA). Generated SQL QueryLet's take a look at the SQL statements that EF Code First sends to the database when we write queries in LINQ to Entities or EntitySQL. For example, the polymorphic query for BillingDetails that you saw, generates the following SQL statement: SELECT  [Extent1].[Discriminator] AS [Discriminator],  [Extent1].[BillingDetailId] AS [BillingDetailId],  [Extent1].[Owner] AS [Owner],  [Extent1].[Number] AS [Number],  [Extent1].[BankName] AS [BankName],  [Extent1].[Swift] AS [Swift],  [Extent1].[CardType] AS [CardType],  [Extent1].[ExpiryMonth] AS [ExpiryMonth],  [Extent1].[ExpiryYear] AS [ExpiryYear] FROM [dbo].[BillingDetails] AS [Extent1] WHERE [Extent1].[Discriminator] IN ('BankAccount','CreditCard') Or the non-polymorphic query for the BankAccount subclass generates this SQL statement: SELECT  [Extent1].[BillingDetailId] AS [BillingDetailId],  [Extent1].[Owner] AS [Owner],  [Extent1].[Number] AS [Number],  [Extent1].[BankName] AS [BankName],  [Extent1].[Swift] AS [Swift] FROM [dbo].[BillingDetails] AS [Extent1] WHERE [Extent1].[Discriminator] = 'BankAccount' Note how Code First adds a restriction on the discriminator column and also how it only selects those columns that belong to BankAccount entity. Change Discriminator Column Data Type and Values With Fluent API Sometimes, especially in legacy schemas, you need to override the conventions for the discriminator column so that Code First can work with the schema. The following fluent API code will change the discriminator column name to "BillingDetailType" and the values to "BA" and "CC" for BankAccount and CreditCard respectively: protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder) {     modelBuilder.Entity<BillingDetail>()                 .Map<BankAccount>(m => m.Requires("BillingDetailType").HasValue("BA"))                 .Map<CreditCard>(m => m.Requires("BillingDetailType").HasValue("CC")); } Also, changing the data type of discriminator column is interesting. In the above code, we passed strings to HasValue method but this method has been defined to accepts a type of object: public void HasValue(object value); Therefore, if for example we pass a value of type int to it then Code First not only use our desired values (i.e. 1 & 2) in the discriminator column but also changes the column type to be (INT, NOT NULL): modelBuilder.Entity<BillingDetail>()             .Map<BankAccount>(m => m.Requires("BillingDetailType").HasValue(1))             .Map<CreditCard>(m => m.Requires("BillingDetailType").HasValue(2)); SummaryIn this post we learned about Table per Hierarchy as the default mapping strategy in Code First. The disadvantages of the TPH strategy may be too serious for your design—after all, denormalized schemas can become a major burden in the long run. Your DBA may not like it at all. In the next post, we will learn about Table per Type (TPT) strategy that doesn’t expose you to this problem. References ADO.NET team blog Java Persistence with Hibernate book a { text-decoration: none; } a:visited { color: Blue; } .title { padding-bottom: 5px; font-family: Segoe UI; font-size: 11pt; font-weight: bold; padding-top: 15px; } .code, .typeName { font-family: consolas; } .typeName { color: #2b91af; } .padTop5 { padding-top: 5px; } .padTop10 { padding-top: 10px; } p.MsoNormal { margin-top: 0in; margin-right: 0in; margin-bottom: 10.0pt; margin-left: 0in; line-height: 115%; font-size: 11.0pt; font-family: "Calibri" , "sans-serif"; }

    Read the article

  • Replacing “if”s with your own number system

    - by Michael Williamson
    During our second code retreat at Red Gate, the restriction for one of the sessions was disallowing the use of if statements. That includes other constructs that have the same effect, such as switch statements or loops that will only be executed zero or one times. The idea is to encourage use of polymorphism instead, and see just how far it can be used to get rid of “if”s. The main place where people struggled to get rid of numbers from their implementation of Conway’s Game of Life was the piece of code that decides whether a cell is live or dead in the next generation. For instance, for a cell that’s currently live, the code might look something like this: if (numberOfNeighbours == 2 || numberOfNeighbours == 3) { return CellState.LIVE; } else { return CellState.DEAD; } The problem is that we need to change behaviour depending on the number of neighbours each cell has, but polymorphism only allows us to switch behaviour based on the type of a value. It follows that the solution is to make different numbers have different types: public interface IConwayNumber { IConwayNumber Increment(); CellState LiveCellNextGeneration(); } public class Zero : IConwayNumber { public IConwayNumber Increment() { return new One(); } public CellState LiveCellNextGeneration() { return CellState.DEAD; } } public class One : IConwayNumber { public IConwayNumber Increment() { return new Two(); } public CellState LiveCellNextGeneration() { return CellState.LIVE; } } public class Two : IConwayNumber { public IConwayNumber Increment() { return new ThreeOrMore(); } public CellState LiveCellNextGeneration() { return CellState.LIVE; } } public class ThreeOrMore : IConwayNumber { public IConwayNumber Increment() { return this; } public CellState LiveCellNextGeneration() { return CellState.DEAD; } } In the code that counts the number of neighbours, we use our new number system by starting with Zero and incrementing when we find a neighbour. To choose the next state of the cell, rather than inspecting the number of neighbours, we ask the number of neighbours for the next state directly: return numberOfNeighbours.LiveCellNextGeneration(); And now we have no “if”s! If C# had double-dispatch, or if we used the visitor pattern, we could move the logic for choosing the next cell out of the number classes, which might feel a bit more natural. I suspect that reimplementing the natural numbers is still going to feel about the same amount of crazy though.

    Read the article

  • Computer Engineer in CS Interview

    - by blasteye
    As a Computer Engineering student, while in school I've primarily dealt with C, Matlab, and VHDL. On my own though, i learned a bit about OOP (Polymorphism, inheritance, encapsulation), and have done quite a bit of web development using JavaScript/PHP/Node.js While at coding interviews I've be asked academia CS questions such as "abstract vs interface". The problem is that I didn't know the official terminology, but I have dealt with this type of programming decisions/concepts. Could anyone recommend a good resource for me to learn these academia CS terms?

    Read the article

  • Implenting ActiveRecord with inheritance?

    - by King
    I recently converted an old application that was using XML files as the data store to use SQL instead. To avoid a lot of changes I basically created ActiveRecord style classes that inherited from the original business objects. For example SomeClassRecord :SomeClass //ID Property //Save method I then used this new class in place of the other one, because of polymorphism I didn't need to change any methods that took SomeClass as a parameter. Would this be considered 'Bad'? What would be a better alternative?

    Read the article

< Previous Page | 4 5 6 7 8 9 10 11 12 13  | Next Page >