Search Results

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

Page 12/13 | < Previous Page | 8 9 10 11 12 13  | Next Page >

  • Does my use of the strategy pattern violate the fundamental MVC pattern in iOS?

    - by Goodsquirrel
    I'm about to use the 'strategy' pattern in my iOS app, but feel like my approach violates the somehow fundamental MVC pattern. My app is displaying visual "stories", and a Story consists (i.e. has @properties) of one Photo and one or more VisualEvent objects to represent e.g. animated circles or moving arrows on the photo. Each VisualEvent object therefore has a eventType @property, that might be e.g. kEventTypeCircle or kEventTypeArrow. All events have things in common, like a startTime @property, but differ in the way they are being drawn on the StoryPlayerView. Currently I'm trying to follow the MVC pattern and have a StoryPlayer object (my controller) that knows about both the model objects (like Story and all kinds of visual events) and the view object StoryPlayerView. To chose the right drawing code for each of the different visual event types, my StoryPlayer is using a switch statement. @implementation StoryPlayer // (...) - (void)showVisualEvent:(VisualEvent *)event onStoryPlayerView:storyPlayerView { switch (event.eventType) { case kEventTypeCircle: [self showCircleEvent:event onStoryPlayerView:storyPlayerView]; break; case kEventTypeArrow: [self showArrowDrawingEvent:event onStoryPlayerView:storyPlayerView]; break; // (...) } But switch statements for type checking are bad design, aren't they? According to Uncle Bob they lead to tight coupling and can and should almost always be replaced by polymorphism. Having read about the "Strategy"-Pattern in Head First Design Patterns, I felt this was a great way to get rid of my switch statement. So I changed the design like this: All specialized visual event types are now subclasses of an abstract VisualEvent class that has a showOnStoryPlayerView: method. @interface VisualEvent : NSObject - (void)showOnStoryPlayerView:(StoryPlayerView *)storyPlayerView; // abstract Each and every concrete subclass implements a concrete specialized version of this drawing behavior method. @implementation CircleVisualEvent - (void)showOnStoryPlayerView:(StoryPlayerView *)storyPlayerView { [storyPlayerView drawCircleAtPoint:self.position color:self.color lineWidth:self.lineWidth radius:self.radius]; } The StoryPlayer now simply calls the same method on all types of events. @implementation StoryPlayer - (void)showVisualEvent:(VisualEvent *)event onStoryPlayerView:storyPlayerView { [event showOnStoryPlayerView:storyPlayerView]; } The result seems to be great: I got rid of the switch statement, and if I ever have to add new types of VisualEvents in the future, I simply create new subclasses of VisualEvent. And I won't have to change anything in StoryPlayer. But of cause this approach violates the MVC pattern since now my model has to know about and depend on my view! Now my controller talks to my model and my model talks to the view calling methods on StoryPlayerView like drawCircleAtPoint:color:lineWidth:radius:. But this kind of calls should be controller code not model code, right?? Seems to me like I made things worse. I'm confused! Am I completely missing the point of the strategy pattern? Is there a better way to get rid of the switch statement without breaking model-view separation?

    Read the article

  • What common interface would be appropriate for these game object classes?

    - by Jefffrey
    Question A component based system's goal is to solve the problems that derives from inheritance: for example the fact that some parts of the code (that are called components) are reused by very different classes that, hypothetically, would lie in a very different branch of the inheritance tree. That's a very nice concept, but I've found out that CBS is often hard to accomplish without using ugly hacks. Implementations of this system are often far from clean. But I don't want to discuss this any further. My question is: how can I solve the same problems a CBS try to solve with a very clean interface? (possibly with examples, there are a lot of abstract talks about the "perfect" design already). Context Here's an example I was going for before realizing I was just reinventing inheritance again: class Human { public: Position position; Movement movement; Sprite sprite; // other human specific components }; class Zombie { Position position; Movement movement; Sprite sprite; // other zombie specific components }; After writing that I realized I needed an interface, otherwise I would have needed N containers for N different types of objects (or to use boost::variant to gather them all together). So I've thought of polymorphism (move what systems do in a CBS design into class specific functions): class Entity { public: virtual void on_event(Event) {} // not pure virtual on purpose virtual void on_update(World) {} virtual void on_draw(Window) {} }; class Human : public Entity { private: Position position; Movement movement; Sprite sprite; public: virtual void on_event(Event) { ... } virtual void on_update(World) { ... } virtual void on_draw(Window) { ... } }; class Zombie : public Entity { private: Position position; Movement movement; Sprite sprite; public: virtual void on_event(Event) { ... } virtual void on_update(World) { ... } virtual void on_draw(Window) { ... } }; Which was nice, except for the fact that now the outside world would not even be able to know where a Human is positioned (it does not have access to its position member). That would be useful to track the player position for collision detection or if on_update the Zombie would want to track down its nearest human to move towards him. So I added const Position& get_position() const; to both the Zombie and Human classes. And then I realized that both functionality were shared, so it should have gone to the common base class: Entity. Do you notice anything? Yes, with that methodology I would have a god Entity class full of common functionality (which is the thing I was trying to avoid in the first place). Meaning of "hacks" in the implementation I'm referring to I'm talking about the implementations that defines Entities as simple IDs to which components are dynamically attached. Their implementation can vary from C-stylish: int last_id; Position* positions[MAX_ENTITIES]; Movement* movements[MAX_ENTITIES]; Where positions[i], movements[i], component[i], ... make up the entity. Or to more C++-style: int last_id; std::map<int, Position> positions; std::map<int, Movement> movements; From which systems can detect if an entity/id can have attached components.

    Read the article

  • How do people know so much about programming?

    - by Luciano
    I see people in this forums with a lot of points, so I assume they know about a lot of different programming stuff. When I was young I knew about basic (commodore) and the turbo pascal (pc). Then in college I learnt about C, memory management, x86 set, loop invariants, graphs, db query optimization, oop, functional, lambda calculus, prolog, concurrency, polymorphism, newton method, simplex, backtracking, dynamic programming, heuristics, np completeness, LR, LALR, neural networks, static & dynamic typing, turing, godel, and more in between. Then in industry I started with Java several years ago and learnt about it, and its variety of frameworks, and also design patterns, architecture patterns, web development, server development, mobile development, tdd, bdd, uml, use cases, bug trackers, process management, people management if you are a tech lead, profiling, security concerns, etc. I started to forget what I learnt in college... And then there is the stuff I don't know yet, like python, .net, perl, JVM stuff like groovy or scala.. Of course Google is a must for rapid documentation access to know if a problem has been solved already and how, and to keep informed about new stuff by blogs and places like this one. It's just too much or I just have a bad memory.. how do you guys manage it?

    Read the article

  • What is a good standard exercise to learn the OO features of a language?

    - by FarmBoy
    When I'm learning a new language, I often program some mathematical functions to get used to the control flow syntax. After that, I like to implement some sorting algorithms to get used to the array/list constructs. But I don't have a standard exercise for exploring the languages OO features. Does anyone have a stock exercise for this? A good answer would naturally lend to inheritance, polymorphism, etc., for a programmer already comfortable with these concepts. An ideal answer would be one that could be communicated in a few words, without ambiguity, in the way that "implement mergesort" is completely unambiguous. (As an example, answering "design a game" is so vague as to be useless.) Any ideas? EDIT: I have to remark that the results here are somewhat ironic. 10 upvotes and (originally) 5 favorites suggest that this is a question others are interested in. Yet the most upvoted answer is one that says there is no good answer. Oh well. I think I'll look at the textbook below, I've found games useful in the past for OO.

    Read the article

  • What are the most interesting equivalences arising from the Curry-Howard Isomorphism?

    - by Tom
    I came upon the Curry-Howard Isomorphism relatively late in my programming life, and perhaps this contributes to my being utterly fascinated by it. It implies that for every programming concept there exists a precise analogue in formal logic, and vice versa. Here's an "obvious" list of such analogies, off the top of my head: program/definition | proof type/declaration | proposition inhabited type | theorem function | implication function argument | hypothesis/antecedent function result | conclusion/consequent function application | modus ponens recursion | induction identity function | tautology non-terminating function | absurdity tuple | conjunction (and) disjoint union | exclusive disjunction (xor) parametric polymorphism | universal quantification So, to my question: what are some of the more interesting/obscure implications of this isomorphism? I'm no logician so I'm sure I've only scratched the surface with this list. For example, here are some programming notions for which I'm unaware of pithy names in logic: currying | "((a & b) => c) iff (a => (b => c))" scope | "known theory + hypotheses" And here are some logical concepts which I haven't quite pinned down in programming terms: primitive type? | axiom set of valid programs? | theory ? | disjunction (or)

    Read the article

  • How to suggest changes as a recently-hired employee ?

    - by ereOn
    Hi, I was recently hired in a big company (thousands of people, to give an idea of the size). They said they hired me because of my rigor and because I was, despite my youngness (i'm 25), experienced as a C/C++ programer. Now that I'm in, I can see that the whole system is old and often uses obsolete technologies. There is no naming convention (files, functions, variables, ...), they don't use Version Control, don't use exceptions or polymorphism and it seems like almost everybody lost his passion (some of them are only 30 years old). I'd like to suggest somes changes but i don't want to be "the new guy that wants to change everything just because he doesn't want to fit in". I tried to "fit in", but actually, It takes me one week to do what I would do in one afternoon, just because of the poor tools we're forced to use. A lot my collegues never look at the new "things" and techniques that people use nowadays. It's like they just given up. The situation is really frustrating. Have you ever been in a similar situation and, if so, what advices would you give me ? Is there a subtle way of changing things without becoming the black sheep here ? Or should I just give up my passion and energy as well ? Thank you.

    Read the article

  • How to get rid of void-pointers.

    - by Patrick
    I inherited a big application that was originally written in C (but in the mean time a lot of C++ was also added to it). Because of historical reasons, the application contains a lot of void-pointers. Before you start to choke, let me explain why this was done. The application contains many different data structures, but they are stored in 'generic' containers. Nowadays I would use templated STL containers for it, or I would give all data structures a common base class, so that the container can store pointers to the base class, but in the [good?] old C days, the only solution was to cast the struct-pointer to a void-pointer. Additionally, there is a lot of code that works on these void-pointers, and uses very strange C constructions to emulate polymorphism in C. I am now reworking the application, and trying to get rid of the void-pointers. Adding a common base-class to all the data structures isn't that hard (few days of work), but the problem is that the code is full of constructions like shown below. This is an example of how data is stored: void storeData (int datatype, void *data); // function prototype ... Customer *myCustomer = ...; storeData (TYPE_CUSTOMER, myCustomer); This is an example of how data is fetched again: Customer *myCustomer = (Customer *) fetchData (int datatype, char *key); I actually want to replace all the void-pointers with some smart-pointer (reference-counted), but I can't find a trick to automate (or at least) help me to get rid of all the casts to and from void-pointers. Any tips on how to find, replace, or interact in any possible way with these conversions?

    Read the article

  • Polymorphic Numerics on .Net and In C#

    - by Bent Rasmussen
    It's a real shame that in .Net there is no polymorphism for numbers, i.e. no INumeric interface that unifies the different kinds of numerical types such as bool, byte, uint, int, etc. In the extreme one would like a complete package of abstract algebra types. Joe Duffy has an article about the issue: http://www.bluebytesoftware.com/blog/CommentView,guid,14b37ade-3110-4596-9d6e-bacdcd75baa8.aspx How would you express this in C#, in order to retrofit it, without having influence over .Net or C#? I have one idea that involves first defining one or more abstract types (interfaces such as INumeric - or more abstract than that) and then defining structs that implement these and wrap types such as int while providing operations that return the new type (e.g. Integer32 : INumeric; where addition would be defined as public Integer32 Add(Integer32 other) { return Return(Value + other.Value); } I am somewhat afraid of the execution speed of this code but at least it is abstract. No operator overloading goodness... Any other ideas? .Net doesn't look like a viable long-term platform if it cannot have this kind of abstraction I think - and be efficient about it. Abstraction is reuse.

    Read the article

  • Is this a good job description? What title would you give this position?

    - by Zack Peterson
    Department: Information Technology Reports To: Chief Information Officer Purpose: Company's ________________ is specifically engaged in the development of World Wide Web applications and distributed network applications. This person is concerned with all facets of the software development process and specializes in software product management. He or she contributes to projects in an application architect role and also performs individual programming tasks. Essential Duties & Responsibilities: This person is involved in all aspects of the software development process such as: Participation in software product definitions, including requirements analysis and specification Development and refinement of simulations or prototypes to confirm requirements Feasibility and cost-benefit analysis, including the choice of architecture and framework Application and database design Implementation (e.g. installation, configuration, customization, integration, data migration) Authoring of documentation needed by users and partners Testing, including defining/supporting acceptance testing and gathering feedback from pre-release testers Participation in software release and post-release activities, including support for product launch evangelism (e.g. developing demonstrations and/or samples) and subsequent product build/release cycles Maintenance Qualifications: Bachelor's degree in computer science or software engineering Several years of professional programming experience Proficiency in the general technology of the World Wide Web: Hypertext Transfer Protocol (HTTP) Hypertext Markup Language (HTML) JavaScript Cascading Style Sheets (CSS) Proficiency in the following principles, practices, and techniques: Accessibility Interoperability Usability Security (especially prevention of SQL injection and cross-site scripting (XSS) attacks) Object-oriented programming (e.g. encapsulation, inheritance, modularity, polymorphism, etc.) Relational database design (e.g. normalization, orthogonality) Search engine optimization (SEO) Asynchronous JavaScript and XML (AJAX) Proficiency in the following specific technologies utilized by Company: C# or Visual Basic .NET ADO.NET (including ADO.NET Entity Framework) ASP.NET (including ASP.NET MVC Framework) Windows Presentation Foundation (WPF) Language Integrated Query (LINQ) Extensible Application Markup Language (XAML) jQuery Transact-SQL (T-SQL) Microsoft Visual Studio Microsoft Internet Information Services (IIS) Microsoft SQL Server Adobe Photoshop

    Read the article

  • Cast errors with IXmlSerializable

    - by Nathan
    I am trying to use the IXmlSerializable interface to deserialize an Object (I am using it because I need specific control over what gets deserialized and what does not. See my previous question for more information). However, I'm stumped as to the error message I get. Below is the error message I get (I have changed some names for clarity): An unhandled exception of type 'System.InvalidCastException' occurred in App.exe Additional information: Unable to cast object of type 'System.Xml.XmlNode[]' to type 'MyObject'. MyObject has all the correct methods defined for the interface, and regardless of what I put in the method body for ReadXml() I still get this error. It doesn't matter if it has my implementation code or if it's just blank. I did some googling and found an error that looks similar to this involving polymorphic objects that implement IXmlSerializable. However, my class does not inherit from any others (besides Object). I suspected this may be an issue because I never reference XmlNode any other time in my code. Microsoft describes a solution to the polymorphism error: https://connect.microsoft.com/VisualStudio/feedback/details/422577/incorrect-deserialization-of-polymorphic-type-that-implements-ixmlserializable?wa=wsignin1.0#details The code the error occurs at is as follows. The object to be read back in is an ArrayList of "MyObjects" IO::FileStream ^fs = gcnew IO::FileStream(filename, IO::FileMode::Open); array<System::Type^>^ extraTypes = gcnew array<System::Type^>(1); extraTypes[0] = MyObject::typeid; XmlSerializer ^xmlser = gcnew XmlSerializer(ArrayList::typeid, extraTypes); System::Object ^obj; obj = xmlser->Deserialize(fs); fs->Close(); ArrayList ^al = safe_cast<ArrayList^>(obj); MyObject ^objs; for each(objs in al) //Error occurs here { //do some processing } Thanks for reading and for any help.

    Read the article

  • Ways to gain a deeper understanding of programming concepts?

    - by MrPlow
    I'm a marketer and have been messing around in PHP/MySQL for years. Recently (the last several months) I've been making my own scripts/programs in Python and I've really enjoyed the whole problem solving process. I've read(skimmed) some books and understand the basics of OOP, polymorphism, etc.. I have a general interest in AI and Natural Language in particular but it seems these things require a masters in Computer Science. My knowledge of math is poor. The last class I took was calculus, and I've forgotten the majority of it. Basically I'm looking for things to learn that will help me think in a more analytic way, and maybe see solutions where I didn't before. Improving my ability to program in Python would be nice too. I don't need to learn a specific language or something for employment, just enjoyment. Although my work often involves web development so some utility would be nice. I don't like learning concepts by just reading them. I need to apply them, even if the examples are contrived. A recommendation of a couple good books or other resources would be nice. :) Apologies if this is too vague/misplaced...

    Read the article

  • Is there any reason to use C instead of C++ for embedded development?

    - by Piotr Czapla
    Question I have two compilers on my hardware C++ and C89 I'm thinking about using C++ with classes but without polymorphism (to avoid vtables). The main reasons I’d like to use C++ are: I prefer to use “inline” functions instead of macro definitions. I’d like to use namespaces as I prefixes clutter the code. I see C++ a bit type safer mainly because of templates, and verbose casting. I really like overloaded functions and constructors (used for automatic casting). Do you see any reason to stick with C89 when developing for very limited hardware (4kb of RAM)? Conclusion Thank you for your answers, they were really helpful! I though the subject through and I will stick with C mainly because: It is easier to predict actual code in C and this is really important if you have only 4kb of ram. My team consists of C developers mainly so advance features of C++ won't be frequently used. I've found a way to inline functions in my C compiler (C89). It is hard to accept one answer as you provided so many good answers. Unfortunately I can't create a wiki and accept it so I will choose one answer that made me think most.

    Read the article

  • Reverse mapping from a table to a model in SQLAlchemy

    - by Jace
    To provide an activity log in my SQLAlchemy-based app, I have a model like this: class ActivityLog(Base): __tablename__ = 'activitylog' id = Column(Integer, primary_key=True) activity_by_id = Column(Integer, ForeignKey('users.id'), nullable=False) activity_by = relation(User, primaryjoin=activity_by_id == User.id) activity_at = Column(DateTime, default=datetime.utcnow, nullable=False) activity_type = Column(SmallInteger, nullable=False) target_table = Column(Unicode(20), nullable=False) target_id = Column(Integer, nullable=False) target_title = Column(Unicode(255), nullable=False) The log contains entries for multiple tables, so I can't use ForeignKey relations. Log entries are made like this: doc = Document(name=u'mydoc', title=u'My Test Document', created_by=user, edited_by=user) session.add(doc) session.flush() # See note below log = ActivityLog(activity_by=user, activity_type=ACTIVITY_ADD, target_table=Document.__table__.name, target_id=doc.id, target_title=doc.title) session.add(log) This leaves me with three problems: I have to flush the session before my doc object gets an id. If I had used a ForeignKey column and a relation mapper, I could have simply called ActivityLog(target=doc) and let SQLAlchemy do the work. Is there any way to work around needing to flush by hand? The target_table parameter is too verbose. I suppose I could solve this with a target property setter in ActivityLog that automatically retrieves the table name and id from a given instance. Biggest of all, I'm not sure how to retrieve a model instance from the database. Given an ActivityLog instance log, calling self.session.query(log.target_table).get(log.target_id) does not work, as query() expects a model as parameter. One workaround appears to be to use polymorphism and derive all my models from a base model which ActivityLog recognises. Something like this: class Entity(Base): __tablename__ = 'entities' id = Column(Integer, primary_key=True) title = Column(Unicode(255), nullable=False) edited_at = Column(DateTime, onupdate=datetime.utcnow, nullable=False) entity_type = Column(Unicode(20), nullable=False) __mapper_args__ = {'polymorphic_on': entity_type} class Document(Entity): __tablename__ = 'documents' __mapper_args__ = {'polymorphic_identity': 'document'} body = Column(UnicodeText, nullable=False) class ActivityLog(Base): __tablename__ = 'activitylog' id = Column(Integer, primary_key=True) ... target_id = Column(Integer, ForeignKey('entities.id'), nullable=False) target = relation(Entity) If I do this, ActivityLog(...).target will give me a Document instance when it refers to a Document, but I'm not sure it's worth the overhead of having two tables for everything. Should I go ahead and do it this way?

    Read the article

  • Java - Call to start method on thread : how does it route to Runnable interface's run () ?

    - by Bhaskar
    Ok , I know the two standard ways to create a new thread and run it in Java : 1 Implement Runnable in a class , define run method ,and pass an instance of the class to a new Thread. When the start method on the thread instance is called , the run method of the class instance will be invoked. 2 Let the class derive from Thread, so it can to override the method run() and then when a new instance's start method is called , the call is routed to overridden method. In both methods , basically a new Thread object is created and its start method invoked. However , while in the second method , the mechanism of the call being routed to the user defined run() method is very clear ,( its a simple runtime polymorphism in play ), I dont understand how the call to start method on the Thread object gets routed to run() method of the class implementing Runnable interface. Does the Thread class have an private field of Type Runnable which it checks first , and if it is set then invokes the run method if it set to an object ? that would be a strange mechanism IMO. How does the call to start() on a thread get routed to the run method of the Runnable interface implemented by the class whose object is passed as a parameter when contructing the thread ?

    Read the article

  • c++ Design pattern for CoW, inherited classes, and variable shared data?

    - by krunk
    I've designed a copy-on-write base class. The class holds the default set of data needed by all children in a shared data model/CoW model. The derived classes also have data that only pertains to them, but should be CoW between other instances of that derived class. I'm looking for a clean way to implement this. If I had a base class FooInterface with shared data FooDataPrivate and a derived object FooDerived. I could create a FooDerivedDataPrivate. The underlying data structure would not effect the exposed getters/setters API, so it's not about how a user interfaces with the objects. I'm just wondering if this is a typical MO for such cases or if there's a better/cleaner way? What peeks my interest, is I see the potential of inheritance between the the private data classes. E.g. FooDerivedDataPrivate : public FooDataPrivate, but I'm not seeing a way to take advantage of that polymorphism in my derived classes. class FooDataPrivate { public: Ref ref; // atomic reference counting object int a; int b; int c; }; class FooInterface { public: // constructors and such // .... // methods are implemented to be copy on write. void setA(int val); void setB(int val); void setC(int val); // copy constructors, destructors, etc. all CoW friendly private: FooDataPrivate *data; }; class FooDerived : public FooInterface { public: FooDerived() : FooInterface() {} private: // need more shared data for FooDerived // this is the ???, how is this best done cleanly? };

    Read the article

  • Retrieve only the superclass from a class hierarchy

    - by user1792724
    I have an scenario as the following: @Entity @Table(name = "ANIMAL") @Inheritance(strategy = InheritanceType.JOINED) public class Animal implements Serializable { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "S_ANIMAL") @SequenceGenerator(name = "S_ANIMAL", sequenceName = "S_ANIMAL", allocationSize = 1) public int getNumero() { return numero; } public void setNumero(int numero) { this.numero = numero; } . . . } and as the subclass: @Entity @Table(name = "DOG") public class Dog extends Animal { private static final long serialVersionUID = -7341592543130659641L; . . . } I have a JPA Select statement like this: SELECT a FROM Animal a; I'm using Hibernate 3.3.1 As I can see the framework retrieves instances of Animal and also of Dog using a left outer join. Is there a way to Select only the "part" Animal? I mean, the previous Select will get all the Animals, those that are only Animals but not Dogs and those that are Dogs. I want them all, but in the case of Dogs I want to only retrieve the "Animal part" of them. I found the @org.hibernate.annotations.Entity(polymorphism = PolymorphismType.EXPLICIT) but as I could see this only works if Animal isn't an @Entity. Thanks a lot.

    Read the article

  • Is it poor design to create objects that only execute code during the constructor?

    - by Curtix
    In my design I am using objects that evaluate a data record. The constructor is called with the data record and type of evaluation as parameters and then the constructor calls all of the object's code necessary to evaluate the record. This includes using the type of evaluation to find additional parameter-like data in a text file. There are in the neighborhood of 250 unique evaluation types that use the same or similar code and unique parameters coming from the text file. Some of these evaluations use different code so I benefit a lot from this model because I can use inheritance and polymorphism. Once the object is created there isn't any need to execute additional code on the object (at least for now) and it is used more like a struct; its kept on a list and 3 properties are used later. I think this design is the easiest to understand, code, and read. A logical alternative I guess would be using functions that return score structs, but you can't inherit from methods so it would make it kind of sloppy imo. I am using vb.net and these classes will be used in an asp.net web app as well as in a distributed app. thanks for your input

    Read the article

  • Approaches for animating a C# property over time?

    - by Mario Fritsch
    I'm currently trying to animate a bunch of public properties on certain objects. Usually they are of type float or vectors of floats (the type is known at compile-time). I want to be able to: assign a static value to them (MyObject.Duration = 10f;) or assign a random value to them by specifying a minimum and maximum value and optionally also a weight (MyObject.Duration = new RandomFloat(5f, 20f, 2f);) or "bind" this property to the property of another object (think of a child object binding some of its properties to its parent object, like its color or size or sth.) or assign sort of a keyframe animation to them, specifying a variable number of keyframes with timecode and the property's value at that specific point in time as well as information about how to interpolate between these frames The keyframes should be able to accept random values for each frame, both for the time and the property's value. What would be a practical approach for this kind of system? Currently I'm thinking about polymorphism: implement a base class or interface with a public Value-property and/or GetValue(float time)-method and then creating different sub classes like StaticValue, RandomValue, BindingValue and AnimatedValue implementing this base class or interface. Doesn't seem very elegant, though, and the initialization of even simple objects becomes a bit tedious. Another idea would be to implement these properties just as regular floats or vectors and create special "Modifier"-types binding to these properties. To retrieve the "real" value of the property, I'd first call any Modifier bound to the property, which would in turn update the actual object's property for me to retrieve later on. That would most likely mean using reflection at some point, which could be quite bad for performance as I'll probably have thousands of properties to update dozens of times per second. Any suggestions on this? Being a novice I'm (hopefully) missing some far more elegant and/or practical solution than I'm already playing around with :( Edit: Probably should have mentioned this earlier, but WPF isn't an option - it's not available on all targetted platforms, so I can't rely on it. I'm aware of its powerful databinding and animation capabilities, but I need to roll my own (or find some other lightweight alternative meeting my needs).

    Read the article

  • Large Switch statements: Bad OOP?

    - by Mystere Man
    I've always been of the opinion that large switch statements are a symptom of bad OOP design. In the past, I've read articles that discuss this topic and they have provided altnerative OOP based approaches, typically based on polymorphism to instantiate the right object to handle the case. I'm now in a situation that has a monsterous switch statement based on a stream of data from a TCP socket in which the protocol consists of basically newline terminated command, followed by lines of data, followed by an end marker. The command can be one of 100 different commands, so I'd like to find a way to reduce this monster switch statement to something more manageable. I've done some googling to find the solutions I recall, but sadly, Google has become a wasteland of irrelevant results for many kinds of queries these days. Are there any patterns for this sort of problem? Any suggestions on possible implementations? One thought I had was to use a dictionary lookup, matching the command text to the object type to instantiate. This has the nice advantage of merely creating a new object and inserting a new command/type in the table for any new commands. However, this also has the problem of type explosion. I now need 100 new classes, plus I have to find a way to interface them cleanly to the data model. Is the "one true switch statement" really the way to go? I'd appreciate your thoughts, opinions, or comments.

    Read the article

  • If I cast an IQueryable as an IEnumerable then call a Linq extension method, which implementation gets called?

    - by James Morcom
    Considering the following code: IQueryable<T> queryable; // something to instantiate queryable var enumerable = (IEnumerable<T>) queryable; var filtered = enumerable.Where(i => i > 3); In the final line, which extension method gets called? Is it IEnumerable<T>.Where(...)? Or will IQueryable<T>.Where(...) be called because the actual implementation is still obviously a queryable? Presumably the ideal would be for the IQueryable version to be called, in the same way that normal polymorphism will always use the more specific override. In Visual Studio though when I right-click on the Where method and "Go to Definition" I'm taken to the IEnumerable version, which kind of makes sense from a visual point-of-view. My main concern is that if somewhere in my app I use Linq to NHibernate to get a Queryable, but I pass it around using an interface that uses the more general IEnumerable signature, I'll lose the wonders of deferred database execution!

    Read the article

  • when is a v-table created in C++?

    - by saminny
    When exactly does the compiler create a virtual function table? 1) when the class contains at least one virtual function. OR 2) when the immediate base class contains at least one virtual function. OR 3) when any parent class at any level of the hierarchy contains at least one virtual function. A related question to this: Is it possible to give up dynamic dispatch in a C++ hierarchy? e.g. consider the following example. #include <iostream> using namespace std; class A { public: virtual void f(); }; class B: public A { public: void f(); }; class C: public B { public: void f(); }; Which classes will contain a V-Table? Since B does not declare f() as virtual, does class C get dynamic polymorphism?

    Read the article

  • Using enum values to represent binary operators (or functions)

    - by Bears will eat you
    I'm looking for an elegant way to use values in a Java enum to represent operations or functions. My guess is, since this is Java, there just isn't going to be a nice way to do it, but here goes anyway. My enum looks something like this: public enum Operator { LT, LTEQ, EQEQ, GT, GTEQ, NEQ; ... } where LT means < (less than), LTEQ means <= (less than or equal to), etc - you get the idea. Now I want to actually use these enum values to apply an operator. I know I could do this just using a whole bunch of if-statements, but that's the ugly, OO way, e.g.: int a = ..., b = ...; Operator foo = ...; // one of the enum values if (foo == Operator.LT) { return a < b; } else if (foo == Operator.LTEQ) { return a <= b; } else if ... // etc What I'd like to be able to do is cut out this structure and use some sort of first-class function or even polymorphism, but I'm not really sure how. Something like: int a = ..., b = ...; Operator foo = ...; return foo.apply(a, b); or even int a = ..., b = ...; Operator foo = ...; return a foo.convertToOperator() b; But as far as I've seen, I don't think it's possible to return an operator or function (at least, not without using some 3rd-party library). Any suggestions?

    Read the article

  • Avoiding instanceof in Java

    - by Mark Lutton
    Having a chain of "instanceof" operations is considered a "code smell". The standard answer is "use polymorphism". How would I do it in this case? There are a number of subclasses of a base class; none of them are under my control. An analogous situation would be with the Java classes Integer, Double, BigDecimal etc. if (obj instanceof Integer) {NumberStuff.handle((Integer)obj);} else if (obj instanceof BigDecimal) {BigDecimalStuff.handle((BigDecimal)obj);} else if (obj instanceof Double) {DoubleStuff.handle((Double)obj);} I do have control over NumberStuff and so on. I don't want to use many lines of code where a few lines would do. (Sometimes I make a HashMap mapping Integer.class to an instance of IntegerStuff, BigDecimal.class to an instance of BigDecimalStuff etc. But today I want something simpler.) I'd like something as simple as this: public static handle(Integer num) { ... } public static handle(BigDecimal num) { ... } But Java just doesn't work that way. I'd like to use static methods when formatting. The things I'm formatting are composite, where a Thing1 can contain an array Thing2s and a Thing2 can contain an array of Thing1s. I had a problem when I implemented my formatters like this: class Thing1Formatter { private static Thing2Formatter thing2Formatter = new Thing2Formatter(); public format(Thing thing) { thing2Formatter.format(thing.innerThing2); } } class Thing2Formatter { private static Thing1Formatter thing1Formatter = new Thing1Formatter(); public format(Thing2 thing) { thing1Formatter.format(thing.innerThing1); } } Yes, I know the HashMap and a bit more code can fix that too. But the "instanceof" seems so readable and maintainable by comparison. Is there anything simple but not smelly?

    Read the article

  • Book Review: Oracle ADF Real World Developer’s Guide

    - by Frank Nimphius
    Recently PACKT Publishing published "Oracle ADF Real World Developer’s Guide" by Jobinesh Purushothaman, a product manager in our team. Though already the sixth book dedicated to Oracle ADF, it has a lot of great information in it that none of the previous books covered, making it a safe buy even for those who own the other books published by Oracle Press (McGrwHill) and PACKT Publishing. More than the half of the "Oracle ADF Real World Developer’s Guide" book is dedicated to Oracle ADF Business Components in a depth and clarity that allows you to feel the expertise that Jobinesh gained in this area. If you enjoy Jobinesh blog (http://jobinesh.blogspot.co.uk/) about Oracle ADF, then, no matter what expert you are in Oracle ADF, this book makes you happy as it provides you with detail information you always wished to have. If you are new to Oracle ADF, then this book alone doesn't get you flying, but, if you have some Java background, accelerates your learning big, big, big times. Chapter 1 is an introduction to Oracle ADF and not only explains the layers but also how it compares to plain Java EE solutions (page 13). If you are new to Oracle JDeveloper and ADF, then at the end of this chapter you know how to start JDeveloper and begin your ADF development Chapter 2 starts with what Jobinesh really is good at: ADF Business Components. In this chapter you learn about the architecture ingredients of ADF Business Components: View Objects, View Links, Associations, Entities, Row Sets, Query Collections and Application Modules. This chapter also provides a introduction to ADFBC SDO services, as well as sequence diagrams for what happens when you execute queries or commit updates. Chapter 3 is dedicated to entity objects and  is one of many chapters in this book you will enjoy and never want to miss. Jobinesh explains the artifacts that make up an entity object, how to work with entities and resource bundles, and many advanced topics, including inheritance, change history tracking, custom properties, validation and cursor handling.  Chapter 4 - you guessed it - is all about View objects. Comparable to entities, you learn about the XM files and classes that make a view object, as well as how to define and work with queries. List-of-values, inheritance, polymorphism, bind variables and data filtering are interesting - and important topics that follow. Again the chapter provides helpful sequence diagrams for you to understand what happens internally within a view object. Chapter 5 focuses on advanced view object and entity object topics, like lifecycle callback methods and when you want to override them. This chapter is a good digest of Jobinesh's blog entries (which most ADF developers have in their bookmark list). Really worth reading ! Chapter 6 then is bout Application Modules. Beside of what application modules are, this chapter covers important topics like properties, passivation, activation, application module pooling, how and where to write custom logic. In addition you learn about the AM lifecycle and request sequence. Chapter 7 is about the ADF binding layer. If you are new to Oracle ADF and got lost in the more advanced ADF Business Components chapters, then this chapter is where you get back into the game. In very easy terms, Jobinesh explains what the ADF binding is, how it fits into the JSF request lifecycle and what are the metadata file involved. Chapter 8 then goes into building data bound web user interfaces. In this chapter you get the basics of JavaServer Faces (e.g. managed beans) and learn about the interaction between the JSF UI and the ADF binding layer. Later this chapter provides advanced solutions for working with tree components and list of values. Chapter 9 introduces bounded task flows and ADF controller. This is a chapter you want to read if you are new to ADF of have started. Experts don't find anything new here, which doesn't mean that it is not worth reading it (I for example, enjoyed the controller talk very much) Chapter 10 is an advanced coverage of bounded task flow and talks about contextual events  Chapter 11 is another highlight and explains error handling, trains, transactions and more. I can only recommend you read this chapter. I am aware of many documents that cover exception handling in Oracle ADF (and my Oracle Magazine article for January/February 2013 does the same), but none that covers it in such a great depth. Chapter 12 covers ADF best practices, which is a great round-up of all the tips provided in this book (without Jobinesh to repeat himself). Its all cool stuff that helps you with your ADF projects. In summary, "Oracle ADF Real World Developer’s Guide" by Jobinesh Purushothaman is a great book and addition for all Oracle ADF developers and those who want to become one. Frank

    Read the article

  • Breaking through the class sealing

    - by Jason Crease
    Do you understand 'sealing' in C#?  Somewhat?  Anyway, here's the lowdown. I've done this article from a C# perspective, but I've occasionally referenced .NET when appropriate. What is sealing a class? By sealing a class in C#, you ensure that you ensure that no class can be derived from that class.  You do this by simply adding the word 'sealed' to a class definition: public sealed class Dog {} Now writing something like " public sealed class Hamster: Dog {} " you'll get a compile error like this: 'Hamster: cannot derive from sealed type 'Dog' If you look in an IL disassembler, you'll see a definition like this: .class public auto ansi sealed beforefieldinit Dog extends [mscorlib]System.Object Note the addition of the word 'sealed'. What about sealing methods? You can also seal overriding methods.  By adding the word 'sealed', you ensure that the method cannot be overridden in a derived class.  Consider the following code: public class Dog : Mammal { public sealed override void Go() { } } public class Mammal { public virtual void Go() { } } In this code, the method 'Go' in Dog is sealed.  It cannot be overridden in a subclass.  Writing this would cause a compile error: public class Dachshund : Dog { public override void Go() { } } However, we can 'new' a method with the same name.  This is essentially a new method; distinct from the 'Go' in the subclass: public class Terrier : Dog { public new void Go() { } } Sealing properties? You can also seal seal properties.  You add 'sealed' to the property definition, like so: public sealed override string Name {     get { return m_Name; }     set { m_Name = value; } } In C#, you can only seal a property, not the underlying setters/getters.  This is because C# offers no override syntax for setters or getters.  However, in underlying IL you seal the setter and getter methods individually - a property is just metadata. Why bother sealing? There are a few traditional reasons to seal: Invariance. Other people may want to derive from your class, even though your implementation may make successful derivation near-impossible.  There may be twisted, hacky logic that could never be second-guessed by another developer.  By sealing your class, you're protecting them from wasting their time.  The CLR team has sealed most of the framework classes, and I assume they did this for this reason. Security.  By deriving from your type, an attacker may gain access to functionality that enables him to hack your system.  I consider this a very weak security precaution. Speed.  If a class is sealed, then .NET doesn't need to consult the virtual-function-call table to find the actual type, since it knows that no derived type can exist.  Therefore, it could emit a 'call' instead of 'callvirt' or at least optimise the machine code, thus producing a performance benefit.  But I've done trials, and have been unable to demonstrate this If you have an example, please share! All in all, I'm not convinced that sealing is interesting or important.  Anyway, moving-on... What is automatically sealed? Value types and structs.  If they were not always sealed, all sorts of things would go wrong.  For instance, structs are laid-out inline within a class.  But what if you assigned a substruct to a struct field of that class?  There may be too many fields to fit. Static classes.  Static classes exist in C# but not .NET.  The C# compiler compiles a static class into an 'abstract sealed' class.  So static classes are already sealed in C#. Enumerations.  The CLR does not track the types of enumerations - it treats them as simple value types.  Hence, polymorphism would not work. What cannot be sealed? Interfaces.  Interfaces exist to be implemented, so sealing to prevent implementation is dumb.  But what if you could prevent interfaces from being extended (i.e. ban declarations like "public interface IMyInterface : ISealedInterface")?  There is no good reason to seal an interface like this.  Sealing finalizes behaviour, but interfaces have no intrinsic behaviour to finalize Abstract classes.  In IL you can create an abstract sealed class.  But C# syntax for this already exists - declaring a class as a 'static', so it forces you to declare it as such. Non-override methods.  If a method isn't declared as override it cannot be overridden, so sealing would make no difference.  Note this is stated from a C# perspective - the words are opposite in IL.  In IL, you have four choices in total: no declaration (which actually seals the method), 'virtual' (called 'override' in C#), 'sealed virtual' ('sealed override' in C#) and 'newslot virtual' ('new virtual' or 'virtual' in C#, depending on whether the method already exists in a base class). Methods that implement interface methods.  Methods that implement an interface method must be virtual, so cannot be sealed. Fields.  A field cannot be overridden, only hidden (using the 'new' keyword in C#), so sealing would make no sense.

    Read the article

< Previous Page | 8 9 10 11 12 13  | Next Page >