答:
An idiomatic Scala/LWJGL implementation of Space Invaders wouldn’t look that much like a Haskell/OpenGL implementation. Writing a Haskell implementation might be a better exercise in my opinion. But if you want to stick with Scala, here are some ideas for how to write it in functional style.

Try to use immutable objects only. You could have a Game object which holds a Player, a Set[Invader] (be sure to use immutable.Set), etc. Give Player an update(state: Game): Player (it could also take depressedKeys: Set[Int], etc), and give the other classes similar methods.

For randomness, scala.util.Random isn’t immutable like Haskell’s System.Random, but you could make your own immmutable generator. This one is inefficient but it demonstrates the idea.

case class ImmutablePRNG(val seed: Long) extends Immutable {
    lazy val nextLong: (Long, ImmutableRNG) =
        (seed, ImmutablePRNG(new Random(seed).nextLong()))
    ...
}
```

<p>For keyboard/mouse input and rendering, there’s no way around calling impure functions. They’re impure in Haskell too, they’re just encapsulated in <code>IO</code> etc. so that your actual function objects are technically pure (they don’t read or write state themselves, they <em>describe</em> routines which do, and the runtime system executes those routines).</p>

<p>Just don’t put I/O code in your immutable objects like <code>Game</code>, <code>Player</code> and <code>Invader</code>. You can give <code>Player</code> a <code>render</code> method, but it should look like</p>

<pre class="lang-scala prettyprint-override"><code>render(state: Game, buffer: Image): Image
</code>```

Unfortunately this doesn’t fit well with LWJGL since it’s so state-based, but you could build your own abstractions on top of it. You could have an ImmutableCanvas class that holds an AWT Canvas, and its blit (and other methods) could clone the underlying Canvas, pass it to Display.setParent, then perform the rendering and return the new Canvas (in your immutable wrapper).

Update: Here is some Java code showing how I would go about this. (I would have written almost the same code in Scala, except that an immutable set is built-in and a few for-each loops could be replaced with maps or folds.) I made a player which moves around and fires bullets, but I didn’t add enemies since the code was getting long already. I made just about everything copy-on-write – I think this is the most important concept.

import java.awt.*;
import java.awt.geom.*;
import java.awt.image.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;

import static java.awt.event.KeyEvent.*;

// An immutable wrapper around a Set. Doesn't implement Set or Collection
// because that would require quite a bit of code.
class ImmutableSet<T> implements Iterable<T> {
  final Set<T> backingSet;

  // Construct an empty set.
  ImmutableSet() {
    backingSet = new HashSet<T>();
  }

  // Copy constructor.
  ImmutableSet(ImmutableSet<T> src) {
    backingSet = new HashSet<T>(src.backingSet);
  }

  // Return a new set with an element added.
  ImmutableSet<T> plus(T elem) {
    ImmutableSet<T> copy = new ImmutableSet<T>(this);
    copy.backingSet.add(elem);
    return copy;
  }

  // Return a new set with an element removed.
  ImmutableSet<T> minus(T elem) {
    ImmutableSet<T> copy = new ImmutableSet<T>(this);
    copy.backingSet.remove(elem);
    return copy;
  }

  boolean contains(T elem) {
    return backingSet.contains(elem);
  }

  @Override public Iterator<T> iterator() {
    return backingSet.iterator();
  }
}

// An immutable, copy-on-write wrapper around BufferedImage.
class ImmutableImage {
  final BufferedImage backingImage;

  // Construct a blank image.
  ImmutableImage(int w, int h) {
    backingImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
  }

  // Copy constructor.
  ImmutableImage(ImmutableImage src) {
    backingImage = new BufferedImage(
        src.backingImage.getColorModel(),
        src.backingImage.copyData(null),
        false, null);
  }

  // Clear the image.
  ImmutableImage clear(Color c) {
    ImmutableImage copy = new ImmutableImage(this);
    Graphics g = copy.backingImage.getGraphics();
    g.setColor(c);
    g.fillRect(0, 0, backingImage.getWidth(), backingImage.getHeight());
    return copy;
  }

  // Draw a filled circle.
  ImmutableImage fillCircle(int x, int y, int r, Color c) {
    ImmutableImage copy = new ImmutableImage(this);
    Graphics g = copy.backingImage.getGraphics();
    g.setColor(c);
    g.fillOval(x - r, y - r, r * 2, r * 2);
    return copy;
  }
}

// An immutable, copy-on-write object describing the player.
class Player {
  final int x, y;
  final int ticksUntilFire;

  Player(int x, int y, int ticksUntilFire) {
    this.x = x;
    this.y = y;
    this.ticksUntilFire = ticksUntilFire;
  }

  // Construct a player at the starting position, ready to fire.
  Player() {
    this(SpaceInvaders.W / 2, SpaceInvaders.H - 50, 0);
  }

  // Update the game state (repeatedly called for each game tick).
  GameState update(GameState currentState) {
    // Update the player's position based on which keys are down.
    int newX = x;
    if (currentState.keyboard.isDown(VK_LEFT) || currentState.keyboard.isDown(VK_A))
      newX -= 2;
    if (currentState.keyboard.isDown(VK_RIGHT) || currentState.keyboard.isDown(VK_D))
      newX += 2;

    // Update the time until the player can fire.
    int newTicksUntilFire = ticksUntilFire;
    if (newTicksUntilFire > 0)
      --newTicksUntilFire;

    // Replace the old player with an updated player.
    Player newPlayer = new Player(newX, y, newTicksUntilFire);
    return currentState.setPlayer(newPlayer);
  }

  // Update the game state in response to a key press.
  GameState keyPressed(GameState currentState, int key) {
    if (key == VK_SPACE && ticksUntilFire == 0) {
      // Fire a bullet.
      Bullet b = new Bullet(x, y);
      ImmutableSet<Bullet> newBullets = currentState.bullets.plus(b);
      currentState = currentState.setBullets(newBullets);

      // Make the player wait 25 ticks before firing again.
      currentState = currentState.setPlayer(new Player(x, y, 25));
    }
    return currentState;
  }

  ImmutableImage render(ImmutableImage img) {
    return img.fillCircle(x, y, 20, Color.RED);
  }
}

// An immutable, copy-on-write object describing a bullet.
class Bullet {
  final int x, y;
  static final int radius = 5;

  Bullet(int x, int y) {
    this.x = x;
    this.y = y;
  }

  // Update the game state (repeatedly called for each game tick).
  GameState update(GameState currentState) {
    ImmutableSet<Bullet> bullets = currentState.bullets;
    bullets = bullets.minus(this);
    if (y + radius >= 0)
      // Add a copy of the bullet which has moved up the screen slightly.
      bullets = bullets.plus(new Bullet(x, y - 5));
    return currentState.setBullets(bullets);
  }

  ImmutableImage render(ImmutableImage img) {
    return img.fillCircle(x, y, radius, Color.BLACK);
  }
}

// An immutable, copy-on-write snapshot of the keyboard state at some time.
class KeyboardState {
  final ImmutableSet<Integer> depressedKeys;

  KeyboardState(ImmutableSet<Integer> depressedKeys) {
    this.depressedKeys = depressedKeys;
  }

  KeyboardState() {
    this(new ImmutableSet<Integer>());
  }

  GameState keyPressed(GameState currentState, int key) {
    return currentState.setKeyboard(new KeyboardState(depressedKeys.plus(key)));
  }

  GameState keyReleased(GameState currentState, int key) {
    return currentState.setKeyboard(new KeyboardState(depressedKeys.minus(key)));
  }

  boolean isDown(int key) {
    return depressedKeys.contains(key);
  }
}

// An immutable, copy-on-write description of the entire game state.
class GameState {
  final Player player;
  final ImmutableSet<Bullet> bullets;
  final KeyboardState keyboard;

  GameState(Player player, ImmutableSet<Bullet> bullets, KeyboardState keyboard) {
    this.player = player;
    this.bullets = bullets;
    this.keyboard = keyboard;
  }

  GameState() {
    this(new Player(), new ImmutableSet<Bullet>(), new KeyboardState());
  }

  GameState setPlayer(Player newPlayer) {
    return new GameState(newPlayer, bullets, keyboard);
  }

  GameState setBullets(ImmutableSet<Bullet> newBullets) {
    return new GameState(player, newBullets, keyboard);
  }

  GameState setKeyboard(KeyboardState newKeyboard) {
    return new GameState(player, bullets, newKeyboard);
  }

  // Update the game state (repeatedly called for each game tick).
  GameState update() {
    GameState current = this;
    current = current.player.update(current);
    for (Bullet b : current.bullets)
      current = b.update(current);
    return current;
  }

  // Update the game state in response to a key press.
  GameState keyPressed(int key) {
    GameState current = this;
    current = keyboard.keyPressed(current, key);
    current = player.keyPressed(current, key);
    return current;
  }

  // Update the game state in response to a key release.
  GameState keyReleased(int key) {
    GameState current = this;
    current = keyboard.keyReleased(current, key);
    return current;
  }

  ImmutableImage render() {
    ImmutableImage img = new ImmutableImage(SpaceInvaders.W, SpaceInvaders.H);
    img = img.clear(Color.BLUE);
    img = player.render(img);
    for (Bullet b : bullets)
      img = b.render(img);
    return img;
  }
}

public class SpaceInvaders {
  static final int W = 640, H = 480;

  static GameState currentState = new GameState();

