Search Results

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

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

  • Multi-level inheritance with Implements on properties in VB.NET vs C#

    - by Ben McCormack
    Let's say I have 2 interfaces defined like so: public interface ISkuItem { public string SKU { get; set; } } public interface ICartItem : ISkuItem { public int Quantity { get; set; } public bool IsDiscountable { get; set; } } When I go to implement the interface in C#, VS produces the following templated code: public class CartItem : ICartItem { #region ICartItem Members public int Quantity { get {...} set {...} } public bool IsDiscountable { get {...} set {...} } #endregion #region ISkuItem Members public string SKU { get {...} set {...} } #endregion } In VB.NET, the same class is built out like so: Public Class CartItem Implements ICartItem Public Property IsDiscountable As Boolean Implements ICartItem.IsDiscountable 'GET SET' End Property Public Property Quantity As Integer Implements ICartItem.Quantity 'GET SET' End Property Public Property SKU As String Implements ISkuItem.SKU 'GET SET' End Property End Class VB.NET explicitly requires you to add Implements IInterfaceName.PropertyName after each property that gets implemented whereas C# simply uses regions to indicate which properties and methods belong to the interface. Interestingly in VB.NET, on the SKU property, I can specify either Implements ISkuItem.SKU or Implements ICartItem.SKU. Although the template built by VS defaults to ISkuItem, I can also specify ICartItem if I want. Oddly, because C# only uses regions to block out inherited properties, it seems that I can't explicitly specify the implementing interface of SKU in C# like I can in VB.NET. My question is: Is there any importance behind being able to specify one interface or another to implement properites in VB.NET, and if so, is there a way to mimic this functionality in C#?

    Read the article

  • static void classes

    - by ivor
    Hello, I'm tidying up some of my code with the correct scope on some methods and attributes (I have two classes and at the moment I have a number which I just declared as public to get working, but I feel I should look into this and make private where possible, for better practice) When working in eclipse it's suggested on one method, when i change it private from public, that I can fix it by dropping off the scope so the method just says "static void" instead of public/private static void. Is this a better scenario to have nothing, rather than private or public - or is the default scope equivelant to public anyway ? Thanks

    Read the article

  • Can the Diamond Problem be really solved?

    - by Mecki
    A typical problem in OO programming is the diamond problem. I have parent class A with two sub-classes B and C. A has an abstract method, B and C implement it. Now I have a sub-class D, that inherits of B and C. The diamond problem is now, what implementation shall D use, the one of B or the one of C? People claim Java knows no diamond problem. I can only have multiple inheritance with interfaces and since they have no implementation, I have no diamond problem. Is this really true? I don't think so. See below: [removed vehicle example] Is a diamond problem always the cause of bad class design and something neither programmer nor compiler needs to solve, because it shouldn't exist in the first place? Update: Maybe my example was poorly chosen. See this image Of course you can make Person virtual in C++ and thus you will only have one instance of person in memory, but the real problem persists IMHO. How would you implement getDepartment() for GradTeachingFellow? Consider, he might be student in one department and teach in another one. So you can either return one department or the other one; there is no perfect solution to the problem and the fact that no implementation might be inherited (e.g. Student and Teacher could both be interfaces) doesn't seem to solve the problem to me.

    Read the article

  • What is the exact problem with multiple inheritance?

    - by Totophil
    I can see people asking all the time whether multiple inheritance should be included into the next version of C# or Java and C++ folks, who are fortunate enough to have this ability, say that this is like giving someone a rope to eventually hang themselves. What’s the matter with the multiple inheritance? Are there any concrete samples?

    Read the article

  • class composition instead of object composition?

    - by fayer
    I want a class property to be reference to another class, not its object and then use this property to call the class's static methods. class Database { private static $log; public static function addLog($LogClass) { self::$log = $LogClass; } public static function log() { self::$log::write(); // seems not possible to write it like this } } any suggestions how i can accomplish this? cause i have no reason making them objects, i want to use the classes for it.

    Read the article

  • Adding scope variable to an constructor

    - by Lupus
    I'm trying to create a class like architecture on javascript but stuck on a point. Here is the code: var make = function(args) { var priv = args.priv, cons = args.cons, pub = args.pub; return function(consParams) { var priv = priv, cons = args.cons; cons.prototype.constructor = cons; cons.prototype = $.extend({}, pub); if (!$.isFunction(cons)) { throw new Hata(100001); } return new cons(consParams); } }; I'm trying to add the priv variable on the returned function objects's scope and object scope of the cons.prototype but I could not make it; Here is the usage of the make object: var myClass = make({ cons: function() { alert(this.acik); }, pub: { acik: 'acik' }, priv: { gizli: 'gizli' } }) myObj = myClass(); PS: Please forgive my english...

    Read the article

  • CakePHP form $options['options']

    - by James
    Hey! Total CakePHP noob here. This is sort of a two fold question. In a view that is used for adding user objects I would like to use a drop down (selection) field in the form. Each user belongs to a group so when I add a user I want a drop down that contains all of the groups that the user could possibly join. Currently the group_id field is a textfield. I know how to force it to be a selection field, but I don't know how to populate the selection with the names of the groups programmatically. The Current method: echo $form->input('group_id', array( '1' => 'NameOfGroup1', '2' => 'NameOfGroup2', '3' => 'NameOfGroup3') ); I want to generate the options array programmatically though. echo $form->input('group_id', $this->Group->find('list')); This doesn't work though. I get an error: Undefined property: View::$Group [APP/views/users/add.ctp, line 8] To me this means that I don't have access to the Group object from inside my user view. How can I accomplish this? Again, I want to do it programmatically so that it updates as I add groups or remove them.

    Read the article

  • Thread not behaving correctly

    - by ivor
    Hello, I wonder if anyone can help me to understand where I could be going wrong with this code; Basically I'm working on a turorial and calling the class below from another class - and it is getting the following error; Exception in thread "Thread-1" java.lang.NullPointerException at org.newdawn.spaceinvaders.TCPChat.run(TCPChat.java:322) at java.lang.Thread.run(Unknown Source) I realise the error is beibg flagged in another class- but I have tested the other class with a small class which sets up a separate thread - and it works fine, but as soon as I try and implement a new thread in this class - it causes all sorts of problems. Am I setting up the thread correctly in this class? Basically I can set up a thread in this class, with a test loop and it's fine, but when I bring in the functionality of the rest of the game it sometimes hangs, or does not display at all. Any suggestions on where I could be going wrong would be greatly appreciated. Thanks for looking. package org.newdawn.spaceinvaders; import java.awt.BorderLayout; import java.awt.Canvas; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Graphics2D; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.image.BufferStrategy; import java.util.ArrayList; import java.util.Scanner; import java.awt.*;//maybe not needed import javax.swing.*;//maybenot needed import java.util.Random; //import java.io.*; /** * The main hook of our game. This class with both act as a manager * for the display and central mediator for the game logic. * * Display management will consist of a loop that cycles round all * entities in the game asking them to move and then drawing them * in the appropriate place. With the help of an inner class it * will also allow the player to control the main ship. * * As a mediator it will be informed when entities within our game * detect events (e.g. alient killed, played died) and will take * appropriate game actions. * * @author Kevin Glass */ public class Game extends Canvas implements Runnable{ /** The stragey that allows us to use accelerate page flipping */ private BufferStrategy strategy; /** True if the game is currently "running", i.e. the game loop is looping */ private boolean gameRunning = true; /** The list of all the entities that exist in our game */ private ArrayList entities = new ArrayList(); /** The list of entities that need to be removed from the game this loop */ private ArrayList removeList = new ArrayList(); /** The entity representing the player */ private Entity ship; /** The speed at which the player's ship should move (pixels/sec) */ private double moveSpeed = 300; /** The time at which last fired a shot */ private long lastFire = 0; /** The interval between our players shot (ms) */ private long firingInterval = 500; /** The number of aliens left on the screen */ private int alienCount; /** The number of levels progressed */ private double levelCount; /** high score for the user */ private int highScore; /** high score for the user */ private String player = "bob"; //private GetUserInput getPlayer; /** The list of entities that need to be removed from the game this loop */ /** The message to display which waiting for a key press */ private String message = ""; /** True if we're holding up game play until a key has been pressed */ private boolean waitingForKeyPress = true; /** True if the left cursor key is currently pressed */ private boolean leftPressed = false; /** True if the right cursor key is currently pressed */ private boolean rightPressed = false; /** True if we are firing */ private boolean firePressed = false; /** True if game logic needs to be applied this loop, normally as a result of a game event */ private boolean logicRequiredThisLoop = false; //private Thread cThread = new Thread(this); //public Thread t = new Thread(this); //private Thread g = new Thread(this); void setHighscore(int setHS) { highScore = setHS; } public int getHighscore() { return highScore; } public void setPlayer(String setPlayer) { player = setPlayer; } public String getPlayer() { return player; } public void run() { //setup(); System.out.println("hello im running bob"); /*int count = 1; do { System.out.println("Count is: " + count); count++; try{Thread.sleep(1);} catch(InterruptedException e){} } while (count <= 2000000);*/ //Game g =new Game(); //Game g = this; // Start the main game loop, note: this method will not // return until the game has finished running. Hence we are // using the actual main thread to run the game. //setup(); //this.gameLoop(); //try{thread.sleep(1);} //catch{InterruptedException e} } /** * Construct our game and set it running. */ public Game () { //Thread t = new Thread(this);//set up new thread for invaders game //t.run();//run the run method of the game //Game g =new Game(); //setup(); //Thread t = new Thread(this); //thread.start(); //SwingUtilities.invokeLater(this); Thread er = new Thread(this); er.start(); } public void setup(){ //initialise highscore setHighscore(0); // create a frame to contain our game JFrame container = new JFrame("Space Invaders 101"); // get hold the content of the frame and set up the resolution of the game JPanel panel = (JPanel) container.getContentPane(); panel.setPreferredSize(new Dimension(800,600)); //panel.setLayout(null); // setup our canvas size and put it into the content of the frame setBounds(0,0,800,600); panel.add(this); // Tell AWT not to bother repainting our canvas since we're // going to do that our self in accelerated mode setIgnoreRepaint(true); // finally make the window visible container.pack(); container.setResizable(false); container.setVisible(true); // add a listener to respond to the user closing the window. If they // do we'd like to exit the game container.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { //cThread.interrupt(); System.exit(0); } }); // add a key input system (defined below) to our canvas // so we can respond to key pressed addKeyListener(new KeyInputHandler()); // request the focus so key events come to us requestFocus(); // create the buffering strategy which will allow AWT // to manage our accelerated graphics createBufferStrategy(2); strategy = getBufferStrategy(); // initialise the entities in our game so there's something // to see at startup initEntities(); } /** * Start a fresh game, this should clear out any old data and * create a new set. */ private void startGame() { // clear out any existing entities and intialise a new set entities.clear(); initEntities(); //initialise highscore setHighscore(0); // blank out any keyboard settings we might currently have leftPressed = false; rightPressed = false; firePressed = false; } /** * Initialise the starting state of the entities (ship and aliens). Each * entitiy will be added to the overall list of entities in the game. */ //private void initEntities() { public void initEntities() { Random randomAlien = new Random(); // create the player ship and place it roughly in the center of the screen //ship = new ShipEntity(this,"sprites/ship.gif",370,550);//orignal ship = new ShipEntity(this,"sprites/ship.gif",700,300);//changed postioning to right hand side entities.add(ship); // create a block of aliens (5 rows, by 12 aliens, spaced evenly) alienCount = 0; levelCount = 1.02; for (int row=0;row<7;row++) {//altered number of rows for (int x=0;x<5;x++) { int r = randomAlien.nextInt(100);//loop added to produce random aliens if (r < 50){ //Entity alien = new AlienEntity(this,"sprites/alien.gif",/*100+*/(x*50),(50)+row*30); Entity alien = new AlienEntity(this,"sprites/alien.gif",100+(x*90),(12)+row*85); entities.add(alien); alienCount++; } } } } //private void initEntities() { public void initAlienEntities() { Random randomAlien = new Random(); // create the player ship and place it roughly in the center of the screen //ship = new ShipEntity(this,"sprites/ship.gif",370,550);//orignal //ship = new ShipEntity(this,"sprites/ship.gif",700,300);//changed postioning to right hand side //entities.add(ship); // create a block of aliens (5 rows, by 12 aliens, spaced evenly) alienCount = 0; levelCount = levelCount + 0.10;//this increases the speed on every level for (int row=0;row<7;row++) {//altered number of rows for (int x=0;x<5;x++) { int r = randomAlien.nextInt(100);//loop added to produce random aliens if (r < 50){//randome check to show alien //Entity alien = new AlienEntity(this,"sprites/alien.gif",/*100+*/(x*50),(50)+row*30); Entity alien = new AlienEntity(this,"sprites/alien.gif",-250+(x*90),(12)+row*85); entities.add(alien); alienCount++; } } } advanceAlienSpeed(levelCount); } /** * Notification from a game entity that the logic of the game * should be run at the next opportunity (normally as a result of some * game event) */ public void updateLogic() { logicRequiredThisLoop = true; } /** * Remove an entity from the game. The entity removed will * no longer move or be drawn. * * @param entity The entity that should be removed */ public void removeEntity(Entity entity) { removeList.add(entity); } /** * Notification that the player has died. */ public void notifyDeath() { message = "Oh no! They got you, try again?"; waitingForKeyPress = true; } /** * Notification that the player has won since all the aliens * are dead. */ public void notifyWin() { message = "Well done! You Win!"; waitingForKeyPress = true; } /** * Notification that an alien has been killed */ public void notifyAlienKilled() { // reduce the alient count, if there are none left, the player has won! alienCount--; if (alienCount == 0) { //notifyWin();win not relevant here... this.initAlienEntities();//call fresh batch of aliens } // if there are still some aliens left then they all need to get faster, so // speed up all the existing aliens advanceAlienSpeed(1.30); } public void advanceAlienSpeed(double speed) { // if there are still some aliens left then they all need to get faster, so // speed up all the existing aliens for (int i=0;i<entities.size();i++) { Entity entity = (Entity) entities.get(i); if (entity instanceof AlienEntity) { // speed up by 2% entity.setHorizontalMovement(entity.getHorizontalMovement() * speed); //entity.setVerticalMovement(entity.getVerticalMovement() * 1.02); } } } /** * Attempt to fire a shot from the player. Its called "try" * since we must first check that the player can fire at this * point, i.e. has he/she waited long enough between shots */ public void tryToFire() { // check that we have waiting long enough to fire if (System.currentTimeMillis() - lastFire < firingInterval) { return; } // if we waited long enough, create the shot entity, and record the time. lastFire = System.currentTimeMillis(); ShotEntity shot = new ShotEntity(this,"sprites/shot.gif",ship.getX()+10,ship.getY()-30); entities.add(shot); } /** * The main game loop. This loop is running during all game * play as is responsible for the following activities: * <p> * - Working out the speed of the game loop to update moves * - Moving the game entities * - Drawing the screen contents (entities, text) * - Updating game events * - Checking Input * <p> */ public void gameLoop() { long lastLoopTime = System.currentTimeMillis(); // keep looping round til the game ends while (gameRunning) { // work out how long its been since the last update, this // will be used to calculate how far the entities should // move this loop long delta = System.currentTimeMillis() - lastLoopTime; lastLoopTime = System.currentTimeMillis(); // Get hold of a graphics context for the accelerated // surface and blank it out Graphics2D g = (Graphics2D) strategy.getDrawGraphics(); g.setColor(Color.black); g.fillRect(0,0,800,600); // cycle round asking each entity to move itself if (!waitingForKeyPress) { for (int i=0;i<entities.size();i++) { Entity entity = (Entity) entities.get(i); entity.move(delta); } } // cycle round drawing all the entities we have in the game for (int i=0;i<entities.size();i++) { Entity entity = (Entity) entities.get(i); entity.draw(g); } // brute force collisions, compare every entity against // every other entity. If any of them collide notify // both entities that the collision has occured for (int p=0;p<entities.size();p++) { for (int s=p+1;s<entities.size();s++) { Entity me = (Entity) entities.get(p); Entity him = (Entity) entities.get(s); if (me.collidesWith(him)) { me.collidedWith(him); him.collidedWith(me); } } } // remove any entity that has been marked for clear up entities.removeAll(removeList); removeList.clear(); // if a game event has indicated that game logic should // be resolved, cycle round every entity requesting that // their personal logic should be considered. if (logicRequiredThisLoop) { //g.drawString("Press any key",(800-g.getFontMetrics().stringWidth("Press any key"))/2,300); for (int i=0;i<entities.size();i++) { Entity entity = (Entity) entities.get(i); entity.doLogic(); } logicRequiredThisLoop = false; } // if we're waiting for an "any key" press then draw the // current message //show highscore at top of screen //show name at top of screen g.setColor(Color.white); g.drawString("Player : "+getPlayer()+" : Score : "+getHighscore(),20,20); if (waitingForKeyPress) { g.setColor(Color.white); g.drawString(message,(800-g.getFontMetrics().stringWidth(message))/2,250); g.drawString("Press any key",(800-g.getFontMetrics().stringWidth("Press any key"))/2,300); } // finally, we've completed drawing so clear up the graphics // and flip the buffer over g.dispose(); strategy.show(); // resolve the movement of the ship. First assume the ship // isn't moving. If either cursor key is pressed then // update the movement appropraitely ship.setVerticalMovement(0);//set to vertical movement if ((leftPressed) && (!rightPressed)) { ship.setVerticalMovement(-moveSpeed);//**took out setHorizaontalMOvement } else if ((rightPressed) && (!leftPressed)) { ship.setVerticalMovement(moveSpeed);//**took out setHorizaontalMOvement } // if we're pressing fire, attempt to fire if (firePressed) { tryToFire(); } // finally pause for a bit. Note: this should run us at about // 100 fps but on windows this might vary each loop due to // a bad implementation of timer try { Thread.sleep(10); } catch (Exception e) {} } } /** * A class to handle keyboard input from the user. The class * handles both dynamic input during game play, i.e. left/right * and shoot, and more static type input (i.e. press any key to * continue) * * This has been implemented as an inner class more through * habbit then anything else. Its perfectly normal to implement * this as seperate class if slight less convienient. * * @author Kevin Glass */ private class KeyInputHandler extends KeyAdapter { /** The number of key presses we've had while waiting for an "any key" press */ private int pressCount = 1; /** * Notification from AWT that a key has been pressed. Note that * a key being pressed is equal to being pushed down but *NOT* * released. Thats where keyTyped() comes in. * * @param e The details of the key that was pressed */ public void keyPressed(KeyEvent e) { // if we're waiting for an "any key" typed then we don't // want to do anything with just a "press" if (waitingForKeyPress) { return; } // if (e.getKeyCode() == KeyEvent.VK_LEFT) { ////leftPressed = true; ///} //// if (e.getKeyCode() == KeyEvent.VK_RIGHT) { //rightPressed = true; if (e.getKeyCode() == KeyEvent.VK_UP) { leftPressed = true; } if (e.getKeyCode() == KeyEvent.VK_DOWN) { rightPressed = true; } if (e.getKeyCode() == KeyEvent.VK_SPACE) { firePressed = true; } } /** * Notification from AWT that a key has been released. * * @param e The details of the key that was released */ public void keyReleased(KeyEvent e) { // if we're waiting for an "any key" typed then we don't // want to do anything with just a "released" if (waitingForKeyPress) { return; } if (e.getKeyCode() == KeyEvent.VK_UP) {//changed from VK_LEFT leftPressed = false; } if (e.getKeyCode() == KeyEvent.VK_DOWN) {//changed from VK_RIGHT rightPressed = false; } if (e.getKeyCode() == KeyEvent.VK_SPACE) { firePressed = false; } } /** * Notification from AWT that a key has been typed. Note that * typing a key means to both press and then release it. * * @param e The details of the key that was typed. */ public void keyTyped(KeyEvent e) { // if we're waiting for a "any key" type then // check if we've recieved any recently. We may // have had a keyType() event from the user releasing // the shoot or move keys, hence the use of the "pressCount" // counter. if (waitingForKeyPress) { if (pressCount == 1) { // since we've now recieved our key typed // event we can mark it as such and start // our new game waitingForKeyPress = false; startGame(); pressCount = 0; } else { pressCount++; } } // if we hit escape, then quit the game if (e.getKeyChar() == 27) { //cThread.interrupt(); System.exit(0); } } } /** * The entry point into the game. We'll simply create an * instance of class which will start the display and game * loop. * * @param argv The arguments that are passed into our game */ //public static void main(String argv[]) { //Game g =new Game(); // Start the main game loop, note: this method will not // return until the game has finished running. Hence we are // using the actual main thread to run the game. //g.gameLoop(); //} }

    Read the article

  • In ParallelPython, a method of an object ( object.func() ) fails to manipulate a variable of an object ( object.value )

    - by mehmet.ali.anil
    With parallelpython, I am trying to convert my old serial code to parallel, which heavily relies on objects that have methods that change that object's variables. A stripped example in which I omit the syntax in favor of simplicity: class Network: self.adjacency_matrix = [ ... ] self.state = [ ... ] self.equilibria = [ ... ] ... def populate_equilibria(self): # this function takes every possible value that self.state can be in # runs the boolean dynamical system # and writes an integer within self.equilibria for each self.state # doesn't return anything I call this method as: Code: j1 = jobserver.submit(net2.populate_equilibria,(),(),("numpy as num")) The job is sumbitted, and I know that a long computation takes place, so I speculate that my code is ran. The problem is, i am new to parallelpython , I was expecting that, when the method is called, the variable net2.equilibria would be written accordingly, and I would get a revised object (net2) . That is how my code works, independent objects with methods that act upon the object's variables. Rather, though the computation is apparent, and reasonably timed, the variable net2.equilibria remains unchanged. As if PP only takes the function and the object, computes it elsewhere, but never returns the object, so I am left with the old one. What do I miss? Thanks in advance.

    Read the article

  • Magento - Show Custom Attributes in Grouped Product table.

    - by greencoconut
    I need to find a way to show the value of a custom attribute in place of the "Product Name" shown in the image below. I'm working with /app/design/frontend/default/defaultx/template/catalog/product/view/type/grouped.php The code below doesn't work(the custom attribute is yearmade): <?php if (count($_associatedProducts)): ?> <?php foreach ($_associatedProducts as $_item): ?> <tr> <td><?php echo $this->htmlEscape($_item->getYearmade()) ?></td> Any help would be appreciated. EDIT: So the answer turned out to be quite simple. You see what I failed to mention above was that there was indeed output... but that it was just a number (eg: 52). Turns out this was the ID for that custom attribute value (It was a Dropdown type of custom attribute). So in summary This works for custom attributes of type text: echo $this->htmlEscape($_item->getYearmade()) But for all other types of custom attribute (I think), the following should be used: echo $this->htmlEscape($_item->getAttributeText('yearmade')) I would not have discovered this without the most excellent answer provided by Alan Storm, below. Thank you sir.

    Read the article

  • What to name this class?

    - by orlandu63
    (This is not an interface: I simply omitted the method bodies) class _ { protected $_data = array(); function __construct($data); function set($name, $value); function get($name); function __set($name, $value); function __get($name); //aliases for their respective non-magic methods. # and some other generic methods } Essentially it's a class that provides a magical object-oriented reusable access layer to some data. I've considered DataLayer, DataObject and some others; I'd like to hear some suggestions from someone who's more terminologically savvy.

    Read the article

  • Should DAL always return business objects in MVP

    - by Chathuranga
    In Model View Presenter (MVP) pattern, it is said that our DAL always should returns business models. But let's say if I want to get just a number from database like the last ClientID (the latest clients ID) which is a string, should my DAL method returns a ClientInfo object which has about 10 other fields as well like ClientName, Address etc.? If I want to get a list of business objects from my DAL, is it acceptable to do it as follows or better to get a DataTable from DAL and then in the applications BLL, converts it a List? public List<Employee> GetNewEmployees() { string selectStatement = "SELECT Employee.Emp_ID, Employee.Initials + ' ' + Employee.Surname AS Name,..."; using (SqlConnection sqlConnection = new SqlConnection(db.GetConnectionString)) { using (SqlCommand sqlCommand = new SqlCommand(selectStatement, sqlConnection)) { sqlConnection.Open(); using (SqlDataReader dataReader = sqlCommand.ExecuteReader()) { List<Employee> list = new List<Employee>(); while (dataReader.Read()) { list.Add ( new EpfEtfMaster { EmployeeID = (int) dataReader ["emp_id"], EmployeeName = (string) dataReader ["Name"], AppointmentDate = (DateTime) dataReader["appointment_date"], }); } return list; } } } }

    Read the article

  • What objects would get defined in a Bridge scoring app (Javascript)

    - by Alex Mcp
    I'm writing a Bridge (card game) scoring application as practice in javascript, and am looking for suggestions on how to set up my objects. I'm pretty new to OO in general, and would love a survey of how and why people would structure a program to do this (the "survey" begets the CW mark. Additionally, I'll happily close this if it's out of range of typical SO discussion). The platform is going to be a web-app for webkit on the iPhone, so local storage is an option. My basic structure is like this: var Team = { player1: , player2: , vulnerable: , //this is a flag for whether or //not you've lost a game yet, affects scoring scoreAboveLine: , scoreBelowLine: gamesWon: }; var Game = { init: ,//function to get old scores and teams from DB currentBid: , score: , //function to accept whether bid was made and apply to Teams{} save: //auto-run that is called after each game to commit to DB }; So basically I'll instantiate two teams, and then run loops of game.currentBid() and game.score. Functionally the scoring is working fine, but I'm wondering if this is how someone else would choose to break down the scoring of Bridge, and if there are any oversights I've made with regards to OO-ness and how I've abstracted the game. Thanks!

    Read the article

  • objective C architecture question

    - by thekevinscott
    Hey folks, I'm currently teaching myself objective C. I've gone through the tutorials, but I find I learn best when slogging through a project of my own, so I've embarked on making a backgammon app. Now that I'm partway in, I'm realizing there's some overall architecture things I just don't understand. I've established a "player" class, a "piece" class, and a "board" class. A piece theoretically belongs to both a player and the board. For instance, a player has a color, and every turn makes a move; so the player owns his pieces. At the same time, when moving a piece, it has to check whether it's a valid move, whether there are pieces on the board, etc. From my reading it seems like it's frowned upon to reach across classes. For instance, when a player makes a move, where should the function live that moves the piece? Should it exist on board? This would be my instinct, as the board should decide whether a move is valid or not; but the piece needs to initialize that query, as its the one being moved, no? Any info to help a noob would be super appreciated. Thanks guys!

    Read the article

  • HMVC/PAC - how to handle shared abstractions/models?

    - by fig-gnuton
    In HMVC/PAC, what's the recommended way to code if two or more triads/agents share a common model/abstraction? Do you instantiate a new instance of that model wherever needed, and propogate a change in one to all the other instances via the controllers? Or do instantiate one model at some common upper level, and inject that instance wherever needed? (Or neither if I'm missing something fundamental about these patterns?)

    Read the article

  • Naming convention for non-virtual and abstract methods

    - by eagle
    I frequently find myself creating classes which use this form (A): abstract class Animal { public void Walk() { // TODO: do something before walking // custom logic implemented by each subclass WalkInternal(); // TODO: do something after walking } protected abstract void WalkInternal(); } class Dog : Animal { protected override void WalkInternal() { // TODO: walk with 4 legs } } class Bird : Animal { protected override void WalkInternal() { // TODO: walk with 2 legs } } Rather than this form (B): abstract class Animal { public abstract void Walk(); } class Dog : Animal { public override void Walk() { // TODO: do something before walking // custom logic implemented by each subclass // TODO: walk with 4 legs // TODO: do something after walking } } class Bird : Animal { public override void Walk() { // TODO: do something before walking // custom logic implemented by each subclass // TODO: walk with 2 legs // TODO: do something after walking } } As you can see, the nice thing about form A is that every time you implement a subclass, you don't need to remember to include the initialization and finalization logic. This is much less error prone than form B. What's a standard convention for naming these methods? I like naming the public method Walk since then I can call Dog.Walk() which looks better than something like Dog.WalkExternal(). However, I don't like my solution of adding the suffix "Internal" for the protected method. I'm looking for a more standardized name. Btw, is there a name for this design pattern?

    Read the article

  • Generics and Constrained Polymorphism versus Subtyping

    - by Rahul G
    Hullo all. In this (Warning: PDF) presentation on Haskell Type Classes, on slide #54, there's this question: Open Question: In a language with generics and constrained polymorphism, do you need subtyping too? My questions are: How do generics and constrained polymorphism make subtyping unnecessary? If generics and constrained polymorphism make subtyping unnecessary, why does Scala have subtyping?

    Read the article

  • constructors and inheritance in JS

    - by nandinga
    Hi all, This is about "inheritance" in JavaScript. Supose I create a constructor Bird(), and another called Parrot() which I make to "inherit" the props of Bird by asigning an instance of it to Parrot's prototype, like the following code shows: function Bird() { this.fly = function(){}; } function Parrot() { this.talk = function(){ alert("praa!!"); }; } Parrot.prototype = new Bird(); var p = new Parrot(); p.talk(); // Alerts "praa!!" alert(p.constructor); // Alerts the Bird function!?!?! After I've created an instance of Parrot, how comes that the .constructor property of it is Bird(), and not Parrot(), which is the constructor I've used to create the object? Thanks!!

    Read the article

  • Is it possible to create static classes in PHP (like in C#)?

    - by aleemb
    I want to create a static class in PHP and have it behave like it does in C#, so Constructor is automatically called on the first call to the class No instantiation required Something of this sort... static class Hello { private static $greeting = 'Hello'; private __construct() { $greeting .= ' There!'; } public static greet(){ echo $greeting; } } Hello::greet(); // Hello There!

    Read the article

  • Non-Linear Database Retrieval

    - by pws5068
    I'm building an article system, and each article will have one more Tags associated with it (similar to the Tags on this site). The tables are set up something like this: Article_Table Article_ID | Title | Author_ID | Content | Date_Posted | IP ... Tag_Table Tag_ID | Name ... Tag_Intersect_Table Tag_ID | Article_ID Is it possible query an article and all of its associated tags in one database call? If so, how is this done?

    Read the article

  • Is this a good way to expose generic base class methods through an interface?

    - by Nate Heinrich
    I am trying to provide an interface to an abstract generic base class. I want to have a method exposed on the interface that consumes the generic type, but whose implementation is ultimately handled by the classes that inherit from my abstract generic base. However I don't want the subclasses to have to downcast to work with the generic type (as they already know what the type should be). Here is a simple version of the only way I can see to get it to work at the moment. public interface IFoo { void Process(Bar_base bar); } public abstract class FooBase<T> : IFoo where T : Bar_base { abstract void Process(T bar); // Explicit IFoo Implementation void IFoo.Process(Bar_base bar) { if (bar == null) throw new ArgumentNullException(); // Downcast here in base class (less for subclasses to worry about) T downcasted_bar = bar as T; if (downcasted_bar == null) { throw new InvalidOperationException( string.Format("Expected type '{0}', not type '{1}'", T.ToString(), bar.GetType().ToString()); } //Process downcasted object. Process(downcasted_bar); } } Then subclasses of FooBase would look like this... public class Foo_impl1 : FooBase<Bar_impl1> { void override Process(Bar_impl1 bar) { //No need to downcast here! } } Obviously this won't provide me compile time Type Checking, but I think it will get the job done... Questions: 1. Will this function as I think it will? 2. Is this the best way to do this? 3. What are the issues with doing it this way? 4. Can you suggest a different approach? Thanks!

    Read the article

  • PHP: Recursive array function

    - by Industrial
    Hi everybody, I want to create a function that returns the full path from a set node, back to the root value. I tried to make a recursive function, but ran out of luck totally. What would be an appropriate way to do this? I assume that a recursive function is the only way? Here's the array: Array ( [0] => Array ( [id] => 1 [name] => Root category [_parent] => ) [1] => Array ( [id] => 2 [name] => Category 2 [_parent] => 1 ) [2] => Array ( [id] => 3 [name] => Category 3 [_parent] => 1 ) [3] => Array ( [id] => 4 [name] => Category 4 [_parent] => 3 ) ) The result I want my function to output when getting full path of node id#4: Array ( [0] => Array ( [id] => 1 [name] => Root category [_parent] => ) [1] => Array ( [id] => 3 [name] => Category 3 [_parent] => 1 ) [2] => Array ( [id] => 4 [name] => Category 4 [_parent] => 3 ) ) The notoriously bad example of my recursive skills: function recursive ($id, $array) { $innerarray = array(); foreach ($array as $k => $v) { if ($v['id'] === $id) { if ($v['_parent'] !== '') { $innerarray[] = $v; recursive($v['id'], $array); } } } return $innerarray; } Thanks!

    Read the article

  • Can a function return an object? Objective-C and NSMutableArray

    - by seaworthy
    I have an NSMutableArray. It's members eventually become members of an array instance in a class. I want to put the instantiantion of NSMutable into a function and to return an array object. If I can do this, I can make some of my code easier to read. Is this possible? Here is what I am trying to figure out. //Definition: > function Objects (float a, float b) { > NSMutableArray *array = [[NSMutableArray alloc] init]; > [array addObject:[NSNumber numberWithFloat:a]]; > [array addObject:[NSNumber numberWithFloat:b]]; > //[release array]; ???????? return array; > } //Declaration: Math *operator = [[Math alloc] init]; [operator findSum:Objects(20.0,30.0)]; My code compiles if I instantiate NSMutableArray right before I send the message to the receiver. I know I can have an array argument along with the method. What I have problem seeing is how to use a function and to replace the argument with a function call. Any help is appreciated. I am interested in the concept not in suggestions to replace the findSum method.

    Read the article

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