Search Results

Search found 1591 results on 64 pages for 'oop criticism'.

Page 19/64 | < Previous Page | 15 16 17 18 19 20 21 22 23 24 25 26  | Next Page >

  • Multiple classes in Codeigniter

    - by Leon
    I want to create an array of objects, so what I did was to create a library but I can't figure out how to actually dynamically create instances of it in a loop and store each instance in an array. Can anyone tell me please?

    Read the article

  • Why is execution-time method resolution faster than compile-time resolution?

    - by Felix
    At school, we about virtual functions in C++, and how they are resolved (or found, or matched, I don't know what the terminology is -- we're not studying in English) at execution time instead of compile time. The teacher also told us that compile-time resolution is much faster than execution-time (and it would make sense for it to be so). However, a quick experiment would suggest otherwise. I've built this small program: #include <iostream> #include <limits.h> using namespace std; class A { public: void f() { // do nothing } }; class B: public A { public: void f() { // do nothing } }; int main() { unsigned int i; A *a = new B; for (i=0; i < UINT_MAX; i++) a->f(); return 0; } Where I made A::f() once normal, once virtual. Here are my results: [felix@the-machine C]$ time ./normal real 0m25.834s user 0m25.742s sys 0m0.000s [felix@the-machine C]$ time ./virtual real 0m24.630s user 0m24.472s sys 0m0.003s [felix@the-machine C]$ time ./normal real 0m25.860s user 0m25.735s sys 0m0.007s [felix@the-machine C]$ time ./virtual real 0m24.514s user 0m24.475s sys 0m0.000s [felix@the-machine C]$ time ./normal real 0m26.022s user 0m25.795s sys 0m0.013s [felix@the-machine C]$ time ./virtual real 0m24.503s user 0m24.468s sys 0m0.000s There seems to be a steady ~1 second difference in favor of the virtual version. Why is this? Relevant or not: dual-core pentium @ 2.80Ghz, no extra applications running between two tests. Archlinux with gcc 4.5.0. Compiling normally, like: $ g++ test.cpp -o normal Also, -Wall doesn't spit out any warnings, either.

    Read the article

  • DDD and MVC: Difference between 'Model' and 'Entity'

    - by Nathan Loding
    I'm seriously confused about the concept of the 'Model' in MVC. Most frameworks that exist today put the Model between the Controller and the database, and the Model almost acts like a database abstraction layer. The concept of 'Fat Model Skinny Controller' is lost as the Controller starts doing more and more logic. In DDD, there is also the concept of a Domain Entity, which has a unique identity to it. As I understand it, a user is a good example of an Entity (unique userid, for instance). The Entity has a life-cycle -- it's values can change throughout the course of the action -- and then it's saved or discarded. The Entity I describe above is what I thought Model was supposed to be in MVC? How off-base am I? To clutter things more, you throw in other patterns, such as the Repository pattern (maybe putting a Service in there). It's pretty clear how the Repository would interact with an Entity -- how does it with a Model? Controllers can have multiple Models, which makes it seem like a Model is less a "database table" than it is a unique Entity. So, in very rough terms, which is better? No "Model" really ... class MyController { public function index() { $repo = new PostRepository(); $posts = $repo->findAllByDateRange('within 30 days'); foreach($posts as $post) { echo $post->Author; } } } Or this, which has a Model as the DAO? class MyController { public function index() { $model = new PostModel(); // maybe this returns a PostRepository? $posts = $model->findAllByDateRange('within 30 days'); while($posts->getNext()) { echo $posts->Post->Author; } } } Both those examples didn't even do what I was describing above. I'm clearly lost. Any input?

    Read the article

  • C#: Inheritance, Overriding, and Hiding

    - by Rosarch
    I'm having difficulty with an architectural decision for my C# XNA game. The basic entity in the world, such as a tree, zombie, or the player, is represented as a GameObject. Each GameObject is composed of at least a GameObjectController, GameObjectModel, and GameObjectView. These three are enough for simple entities, like inanimate trees or rocks. However, as I try to keep the functionality as factored out as possible, the inheritance begins to feel unwieldy. Syntactically, I'm not even sure how best to accomplish my goals. Here is the GameObjectController: public class GameObjectController { protected GameObjectModel model; protected GameObjectView view; public GameObjectController(GameObjectManager gameObjectManager) { this.gameObjectManager = gameObjectManager; model = new GameObjectModel(this); view = new GameObjectView(this); } public GameObjectManager GameObjectManager { get { return gameObjectManager; } } public virtual GameObjectView View { get { return view; } } public virtual GameObjectModel Model { get { return model; } } public virtual void Update(long tick) { } } I want to specify that each subclass of GameObjectController will have accessible at least a GameObjectView and GameObjectModel. If subclasses are fine using those classes, but perhaps are overriding for a more sophisticated Update() method, I don't want them to have to duplicate the code to produce those dependencies. So, the GameObjectController constructor sets those objects up. However, some objects do want to override the model and view. This is where the trouble comes in. Some objects need to fight, so they are CombatantGameObjects: public class CombatantGameObject : GameObjectController { protected new readonly CombatantGameModel model; public new virtual CombatantGameModel Model { get { return model; } } protected readonly CombatEngine combatEngine; public CombatantGameObject(GameObjectManager gameObjectManager, CombatEngine combatEngine) : base(gameObjectManager) { model = new CombatantGameModel(this); this.combatEngine = combatEngine; } public override void Update(long tick) { if (model.Health <= 0) { gameObjectManager.RemoveFromWorld(this); } base.Update(tick); } } Still pretty simple. Is my use of new to hide instance variables correct? Note that I'm assigning CombatantObjectController.model here, even though GameObjectController.Model was already set. And, combatants don't need any special view functionality, so they leave GameObjectController.View alone. Then I get down to the PlayerController, at which a bug is found. public class PlayerController : CombatantGameObject { private readonly IInputReader inputReader; private new readonly PlayerModel model; public new PlayerModel Model { get { return model; } } private float lastInventoryIndexAt; private float lastThrowAt; public PlayerController(GameObjectManager gameObjectManager, IInputReader inputReader, CombatEngine combatEngine) : base(gameObjectManager, combatEngine) { this.inputReader = inputReader; model = new PlayerModel(this); Model.Health = Constants.PLAYER_HEALTH; } public override void Update(long tick) { if (Model.Health <= 0) { gameObjectManager.RemoveFromWorld(this); for (int i = 0; i < 10; i++) { Debug.WriteLine("YOU DEAD SON!!!"); } return; } UpdateFromInput(tick); // .... } } The first time that this line is executed, I get a null reference exception: model.Body.ApplyImpulse(movementImpulse, model.Position); model.Position looks at model.Body, which is null. This is a function that initializes GameObjects before they are deployed into the world: public void Initialize(GameObjectController controller, IDictionary<string, string> data, WorldState worldState) { controller.View.read(data); controller.View.createSpriteAnimations(data, _assets); controller.Model.read(data); SetUpPhysics(controller, worldState, controller.Model.BoundingCircleRadius, Single.Parse(data["x"]), Single.Parse(data["y"]), bool.Parse(data["isBullet"])); } Every object is passed as a GameObjectController. Does that mean that if the object is really a PlayerController, controller.Model will refer to the base's GameObjectModel and not the PlayerController's overriden PlayerObjectModel? In response to rh: This means that now for a PlayerModel p, p.Model is not equivalent to ((CombatantGameObject)p).Model, and also not equivalent to ((GameObjectController)p).Model. That is exactly what I do not want. I want: PlayerController p; p.Model == ((CombatantGameObject)p).Model p.Model == ((GameObjectController)p).Model How can I do this? override?

    Read the article

  • Proper way to set object instance variables

    - by ensnare
    I'm writing a class to insert users into a database, and before I get too far in, I just want to make sure that my OO approach is clean: class User(object): def setName(self,name): #Do sanity checks on name self._name = name def setPassword(self,password): #Check password length > 6 characters #Encrypt to md5 self._password = password def commit(self): #Commit to database >>u = User() >>u.setName('Jason Martinez') >>u.setPassword('linebreak') >>u.commit() Is this the right approach? Should I declare class variables up top? Should I use a _ in front of all the class variables to make them private? Thanks for helping out.

    Read the article

  • JavaScript check if anonymous object has a method

    - by Baddie
    How can I check if an anonymous object that was created as such: var myObj = { prop1: 'no', prop2: function () { return false; } } does indeed have a prop2 defined? prop2 will always be defined as a function, but for some objects it is not required and will not be defined. I tried what was suggested here: http://stackoverflow.com/questions/595766/how-to-determine-if-native-javascript-object-has-a-property-method but I don't think it works for anonymous objects .

    Read the article

  • Best Practice for Utilities Class?

    - by Sonny Boy
    Hey all, We currently have a utilities class that handles a lot of string formatting, date displays, and similar functionality and it's a shared/static class. Is this the "correct" way of doing things or should we be instanciating the utility class as and when we need it? Our main goal here is to reduce memory footprint but performance of the application is also a consideration. Thanks, Matt PS. We're using .NET 2.0

    Read the article

  • How do I dynamically instantiate a class in javascript?

    - by Adam
    I'm starting out with classes in Javascript and have hit a wall. I've looked all over for a tutorial that goes a little further than simply how to construct a class (usually Animal) then extend the class and have a Method do something (Dog alert('Bark');). I have created a class that I want a user to be able to instantiate (is that the right word)? For example the first stage in my program is for the user to give the class a name, and then start to populate the various variables in the class. When they've done that they may do it again many times. So if: var className = new MyObject(); How do I dynamically create the name of the new object className and then refer to it later in the code?

    Read the article

  • characteristics of the abstract class

    - by Harsha
    Hello All, I like to know what makes a class to be called as absract class. I believe, abract key word definetly make a class class, but if one takes out the keyword, then we can create the instance of the class. In otherwords, what are the characteristics of the abstract class. Thanks in advance. -Harsha

    Read the article

  • Implementation question involving implementing an interface

    - by Vivin Paliath
    I'm writing a set of collection classes for different types of Trees. I'm doing this as a learning exercise and I'm also hoping it turns out to be something useful. I really want to do this the right way and so I've been reading Effective Java and I've also been looking at the way Joshua Bloch implemented the collection classes by looking at the source. I seem to have a fair idea of what is being done, but I still have a few things to sort out. I have a Node<T> interface and an AbstractNode<T> class that implements the Node interface. I then created a GenericNode<T> (a node that can have 0 to n children, and that is part of an n-ary tree) class that extends AbstractNode<T> and implements Node<T>. This part was easy. Next, I created a Tree<T> interface and an AbstractTree<T> class that implements the Tree<T> interface. After that, I started writing a GenericTree<T> class that extends AbstractTree<T> and implements Tree<T>. This is where I started having problems. As far as the design is concerned, a GenericTree<T> can only consist of nodes of type GenericTreeNode<T>. This includes the root. In my Tree<T> interface I have: public interface Tree<T> { void setRoot(Node<T> root); Node<T> getRoot(); List<Node<T>> postOrder(); ... rest omitted ... } And, AbstractTree<T> implements this interface: public abstract class AbstractTree<T> implements Tree<T> { protected Node<T> root; protected AbstractTree() { } protected AbstractTree(Node<T> root) { this.root = root; } public void setRoot(Node<T> root) { this.root = root; } public Node<T> getRoot() { return this.root; } ... rest omitted ... } In GenericTree<T>, I can have: public GenericTree(Node<T> root) { super(root); } But what this means is that you can create a generic tree using any subtype of Node<T>. You can also set the root of a tree to any subtype of Node<T>. I want to be able to restrict the type of the node to the type of the tree that it can represent. To fix this, I can do this: public GenericTree(GenericNode<T> root) { super(root); } However, setRoot still accepts a parameter of type Node<T>. Which means a user can still create a tree with the wrong type of root node. How do I enforce this constraint? The only way I can think of doing is either: Do an instanceof which limits the check to runtime. I'm not a huge fan of this. Remove setRoot from the interface and have the base class implement this method. This means that it is not part of the contract and anyone who wants to make a new type of tree needs to remember to implement this method. Is there a better way? The second question I have concerns the return type of postOrder which is List<Node<T>>. This means that if a user is operating on a GenericTree<T> object and calls postOrder, he or she receives a list that consists of Node<T> objects. This means when iterating through (using a foreach construct) they would have perform an explicit cast to GenericNode<T> if they want to use methods that are only defined in that class. I don't like having to place this burden on the user. What are my options in this case? I can only think of removing the method from the interface and have the subclass implement this method making sure that it returns a list of appropriate subtype of Node<T>. However, this once again removes it from the contract and it's anyone who wants to create a new type of tree has to remember to implement this method. Is there a better way?

    Read the article

  • Can you declare <canvas> methods within a template in javascript?

    - by Binarytales
    Not entirely sure I posed the question in the best way but here goes... I have been playing around with the HTML5 canvas API and have got as far as drawing a shape in the canvas and getting it to move around with the arrow keys. I then tried to move my various variables and functions to a template so I could spawn multiple shapes (that would eventually be controlled by different keys). This is what I have: function player(x, y, z, colour, speed){ this.lx = x; this.ly = y; this.speed = 10; this.playerSize = z; this.colour = colour; } playerOne = new player(100, 100, 10, "#F0F"); function persona(z, colour){ zone.fillStyle = colour; offset = 0 - (z / 2); zone.fillRect(offset, offset, z, z); } function move(x, y){ playerOne.lx = playerOne.lx + x; playerOne.ly = playerOne.ly + y; zone.clearRect(0, 0, 500, 500); zone.save(); zone.translate(playerOne.lx, playerOne.ly); persona(playerOne.playerSize, playerOne.colour); zone.restore(); } window.onkeydown = function() { var direction = this.event.keyCode; var s = playerOne.speed; // Arrow Keys if( direction == 38 && playerOne.ly >= 10){ // Up move(0,-s); } if( direction == 40 && playerOne.ly <= 490){ // Down move(0,s); } if( direction == 37 && playerOne.lx >= 10){ // Left move(-s,0); } if( direction == 39 && playerOne.lx <= 490){ // Right move(s,0); } }; window.onload = function() { zone = document.getElementById('canvas').getContext('2d'); zone.save(); zone.translate(playerOne.lx, playerOne.ly); persona(playerOne.playerSize, playerOne.colour); zone.restore(); }; So what I tried to do was move the persona function into the player template like this: function player(x, y, z, colour, speed){ this.lx = x; this.ly = y; this.speed = 10; function persona(){ zone.fillStyle = colour; var offset = 0 - (z / 2); zone.fillRect(offset, offset, z, z); } } And then where before it said persona(playerOne.playerSize, playerOne.colour); it now just says playerOne.persona(); But this is just totally flaking out and not working and I can't figure out why. I'm probably going about it all the wrong way and I think the problem is that I'm trying to manipulate the canvas.context (call zone in my script) from within a object/template. Perhaps its nothing to do with that at all and I an just not declaring my persona functions properly in the context of the template. Documentation for the canvas API is very thin on the ground and any hint in the right direction will be very much appreciated.

    Read the article

  • Where should Nhibernate IPostInsertEventListener go in the 3 tier architecture

    - by Quintin Par
    I have a IPostInsertEventListener implementation like public class NHibernateEventListener : IPostInsertEventListener, IPostUpdateEventListener which catches some entity inserts and does an additional insert to another table for ETL. Essentially it requires references to the Nhibernate, Domain entity and Repository<> Now where do I go about adding this class? If I add it to ApplicationServices I’ll end up referencing Nhibernate at that layer. If I add this to the Data layer, I’ll have to reference Domain (circular). How do I go implementing this class with S#arp principles? Any thoughts?

    Read the article

  • jQuery style Constructors in PHP

    - by McB
    Is there a way to instantiate a new PHP object in a similar manner to those in jQuery? I'm talking about assigning a variable number of arguments when creating the object. For example, I know I could do something like: ... //in my Class __contruct($name, $height, $eye_colour, $car, $password) { ... } $p1 = new person("bob", "5'9", "Blue", "toyota", "password"); But I'd like to set only some of them maybe. So something like: $p1 = new person({ name: "bob", eyes: "blue"}); Which is more along the lines of how it is done in jQuery and other frameworks. Is this built in to PHP? Is there a way to do it? Or a reason I should avoid it?

    Read the article

  • PHP sessions and class members.

    - by JDW
    Ok, messing about with classes in PHP and can't get it to work the way I'm used to as a C++/Java-guy. In the "_init" funtion, if I run a query at the "// query works here" line", everythong works, but in the "getUserID" function, all that happens is said warning... "getUserID" gets called from login.php (they are in the same dir): login.php <?php include_once 'sitehandler.php'; include_once 'dbhandler.php'; session_start(); #TODO: Safer input handling $t_userName = $_POST["name"]; $t_userId = $_SESSION['handler']['db']->getUserID($t_userName); if ($t_userId != -1) { $_SESSION['user']['name'] = $t_userName; $_SESSION['user']['id'] = $t_userId; } //error_log("user: " . $_SESSION['user']['name'] . ", id: ". $_SESSION['user']['id']); header("Location: " . $_SERVER["HTTP_REFERER"]); ? dbhandler.php <?php include_once 'handler.php'; class DBHandler extends HandlerAbstract { private $m_handle; function __construct() { parent::__construct(); } public function test() { #TODO: isdir liquibase #TODO: isfile liquibase-195/liquibase + .bat + execrights $this->m_isTested = true; } public function _init() { if (!$this->isTested()) $this->test(); if (!file_exists('files/data.db')) { #TODO: How to to if host is Windows based? exec('./files/liquibase-1.9.5/liquibase --driver=org.sqlite.JDBC --changeLogFile=files/data_db.xml --url=jdbc:sqlite:files/data.db update'); #TODO: quit if not success } #TODO: Set with default data try { $this->m_handle = new SQLite3('files/data.db'); } catch (Exception $e) { die("<hr />" . $e->getMessage() . "<hr />"); } // query works here $this->m_isSetup = true; } public function teardown() { } public function getUserID($name) { // PHP Warning: SQLite3::prepare(): The SQLite3 object has not been correctly initialised in $t_statement = $this->m_handle->prepare("SELECT id FROM users WHERE name = :name"); $t_statement->bindValue(":name", $name, SQLITE3_TEXT); $t_result = $t_statement->execute(); //var_dump($this->m_handle); return ($t_result)? (int)$t_result['id']: -1; } }

    Read the article

  • How Can I Learn about Interfaces

    - by BDotA
    I am using C# and I know what are the interfaces and how syntatically use them,etc. but what I have not learned yet is that when I am tasked to write a project, create a component,... How should I learn better about interfaces so when I want to do something I be able to Think about using them in my design...or for example I want to learn about dependency injection or even using mocking objects for testing, these are all related to good understanding of interfaces and know when and how to use them ... Can you plase provide me some good advice, reading,... then can help me with that?

    Read the article

  • My abstract class implements an interface but doesn't implement some of its methods. How do I make i

    - by Stefan Monov
    interface ICanvasTool { void Motion(Point newLocation); void Tick(); } abstract class CanvasTool_BaseDraw : ICanvasTool { protected abstract void PaintAt(Point location); public override void Motion(Point newLocation) { // implementation } } class CanvasTool_Spray : CanvasTool_BaseDraw { protected abstract void PaintAt(Point location) { // implementation } public override void Tick() { // implementation } } This doesn't compile. I could add an abstract method "Tick_Implementation" to CanvasTool_BaseDraw, then implement ICanvasTool.Tick in CanvasTool_BaseDraw with a one-liner that just calls Tick_Implementation. Is this the recommended workaround?

    Read the article

  • When should I use Dependency Injection and when utility methods?

    - by Roman
    I have a Java EE project with Spring IoC container. I've just found in Utils class static method sendMail(long list of params). I don't know why but I feel that it would look better if we had separate class (Spring bean with singleton scope) which will be responsible for sending email. But I can't find any arguments which can prove my position. So, are there any pros (or cons) in using DI in this (rather general) situation?

    Read the article

  • Two objects with dependencies for each other. Is that bad?

    - by Kasper Grubbe
    Hi SO. I am learning a lot about design patterns these days. And I want to ask you about a design question that I can't find an answer to. Currently I am building a little Chat-server using sockets, with multiple Clients. Currently I have three classes. Person-class which holds information like nick, age and a Room-object. Room-class which holds information like room-name, topic and a list of Persons currently in that room. Hotel-class which have a list of Persons and a list of Rooms on the server. I have made a diagram to illustrate it (Sorry for the big size!): http://i.imgur.com/Kpq6V.png I have a list of players on the server in the Hotel-class because it would be nice to keep track of how many there are online right now (Without having to iterate through all of the rooms). The persons live in the Hotel-class because I would like to be able to search for a specific Person without searching the rooms. Is this bad design? Is there another way of achieve it? Thanks.

    Read the article

  • How do I echo the number of items in an array?

    - by Joel
    A total newbie question I know. I'm sing Zend framework, and sending an array from the controller: $this->view->googleArray = $viewFeedArray; In the view, I have a foreach loop that is populating a table with the array contents. <?php foreach($this->googleArray as $row) { ?> <tr> <td><?php echo $row['when']; ?></td> ... ... </tr> <?php } ?> It all works fine. At the top of the table, I want to list the number of items in the array. Something like (which doesn't work): <?php echo $this->googleArray->totalResults; ?> event(s) found How would I do that? Thanks!

    Read the article

  • Lightweight PHP library alternative to common frameworks

    - by artarad
    Hi hi, I'm looking for a easy to learn php library to use for my coming web app project. I've recently finished a web app with fully handwritten raw php code and it's absolutely hard to be done again for another project. even though I have the recent project code snippets to be used again, but due to their non-structural arrangement (not object oriented), i have no passion to use 'em again. I have no experience with common frameworks like ZF, CakePhp, CodeIgniter, so I think to get my hands on a multipurpose OO library for my web app and the framework learning will be the next step! any suggestion? UPDATE: Many thanks guys, I have not enough time to get through the depth of every lib or framework you have kindly introduced. Since I'm going one step further I'm going to use ZF as famous framework which could provide me more job opportunities perhaps. thankssss :)

    Read the article

  • Can't declare even the most simple class in PHP - Am I going insane?

    - by Phil
    I'm getting this error whenever I attempt to declare a class: Parse error: syntax error, unexpected T_VARIABLE, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or '}' in /home3/foundloc/public_html/booka/page2.php on line 7 (line 7 is the class declaration by the way). Here's the incredibly simple class I am attempting to declare: Class abc { $a = “Hello!”; } Is there some setting on PHP that i need to turn on? I feel like this is one of those 'did you check if the TV is plugged in' type of issues....

    Read the article

< Previous Page | 15 16 17 18 19 20 21 22 23 24 25 26  | Next Page >