  public static void main(String[] _) {
    JFrame frame = new JFrame() {{
      setSize(W, H);
      setTitle("Space Invaders");
      setContentPane(new JPanel() {
        @Override public void paintComponent(Graphics g) {
          BufferedImage img = SpaceInvaders.currentState.render().backingImage;
          ((Graphics2D) g).drawRenderedImage(img, new AffineTransform());
        }
      });
      addKeyListener(new KeyAdapter() {
        @Override public void keyPressed(KeyEvent e) {
          currentState = currentState.keyPressed(e.getKeyCode());
        }
        @Override public void keyReleased(KeyEvent e) {
          currentState = currentState.keyReleased(e.getKeyCode());
        }
      });
      setLocationByPlatform(true);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setVisible(true);
    }};

    for (;;) {
      currentState = currentState.update();
      frame.repaint();
      try {
        Thread.sleep(20);
      } catch (InterruptedException e) {}
    }
  }
}
```

Title: Functional Programming approach for a simplified game using Scala and LWJGL

Body:
I, a Java imperative programmer, would like to understand how to generate a simple version of Space Invaders based on Functional Programming design principles (in particular Referential Transparency). However, each time I try to think of a design, I get lost in the morass of extreme mutability, the same mutability which is shunned by the functional programming purists.

As an attempt to learn Functional Programming, I decided to attempt to create a very simple 2D interactive game, Space Invader (note the lack of plural), in Scala using the LWJGL. Here are the requirements for the basic game:

User ship at the bottom of the screen moved left and right by the "A" and "D" keys respectively

User ship bullet fired straight up activated by the space bar with a minimum pause between shots to be .5 seconds

Alien ship bullet fired straight down activated by a random time of .5 to 1.5 seconds between shots

Things intentionally left out from the original game are WxH aliens, degradable defense barriers x3, high speed saucer ship at at the top of the screen.

Okay, now to the actual problem domain. For me, all the deterministic parts are obvious. It's the non-deterministic parts that seem to be blocking my ability to consider how to approach. The deterministic parts are the bullet's trajectory once they exist, the continuous motion of the alien and the explosion due to a hit on either (or both) of the player's ship or the alien. The non-deterministic parts (to me) are handling the stream of user input, handling fetching a random value for determining alien bullet firings and handling the output (both graphics and sound).

I can do (and have done) lots of this type of game development over the years. However, all of it was from the imperative paradigm. And LWJGL even provides a very simple Java version of Space invaders (of which I began moving to Scala using Scala as Java-without-semicolons).

Here are some links that talk around this area of which none seem to have directly dealt with the ideas in a way a person coming from Java/Imperative programming would understand:

Purely Functional Retrogames, Part 1 by James Hague

Similar Stack Overflow post

Clojure/Lisp Games

Haskell Games on Stack Overflow

Yampa's (in Haskell) Functional Reactive Programming

It appears that there are some ideas in the Clojure/Lisp and Haskell games (with source). Unfortunately, I am not able to read/interpret the code into mental models that make any sense to my simpleminded Java imperative brain.

I'm so excited by the possibilities offered by FP, I can just taste the multi-threaded scalability capabilities. I feel like if were able to grok how something as simple as the time + event + randomness model for Space Invader can be implemented, segregating the deterministic and non-deterministic parts in a properly designed system without it turning into what feels like advanced mathematical theory; i.e. Yampa, I'd be set. If learning the level of theory Yampa seems to require to successfully generate simple games is necessary, then the overhead of acquiring all the necessary training and conceptual framework will vastly outweigh my understanding of the benefits of FP (at least for this over-simplified learning experiment).

Any feedback, proposed models, suggested methods of approaching the problem domain (more specific than the generalities covered by James Hague) would be greatly appreciated.

Body:
An idiomatic Scala/LWJGL implementation of Space Invaders wouldn’t look that much like a Haskell/OpenGL implementation. Writing a Haskell implementation might be a better exercise in my opinion. But if you want to stick with Scala, here are some ideas for how to write it in functional style.

Try to use immutable objects only. You could have a Game object which holds a Player, a Set[Invader] (be sure to use immutable.Set), etc. Give Player an update(state: Game): Player (it could also take depressedKeys: Set[Int], etc), and give the other classes similar methods.

For randomness, scala.util.Random isn’t immutable like Haskell’s System.Random, but you could make your own immmutable generator. This one is inefficient but it demonstrates the idea.

case class ImmutablePRNG(val seed: Long) extends Immutable {
    lazy val nextLong: (Long, ImmutableRNG) =
        (seed, ImmutablePRNG(new Random(seed).nextLong()))
    ...
}

For keyboard/mouse input and rendering, there’s no way around calling impure functions. They’re impure in Haskell too, they’re just encapsulated in IO etc. so that your actual function objects are technically pure (they don’t read or write state themselves, they describe routines which do, and the runtime system executes those routines).

Just don’t put I/O code in your immutable objects like Game, Player and Invader. You can give Player a render method, but it should look like

render(state: Game, buffer: Image): Image

Unfortunately this doesn’t fit well with LWJGL since it’s so state-based, but you could build your own abstractions on top of it. You could have an ImmutableCanvas class that holds an AWT Canvas, and its blit (and other methods) could clone the underlying Canvas, pass it to Display.setParent, then perform the rendering and return the new Canvas (in your immutable wrapper).

Update: Here is some Java code showing how I would go about this. (I would have written almost the same code in Scala, except that an immutable set is built-in and a few for-each loops could be replaced with maps or folds.) I made a player which moves around and fires bullets, but I didn’t add enemies since the code was getting long already. I made just about everything copy-on-write – I think this is the most important concept.

import java.awt.*;
import java.awt.geom.*;
import java.awt.image.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;

import static java.awt.event.KeyEvent.*;

// An immutable wrapper around a Set. Doesn't implement Set or Collection
// because that would require quite a bit of code.
class ImmutableSet<T> implements Iterable<T> {
  final Set<T> backingSet;

  // Construct an empty set.
  ImmutableSet() {
    backingSet = new HashSet<T>();
  }

  // Copy constructor.
  ImmutableSet(ImmutableSet<T> src) {
    backingSet = new HashSet<T>(src.backingSet);
  }

  // Return a new set with an element added.
  ImmutableSet<T> plus(T elem) {
    ImmutableSet<T> copy = new ImmutableSet<T>(this);
    copy.backingSet.add(elem);
    return copy;
  }

  // Return a new set with an element removed.
  ImmutableSet<T> minus(T elem) {
    ImmutableSet<T> copy = new ImmutableSet<T>(this);
    copy.backingSet.remove(elem);
    return copy;
  }

  boolean contains(T elem) {
    return backingSet.contains(elem);
  }

  @Override public Iterator<T> iterator() {
    return backingSet.iterator();
  }
}

// An immutable, copy-on-write wrapper around BufferedImage.
class ImmutableImage {
  final BufferedImage backingImage;

  // Construct a blank image.
  ImmutableImage(int w, int h) {
    backingImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
  }

  // Copy constructor.
  ImmutableImage(ImmutableImage src) {
    backingImage = new BufferedImage(
        src.backingImage.getColorModel(),
        src.backingImage.copyData(null),
        false, null);
  }

  // Clear the image.
  ImmutableImage clear(Color c) {
    ImmutableImage copy = new ImmutableImage(this);
    Graphics g = copy.backingImage.getGraphics();
    g.setColor(c);
    g.fillRect(0, 0, backingImage.getWidth(), backingImage.getHeight());
    return copy;
  }

  // Draw a filled circle.
  ImmutableImage fillCircle(int x, int y, int r, Color c) {
    ImmutableImage copy = new ImmutableImage(this);
    Graphics g = copy.backingImage.getGraphics();
    g.setColor(c);
    g.fillOval(x - r, y - r, r * 2, r * 2);
    return copy;
  }
}

// An immutable, copy-on-write object describing the player.
class Player {
  final int x, y;
  final int ticksUntilFire;

  Player(int x, int y, int ticksUntilFire) {
    this.x = x;
    this.y = y;
    this.ticksUntilFire = ticksUntilFire;
  }

  // Construct a player at the starting position, ready to fire.
  Player() {
    this(SpaceInvaders.W / 2, SpaceInvaders.H - 50, 0);
  }

  // Update the game state (repeatedly called for each game tick).
  GameState update(GameState currentState) {
    // Update the player's position based on which keys are down.
    int newX = x;
    if (currentState.keyboard.isDown(VK_LEFT) || currentState.keyboard.isDown(VK_A))
      newX -= 2;
    if (currentState.keyboard.isDown(VK_RIGHT) || currentState.keyboard.isDown(VK_D))
      newX += 2;

    // Update the time until the player can fire.
    int newTicksUntilFire = ticksUntilFire;
    if (newTicksUntilFire > 0)
      --newTicksUntilFire;

    // Replace the old player with an updated player.
    Player newPlayer = new Player(newX, y, newTicksUntilFire);
    return currentState.setPlayer(newPlayer);
  }

  // Update the game state in response to a key press.
  GameState keyPressed(GameState currentState, int key) {
    if (key == VK_SPACE && ticksUntilFire == 0) {
      // Fire a bullet.
      Bullet b = new Bullet(x, y);
      ImmutableSet<Bullet> newBullets = currentState.bullets.plus(b);
      currentState = currentState.setBullets(newBullets);

      // Make the player wait 25 ticks before firing again.
      currentState = currentState.setPlayer(new Player(x, y, 25));
    }
    return currentState;
  }

  ImmutableImage render(ImmutableImage img) {
    return img.fillCircle(x, y, 20, Color.RED);
  }
}

// An immutable, copy-on-write object describing a bullet.
class Bullet {
  final int x, y;
  static final int radius = 5;

  Bullet(int x, int y) {
    this.x = x;
    this.y = y;
  }

  // Update the game state (repeatedly called for each game tick).
  GameState update(GameState currentState) {
    ImmutableSet<Bullet> bullets = currentState.bullets;
    bullets = bullets.minus(this);
    if (y + radius >= 0)
      // Add a copy of the bullet which has moved up the screen slightly.
      bullets = bullets.plus(new Bullet(x, y - 5));
    return currentState.setBullets(bullets);
  }

  ImmutableImage render(ImmutableImage img) {
    return img.fillCircle(x, y, radius, Color.BLACK);
  }
}

// An immutable, copy-on-write snapshot of the keyboard state at some time.
class KeyboardState {
  final ImmutableSet<Integer> depressedKeys;

  KeyboardState(ImmutableSet<Integer> depressedKeys) {
    this.depressedKeys = depressedKeys;
  }

  KeyboardState() {
    this(new ImmutableSet<Integer>());
  }

  GameState keyPressed(GameState currentState, int key) {
    return currentState.setKeyboard(new KeyboardState(depressedKeys.plus(key)));
  }

  GameState keyReleased(GameState currentState, int key) {
    return currentState.setKeyboard(new KeyboardState(depressedKeys.minus(key)));
  }

  boolean isDown(int key) {
    return depressedKeys.contains(key);
  }
}

// An immutable, copy-on-write description of the entire game state.
class GameState {
  final Player player;
  final ImmutableSet<Bullet> bullets;
  final KeyboardState keyboard;

  GameState(Player player, ImmutableSet<Bullet> bullets, KeyboardState keyboard) {
    this.player = player;
    this.bullets = bullets;
    this.keyboard = keyboard;
  }

  GameState() {
    this(new Player(), new ImmutableSet<Bullet>(), new KeyboardState());
  }

  GameState setPlayer(Player newPlayer) {
    return new GameState(newPlayer, bullets, keyboard);
  }

  GameState setBullets(ImmutableSet<Bullet> newBullets) {
    return new GameState(player, newBullets, keyboard);
  }

  GameState setKeyboard(KeyboardState newKeyboard) {
    return new GameState(player, bullets, newKeyboard);
  }

  // Update the game state (repeatedly called for each game tick).
  GameState update() {
    GameState current = this;
    current = current.player.update(current);
    for (Bullet b : current.bullets)
      current = b.update(current);
    return current;
  }

  // Update the game state in response to a key press.
  GameState keyPressed(int key) {
    GameState current = this;
    current = keyboard.keyPressed(current, key);
    current = player.keyPressed(current, key);
    return current;
  }

  // Update the game state in response to a key release.
  GameState keyReleased(int key) {
    GameState current = this;
    current = keyboard.keyReleased(current, key);
    return current;
  }

  ImmutableImage render() {
    ImmutableImage img = new ImmutableImage(SpaceInvaders.W, SpaceInvaders.H);
    img = img.clear(Color.BLUE);
    img = player.render(img);
    for (Bullet b : bullets)
      img = b.render(img);
    return img;
  }
}

public class SpaceInvaders {
  static final int W = 640, H = 480;

  static GameState currentState = new GameState();

  public static void main(String[] _) {
    JFrame frame = new JFrame() {{
      setSize(W, H);
      setTitle("Space Invaders");
      setContentPane(new JPanel() {
        @Override public void paintComponent(Graphics g) {
          BufferedImage img = SpaceInvaders.currentState.render().backingImage;
          ((Graphics2D) g).drawRenderedImage(img, new AffineTransform());
        }
      });
      addKeyListener(new KeyAdapter() {
        @Override public void keyPressed(KeyEvent e) {
          currentState = currentState.keyPressed(e.getKeyCode());
        }
        @Override public void keyReleased(KeyEvent e) {
          currentState = currentState.keyReleased(e.getKeyCode());
        }
      });
      setLocationByPlatform(true);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setVisible(true);
    }};

    for (;;) {
      currentState = currentState.update();
      frame.repaint();
      try {
        Thread.sleep(20);
      } catch (InterruptedException e) {}
    }
  }
}


问:
Design Patterns in Delphi
Delphi has a few problems implementing some design patterns because some features it lacks, like multiple inheritance and no pure abstract classes.

Are there any good resources or "Adaptation-Patterns" to convert some or all of the Design Patterns in the GoF book, to Delphi applications?

答:
The Design Patterns as presented in the GoF book are very heavyweight solutions. I would consider them over engineering in many cases. I would suggest implementing the patterns using much simpler class structures. </p>

<p>I think it is the complexity of the structures you are trying to recreate, rather than the patterns themselves, that are causing you problems. </p>

ContentLicense: CC BY-SA 2.5

Title: Design Patterns in Delphi

Body:
The Design Patterns as presented in the GoF book are very heavyweight solutions. I would consider them over engineering in many cases. I would suggest implementing the patterns using much simpler class structures.

I think it is the complexity of the structures you are trying to recreate, rather than the patterns themselves, that are causing you problems.

ContentLicense: CC BY-SA 3.0


问:
How do you read other's code?
Almost every advanced programmer says that it's very useful to read the code of other professionals. Usually they advice open source.

Do you read it or not? If you do, how often and what's the procedure of reading the code? Also, it's a bit difficult for newbies to deal with SVN - a bunches of files. What's the solution?

答:
The best thing you can hope for when reading the code of another project, be it an API or piece of software is that the variables, functions and macro names aren't abbreviated ambiguously or named so that you can figure out their intent.

But other than that, it takes a decent amount of knowledge spread across language, programming techniques and also about the code's purpose itself to be able to dive into complex code.

I'm currently trying to see how Lua does some of it's magic, but I'm getting to the point above where a lot of the identifiers are named vaguely and rather abbreviated to the point where I can't figure out which line is trying to do the thing I know has to be done at some point in the function code... The frequent single letter variables and rather abbreviated macro/function names are doing my head in.

Title: How do you read other's code?


问:
Project organization with professionals and students
I am working as a PhD student developing scientific/engineering simulations and algorithms to be tested in these simulations. These days the first student started to work on my project (for his Bachelor thesis) and I am wondering: how should I organize the project now? I think I have some good C++ knowledge (although I still want to improve everyday!) and the code contains some design patterns, lots of templated classes etc. These techniques are new to the student and I wonder if it's a good idea to have him work directly in the trunk of the project.

Do you have any experiences what happens if programming newbies and more experienced programmers are mixed? Does the code get messed up or do the newbies learn more by this? Is it wise to have a branch for the student to test his algorithms and maybe merge them into the trunk later? Should I first give him a book like The Pragmatic Programmer for reading (better suggestions?)?

Thanks for every answer!

PLEASE NOTE: I asked this question on Stackoverflow. The answer was about code reviews and I think this is a good way, but I was also advised that this site might be the more correct one, so I wanted to see if there are more things that might help or other opinions?

答:
I'd suggest you create one or more branches for each student. Let them work with the code and mess it up, but don't merge it into the trunk until it is un-messed. If they can write more-or-less independent code, which is what your description sounds like, then to some extent you can just leave them to it and let them learn. If they need to modify core components then you'll need to be more hands-on with code reviews, testing and style requirements.

Once you know how good a coder the student is then you can think about giving them commit rights to the trunk.

It's difficult to apply industry principles (code review, style guidelines etc) to students because of the temporary nature of the work and the fact that research is the primary goal, not code writing. There is often some resistance to meeting industry standards because students often feel it is not worth their time writing unit tests and documentation: they've got a dissertation to write!

That said, whatever tools you can set up to encourage best practice will help. I recommend Git for version control because it makes branching and merging very easy, and you can set up a continuous integration server like Hudson or Cruise Control to help encourage cleaner coding - the dashboards will show things like test coverage, style violations etc if set up properly. I'm not too familiar with static analysis tools for C++, but in Java you can use things like Checkstyle and Findbugs to encourage good style. There must be similar tools for C++.


问:
Why do .NET shops seem to prefer Crystal Report over RDLC reports?
I am currently using RDLC reports. But when interviewing for .NET jobs, they frequently ask "Have you worked with Crystal Reports?".

Why do they like Crystal Reports when Visual Studio already has RDLC reports integrated?

答: Interviewers ask more about Crystal Reports because it is a way more common name, and has been quite popular for years.  If you don't use Crystal Reports, when they ask that you can answer and say RDLC Reports, and then explain the similarities and differences.</p>


问:
Why is OOP difficult?
When I started using an object-oriented language (Java), I pretty much just went "Cool" and started coding. I've never really thought about it until only recently after having read lots of questions about OOP. The general impression I get is that people struggle with it. Since I haven't thought of it as hard, and I wouldn't say I'm any genius, I'm thinking that I must have missed something or misunderstood it.

Why is OOP difficult to understand? Is it difficult to understand?

答:
Recipe

Good OOP understanding = Good Mentor Or Good Books Or Both + Personal Interest + Practice.

Personal Interest

From my personal experience, personal interest comes a long way to cross the bridge from procedural programming to OOP with the right inputs from mentors or good books or both combined.

Practice, Practice and Practice

My best friend to get better understanding of OOP has been nothing but practice. This will definitely foster your OOP abilities.

As the saying goes “There is no substitute to hard work and no shortcut to success.”

Good luck!

Title: Why is OOP difficult?


问:
Approaches against code base becoming uniformly slow
We are working on a moderately-sized C++ code base (10Mloc) which through our optimization efforts is becoming uniformly slow.

This code base is a set of libraries which we combine to put them to work. When the general framework of how these libraries communicate was developed there was some emphasis on performance and later on, when more parts where added, the general framework wasn't changed much. Optimization was done when needed and as our hardware evolved. This made expensive early decision apparent only much later. We are now at a point where further optimizations are much more expensive since they would require rewriting large parts of the code base. We find ourselves approaching an undesirable local minimum since we know that in principle the code should be able to run much faster.

Are there any successful methodologies which help to decide what turns to take over the evolution of a code base towards a globally optimally performing solution which aren't easily confused by easy optimization opportunities?

EDIT

To answer the question how we currently profile:

We really only have 2 different scenarios how this code can be used, both embarrassingly parallel. Profiling is done both with wall clock time averaged over a large sample of inputs and more detailed runs (instruction costs, branch mispredictions and caching issues). This works well since we run exclusively on our extremely homogeneous machines (a cluster of a couple thousand identical machines). Since we usually keep all our machines busy most of the time running faster means we can look at additional new stuff. The issue is of course that when new input variations show up, they might get a late-comer penalty since we removed most obvious micro-inefficiencies for the other use cases, thus possibly narrowing down the number of "optimally running" scenarios. The current answers rightly suggest to separate data and algorithms so this becomes easier to adjust.

答:
A nice practical trick is to use your unit test suite as a performance test suite.

The following approach worked well in my code bases:

Ensure your unit test coverage is good (you did this already, right?)

Make sure your test running framework reports runtime on each individual test. This is important because you want to find where slow performance is happening.

If a test is running slowly, use this as a way to dive in and target optimisation at this area. Optimising before identifying a performance issue might be considered premature, so the great thing about this approach is that you get concrete evidence of poor performance first. If needed, break the test into smaller tests that benchmark different aspects so you can identify where the root problem is.

If a test runs extremely fast that's usually good, although you might then consider running the test in a loop with different parameters. This makes it into a better performance test and also increases your test coverage of the parameter space.

Write a few extra test that specifically target performance, e.g. end-to-end transaction times or time to complete 1,000 rule applications. If you have specific non-functional performance requirements (e.g. <300ms response time), then make the test fail if it takes too long.

If you keep doing all this, then over time the average performance of your code base should organically improve.

It would also be possible to track historical test times and draw performance charts and spot regressions over time in average performance. I never bothered with this mainly because it's a bit tricky to ensure you are comparing like with like as you change and add new tests, but it could be an interesting exercise if performance is sufficiently important to you.


答:
After looking at the "First, start at the high level, a birds-eye view" as @Berin Loritsch sugested you can look for unittests and/or integrationtests if there are any.

unittests are interesting to see how (api-)details work.

integrationtest usually give a good overview over businesprocesses.

Title: How do you read other's code?

Body:
Almost every advanced programmer says that it's very useful to read the code of other professionals. Usually they advice open source.

Do you read it or not? If you do, how often and what's the procedure of reading the code? Also, it's a bit difficult for newbies to deal with SVN - a bunches of files. What's the solution?


答:
The VCL is literally filled with implementations of patterns, many of which have come straight out of the GoF book itself.

I think that one problem that many people have when using Delphi is that Delphi allows a class with abstract methods to be compiled and used at run time provided the abstract methods are not called. The only thing that is purely abstract are Interfaces. Everything else that is needed for class inheritance and supporting multiple interfaces works with Delphi, so I can't really see how you would have any difficulty implementing ANY of the GoF Patterns. I've certainly never had any difficulty in the 14 or so years that I've been using the language.

As for multiple inheritance, what does that have to do with patterns?  Multiple inheritance is rife with problems conceptually, particularly if you are attempting to implement a descendant of two classes that present interfaces where there are identical methods with slightly different implementations. Which one would be used, and how would you choose? Interfaces solve this problem very elegantly in that you can use many interfaces in a single class implementation, and at different levels of the ancestry of a class.

If you have problems implementing specific patterns, perhaps a question on ProgrammersSE with some example code would help you to gain a better understanding about ways to overcome a particular problem in Delphi.  I'm sure they would make great questions.

Cheers,

Title: Design Patterns in Delphi

Body:
Delphi has a few problems implementing some design patterns because some features it lacks, like multiple inheritance and no pure abstract classes.

Are there any good resources or "Adaptation-Patterns" to convert some or all of the Design Patterns in the GoF book, to Delphi applications?


问:
How do you prevent getting stuck in "research-mode" on a big project you're unfamiliar with?
I'm in a situation where there's a big project that I need a lot of background know-how to accomplish. yet I'm not moving fast enough in the research/study phase - and seeing myself off-track frequently. What it amounts to is procrastination, except it's mixed with simply being overwhelmed and delaying the necessary background study.

How do you extract yourself from that limbo? My intuition says I should quickly study the material and start a tiny part of the whole project.

I appreciate any tips or advice.

答:
Simply, divide and conquer.

Perhaps offer to create a set of top-level documents which would help subsequent people in your position. There may be a business case for such documents existing.

Define a set of deliverables, each deliverable being a separate document which addresses a certain area or audience.

Timebox each deliverable and commit to a deadline date for it. Agree on a level of technical detail for each document, relevant to the audience, and when you feel time or scope slipping, add an assumption or recommendation that another focused analysis piece should be created at some point in the future.


问:
How can I simulate clicks for a mobile browser?
I am creating a web app. I was testing it on a mobile browser and noticed that :active pseudo class doesn't really work. How should I simulate clicks for a mobile browser? I'm specifically interested for Android and iPhone.

I am using css sprites. I stumbled upon ontouchstart but don't know how to use that. Can anyone help me over it?

答:
There seems to be an answer for your question on SO:

https://stackoverflow.com/questions/4940429/how-to-simulate-active-css-pseudo-class-in-android-on-non-link-elements

Even though the most upvoted answer has not been selected as THE answer by the poster, it seems to me that it is a valid solution for your problem. Also, the author indicates that the solution works on Iphone and Android.


问:
Learning event driven programming
I want to learn more about event driven programming. Especially where and why I would consider using events. What resources/books should I consider reading to this end? (note: I'm indifferent to language. )</p>

答:
.NET/C#

If you're indifferent to languages, you may try it in C# (Visual Studio Express C# is free). C# has specific event and delegate keywords for event-drive programming, and it is quite easy to grasp the idea. It starts with how event listening works, and ends with how to write your own events. There is also an interesting, but a bit further advanced article, on how to implement event-based asynchronous patterns here.

Now, there is an MSDN tutorial to start you up with the basic idea.

Java/Swing

If you want to try it in Java, you may, while programming a Swing application. There is also an Oracle tutorial on that subject, more specifically the intro. Edit: check out @Spoike's answer about the Observable pattern.

Javascript/JQuery

It is more specific to how JQuery's handles events, but you may find Benson Wong's tutorial helpful. Also, you just need to download JQuery, and you're ready to try.

Title: Learning event driven programming


答:
This applies to any learning, reward yourself.

Spend 5 hours learning? Have 1 hours procrastination.  Then review what you learned and see if it's still there.

Also (I'm guessing you have the requirements already) start small.  Find a requirement you know most about, study that.  Then move to one you know less about and study round that.  By the time you get to the real deep learning you will be feeling a lot more confident in your own ability to learn.

Finally, do not be afraid to ask colleagues etc for help in explaining anything.  I would much rather spend 3/4 hours at the start of a project explaining concepts than fixing errors later.

Title: How do you prevent getting stuck in "research-mode" on a big project you're unfamiliar with?

Body:
I'm in a situation where there's a big project that I need a lot of background know-how to accomplish. yet I'm not moving fast enough in the research/study phase - and seeing myself off-track frequently. What it amounts to is procrastination, except it's mixed with simply being overwhelmed and delaying the necessary background study.

How do you extract yourself from that limbo? My intuition says I should quickly study the material and start a tiny part of the whole project.

I appreciate any tips or advice.


答:
People use Crystal Reports because it came in the box with MS tools for so long (or at least a version featuring a subset of the functionality did).

It should be more important to demonstrate an understanding of use of a reporting tool than specific knowledge of Crystal, if its not remember that interviews work both ways...

Title: Why do .NET shops seem to prefer Crystal Report over RDLC reports?

Body:
I am currently using RDLC reports. But when interviewing for .NET jobs, they frequently ask "Have you worked with Crystal Reports?".

Why do they like Crystal Reports when Visual Studio already has RDLC reports integrated?


答:
Other than Jalayn's excellent answer I'd like to add:

Consider learning the Observer pattern

It is a Design Pattern used to implement event handling. If your programming language doesn't have first class support on delegates and events (see in Java how it solves with event handling in AWT and Swing) then you'll be implementing it using this pattern instead.

Note that Java has an Observer/Observable available in it's class library, but it is surprisingly simple to implement these yourself. In C# there are the IObserver/IObservable (that has some LINQ capabilities through Rx), but you can use delegates and events as well for the same purpose.

Title: Learning event driven programming

Body: I want to learn more about event driven programming. Especially where and why I would consider using events. What resources/books should I consider reading to this end? (note: I'm indifferent to language. )</p>


问:
How to get OOAD and Design Patterns hands-on experience in C#?
I have read the concepts and practiced some examples on OOAD and Design Patterns. But when I was asked to implement the singleton pattern in a little bit different manner, I was unable to do it and failed to reach my goal. I think I need some more in-depth understanding of the basics and some real experience with the concepts.

Please suggest me some good books and mini projects for me to get hands on experience on OOAD and Design Patterns in C#. I have almost 9 months of time frame to retake the test.

I have done this for singleton. It's valid code. But i was asked to implement in such a way that, i should be able to create instance of DBConnection class only once. use that instance to get the Connection object. This is where, i have failed to implement singleton :(

```<code>class DBConnection
{
    private Connection _conn = null;
    static Connection GetConnection()
    {
         if(_conn ==null)
              _conn = new Connection(...);
         return _conn;
    }
}
</code>```

答:
Head First into Design Patterns is a great book for beginners that discusses the patterns with practical (but very ficticious) examples.

If you're more inclined into a reference book then the original GoF book might be right up your alley, but is rather lacking in examples other than for descriptive purposes.

There is a book, Agile Software Development, Principles, Patterns, and Practices by Uncle Bob, that is highly regarded and commonly used as college-level course material. It has some practical examples and also goes through the SOLID principles and have a chapter on test driven development (IIRC).


问:
How do you keep emails short but complete?
I'm the odd kind of developer that likes writing and explaining - emails, specs, you name it.  I enjoy helping people understand things deeply. I hate ping-pong communications where groups go through 30 or 40 emails, phone calls and meetings because 25% of the group misunderstood the previous dashed-off email in which the writer only half-explained their position, or was in a hurry and miswrote a critical word or left out a negative or two.

This trait is great for documentation, but my emails are long, so people simply don't read them. A couple strategies I've used are formatting long emails as attached Word documents to encourage people to view them as documentation (works surprisingly well sometimes), or trying to use more bullet points instead of free paragraphs. These strategies increase readership, but the content is still long.

Of course I want to yell and scream that complex technical topics require a lot of exposition and clarification, but that doesn't help anyone. Obviously there are tradeoffs that can be made, but I have a hard time justifying making statements that aren't clear or that will result in a million questions, misunderstandings, or added "terms and conditions" later on.

How do you keep your communications short but complete?

答:
Executive Summary:

Put the important facts at the top then expand below.

Details:

When I have a long technical email that I fear will lose half the audience, I make an effort to put a short, accurate "executive summary" at the top, and include the complete technical details below.   Selective use of bold or underlining also helps.


答:
It's the same whenever you start working for a new company. You need to learn their ways of working and their systems. I think a small overview with a tech bod and some reading around the various systems and their interfaces. Then, ask for some bugs to look at. Fix them and get some more. No better way to get to know the system from the inside (and the technologies the system is built with).

Naturally, to fix the issue, you need an overview so will review javadoc, docs, wikis in the area and talk to related people (product owner, arch, dev). Do this 50/50 with general systems reviews. Stops you going stale (and procrastinating).

Now, not only are you learning but you're contributing and getting involved with team players at all levels (without being a hindrance). Remember though, you can't run before you can walk.


问:
Why doesn't the DART language use a special character to identify variables?
I come from a PHP background and I have been considering looking at DART in more detail.

DART is an, open source, front-end/back-end, language for web development.

PHP has a special $ (dollar) character to indicate variables:

```<code>$variable
CONSTANT
'string'
"etc"
</code>```

I find that dollar sign to be really useful for speeding up the proces of refactoring, especially if PHP code is mixed with HTML or content. It reduces the number of false positives when, say, doing a find and replace.

As DART is a completely fresh language (with no legacy) that can be embedded in HTML, it surprised me to see that it does not have any special identifier to indicate variables.

What's the reasoning behind that design decision?

答:
Actually you can use $ as a a prefix to variable names.

I tried it for you:
http://try.dartlang.org/s/lKco

Please note what happens to the great string interpolation feature. Basically you can access vars in a string with ${yourvar}. If you name a variable with $, then it looks ugly: ${$yourvar}. Therefore I do not recommend the $prefix style.

I have started with PHP too. But I found out soon as I switched to Java, that $ is not really common usus. What is the sense behind - the PHP developer would probably say, easy identification of variables. The Java developer would cry in pain.

The Dart developers try to make an "unexciting" language. It should look familiar to many. Without doubt Java syntax is more widespread than PHP syntax. Maybe this is the reason why Dart developers have left out the $.

On the other hand, personally speaking, I think it is really not necessary and after getting used to Java, I find it ugly. Ruby doesn't use it. JS doesn't use it. And so on.

Anyway here are more answers to the language:
http://www.dartlang.org/support/faq.html#language

If you want to follow the recent blogs on Dart I recommend you:
http://www.dartosphere.org


问:
What are the reasons one would use fully qualified class names in source code?
I recently ran across code where the developers used both fully qualified class names AND imported class names in their source code.

Example:

```<code>import packageA.Foo;

public class Example {
    public packageB.Bar doSomething() {
        final Foo foo = new Foo();
        ...
    }
}
</code>```

I was under the impression that the only reason one might want to use fully qualified name for classes in source code is when they have identical class names in two different packages and they need the fully qualified name to distinguish between the two. Am I wrong?

答:
The other reason (except collissions) would be if you need a class only once. This is especially true if the class implements a common interface and you only need the real classname for instantiation. Using the fully qualified name makes it easier to recognize that an uncommon class is used here, and where to find it (assuming sane naming conventions).</p>

```<code>List li = new com.foobar.veryspecial.MagicList();
</code>```

Body:
The other reason (except collissions) would be if you need a class only once. This is especially true if the class implements a common interface and you only need the real classname for instantiation. Using the fully qualified name makes it easier to recognize that an uncommon class is used here, and where to find it (assuming sane naming conventions).

List li = new com.foobar.veryspecial.MagicList();


问:
CFO's Expectations and Scrum Development
When it comes to financial topics, I'm admittedly not well versed.  I'm trying to lead my organization in our software development effort using a Scrum based development life-cycle.  I am often discouraged when trying to coach executive leadership due to their belief that Scrum and Agile don't play well with their finanacial objectives.  The other day I was challenged to show how my software developers could capitalize %60 of their work hours.

I've found a few articles on the web ( http://itprojectfinancials.com/insights/2011/06/05/capitalizing-software-development-costs-from-sdcl-to-agile/ ), but haven't come up with any great arguments.

I'm looking for advice or examples of organizations that capitalize software costs effectively in an Agile development environment.

This article sums up the issue pretty well, but offers no advise http://blogs.collab.net/agile/2007/12/20/the-scrum-gaap/

答:
This shouldn't be your problem.

Capitalisation of costs is your company CFO and/or accountant's problem. The rules vary in different jurisdictions. The accounting guys are the experts and should be capitalising costs according to the relevant accounting rules.

At most, they may need to ask you for some supporting information (e.g. of the 5,000 developer hours worked this quarter, can you estimate what % was on new software development or enhancement of existing software assets?). But it's up to them to ask you the right question.

If you are doing mostly new software development in a product that your company sells or intends to sell (i.e. the product counts as an intangible asset which returns future economic benefits) then it's perfectly possible to capitalise 100% of development costs. Also some countries have special incentives for R&D investment which is possible your software development work may qualify for.

The software development methodology you use is irrelevant, the only thing that is likely to matter is having some way of categorising which costs were spent on capitalizable projects or assets. But the same problem applies to waterfall development!

But for goodness sake, let the accountants sort this all out. You don't expect the CFO to write code, do you?


答: Write a succinct message and for things you think people may want details, provide hyper links to external Wiki pages from Wikipedia, eHow or even pages written by yourself.</p>

Title: How do you keep emails short but complete?

Body:
I'm the odd kind of developer that likes writing and explaining - emails, specs, you name it.  I enjoy helping people understand things deeply. I hate ping-pong communications where groups go through 30 or 40 emails, phone calls and meetings because 25% of the group misunderstood the previous dashed-off email in which the writer only half-explained their position, or was in a hurry and miswrote a critical word or left out a negative or two.

This trait is great for documentation, but my emails are long, so people simply don't read them. A couple strategies I've used are formatting long emails as attached Word documents to encourage people to view them as documentation (works surprisingly well sometimes), or trying to use more bullet points instead of free paragraphs. These strategies increase readership, but the content is still long.

Of course I want to yell and scream that complex technical topics require a lot of exposition and clarification, but that doesn't help anyone. Obviously there are tradeoffs that can be made, but I have a hard time justifying making statements that aren't clear or that will result in a million questions, misunderstandings, or added "terms and conditions" later on.

How do you keep your communications short but complete?


问:
Handling tough or unexpected technical questions in meetings
Depending on the project I'm working on, I may be required to attend more meetings with both internal stakeholders or technical management in client companies.

During the course of these meetings, there will inevitably be a few questions crop up that either:

You do not have an answer to.

You have not thought about for one reason or another.

You deem to be irrelevant or completely out of scope of the
current meeting.

In each case, how do you answer these questions? Any tips or tricks on remaining authoritative while remaining honest?

答:
You mentioned three types of questions:

a) you do not know the answer to: Tell them I don't know the answer, but that you will find out the answer. Then write down their question/concern and get back to them quickly.

b) you have not thought about for one reason or another: Tell them that is an interesting idea. Then write it down and followup quickly.

c) you deem to be irrelevant or completely out of scope of the current meeting: This answer is more complex. If it is irrelevant to the entire project, try to gently tell them it is not related. But do it carefully because you don't know why they are bringing it up. If it related to the project, but not related to the meeting; tell them you will pass it along to the right person. Then write it down, and followup quickly.

As you gain experience in the project, the embarrassment issues will go way. As you gain more experience on the job, you will be better at handling these types of questions.


答:
a) I will find out what the answer to this is from the person responsible for that area of the project and get back to you within the next two days

b) This is a good point, thank you for raising it.  I have not thought about this aspect but will do and get back to you within the next two days

c) What do you actually mean about this as it does not seem to fit with my understanding of the project.

Sure, just examples but if you read the meaning behind those they are all about managing their expectations and making them feel part of the process.  Also known as being assertive.

Title: Handling tough or unexpected technical questions in meetings

Body:
Depending on the project I'm working on, I may be required to attend more meetings with both internal stakeholders or technical management in client companies.

During the course of these meetings, there will inevitably be a few questions crop up that either:

You do not have an answer to.

You have not thought about for one reason or another.

You deem to be irrelevant or completely out of scope of the
current meeting.

In each case, how do you answer these questions? Any tips or tricks on remaining authoritative while remaining honest?


答:
This happens to everyone from time to time, no matter how experienced or prepared. Honesty is the best policy in these situations, which means acknowledging you don't have the answers. You'll be a lot more credible in the long run than if you try to bluff your way through it.

Specific questions:

(a) If you don't know the answer, instead of just shrugging your shoulders, the important thing is to assure people you understand what they're asking and that you can go away and find out. You may want to provide a timeline and some idea of the work involved if it's likely to require heavy lifting.

(b) If you haven't though about it, again, it's fine. Same as above, just let them know and get back to them.

(c) If you think the questions are irrelevant, you should generally speak up tactfully about why that's the case; it's quite possible they didn't realise it was irrelevant. If you're working with professionals, they'll accept it's irrelevant if you provide evidence/reasoning, and by checking with them, you might well discover it's relevant after all.


问:
Why and for what reasons developers may not like "daily scrum"?
There are advantages in holding daily scrum, like:

Team get coordinated with each other

Everyone knows what amount of task has been done

Burndown chart gets more and more complete

Task board is updated

It doesn't last that much, 15 minutes won't kill anybody

However, recently (after 6 months of implementing and using scrum), I feel like that our developers don't like scrum daily that much anymore. People just update the task board, without explaining enough and it seems that  they're bored of it. I see that when for any reason, we don't hold it, they kind'of become extra-happy.

I just don't know what could be wrong with this. Are there any reasons mentioned somewhere for disadvantages the "daily scrum" can have for a team? What could be the reasons for developers getting tired of daily scrum?

答:
I've managed and been a part of scrum teams many times. The key reason developers don't like scrum are:

Because they run by a very poor scrum master, if it turns into 45 minutes your scrum master needs to improve at controlling the scrum.

The biggest and by far THE most honest reason why they don't like it, is because it's very hard to hide in a bad work ethic, i.e., more blatantly, it shows up lazy people. Some devs I've worked with are shocking, they take days doing tasks that should be 30 minute job. A good PM should remove barriers for devs which means they should be able to plough through their tasks in a sprint. Devs don't like it because they have to stand up each day and demonstrate the progress they've made. It causes anxiety when they can't demonstrate progress for what ever reason. If it's because of a valid issue a good scrum master should resolve that issue asap.

The problem comes when scrum masters doesn't have the authority, skills or capability to resolve blocking issues. In fact I've seen some just bury issues hoping that they will go away. This is disastrous.


答:
I read the link you posted. It is bare basic and riddled with assumptions! If you have to defend it really, hard luck!

Nevertheless, i would say, convincing CFO shouldn't be hard (once you know what matters).

The point is, no CFO is really worried about the money being spent (if there is a due justification) as much as he is worried that money gets wasted because at the end project fails. (The article you posted simply ignores some simple real life situations); If you really want to promote Agile - never promote it to say it will reduce cost. The point primarily is that

it reduces risk : it will ensure you won't have to write off the whole stuff! If at all you do have to - you will ensure that with Agile/Scrum you would have realized this much earlier than other methods.

it reduces your risk on waiting to get to market (and start revenue) much earlier than waiting the whole log finished.

it reduces your risk on building the wrong project!

This is true with any iterative method and not just Agile/Scrum. What you really need to show is not that Agile is better done; but how horrible things are when projects fail. (I guess that's where explaining CFO is even better than IT heads because they start defending stuff straight away!).

In general, if organization (and specially leaders) is attuned to such philosophies (like waterfall), it is probably a bad idea to sell-by-promise. It is better to demonstrate-by-doing it. Start out small where you have a comfortable control. And probably the first stab i would do is to question - why start with so many features? Let's divide them into 10 releases! Next, who stops you from meeting customers? Step-by-step, start adhering some parts of the Agile without making explicitly announced rituals. Once, you go successful, people will see the point as to what Agile will bring on board.

When you make specific recommendations, (rather than philosophy) people tend to listen a lot better.

Title: CFO's Expectations and Scrum Development

Body:
When it comes to financial topics, I'm admittedly not well versed.  I'm trying to lead my organization in our software development effort using a Scrum based development life-cycle.  I am often discouraged when trying to coach executive leadership due to their belief that Scrum and Agile don't play well with their finanacial objectives.  The other day I was challenged to show how my software developers could capitalize %60 of their work hours.

I've found a few articles on the web ( http://itprojectfinancials.com/insights/2011/06/05/capitalizing-software-development-costs-from-sdcl-to-agile/ ), but haven't come up with any great arguments.

I'm looking for advice or examples of organizations that capitalize software costs effectively in an Agile development environment.

This article sums up the issue pretty well, but offers no advise http://blogs.collab.net/agile/2007/12/20/the-scrum-gaap/


问:
What should developers test before submitting their work to testers?
Is there a checklist the developer must go over before passing their work to testers?

Also, what are the conditions/cases the developer must pay attention to ?

答:
Does it do what it was designed to do? Does it throw the appropriate exceptions when given bad input? Is it usable? (that applies to APIs as well as UIs).

Your code should be -- to the best of your knowledge -- bug free before giving it to testers. You should do whatever tests you need to do to feel comfortable with the quality of your own code.


答:
Though i wrote in a different context - here is a best compilation of resources to your query: https://softwareengineering.stackexchange.com/questions/82462/what-is-the-architecture-model-of-an-android-application/131352#131352

Basically, learn various patterns from POSA and related literature from the same author.

Another good resource is here.

Also, if you are in C, consider using libevent. It shows how good scalability is achievable using such constructs.

Title: Learning event driven programming


答:
That depends. There are several philosophies:

Test Driven Development wants you to write Regression/ Unit-Test before you even start to code.

the coder knows the tricky parts of the code and might test accordingly

an independent tester might find errors that the developer never thought about. Also, the tester might be more familiar with the area where the software is actually employed, and might do some validation ("Are you building the right thing?" compared to verification  "Are you building it right?") as well.

So the level of testing each partner does depends on your project and your organization. It's important do agree on this level beforehand. Of course the code should at least compile and run without throwing errors.

Title: What should developers test before submitting their work to testers?

Body:
Is there a checklist the developer must go over before passing their work to testers?

Also, what are the conditions/cases the developer must pay attention to ?


问:
How to use a MessageBox using the MVVM pattern?
I am implementing a UI application using the MVVM design-pattern.

The thing is, sometimes when you detect that something is wrong with data that was inputted by the user, you'd like to notify him somehow.

The solution I used so far was to have a "messaging framework" which allows me to basically show messages in a ListView I integrate within the window.

However, sometimes the windows get a bit "overloaded" with graphical elements, and I would like to be able to show the messages in a message box (basically a modal window).

As the ViewModel is not supposed to be aware of anything about the UI, I cannot instantiate any window "explicitly".

Ideally, this modal window would also use the MVVM pattern and hence I would implement a ViewModel for that window, which would be instantiated within the "main" windows's ViewModel, and passed to the modal window through the DataContext.

I would like to have a "simple" example of how to do such thing? Or should this approach be banned from an MVVM application?

EDIT:

Would the use of the Unity Framework be something you recommend?

答:
Cinch implements a message box service (among others) that can be mocked for unit testing purposes (or completely replaced by something else).  That's what we've been using for the past few months.  The ViewModel is in a way requesting something UI-specific, but really it doesn't know how that will be presented to the user, and it's not "talking" to the UI controls (WPF) directly.  I've seen a couple of other MVVM frameworks adopting a similar approach.

Unity is for dependency injection (mostly).  Cinch uses MEF.  Not that you actually NEED that though - The MVVM pattern doesn't rely on that, even though some frameworks sort of do.


问:
IDEs for dynamic languages - how far can you get?
I find it frustrating how the speed of development that dynamic languages should offer gets significantly compromised by the lack of completions and other assets that IDEs would give you in their static counterparts.

It's not just about typing less - it's the productivity boost and plain fun you get by browsing APIs without constantly having to refer to a documentation that is not integrated with the editor.

To date all IDE + dynamic language combinations -which to be fair aren't that much- I've tried were:

buggy

slow

clueless/overenthusiastic (as in showing all completions ever possible)

or simply not as complete as, say, Eclipse + Java.

I'm aware that dynamic code analysis is not a trivial task. But one can't help wondering - is this piece of code really so hard to figure out?

So my question is:

Have any particular IDEs (or less all-in-one setups) achieved a totally outstanding support for a dynamic language, or is this still an 'unsolved' problem?

答:
At least for PHP many IDEs "understand" something like

```<code>/** @var $foo ClassA **/
</code>```

If you document in a standardized way (in this case phpDocumentor)  the IDE will make the most of it.

Body:
At least for PHP many IDEs "understand" something like

/** @var $foo ClassA **/

If you document in a standardized way (in this case phpDocumentor)  the IDE will make the most of it.


问:
Functional Programming approach for a simplified game using Scala and LWJGL
I, a Java imperative programmer, would like to understand how to generate a simple version of Space Invaders based on Functional Programming design principles (in particular Referential Transparency). However, each time I try to think of a design, I get lost in the morass of extreme mutability, the same mutability which is shunned by the functional programming purists.

As an attempt to learn Functional Programming, I decided to attempt to create a very simple 2D interactive game, Space Invader (note the lack of plural), in Scala using the LWJGL. Here are the requirements for the basic game:

User ship at the bottom of the screen moved left and right by the "A" and "D" keys respectively

User ship bullet fired straight up activated by the space bar with a minimum pause between shots to be .5 seconds

Alien ship bullet fired straight down activated by a random time of .5 to 1.5 seconds between shots

Things intentionally left out from the original game are WxH aliens, degradable defense barriers x3, high speed saucer ship at at the top of the screen.

Okay, now to the actual problem domain. For me, all the deterministic parts are obvious. It's the non-deterministic parts that seem to be blocking my ability to consider how to approach. The deterministic parts are the bullet's trajectory once they exist, the continuous motion of the alien and the explosion due to a hit on either (or both) of the player's ship or the alien. The non-deterministic parts (to me) are handling the stream of user input, handling fetching a random value for determining alien bullet firings and handling the output (both graphics and sound).

I can do (and have done) lots of this type of game development over the years. However, all of it was from the imperative paradigm. And LWJGL even provides a very simple Java version of Space invaders (of which I began moving to Scala using Scala as Java-without-semicolons).

Here are some links that talk around this area of which none seem to have directly dealt with the ideas in a way a person coming from Java/Imperative programming would understand:

Purely Functional Retrogames, Part 1 by James Hague

Similar Stack Overflow post

Clojure/Lisp Games

Haskell Games on Stack Overflow

Yampa's (in Haskell) Functional Reactive Programming

It appears that there are some ideas in the Clojure/Lisp and Haskell games (with source). Unfortunately, I am not able to read/interpret the code into mental models that make any sense to my simpleminded Java imperative brain.

I'm so excited by the possibilities offered by FP, I can just taste the multi-threaded scalability capabilities. I feel like if were able to grok how something as simple as the time + event + randomness model for Space Invader can be implemented, segregating the deterministic and non-deterministic parts in a properly designed system without it turning into what feels like advanced mathematical theory; i.e. Yampa, I'd be set. If learning the level of theory Yampa seems to require to successfully generate simple games is necessary, then the overhead of acquiring all the necessary training and conceptual framework will vastly outweigh my understanding of the benefits of FP (at least for this over-simplified learning experiment).

Any feedback, proposed models, suggested methods of approaching the problem domain (more specific than the generalities covered by James Hague) would be greatly appreciated.

答:
Well, you are hamstringing your efforts by using LWJGL -- nothing against it, but it will impose non-functional idioms.

Your research is in line with what I'd recommend, however. "Events" are well supported in functional programming through concepts such as functional reactive programming or dataflow programming. You may try out Reactive, a FRP library for Scala, to see if it can contain your side effects.

Also, take a page out of Haskell: use monads to encapsulate/isolate side effects. See state and IO monads.


答: I think this presentation by Steve Yegge is still relevant. in a nut shell there are some half decent Java script ides (intelliJ IDEA), but dynamic languages in general are playing catch-up, not because there is anything inherently harder about making these tools (or indeed languages) it's just the static languages got all the attention first.</p>

Title: IDEs for dynamic languages - how far can you get?

Body:
I find it frustrating how the speed of development that dynamic languages should offer gets significantly compromised by the lack of completions and other assets that IDEs would give you in their static counterparts.

It's not just about typing less - it's the productivity boost and plain fun you get by browsing APIs without constantly having to refer to a documentation that is not integrated with the editor.

To date all IDE + dynamic language combinations -which to be fair aren't that much- I've tried were:

buggy

slow

clueless/overenthusiastic (as in showing all completions ever possible)

or simply not as complete as, say, Eclipse + Java.

I'm aware that dynamic code analysis is not a trivial task. But one can't help wondering - is this piece of code really so hard to figure out?

So my question is:

Have any particular IDEs (or less all-in-one setups) achieved a totally outstanding support for a dynamic language, or is this still an 'unsolved' problem?


问:
Make a big deal out of == true?
There is a colleague of mine who constantly writes:

```<code>if (someBool == true)
</code>```

It drives me up the wall!  Should I make a big deal of it or just drop it?

答:
Ah yes, but what if the variable is nullable? (bool?)

Some languages (C#) will require and cast or comparison with 'true'.

```<code>bool? isAccepted = true;

if((bool)isAccepted)
{...}

if(isAccepted == true)
{...}
</code>```

Title: Make a big deal out of == true?

Body:
Ah yes, but what if the variable is nullable? (bool?)

Some languages (C#) will require and cast or comparison with 'true'.

bool? isAccepted = true;

if((bool)isAccepted)
{...}

if(isAccepted == true)
{...}

OwnerDisplayName: Jared G


答:
I have found that Wing IDE's support for Python is really outstanding. It does a good job with code completion, and its debugger is as powerful as Visual Studio's is for the non-dynamic C#.

I can attest that it not buggy, slow or clueless. I have never used Eclipse, so I'm ignorant on that point, but I think that the greater question is: is there some inherent barrier to developing a complete and productivity-enhancing IDE for dynamic languages. Given my experience with Python and Wing, I am inclined to say that it is not the case. It is, however, certainly more difficult.


问:
Can you point me to a nontrivial strategy pattern implementation?
We are faced implementing a registration workflow with many branches. There are three main flows which in some conditions lead to one another. Each flow has at least four different steps; some steps interact with the server, and every step adds more information to the state. Also the requirement is to have it persistent between sessions, so if the user closes the app (this is a mobile app), it will restore the process from the last completed step with the state from the previous session.

I think this could benefit from the use of the strategy pattern, but I've never had to implement it for such a complex case. Does anyone know of any examples in open source or articles from which I could find inspiration? Preferably the examples would be from a live/working/stable application.

I'm interested in Java implementation mostly; we are developing for Java mobile phones: android, blackberry and J2ME. We have an SDK which is quite well separated from platform specific implementations, but examples in C++, C#, Objective-C or Python would be acceptable.

答: Here is an example that does exactly what you are looking for.  The example handles a web registration process that is persisted so the user can resume where they left off.  It is implemented using ASP.NET MVC in C# with Windows Workflow Foundation.</p>


答: Check out the dofactory website. They list all of the GoF patterns with concrete examples in C#.  They are trying to sell a product that implements the patterns for you but there is a lot of useful examples on their website.</p>

Title: How to get OOAD and Design Patterns hands-on experience in C#?

Body:
I have read the concepts and practiced some examples on OOAD and Design Patterns. But when I was asked to implement the singleton pattern in a little bit different manner, I was unable to do it and failed to reach my goal. I think I need some more in-depth understanding of the basics and some real experience with the concepts.

Please suggest me some good books and mini projects for me to get hands on experience on OOAD and Design Patterns in C#. I have almost 9 months of time frame to retake the test.

I have done this for singleton. It's valid code. But i was asked to implement in such a way that, i should be able to create instance of DBConnection class only once. use that instance to get the Connection object. This is where, i have failed to implement singleton :(

```<code>class DBConnection
{
    private Connection _conn = null;
    static Connection GetConnection()
    {
         if(_conn ==null)
              _conn = new Connection(...);
         return _conn;
    }
}
</code>```


答:
You could raise a custom command, i.e. AlertUserCommand,
then have one or more of your view-models implement the command.

The command will need to be implemented in your main view model.

The implementation of the command can be anything from calling the system message dialog to creating a custom message view + setting its datacontext or setting a property on the view-model that something in the current view is binded to (e.g. a list box or status bar).

You can override the command in lower view-models if they want a different type of alert e.g. display in current control instead of where main vm displays it.

You could use the command parameters to specify severity and have the command implementation depend on the severity or set a vm property with the severity.

Title: How to use a MessageBox using the MVVM pattern?

Body:
I am implementing a UI application using the MVVM design-pattern.

The thing is, sometimes when you detect that something is wrong with data that was inputted by the user, you'd like to notify him somehow.

The solution I used so far was to have a "messaging framework" which allows me to basically show messages in a ListView I integrate within the window.

However, sometimes the windows get a bit "overloaded" with graphical elements, and I would like to be able to show the messages in a message box (basically a modal window).

As the ViewModel is not supposed to be aware of anything about the UI, I cannot instantiate any window "explicitly".

Ideally, this modal window would also use the MVVM pattern and hence I would implement a ViewModel for that window, which would be instantiated within the "main" windows's ViewModel, and passed to the modal window through the DataContext.

I would like to have a "simple" example of how to do such thing? Or should this approach be banned from an MVVM application?

EDIT:

Would the use of the Unity Framework be something you recommend?


答:
Is there a checklist the developer must go over before passing their work to testers?

Absolutely. Ideally, this checklist consists of two items:

Verify that the continuous integration cycle has ran to a completion, and

Make an entry in a bug/feature tracking system for the changes going to QA

The real checklist is hidden behind your continuous integration strategy. Since this list is centrally managed and fully automated, individual developers cannot throw their code over the wall to QA "forget" to check something important before submitting their work to the QA team. You know that developers often become "forgetful" under time pressure, right?

The continuous integration system needs to run a build, and run all the unit and integration tests. It goes without saying that developers need to make new unit tests available to the continuous integration system as they develop new features and fix bugs.

Developers should not touch what comes out from the continuous integration system before giving it to QA, not even to install and quickly try it out. If QA says that the build did not install, you need to fix your continuous integration cycle to make sure that it does not spit out non-installable or non-working artifacts.

The second step is a pleasant one (marking a bug fixed or a feature complete), so developers rarely, if ever, forget to do it.


问:
Scientific evaluation of programming methodologies
There are now a a variety of programming methodologies: Scrum, Extreme Programming, Kanban to just name a few. Most of them combine several more basic techniques (for example frequent iterations). However, nearly all of them state that their combination of technics is the only way to write good software.

I don't think that there is one way that's best for each and every project. Instead I'm interested in independent scientific evaluations.

What basic techniques work best for which kind of project?

Is there any advantage in the combination of certain techniques?

As I don't have time to go through primary literature I'm especially looking for a book. I know that there is Peopleware, but it is a bit old. There are already several related questions (Are there any scientifically rigorous studies of coding style principles?, Scientific evidence that supports using long variable names instead of abbreviations?...)

答: The most important factor by far in a software project success is not the methodology. It is the team.</p>


答: From a tester point of view, the biggest mistake of a developer is to provide a code that does not compile. </p>


答:
As much of a fan of empirical data with rigorous statistical validity, I don't think you can scientifically prove that one methodology is any better or worse than any other.

There are many factors that go into chosing a methodology. In Rapid Development: Taming Wild Software Schedules, Steve McConnell identifies a number of factors: level of understanding of the requirements, level of understanding of the architecture, desired reliability, risk management, schedule constraints, amount of process overhead, mid-project "course corrections", ability to provide the customer with visibility, ability to provide management with visibility, and sophistication of the development team and management. There are others, as well, such as organizational culture, so there probably isn't an exhaustive list anywhere.

Even given the exact same project, there is also the team factor. If you take a team that has consistantly delivered software using the plan-driven spiral methodology and throw them into Scrum, they are going to experience a decrease in productivity, an increase in thrashing, and have to overcome a new process model before they can come around to being successful. Even though another methodology might be more suited, there's always the business need to actually deliver the software. That's why process improvement efforts are frequently long-term efforts and not overnight - major changes are shocking to a team and (even if the methodology might be better suited on paper) can cause a decrease in productivity.

I'd recommend picking up Rapid Development, along with Software Project Survival Guide (also by McConnell).

Title: Scientific evaluation of programming methodologies

Body:
There are now a a variety of programming methodologies: Scrum, Extreme Programming, Kanban to just name a few. Most of them combine several more basic techniques (for example frequent iterations). However, nearly all of them state that their combination of technics is the only way to write good software.

I don't think that there is one way that's best for each and every project. Instead I'm interested in independent scientific evaluations.

What basic techniques work best for which kind of project?

Is there any advantage in the combination of certain techniques?

As I don't have time to go through primary literature I'm especially looking for a book. I know that there is Peopleware, but it is a bit old. There are already several related questions (Are there any scientifically rigorous studies of coding style principles?, Scientific evidence that supports using long variable names instead of abbreviations?...)


答:
Modify the meeting to make sure it delivers benefits:

Schedule it at a time that offers some convenience. Why can't it be 30 minutes after work starts so everyone can review email and organize their thoughts for the meetiing. Brevity takes planning. The unprepared can ramble on forever.

Identify problems that could have been avoided had an issue been communicated during the meeting. Everyone needs to understand what is the point.

Do whatever it takes to keep everyone's input to a minimum. It's not the place for debate. Encourge people to privately schedule meetings outside of the daily meeting focused on a topic that needs discussion. Rule: only one person talks at a time.

All the complainers need to make sure they're not contributing to the problem. If you can accomplish your goals for the daily scrum without having one in a less painful manner, we'd like to hear it.

Title: Why and for what reasons developers may not like "daily scrum"?

Body:
There are advantages in holding daily scrum, like:

Team get coordinated with each other

Everyone knows what amount of task has been done

Burndown chart gets more and more complete

Task board is updated

It doesn't last that much, 15 minutes won't kill anybody

However, recently (after 6 months of implementing and using scrum), I feel like that our developers don't like scrum daily that much anymore. People just update the task board, without explaining enough and it seems that  they're bored of it. I see that when for any reason, we don't hold it, they kind'of become extra-happy.

I just don't know what could be wrong with this. Are there any reasons mentioned somewhere for disadvantages the "daily scrum" can have for a team? What could be the reasons for developers getting tired of daily scrum?


答:
Microsoft's Visual Studio is an IDE that is used by many programmers and it supports IronRuby, IronPython and F#. Most would consider Ruby and Python to be a dynamic programming language while F# would be less so.

In response to the comment, F# is a programming language.

F# (pronounced F Sharp) is a multi-paradigm programming language,
  targeting the .NET Framework, that encompasses functional programming
  as well as imperative and object-oriented programming disciplines. It
  is a variant of ML and is largely compatible with the OCaml
  implementation.

While the exact definition of what exactly defines a "dynamic language" is still up for debate, most would agree that JavaScript is more "dynamic" than C# for example. According to Wikipedia:

The definition of a dynamic language is ambiguous because it attempts
  to make distinctions between code and data as well as between
  compilation and runtime which are not universal. Virtual machines,
  just-in-time compilation, and the ability of many programming
  languages on some systems to directly modify machine code make the
  distinction abstract. In general, the assertion that a language is
  dynamic is more an assertion about the ease of use of dynamic features
  than it is a clear statement of the capabilities of the language.

I don't want to open a can of worms here. Some would suggest that F# is more correctly described as a functional rather than a dynamic language, and I would not take exception to that. What I believe would be fair to say that is of the various .Net languages, F# is generally regarded as the more appropriate for dynamic programming than C# or VB.

You may want to see: What qualifies a programming language as dynamic?


答:
Everything you can such that QA doesn't reply back to you, CC'ing your manager saying "you clearly didn't test this deliverable". You could have unit, integration, system and manual (i.e. you) testing at your disposal. Failing to do those would just be wasting the QA's time.

One QA guy who worked for me would ask for "proof" that the developers had tested the deliverable. This could be xUnit results, output from scripts or even a paper-based checklist. Suffice to say that this stopped developers from just forwarding him the build output.


答:
Wherever you can, link to an existing reference when a long explanation is needed, instead of including the entire explanation in the email.

Think about what the recipient wants to do with the information, and give them exactly enough to do that.  Most non-hackers don't want to know any more than they need to get their task at hand done, and anyone who needs more will ask you.

As a general rule, when dealing with non-hackers, any email over one printed page in length (600 or so words) is too long.  Either cut down on the verbiage, or beak most of it out to a link you can reference or a document you can attach.  For example, 2,000 words of documentation should become a manual that you link to from or attach to the email.  This makes it easier to keep the documentation updated and under revision control, too!


问:
What's the benefit of avoiding the use of a debugger?
Over the course of my career, I've noticed that some developers don't use debugging tools, but do spot checking on erroneous code to figure out what the problem is.

While many times being able to quickly find errors in code without a debugger is a good skill to have, it seems it's less productive to spend a lot of time looking for issues when a debugger would easily find little mistakes like typos.

Is it possible to manage a complex without a debugger? Is it advisable? What benefits are there to be had by using "psychic debugging?"

答:
I'm surprised that the discussion on this topic has not mentioned "unit testing".

Because I do test-driven development, I don't spend a lot of time in the debugger.  10 years ago, I used to dutifully step through the debugger:

After writing a piece of code to ensure that it worked and

When I received a bug report to try to diagnose the problem

What I've found after 10 years of test-driven development is that I'm a lot more productive as a programmer if:

I write unit tests before I write the code to ensure that I wrote it correctly

I write unit tests immediately upon receiving a bug report to attempt to duplicate and drill-down on the problem.

Allowing the computer to run through the code and validate the result is thousands of times faster than I can think or step through the code to mentally validate the results, and doesn't make mistakes.

I still have to step through in the debugger occasionally, and I'm still engaged in mentally analyzing the code... but only rarely, and mostly for very tricky code.


答:
Have any particular IDEs (or less all-in-one setups) achieved a totally outstanding support for a dynamic language,

Considering your evaluation is hard to understand ("totally outstanding"? "clueless/overenthusiastic"?) it's doubtful that any IDE could match the implied standard.

Trivially comparing against  Eclipse + Java is silly because dynamic languages are not Java.

or is this still an 'unsolved' problem?

Not quite.

It's probably unsolvable.  Your requirements ("lack of completions and other assets") make it difficult to be more precise.

Dynamic languages cannot have the same kind of code completion that static languages do.  It's essentially impossible.

Some IDE's do a good job of guessing.  Eclipse, for example, has plugins for dynamic languages.


答:
Pretty much everything you know from IDEs was first developed in Smalltak which is a dynamic language. Everything else is just copying them. So clearly, all of these features are possible in dynamic languages.

Today, dynamic languages are behind the static languages. But why?

Until recently it was pretty universally thought that static typing was superior to dynamic typing. Many coders have changed their minds more recently on that point. Focus on IDEs for dynamicly typed languages wasn't there.

I think that the features for IDEs are less useful in dynamically typed languages. When working in Java or Objective-C, I feel that the IDE is necessary to help me work with the language, but the same isn't true of the dynamic languages.

Some parts of the task are easier in a static language. Its straightforward to figure out the type of an expression. Doing the same in a dynamic language requires either whole program analysis or logging the types during runtime. Since a lot of what the IDE revolves around the types, that does have an effect.


问:
What do I need to consider when using code under the Apache License in an application submitted to Mac App Store?
First off, I am new to licenses and app stores.

There is an example app on a framework that has a Class file with much of the functionality I'll need for my own app. It's less than 1000 lines of code and distributed under the Apache License 2.0.

As far as I know I can use/modify the code and just acknowledge the developer and include the license, but does this mean my whole project will be distributed under the Apache License 2.0 or just does it just apply to that source file?

Once my project is done, would I be able to publish my app in the Mac App Store? Would I be able to sell it there?

The file is from an example project that pretty much demonstrates all which is possible in the framework, and using it in my project would save me a ton of time. However, if this is not possible I guess I'll just have to code it myself.

答:
There are licenses which would require you to place your whole project under that license if you use any code which is -- the GPL (Gnu General Public License) is the most famous example of this, but there are others.  These are sometimes referred to as "viral" licenses.  The Apache license is not such a license.

The Apache license is in the tradition of "BSD" style licenses (including the original BSD license, the MIT license, and others), which only require you to keep code which is already under the license so licensed -- additional code which you write using Apache-licensed code is not "infected" by the Apache license, and you may place it under any license you choose.


问:
Is it a really required skill to program without API documentation?
I barely passed my Java programming exam today. I had to answer some general questions about threading which I did well and to write a little threaded program which was worse. I had to connect my laptop to the projector screen and write the program right away. My first attempt was to use anonymous classes but I forgot the exact syntax. Maybe because of some excitement or maybe because last two weeks I was coding mostly in php. Then I asked is it allowed to use the API documentation. The answer was "NO". So I decided to go another way around and I implemented Runnable. The program was doing what was requested at the end. Of course the examiners noticed my first fail and that affected my score greatly. I was amazed that it was not allowed to use the API documentation.

So, my question is: Is it really important to be able to code flawlessly without API documentation? Should I develop this skill? Is it really important in the real world and in the work environment? While on programming courses I focused on learning patterns, developing skills to write good design applications, skills to use API and find the necessary information fast. I was not trying to learn how to program without API documentation. Is it must-have during job interviews (coding without API documentation)?

答:
I would say, no it isn't required, it is physically impossible for the human brain to memorise so much information, but you still need to know the basics or the most used things, since there aren't a lot of those to memorise. Otherwise, it's impossible to memorise everything that there is on java.

Also it is unfair for a teacher to want his students to know everything, or to use that to know if they program with a language, besides the exercises or projects he assigns to you. For me it's like wanting to know what you do when your not on school or doing related work.

EDIT: Obviously, what the teacher asks to you depends on him, some teachers value theory more while others value practise and don't care if you don't understand everything.


答:
I ran into that problem with python, sort of. I wanted vim as my editor, but that meant I wouldn't have an IDE environment. So, I rolled my own with vim plugins. Currently, I think I actually have a better environment for development that any IDE I've used in the past.

My setup is hosted on github, feel free to take a look and crib what you like. For a quick overview of the plugins:

pathogen

python-mode, for rope, pyflakes, and pydoc integration

vimpdb for a python debugger

project for a list of files in a project

taglist for tag jumping

supertab for tab-completion

snipmate for snippets

conqueterm for an integrated shell, either command prompt, bash, python, or ipython

There's some other stuff, but it has all the features that the more popular IDE's have. It didn't cost me a dime, and I get to leverage all of vim's power. Splits, movement commands, registers, jumping, being able to run my entire dev environment with the keyboard...