问:
Are there any OO-principles that are practically applicable for Javascript?
Javascript is a prototype-based object oriented language but can become class-based in a variety of ways, either by:

Writing the functions to be used as classes by yourself

Use a nifty class system in a framework (such as mootools Class.Class)

Generate it from Coffeescript

In the beginning I tended do write class based code in Javascript and heavily relied on it. Recently however I've been using Javascript frameworks, and NodeJS, that go away from this notion of classes and rely more on the dynamic nature of the code such as:

Async programming, using and writing writing code that uses callbacks/events

Loading modules with RequireJS (so that they don't leak to the global namespace)

Functional programming concepts such as list comprehensions (map, filter, etc.)

Among other things

What I gathered so far is that most OO principles and patterns I've read (such as SOLID and GoF patterns) were written for class-based OO languages in mind like Smalltalk and C++. But are there any of them applicable for a prototype-based language such as Javascript?

Are there any principles or patterns that are just specific to Javascript? Principles to avoid callback hell, evil eval, or any other anti-patterns etc.

答:
After many edits, this answer has become a monster in length. I apologize in advance.

First of all, eval() isn't always bad, and can bring benefit in performance when used in lazy-evaluation, for example. Lazy-evaluation is similar to lazy-loading, but you essentially store your code within strings, and then use eval or new Function to evaluate the code. If you use some tricks, then it'll become much more useful than evil, but if you don't, it can lead to bad things. You can look at my module system that uses this pattern: https://github.com/TheHydroImpulse/resolve.js. Resolve.js uses eval instead of new Function primarily to model the CommonJS exports and module variables available in each module, and new Function wraps your code within an anonymous function, though, I do end up wrapping each module in a function I do it manually in combination with eval.

You read more about it in the following two articles, the later also referring to the first.

Lazy evaluation of CommonJS modules

AMD is Not the Answer

Harmony Generators

Now that generators have finally landed in V8 and thus in Node.js, under a flag (--harmony or --harmony-generators). These greatly reduce the amount of callback hell you have. It makes writing asynchronous code truly great.

The best way to utilize generators is to employ some sort of control-flow library. This will enable to flow to continue going as you yield within generators.

Recap/Overview:

If you're unfamiliar with generators, they're a practice of pausing the execution of special functions (called generators). This practice is called yielding using the yield keyword.

Example:

```<code>function* someGenerator() {
  yield []; // Pause the function and pass an empty array.
}
</code>```

Thus, whenever you call this function the first time, it'll return a new generator instance. This allows you to call next() on that object to start or resume the generator.

```<code>var gen = someGenerator();
gen.next(); // { value: Array[0], done: false }
</code>```

You would keep calling next until done returns true. This means the generator has completely finished it's execution, and there are no more yield statements.

Control-Flow:

As you can see, controlling generators are not automatic. You need to manually continue each one. That's why control-flow libraries like co are used.

Example:

```<code>var co = require('co');

co(function*() {
  yield query();
  yield query2();
  yield query3();
  render();
});
</code>```

This allows the possibility to write everything in Node (and the browser with Facebook's Regenerator which takes, as input, source code that utilize harmony generators and splits out fully compatible ES5 code) with a synchronous style.

Generators are still pretty new, and thus requires Node.js >=v11.2. As I'm writing this, v0.11.x is still unstable and thus many native modules are broken and will be until v0.12, where the native API will calm down.

To add to my original answer:

I've recently been preferring a more functional API in JavaScript. The convention does use OOP behind the scenes when needed but it simplifies everything.

Take for example a view system (client or server).

```<code>view('home.welcome');
</code>```

Is much easier to read or follow than:

```<code>var views = {};
views['home.welcome'] = new View('home.welcome');
</code>```

The view function simply checks if the same view already exists in a local map. If the view does not exist, it'll create a new view and add a new entry to the map.

```<code>function view(name) {
  if (!name) // Throw an error

  if (view.views[name]) return view.views[name];

  return view.views[name] = new View({
    name: name
  });
}

// Local Map
view.views = {};
</code>```

Extremely basic, right? I find it dramatically simplifies the public interface and makes it easier to use. I also employ chain-ability...

```<code>view('home.welcome')
   .child('menus')
   .child('auth')
</code>```

Tower, a framework I'm developing (with someone else) or developing the next version (0.5.0) will use this functional approach in most of it's exposing interfaces.

Some people take advantage of fibers as a way to avoid "callback hell". It's quite a different approach to JavaScript, and I'm not a huge fan of it, but many frameworks / platforms use it; including Meteor, as they treat Node.js as a thread/per connection platform.

I'd rather use an abstracted method to avoid callback hell. It may become cumbersome, but it greatly simplifies the actual application code. When helping on building the TowerJS framework, it solved a lot of our problems, though, you'll obviously still have some level of callbacks, but the nesting isn't deep.

```<code>// app/config/server/routes.js
App.Router = Tower.Router.extend({
  root: Tower.Route.extend({
    route: '/',
    enter: function(context, next) {
      context.postsController.page(1).all(function(error, posts) {
        context.bootstrapData = {posts: posts};
        next();
      });
    },
    action: function(context, next) {
      context.response.render('index', context);
      next();
    },
    postRoutes: App.PostRoutes
  })
});
</code>```

An example of our, currently being developed, routing system and "controllers", though fairly different from traditional "rails-like". But the example is extremely powerful and minimizes the amount of callbacks and makes things fairly apparent.

The problem with this approach is that everything is abstracted. Nothing runs as-is, and requires a "framework" behind it. But if these kinds of features and coding style is implemented within a framework, then it's a huge win.

For patterns in JavaScript, it honestly depends. Inheritance is only really useful when using CoffeeScript, Ember, or any "class" framework/infrastructure. When you're inside a "pure" JavaScript environment, using the traditional prototype interface works like a charm:

```<code>function Controller() {
    this.resource = get('resource');
}

Controller.prototype.index = function(req, res, next) {
    next();
};
</code>```

Ember.js started, for me at least, using a different approach to constructing objects. Instead of constructing each prototype methods independently, you'd use a module-like interface.

```<code>Ember.Controller.extend({
   index: function() {
      this.hello = 123;
   },
   constructor: function() {
      console.log(123);
   }
});
</code>```

All these are different "coding" styles, but do add to your code base.

Polymorphism

Polymorphism isn't widely used in pure JavaScript, where working with inheritance and copying the "class"-like model requires a lot of boilerplate code.

Event/Component Based Design

Event-based and Component-based models are the winners IMO, or the easiest to work with,  especially when working with Node.js, which has a built-in EventEmitter component, though, implementing such emitters is trivial, it's just a nice addition.

```<code>var gen = someGenerator();
gen.next(); // { value: Array[0], done: false }
</code>```0

Just an example, but it's a nice model to work with. Especially in a game/component oriented project.

Component design is a separate concept by itself, but I think it works extremely well in combination to event systems. Games are traditionally known for component based design, where object oriented programming takes you only so far.

Component based design has it's uses. It depends on what type of system your building. I'm sure it would work with web apps, but it'd work extremely well in a gaming environment, because of the number of objects, and separate systems, but other examples surely exist.

Pub/Sub Pattern

Event-binding and pub/sub is similar. The pub/sub pattern really shines in Node.js applications because of the unifying language, but it can work in any langauge. Works extremely well in real-time applications, games, etc..

```<code>var gen = someGenerator();
gen.next(); // { value: Array[0], done: false }
</code>```1

Observer

This might be a subjective one, as some people choose to think of the Observer pattern as pub/sub, but they have their differences.

"The Observer is a design pattern where an an object (known as a subject) maintains a list of objects depending on it (observers), automatically notifying them of any changes to state." - The Observer Pattern

The observer pattern is a step beyond typical pub/sub systems. Objects have strict relationships or communication methods with each other. An object "Subject" would keep a list of dependents "Observers". The subject would keep it's observers up-to-date.

Reactive Programming

Reactive programming is a smaller, more unknown concept, especially in JavaScript. There is one framework/library (that I know of) that exposes an easy to work with API to use this "reactive programming".

Resources on reactive programming:

What is (functional) reactive programming?

Reactive programming

Basically, it's having a set of syncing data (be it variables, functions, etc..).

```<code>var gen = someGenerator();
gen.next(); // { value: Array[0], done: false }
</code>```2

I believe reactive programming is considerably hidden, especially in imperative languages. It's an amazingly powerful programming paradigm, especially in Node.js. Meteor has created it's own reactive engine in which the framework is basically based upon. How does Meteor's reactivity work behind the scenes? is a great overview of how it works internally.

```<code>Meteor.autosubscribe(function() {
   console.log("Hello " + Session.get("name"));
});
</code>```

This will execute normally, displaying the value of name, but if we change the it

Session.set('name', 'Bob');

It will re-output the console.log displaying Hello Bob. A basic example, but you can apply this technique to real-time data models and transactions. You can create extremely powerful systems behind this protocol.

Meteor's...

Context Implementation

ContextSet Implementation

Session Implementation

Reactive pattern and Observer pattern are quite similar. The main difference is that the observer pattern commonly describes data-flow with whole objects/classes vs reactive programming describes data-flow to specific properties instead.

Meteor is a great example of reactive programming. It's runtime is a little bit complicated because of JavaScript's lack of native value change events (Harmony proxies change that). Other client-side frameworks, Ember.js and AngularJS also utilize reactive programming (to some extend).

The later two frameworks use the reactive pattern most notably on their templates (auto-updating that is). Angular.js uses a simple dirty checking technique. I wouldn't call this exactly reactive programming, but it's close, as dirty checking isn't real-time. Ember.js uses a different approach. Ember use set() and get() methods which allow them to immediately update depending values. With their runloop it's extremely efficient and allows for more depending values, where angular has a theoretical limit.

Promises

Not a fix to callbacks, but takes some indentation out, and keeps the nested functions to a minimum. It also adds some nice syntax to the problem.

```<code>fs.open("fs-promise.js", process.O_RDONLY).then(function(fd){
  return fs.read(fd, 4096);
}).then(function(args){
  util.puts(args[0]); // print the contents of the file
});
</code>```

You could also spread the callback functions so that they aren't inline, but that's another design decision.

Another approach would be to combine events and promises to where you would have a function to dispatch events appropriately, then the real functional functions (ones that have the real logic within them) would bind to a particular event. You'd then pass the dispatcher method inside each callback position, though, you'd have to work out some kinks that would come to mind, such as parameters, knowing which function to dispatch to, etc...

Single Function Function

Instead of having a huge mess of callback hell, keep a single function to a single task, and do that task well. Sometimes you can get ahead of yourself and add more functionality within each function, but ask yourself: Can this become an independent function? Name the function, and this cleans up your indentation and, as a result, cleans up the callback hell problem.

In the end, I'd suggest developing, or using a small "framework", basically just a backbone for your application, and take time to make abstractions, decide on an event-based system, or a "loads of small modules that are independent" system. I've worked with several Node.js projects where the code was extremely messy with callback hell in particular, but also a lack of thought before they began coding. Take your time to think through the different possibilities in terms of API, and syntax.

Ben Nadel has made some really good blog posts about JavaScript and some pretty strict and advanced patterns that may work in your situation. Some good posts that I'll emphasis:

Thinking About Encapsulation And Direct Object References

Keeping Modules Decoupled Using Signals And Mediators

Managed Dependencies vs. Dependency Injection In RequireJS

Inversion-of-Control

Though not exactly related to callback hell, it can help you overall architecture, especially in the unit tests.

The two main sub-versions of inversion-of-control is Dependency Injection and Service Locator. I find Service Locator to be the easiest within JavaScript, as opposed to Dependency Injection. Why? Mainly because JavaScript is a dynamic language and no static typing exists. Java and C#, among others, are "known" for dependency injection because your able to detect types, and they have built in interfaces, classes, etc... This makes things fairly easy. You can, however, re-create this functionality within JavaScript, though, it's not going to be identical and a bit hacky, I prefer using a service locator inside my systems.

Any kind of inversion-of-control will dramatically decouple your code into separate modules that can be mocked or faked at anytime. Designed a second version of your rendering engine? Awesome, just substitute the old interface for the new one. Service locators are especially interesting with the new Harmony Proxies, though, only effectively usable within Node.js, it provides a nicer API, rather then using Service.get('render'); and instead Service.render. I'm currently working on that kind of system: https://github.com/TheHydroImpulse/Ettore .

Though the lack of static typing (static typing being a possible reason for the effective usages in dependency injection in Java, C#, PHP - It's not static typed, but it has type hints.) might be looked at as a negative point, you can definitely turn it into a strong point. Because everything is dynamic, you can engineer a "fake" static system. In combination with a service locator, you could have each component/module/class/instance tied to a type.

```<code>var Service, componentA;

function Manager() {
  this.instances = {};
}

Manager.prototype.get = function(name) {
  return this.instances[name];
};

Manager.prototype.set = function(name, value) {
  this.instances[name] = value;
};

Service = new Manager();
componentA = {
  type: "ship",
  value: new Ship()
};

Service.set('componentA', componentA);

// DI
function World(ship) {
  if (ship === Service.matchType('ship', ship))
    this.ship = new ship();
  else
    throw Error("Wrong type passed.");
}

// Use Case:
var worldInstance = new World(Service.get('componentA'));
</code>```

A simplistic example. For a real world, effective usage, you'll need to take this concept further, but it could help decouple your system if you really want traditional dependency injection. You might need to fiddle with this concept a little bit. I haven't put much thought into the previous example.

Model-View-Controller

The most obvious pattern, and the most used on the web. A few years ago, JQuery was all the rage, and so, JQuery plugins were born. You didn't need a full-on framework on the client-side, just use jquery and a few plugins.

Now, there's a huge client-side JavaScript framework war. Most of which use the MVC pattern, and they all use it differently. MVC isn't always implemented the same.

If you're using the traditional prototypal interfaces, you might have a hard time getting a syntactical sugar or a nice API when working with MVC, unless you want to do some manual work. Ember.js solves this by creating a "class"/object" system. A controller might look like:

```<code> var Controller = Ember.Controller.extend({
      index: function() {
        // Do something....
      }
 });
</code>```

Most client-side libraries also extend the MVC pattern by introducing view-helpers (becoming views) and templates (becoming views).

New JavaScript Features:

This will only be effective if you're using Node.js, but nonetheless, it's invaluable. This talk at NodeConf by Brendan Eich brings some cool new features. The proposed function syntax, and especially the Task.js js library.

This will probably fix most of the issues with function nesting and will bring slightly better performance because of the lack of function overhead.

I'm not too sure if V8 supports this natively, last I checked you needed to enable some flags, but this works in a port of Node.js that uses SpiderMonkey.

Extra Resources:

Pro JavaScript Design Patterns (Recipes: a Problem-Solution Ap)

JavaScript: The Good Parts

Learning JavaScript Design Patterns

Object-Oriented JavaScript: Create scalable, reusable high-quality JavaScript applications and libraries

Body:
After many edits, this answer has become a monster in length. I apologize in advance.

First of all, eval() isn't always bad, and can bring benefit in performance when used in lazy-evaluation, for example. Lazy-evaluation is similar to lazy-loading, but you essentially store your code within strings, and then use eval or new Function to evaluate the code. If you use some tricks, then it'll become much more useful than evil, but if you don't, it can lead to bad things. You can look at my module system that uses this pattern: https://github.com/TheHydroImpulse/resolve.js. Resolve.js uses eval instead of new Function primarily to model the CommonJS exports and module variables available in each module, and new Function wraps your code within an anonymous function, though, I do end up wrapping each module in a function I do it manually in combination with eval.

You read more about it in the following two articles, the later also referring to the first.

Lazy evaluation of CommonJS modules

AMD is Not the Answer

Harmony Generators

Now that generators have finally landed in V8 and thus in Node.js, under a flag (--harmony or --harmony-generators). These greatly reduce the amount of callback hell you have. It makes writing asynchronous code truly great.

The best way to utilize generators is to employ some sort of control-flow library. This will enable to flow to continue going as you yield within generators.

Recap/Overview:

If you're unfamiliar with generators, they're a practice of pausing the execution of special functions (called generators). This practice is called yielding using the yield keyword.

Example:

function* someGenerator() {
  yield []; // Pause the function and pass an empty array.
}

Thus, whenever you call this function the first time, it'll return a new generator instance. This allows you to call next() on that object to start or resume the generator.

var gen = someGenerator();
gen.next(); // { value: Array[0], done: false }

You would keep calling next until done returns true. This means the generator has completely finished it's execution, and there are no more yield statements.

Control-Flow:

As you can see, controlling generators are not automatic. You need to manually continue each one. That's why control-flow libraries like co are used.

Example:

var co = require('co');

co(function*() {
  yield query();
  yield query2();
  yield query3();
  render();
});

This allows the possibility to write everything in Node (and the browser with Facebook's Regenerator which takes, as input, source code that utilize harmony generators and splits out fully compatible ES5 code) with a synchronous style.

Generators are still pretty new, and thus requires Node.js >=v11.2. As I'm writing this, v0.11.x is still unstable and thus many native modules are broken and will be until v0.12, where the native API will calm down.

To add to my original answer:

I've recently been preferring a more functional API in JavaScript. The convention does use OOP behind the scenes when needed but it simplifies everything.

Take for example a view system (client or server).

view('home.welcome');

Is much easier to read or follow than:

var views = {};
views['home.welcome'] = new View('home.welcome');

The view function simply checks if the same view already exists in a local map. If the view does not exist, it'll create a new view and add a new entry to the map.

function view(name) {
  if (!name) // Throw an error

  if (view.views[name]) return view.views[name];

  return view.views[name] = new View({
    name: name
  });
}

// Local Map
view.views = {};

Extremely basic, right? I find it dramatically simplifies the public interface and makes it easier to use. I also employ chain-ability...

view('home.welcome')
   .child('menus')
   .child('auth')

Tower, a framework I'm developing (with someone else) or developing the next version (0.5.0) will use this functional approach in most of it's exposing interfaces.

Some people take advantage of fibers as a way to avoid "callback hell". It's quite a different approach to JavaScript, and I'm not a huge fan of it, but many frameworks / platforms use it; including Meteor, as they treat Node.js as a thread/per connection platform.

I'd rather use an abstracted method to avoid callback hell. It may become cumbersome, but it greatly simplifies the actual application code. When helping on building the TowerJS framework, it solved a lot of our problems, though, you'll obviously still have some level of callbacks, but the nesting isn't deep.

// app/config/server/routes.js
App.Router = Tower.Router.extend({
  root: Tower.Route.extend({
    route: '/',
    enter: function(context, next) {
      context.postsController.page(1).all(function(error, posts) {
        context.bootstrapData = {posts: posts};
        next();
      });
    },
    action: function(context, next) {
      context.response.render('index', context);
      next();
    },
    postRoutes: App.PostRoutes
  })
});

An example of our, currently being developed, routing system and "controllers", though fairly different from traditional "rails-like". But the example is extremely powerful and minimizes the amount of callbacks and makes things fairly apparent.

The problem with this approach is that everything is abstracted. Nothing runs as-is, and requires a "framework" behind it. But if these kinds of features and coding style is implemented within a framework, then it's a huge win.

For patterns in JavaScript, it honestly depends. Inheritance is only really useful when using CoffeeScript, Ember, or any "class" framework/infrastructure. When you're inside a "pure" JavaScript environment, using the traditional prototype interface works like a charm:

function Controller() {
    this.resource = get('resource');
}

Controller.prototype.index = function(req, res, next) {
    next();
};

Ember.js started, for me at least, using a different approach to constructing objects. Instead of constructing each prototype methods independently, you'd use a module-like interface.

Ember.Controller.extend({
   index: function() {
      this.hello = 123;
   },
   constructor: function() {
      console.log(123);
   }
});

All these are different "coding" styles, but do add to your code base.

Polymorphism

Polymorphism isn't widely used in pure JavaScript, where working with inheritance and copying the "class"-like model requires a lot of boilerplate code.

Event/Component Based Design

Event-based and Component-based models are the winners IMO, or the easiest to work with,  especially when working with Node.js, which has a built-in EventEmitter component, though, implementing such emitters is trivial, it's just a nice addition.

event.on("update", function(){
    this.component.ship.velocity = 0;
    event.emit("change.ship.velocity");
});

Just an example, but it's a nice model to work with. Especially in a game/component oriented project.

Component design is a separate concept by itself, but I think it works extremely well in combination to event systems. Games are traditionally known for component based design, where object oriented programming takes you only so far.

Component based design has it's uses. It depends on what type of system your building. I'm sure it would work with web apps, but it'd work extremely well in a gaming environment, because of the number of objects, and separate systems, but other examples surely exist.

Pub/Sub Pattern

Event-binding and pub/sub is similar. The pub/sub pattern really shines in Node.js applications because of the unifying language, but it can work in any langauge. Works extremely well in real-time applications, games, etc..

model.subscribe("message", function(event){
    console.log(event.params.message);
});

model.publish("message", {message: "Hello, World"});

Observer

This might be a subjective one, as some people choose to think of the Observer pattern as pub/sub, but they have their differences.

"The Observer is a design pattern where an an object (known as a subject) maintains a list of objects depending on it (observers), automatically notifying them of any changes to state." - The Observer Pattern

The observer pattern is a step beyond typical pub/sub systems. Objects have strict relationships or communication methods with each other. An object "Subject" would keep a list of dependents "Observers". The subject would keep it's observers up-to-date.

Reactive Programming

Reactive programming is a smaller, more unknown concept, especially in JavaScript. There is one framework/library (that I know of) that exposes an easy to work with API to use this "reactive programming".

Resources on reactive programming:

What is (functional) reactive programming?

Reactive programming

Basically, it's having a set of syncing data (be it variables, functions, etc..).

 var a = 1;
 var b = 2;
 var c = a + b;

 a = 2;

 console.log(c); // should output 4

I believe reactive programming is considerably hidden, especially in imperative languages. It's an amazingly powerful programming paradigm, especially in Node.js. Meteor has created it's own reactive engine in which the framework is basically based upon. How does Meteor's reactivity work behind the scenes? is a great overview of how it works internally.

Meteor.autosubscribe(function() {
   console.log("Hello " + Session.get("name"));
});

This will execute normally, displaying the value of name, but if we change the it

Session.set('name', 'Bob');

It will re-output the console.log displaying Hello Bob. A basic example, but you can apply this technique to real-time data models and transactions. You can create extremely powerful systems behind this protocol.

Meteor's...

Context Implementation

ContextSet Implementation

Session Implementation

Reactive pattern and Observer pattern are quite similar. The main difference is that the observer pattern commonly describes data-flow with whole objects/classes vs reactive programming describes data-flow to specific properties instead.

Meteor is a great example of reactive programming. It's runtime is a little bit complicated because of JavaScript's lack of native value change events (Harmony proxies change that). Other client-side frameworks, Ember.js and AngularJS also utilize reactive programming (to some extend).

The later two frameworks use the reactive pattern most notably on their templates (auto-updating that is). Angular.js uses a simple dirty checking technique. I wouldn't call this exactly reactive programming, but it's close, as dirty checking isn't real-time. Ember.js uses a different approach. Ember use set() and get() methods which allow them to immediately update depending values. With their runloop it's extremely efficient and allows for more depending values, where angular has a theoretical limit.

Promises

Not a fix to callbacks, but takes some indentation out, and keeps the nested functions to a minimum. It also adds some nice syntax to the problem.

fs.open("fs-promise.js", process.O_RDONLY).then(function(fd){
  return fs.read(fd, 4096);
}).then(function(args){
  util.puts(args[0]); // print the contents of the file
});

You could also spread the callback functions so that they aren't inline, but that's another design decision.

Another approach would be to combine events and promises to where you would have a function to dispatch events appropriately, then the real functional functions (ones that have the real logic within them) would bind to a particular event. You'd then pass the dispatcher method inside each callback position, though, you'd have to work out some kinks that would come to mind, such as parameters, knowing which function to dispatch to, etc...

Single Function Function

Instead of having a huge mess of callback hell, keep a single function to a single task, and do that task well. Sometimes you can get ahead of yourself and add more functionality within each function, but ask yourself: Can this become an independent function? Name the function, and this cleans up your indentation and, as a result, cleans up the callback hell problem.

In the end, I'd suggest developing, or using a small "framework", basically just a backbone for your application, and take time to make abstractions, decide on an event-based system, or a "loads of small modules that are independent" system. I've worked with several Node.js projects where the code was extremely messy with callback hell in particular, but also a lack of thought before they began coding. Take your time to think through the different possibilities in terms of API, and syntax.

Ben Nadel has made some really good blog posts about JavaScript and some pretty strict and advanced patterns that may work in your situation. Some good posts that I'll emphasis:

Thinking About Encapsulation And Direct Object References

Keeping Modules Decoupled Using Signals And Mediators

Managed Dependencies vs. Dependency Injection In RequireJS

Inversion-of-Control

Though not exactly related to callback hell, it can help you overall architecture, especially in the unit tests.

The two main sub-versions of inversion-of-control is Dependency Injection and Service Locator. I find Service Locator to be the easiest within JavaScript, as opposed to Dependency Injection. Why? Mainly because JavaScript is a dynamic language and no static typing exists. Java and C#, among others, are "known" for dependency injection because your able to detect types, and they have built in interfaces, classes, etc... This makes things fairly easy. You can, however, re-create this functionality within JavaScript, though, it's not going to be identical and a bit hacky, I prefer using a service locator inside my systems.

Any kind of inversion-of-control will dramatically decouple your code into separate modules that can be mocked or faked at anytime. Designed a second version of your rendering engine? Awesome, just substitute the old interface for the new one. Service locators are especially interesting with the new Harmony Proxies, though, only effectively usable within Node.js, it provides a nicer API, rather then using Service.get('render'); and instead Service.render. I'm currently working on that kind of system: https://github.com/TheHydroImpulse/Ettore .

Though the lack of static typing (static typing being a possible reason for the effective usages in dependency injection in Java, C#, PHP - It's not static typed, but it has type hints.) might be looked at as a negative point, you can definitely turn it into a strong point. Because everything is dynamic, you can engineer a "fake" static system. In combination with a service locator, you could have each component/module/class/instance tied to a type.

var Service, componentA;

function Manager() {
  this.instances = {};
}

Manager.prototype.get = function(name) {
  return this.instances[name];
};

Manager.prototype.set = function(name, value) {
  this.instances[name] = value;
};

Service = new Manager();
componentA = {
  type: "ship",
  value: new Ship()
};

Service.set('componentA', componentA);

// DI
function World(ship) {
  if (ship === Service.matchType('ship', ship))
    this.ship = new ship();
  else
    throw Error("Wrong type passed.");
}

// Use Case:
var worldInstance = new World(Service.get('componentA'));

A simplistic example. For a real world, effective usage, you'll need to take this concept further, but it could help decouple your system if you really want traditional dependency injection. You might need to fiddle with this concept a little bit. I haven't put much thought into the previous example.

Model-View-Controller

The most obvious pattern, and the most used on the web. A few years ago, JQuery was all the rage, and so, JQuery plugins were born. You didn't need a full-on framework on the client-side, just use jquery and a few plugins.

Now, there's a huge client-side JavaScript framework war. Most of which use the MVC pattern, and they all use it differently. MVC isn't always implemented the same.

If you're using the traditional prototypal interfaces, you might have a hard time getting a syntactical sugar or a nice API when working with MVC, unless you want to do some manual work. Ember.js solves this by creating a "class"/object" system. A controller might look like:

 var Controller = Ember.Controller.extend({
      index: function() {
        // Do something....
      }
 });

Most client-side libraries also extend the MVC pattern by introducing view-helpers (becoming views) and templates (becoming views).

New JavaScript Features:

This will only be effective if you're using Node.js, but nonetheless, it's invaluable. This talk at NodeConf by Brendan Eich brings some cool new features. The proposed function syntax, and especially the Task.js js library.

This will probably fix most of the issues with function nesting and will bring slightly better performance because of the lack of function overhead.

I'm not too sure if V8 supports this natively, last I checked you needed to enable some flags, but this works in a port of Node.js that uses SpiderMonkey.

Extra Resources:

Pro JavaScript Design Patterns (Recipes: a Problem-Solution Ap)

JavaScript: The Good Parts

Learning JavaScript Design Patterns

Object-Oriented JavaScript: Create scalable, reusable high-quality JavaScript applications and libraries


问:
Is Agile a variant of RAD?
Wikipedia says that Agile is a type of "RAD" which I guess is incorrect. From what I know, Agile was developed becasue RAD itself was not that sucessfull in 90'S (too rigid for changes).
Or am I wrong?

(Remark: apparently the Wikipedia article on Agile software development was improved in between, it just lists RAD as a predecessor of Agile, not as a superset).

A reference from a book Radical Project Management (Thomsett)

"..new development fad such as RAD, Agile, Object oriented..."

CISA Certified Information System auditor:

..aware of two alternative software dev. methods: Agile and Rapid
  Application Development

Agile management for Software:

Agile methods are mostly derived from lightweight approach of RAD.

Software estimation best practices:

The major methods of sw. dev. can be summarized as follows:

  1. Waterfall   ..

  4. RAD

  5. Agile

The point of this question is:

Is Agile type of RAD or standalone development approach?

答:
I don't think it is correct to categorize development methodologies in hiearchies. So no methodology is "under" or "above" any other. It is much more logical to think about common points of methodologies. Quite often, real-world application of methodology involves combination of many similar methodologies and it is up to managers to come up with working development model.

In case of RAD (which I'm not experienced with) vs. Agile it seems only commonality is iterative development. RAD seems to prefer rigid phases with specific goals and outputs. Agile is more about single development phase where everything happens. Also Agile develops software directly with possibility of features being removed instead of prototyping beforehand. (which might end up same as agile, because quite often prototypes are immediately integrated into working software, instead of doing it correctly once again)

ContentLicense: CC BY-SA 3.0

Title: Is Agile a variant of RAD?


答:
RAD as a term predates Agile as a term by about ten years, but it isn't really a "parent" of Agile. Both were created as reactions to perceived shortcomings with traditional software development management techniques. However, RAD is a prescriptive method for writing software, using successive prototypes to elicit requirements and refine the application. Agile, in the originally introduced form, is a philosophical position describing the difference between traditional approaches and the values focused on by agile practitioners.

So no, agile software development is not a type of RAD; they address problems at different levels of abstraction.

Title: Is Agile a variant of RAD?

Body:
Wikipedia says that Agile is a type of "RAD" which I guess is incorrect. From what I know, Agile was developed becasue RAD itself was not that sucessfull in 90'S (too rigid for changes).
Or am I wrong?

(Remark: apparently the Wikipedia article on Agile software development was improved in between, it just lists RAD as a predecessor of Agile, not as a superset).

A reference from a book Radical Project Management (Thomsett)

"..new development fad such as RAD, Agile, Object oriented..."

CISA Certified Information System auditor:

..aware of two alternative software dev. methods: Agile and Rapid
  Application Development

Agile management for Software:

Agile methods are mostly derived from lightweight approach of RAD.

Software estimation best practices:

The major methods of sw. dev. can be summarized as follows:

  1. Waterfall   ..

  4. RAD

  5. Agile

The point of this question is:

Is Agile type of RAD or standalone development approach?


问:
Why don't modern libraries use OOP
I'm a beginner-level C++ programmer, but I understand the concepts of the language fairly well. When I began to learn external C++ libraries, like SDL, OpenGL (maybe something else too), to my great surprise I found out that they don't use C++ concepts at all.

For example, neither SDL, nor OpenGL use classes or exceptions, preferring functions and error codes. In OpenGL I've seen functions like glVertex2f, which takes 2 float variables as an input and probably would be better as a template. Moreover, these libraries sometimes use marcos, while it seems to be a common agreement that using macroses is bad.

All in all, they seem to be written more in C style, than in C++ style. But they are completely different incompaitable languages, aren't they?

The question is: why modern libraries do not use the advantages of the language they are written in?

答: Those libraries are not remotely modern at all. They are C APIs, and bad ones at that. Your premise is flawed.</p>

Title: Why don't modern libraries use OOP


问:
Algorithms to Determine How Much A Factor Contributes to A Total Value
Lets say that I have hundreds/thousands of objects(entries) in a database and each object contains 10 attributes. I have a way to quantitatively measure each attribute where a higher number implies that the object is better in that area. I also have a final price associated with that object. Is there any way to programatically (through maybe an algorithm) determine an approximation of how much each attribute contributes to the total cost?

In essence, I want to be able to estimate the

average total cost = a*attribute1+b*attribute2+.....+j*attribute10

by solving for a,b,...,j

I realize that this might be more of a statistics question than a programming question, but I am more interested in the implementation of this through programming than a fully statistics explanation.

Is this something more suited for scipy? numpy? some statistics framework?

答:
You did not tell us if you know for sure that the final price stands in a relation to the attribute values, or if that is just a wild guess of yours. However, I take a guess on my own: I guess what you are looking for is an algorithm to choose a_1, a_2, ..., a_10 so that

```<code>q_j := sum(a_i *attribute_i_j) (where i=1,...10, j = 1,..., number of objects)
</code>```

approximates the price p_j of object j. In this equation, attribute_i_j is the value of the i-th attribute of object j. To optimize the price difference simultanously, one would typically minimize the sum of squares of the differences:

```<code>sum((p_j - q_j)^2)
</code>```

This is known as "linear least squares approximation", and you find the solution here in Wikipedia:

http://en.wikipedia.org/wiki/Linear_least_squares_%28mathematics%29#The_general_problem

To solve this with Python, I would recommend trying scipy's leastsq function:

http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.leastsq.html#scipy.optimize.leastsq

Last but not least, it would be helpful if you clarify if I got your intentions right, or if you want to solve a different problem.

Body:
You did not tell us if you know for sure that the final price stands in a relation to the attribute values, or if that is just a wild guess of yours. However, I take a guess on my own: I guess what you are looking for is an algorithm to choose a_1, a_2, ..., a_10 so that

q_j := sum(a_i *attribute_i_j) (where i=1,...10, j = 1,..., number of objects)

approximates the price p_j of object j. In this equation, attribute_i_j is the value of the i-th attribute of object j. To optimize the price difference simultanously, one would typically minimize the sum of squares of the differences:

sum((p_j - q_j)^2)

This is known as "linear least squares approximation", and you find the solution here in Wikipedia:

http://en.wikipedia.org/wiki/Linear_least_squares_%28mathematics%29#The_general_problem

To solve this with Python, I would recommend trying scipy's leastsq function:

http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.leastsq.html#scipy.optimize.leastsq

Last but not least, it would be helpful if you clarify if I got your intentions right, or if you want to solve a different problem.


问:
What's the most absurd myth about programming issues?
To put it another way... What is the most commonly held and frustrating misunderstanding about programming, you have encountered?

Which widespread and longstanding myths/misconceptions do you find hard for programmers to dispel/correct.

Please, explain why this is a myth.

答: I think the biggest misconception is that it's more important being able to write the code down easily than being able to read and understand the code.</p>

ContentLicense: CC BY-SA 2.5


问:
How do you explain refactoring to a non-technical person?
How do you go about explaining refactoring (and technical debt) to a non-technical person (typically a PHB or customer)? ("What, it's going to cost me a month of your work with no visible difference?!")

UPDATE Thanks for all the answers so far, I think this list will provide several useful analogies to which we can point the appropriate people (though editing out references to PHBs may be wise!)

答:
When you have a big home theater and you add things, slowly but surely a big rats nest forms in the back.

If you are often times replacing parts, sometimes its worth straightening all that stuff out.

Sure, if you do that, it was working before, and it's not going to work better than when you started, but when you have to mess with it again, things will be a lot easier.

In any case its probably best to make a similar comparison to some subject area the PHB or customer is already familiar with, ie car or construction or something...


问:
Free app licensing - Could it be creative commons?
I am creating a free nokia application for which I am about to use images from a creative common website. Now my question is if a free application come under creative commons as it is not a paid one?

Thanks in advance.

答:
There are different creative commons options:
But I think a free app by an individual developer comes under"non-commercial"

There is also an attributions clause, so you might have to mention the source of the icons in the description


问:
Web versus desktop development - is web development worse?
As a longtime desktop developer looking at doing our first large-scale web application, what are the pros and cons of doing web development?

Is developing a web application much worse than developing a desktop app?  E.g., is it more tedious or annoying?  Is the time to market much worse?  Is the web platform excessively limiting?  If the answer to any of these is yes, then why?

(And how does developing a Flash or Silverlight app compare?)

答:
No

As long as you pick the right tools, web development is as clean and easy as desktop development.

The web API's (html, CSS, Javascript and DOM) are the equivalent of the win32 api. Eventually everything talks down to that API level, but you're crazy if you program directly on top of it without a library to abstract the messiness, verbosity and inconsistency away from you.

So, be careful about your choice of frameworks. Some problems are self-inflicted by picking bad tools (e.g. browser compatibility issues).

It is possible to have a clean and consistent web dev platform, with a single language. E.g. if you want it to be "all java all the time", you can use GWT and write both your client-side code and server-side code in Java. Or, if you'd rather have it be all javascript, you can pick something like Ext JS for the client-side and node.js for the server-side.


问:
What pattern should one use to dynamically add multiple small views to one big main view?
Imagine a small calculator GUI, with basic operations (+,-,/,*), and in the menu we can check for example scientific calculator and a small new view with the extra functions appears beside.

I was thinking that the decorator pattern is the solution but after reading some documentation on it, I am confused now. Which pattern would be more suitable for doing such things?

答:
You should really start writing the program/app before applying patterns. See what emerges instead of forcing some arbitrary pattern. Since it is a small calculator app you want to make, then there is really no need to apply a pattern just yet.

This is usually how I work; program something, then refactor towards a pattern if there is any need to. It is quite easy otherwise to over-engineer something.

In your case, you tried to apply the decorator pattern to handling views. In terms of data it might make sense, however views are completely different. Instead start to write one basic view to do the basic operations. Then try to create the scientific view, and refactor the code so that you can reuse the basic view's actions. You might end up with a M-V-C like structure.


问:
Is JSF really ready to deliver high performance web applications?
I have heard a lot of good about JSF but as far as I know people also had lots of serious complains with this technology in the past, not aware of how much the situation has improved. We are considering JSF as a probable technology for a social network project. But we are not aware of the performance scores of JSF neither we could really come across any existing high performance website that had been using JSF. People complain about its performance scalability issues.

We are still not very sure if we are doing the right thing by choosing jsf, and thus would like to hear from you all about this and take your inputs into consideration.

Is it possible to configure JSF to satisfy the high performance needs of social networking service ? Also till what extent is it possible to survive with the current problems in JSF. What exactly are its problems ?

I am not  worried about the development complexities with JSF what others usually complain about because as per my personal experience I believe that's not at all true, but I am more concerned about what performance and scalability issues. And please don't just abuse it on its old issues linked to previous versions. I just care about the present state whatever had been its past.

答: GWT converts your java code into java script. so it runs as a java script on your client side. And also, you can integrate css into your gwt applications. In general, gwt is light weight and can run across all browsers without any problem. I dont know much about JSF. But I think dt, JSF is not that flexible like GWT.</p>


答:
Using MVC in conjunction with something like Prism would be a good choice in a scenario like this.

I'm not a big fan of using patterns, as it feels very restrictive if implemented from the start of a project , but it does create some sense of stability and promotes code re-use in a business if it's company policy.

Title: What pattern should one use to dynamically add multiple small views to one big main view?

Body:
Imagine a small calculator GUI, with basic operations (+,-,/,*), and in the menu we can check for example scientific calculator and a small new view with the extra functions appears beside.

I was thinking that the decorator pattern is the solution but after reading some documentation on it, I am confused now. Which pattern would be more suitable for doing such things?


答:
I think you don't need a pattern in this case, but a principle. In this case, the Liskov Substitution Principle. Your small Views should implement the same Interface, so that the large View can manage them (to the extent that is needed based on the language you are using). The data Classes should also use this principle, so that the small View can be passed in data and return it to your wiring code without special consideration for what, specifically, is going on.

I find that I haven't been able to make an application of any complexity where Liskov Substitution is perfect, and that is possibly due to limitations in me vs. the principle. But I tend to think of it like a soda machine in a restaurant. You care about the specific type in the back room where you hook up the tubes to the boxes of syrup, and you care again when it's in your cup, but in between it all goes through the tube the same.

So I usually will have my endpoint Views type-check the IDataObject to make sure it's congruent with the View.  The other end (the back room) for me is typically a Builder and/or an Abstract Factory that has references to many specific factories and calls on the correct ones based on some condition inherent in the data (I typically have a tag in the XML data source that says "pull the factory registered under this name" and a hash that contains the Factories).

I am fortunate to develop in Flash, and I allow Flash itself to be the Factory for my Views and simply pick up references to them once they've been instantiated, but if you have to manually construct Views, you can probably use something similar to what I've described for data construction.

I applaud that you're thinking through the design on the front in, because in real life few bosses will allow you to go back and rip out your initial experiments in favor of a more robust/maintainable design. Note that it is enough in the short-term to develop your Views and Model to Interfaces--you should find it much easier to add some kind of Factory later than it is to redo the logic that your management can physically see.


问:
Does auto make C++ code harder to understand?
I saw a conference by Herb Sutter where he encourages every C++ programmer to use auto.

I had to read C# code some time ago where var was extensively used and the code was very hard to understand—every time var was used I had to check the return type of the right side. Sometimes more than once, because I forgot the type of the variable after a while!

I know the compiler knows the type and I don’t have to write it, but it is widely accepted that we should write code for programmers, not for compilers.

I also know that is more easy to write:

```<code>auto x = GetX();
</code>```

Than:

```<code>someWeirdTemplate<someOtherVeryLongNameType, ...>::someOtherLongType x = GetX();
</code>```

But this is written only once and the GetX() return type is checked many times to understand what type x has.

This made me wonder—does auto make C++ code harder to understand?

答:
Short answer: More completely, my current opinion on auto is that you should use auto by default unless you explicitly want a conversion. (Slightly more precisely, "... unless you want to explicitly commit to a type, which nearly always is because you want a conversion.")

Longer answer and rationale:

Write an explicit type (rather than auto) only when you really want to explicitly commit to a type, which nearly always means you want to explicitly get a conversion to that type. Off the top of my head, I recall two main cases:

(Common) The initializer_list surprise that auto x = { 1 }; deduces initializer_list. If you don’t want initializer_list, say the type -- i.e., explicitly ask for a conversion.

(Rare) The expression templates case, such as that auto x = matrix1 * matrix 2 + matrix3; captures a helper or proxy type not meant to be visible to the programmer. In many cases, it's fine and benign to capture that type, but sometimes if you really want it to collapse and do the computation then say the type -- i.e., again explicitly ask for a conversion.

Routinely use auto by default otherwise, because using auto avoids pitfalls and makes your code more correct, more maintainable and robust, and more efficient. Roughly in order from most to least important, in the spirit of "write for clarity and correctness first":

Correctness: Using auto guarantees you’ll get the right type. As the saying goes, if you repeat yourself (say the type redundantly), you can and will lie (get it wrong). Here's a usual example: void f( const vector<int>& v ) { for( /*…* -- at this point, if you write the iterator’s type explicitly, you want to remember to write const_iterator (did you?), whereas auto just gets it right.

Maintainability and robustness: Using auto makes your code more robust in the face of change, because when the expression's type changes, auto will continue to resolve to the correct type. If you instead commit to an explicit type, changing the expression's type will inject silent conversions when the new type converts to the old type, or needless build breaks when the new type still works-like the old type but doesn't convert to the old type (for example, when you change a map to an unordered_map, which is always fine if you aren't relying on order, using auto for your iterators you'll seamlessly switch from map<>::iterator to unordered_map<>::iterator, but using map<>::iterator everywhere explicitly means you'll be wasting your valuable time on a mechanical code fix ripple, unless an intern is walking by and you can foist off the boring work on them).

Performance: Because auto guarantees no implicit conversion will happen, it guarantees better performance by default. If instead you say the type, and it requires a conversion, you will often silently get a conversion whether you expected it or not.

Usability: Using auto is your only good option for hard-to-spell and unutterable types, such as lambdas and template helpers, short of resorting to repetitive decltype expressions or less-efficient indirections like std::function.

Convenience: And, yes, auto is less typing. I mention that last for completeness because it's a common reason to like it, but it's not the biggest reason to use it.

Hence: Prefer to say auto by default. It offers so much simplicity and performance and clarity goodness that you're only hurting yourself (and your code's future maintainers) if you don't. Only commit to an explicit type when you really mean it, which nearly always means you want an explicit conversion.

Yes, there is (now) a GotW about this.

OwnerDisplayName: Felics

ContentLicense: CC BY-SA 4.0


问:
How to build completely modular web applications
In the coming months we're going to begin a project where we take a system we've built for a client (v1) and rebuild it from scratch.  Our goal with v2 is to make it modular, so that this specific client will have their own set of modules they use, then another client may use a different set of modules altogether.  The trick here is that Company A might have a series of checkout and user modules that change how that system works.  Company B might stick with the standard checkout procedure but customize how products are browsed.

What are some good approaches to application architecture when you're building an application from scratch that you want to have a Core that's shared among all clients while still maintaining the flexability for anything to be modified specifically for a client?

I've seen CodeIgniter's hooks and don't think that's a good solution as we could end up with 250 hooks and it's still not flexible enough.  What are some other solutions?  Ideally we won't need to draw a line in the sand.

答:
Here are some instructions on how to do modular design:
https://class.coursera.org/saas/lecture/preview/9

also this:
"SOA can be seen in a continuum, from older concepts of distributed computing and modular programming, through SOA, and on to current practices of mashups, SaaS,..."

HMVC code organization by itself, does not necessarily lead to modularity.


答:
I wouldn't explain the concept of technical debt, because it's not necessary. Instead, focus on refactoring: You are changing the design of your program, not necessarily so that it is "better" or "improved,"  you are changing it so that it can accept a change that you need to make.

A car analogy might fit: You need to add an air-conditioner to a car, but it wasn't originally designed for one. Not only do you have to make a weird L-shaped air-conditioner, but you also need to move some other things out of the way first and change the venting system.

I also think it's a better strategy to refactor when you are accommodating new features: otherwise you might be changing the design into something that only looks "better," but might actually be poorly suited to the circumstances surrounding the addition of your next feature.

Title: How do you explain refactoring to a non-technical person?

Body:
How do you go about explaining refactoring (and technical debt) to a non-technical person (typically a PHB or customer)? ("What, it's going to cost me a month of your work with no visible difference?!")

UPDATE Thanks for all the answers so far, I think this list will provide several useful analogies to which we can point the appropriate people (though editing out references to PHBs may be wise!)


答:
I've heard it described as "...the bane of my existence" and I would agree. I've been offered $$$ an hour to do HTML web development and I've turned it down. It's that much of a pain. I've spent a majority of time in HTML and recently started working with the "Flash platform". It's one of the most sophisticated frameworks I've ever seen and no one even knows about it. When people bring up Flash they think of Flash as of 10 years ago. It's grown... a lot. I love writing software again.

It still has it's disadvantages. Bugs sometimes linger forever but it's gotten better (thanks Steve J.).

BTW There's a major shortage for Flex developers. I've been approached by so many companies it's sick. If you know your CS, then spend the next 6+ months learning Flex hardcore then call me. I'll pass on all the job offers I have to turn down.

Update: Cross browser support is the main pain point. What works in one browser won't work in another or it will but not in a previous version.

The process goes something like this:
- get design of site
- attempt to recreate it in one target browser (this can be difficult)
- show client
- client changes design
- scrape all the layout work you originally did
- get it functional
- client approves
- get it to work in other browsers.
This is the most difficult part. There are obscure bugs all along the way. Then you'll encounter features that earlier browsers don't support such as rounded corners. You'll try to reuse your code and css but that quickly becomes fragmented. Simply it can become high maintenance very quickly. Add in animations and older browsers choke.

The client will make changes. You'll end up spending all your time doing "what should be simple things" and hate your life. You'll become a guru and know things you don't want to know. I know it sounds dramatic but I'm not embellishing the issues you'll face. Frameworks will make it easier. If you are persistent in working in HTML then to prepare yourself recreate one of your favorite sites in HTML making sure to match the design and functionality in all browsers it supports. Get the issues you encounter out of the way before going into a job. Issues such as best design tools, best javascript frameworks, best debugging tools, best IDEs, etc.

Title: Web versus desktop development - is web development worse?

Body:
As a longtime desktop developer looking at doing our first large-scale web application, what are the pros and cons of doing web development?

Is developing a web application much worse than developing a desktop app?  E.g., is it more tedious or annoying?  Is the time to market much worse?  Is the web platform excessively limiting?  If the answer to any of these is yes, then why?

(And how does developing a Flash or Silverlight app compare?)

OwnerDisplayName: 1.21 gigawatts

LastEditorDisplayName: 1.21 gigawatts


答:
I would say ”code maintenance”. It's important to use words that the non-technical person is familiar with and that make sense to a non-technical world view.
If non-technical person (customer) is familiar with application maintenance then it's easy to make parallel of code maintenance and application maintenance. Even if they are not the same, you can explain that the end customer here are developers or those how maintain the system.


答: Re-factoring is just like the process of re-packing a suitcase until everything fits in neatly. Sometimes, in the process, you wonder why you were trying to get so much junk in there to begin with.</p>


问:
Describing requirements in SRS - use cases?
I do not have the access to the IEEE standard and information on the net are contradictory. Can I capture user requirements in SRS using use cases? Or I should keep use cases separate as they are more like scenarios than separate requirements?</p>

答:
UML Use Cases were written long after the IEEE standards on SRS (UML in 1994 and SRS ten years earlier in 1984). Therefore there aren't really a reliable source on answering the if-and-where use cases should be in an SRS.

The IEEE standard for an SRS document mostly tells you how the document should be formed. So if you really want the use-cases placed somewhere in the SRS it would be under the "Specific Requirements" part of the document. Use-cases are specific scenarios and should be treated as specific requirements.

However the first step you should ask your client or reciever what they want from the requirements document. Do they really want to have UML Use Cases or something else? There are a bunch of ways to elicit requirements and some clients most likely want it their way. For reference check out the book "Software Requirements - Styles and Techniques" by Soren Lauesen.


问:
Algorithm to use for shop floor layout?
I ran into a classroom problem yesterday (business oriented class, not computer science) and I found it interesting from an algorithmic perspective.

The problem goes something like this:

Assume there is a shop floor with N different rooms, and you have N different departments that need to go in those rooms.  The departments and the rooms are all the same size, so any department could go in any room.  There is a known travel distance from each room to each other room.  There is also a known amount of trips necessary from one department to another (trips are counted the same regardless which room they originate from, so a trip from A to B is equivalent to a trip from B to A).  Given those inputs, determine a layout of departments into rooms which minimizes travel time.

What is the best way to approach this problem algorithmically?  Is there already a particular algorithm or class of algorithms designed to solve this type of problem?  Does this type of problem have a name in computer science?

I am not looking for you to design an algorithm to solve this, although feel free to do so if you would like.  I'm wondering if this is a problem space that has already been well defined and studied algorithmically and if so get some links to research further.  I can see a lot of different data structures and algorithms that might apply to this and I'm curious which approach would be "best".

And don't worry, you are not doing my homework for me.  This is not a homework problem per se, as this is a business course and we were simply discussing the concepts and not trying to solve the problem algorithmically.

答: Simplest way is: get the civil layout of the building, mark the department locations pictorially using a graph sheet (best way is to use Auto CAD or any other 2D/3D software). You then have to assess how much space you have and how you want to place the departments. From the sheet, you can get the travel distances between departments.</p>

Title: Algorithm to use for shop floor layout?


问:
How can a single database work for website, mobile apps?
We have developed a job-portal where users can view jobs and and also post jobs. We have used Php and MySQL. We hosted this on web faction. Now we want to develop the mobile app of the job portal for android, ios and windows. As the database should be synchronous and aligned dynamically with apps and website database. As the back-end code has to be changed to Java in android and c# in windows, how to manage a single synchronous database?</p>

答:
You need a Service Oriented Architecture.
Because you are sharing data across all those platforms, Web Services..

Basically rather that calling a "function" you make an HTTP request to a URL, parameters are passed in via the query string or Http header. XML or JSON is returned. Read up on it.

Thing is, your app need to be online at all times...


问:
How to properly include field validation in a Software Documenation
I'm developing a software documentation in a project, and much of it are just CRUD or CRUD based functions. As you can imagine, a lot of the rules are constraints about fields validation, things like length, range, data type and masks of the field.

Writing all those rules would be cumbersome to write and to read, so I'm wondering, what are the option available to include such rules in a software documentation, in a way that it is not tedious to write/read it all?

Edit - Clarification

The rules and being taken from an old desktop legacy application, and we are going to document the current validations, features and forms; so the application will be implemented in a more up-to-date (web) platform, considering usability and consistency in the new system. The documentation is handwritten using the Sybase PowerDesigner tool, but the document can be written in doc inside the tool.

Some of it are cross-field validation rules, for example;

For a person of type X, residing on country Y, the value of field A must be validated using the B rule.

For a person of type X, residing on country Z, the value of field A must be validated using the C rule, and the field D, validated through E rule.

Type X, country Y, field A, field D, etc, are all values extracted from fields on the forms.

答:
The best to make this readable is to keep the layout of these requirements consistent across the Doc.

I think that is more important that the format itself, that being said i would use a basic grid. If no value is needed, leave it Blank. (as opposed to writing None)

Column One is Filed Property, Column 2 is that value (or description).

```<code>Name                Email
Type                Text
Length              150
FK Constraint
Other Validation    Standard Email Validation
</code>```

Body:
The best to make this readable is to keep the layout of these requirements consistent across the Doc.

I think that is more important that the format itself, that being said i would use a basic grid. If no value is needed, leave it Blank. (as opposed to writing None)

Column One is Filed Property, Column 2 is that value (or description).

Name                Email
Type                Text
Length              150
FK Constraint
Other Validation    Standard Email Validation


问:
Are there any programming languages that follow a minimalist development approach?
I find it that when languages are considered the same as commercial software, there is always a constant need to add new features to justify new releases.

Can there be or are there languages where version 1.0 is the final version? Of course bug fixes are exempt from this, but the feature set always remains the same?

This way every feature in the language fits together nicely and not seem like they are bolted on after the fact with obsolete features still around because of backwards compatibility.

I assume some academic languages are like this? But are there commercially successful languages that follows this idea? The accompanying library is also free to get new features too, but the language always remains constant.

One example I can give is, one of my favourite languages C#, which I use pretty often, more and more features are being added every release. To take advantages of these, I have to drop actual tasks in hand, and spend considerable time learning these instead of being able to pick up trivial concepts and combine those myself to solve more complex problems with ease.

So I guess I am looking for a minimalist approach where everything is consistent, makes sense, and is as orthogonal as possible.

答:
Lisp, Smalltalk.  Coincidentally, those are also the best languages in the whole bunch.

Both Lisp and Smalltalk are languages which are built around strong unifying metaphor. Lisp's metaphor is "everything is a list; this list represents both data and code (as functions)".  Smalltalk's metaphor is "everything is an object; the only way to invoke a behaviour is to pass a message to an object".  These metaphors allows the languages to be stable, minimal and powerful. The rest is in the library.

Things that are called "control structures" in all non-minimal (I wanted to write "bloated") languages, are parts of the library here (as an example: cond function in lisp; ifTrue:/ifFalse: family of messages in Smalltalk both implement a conditional, where other languages have if keyword).

It can be seen that Lisp / Smalltalk are nearly minimal embodiments of their paradigm and nothing more (Lisp: functional programming; Smalltalk: object-oriented programming).


问:
Rearranging Cartons Algorithm
Problem Statement -

The task is to find the minimum number of swaps required in the given arrangement of cartons to get the desired arrangement of cartons. Only adjacent cartons can be swapped.

I have tried an ad hoc approach, but it proved inefficient towards the upper limit of the data range. Here it is for reference -

```<code>Traversing through the given arrangement of cartons
 if position of carton>than the desired position
  swap back
  go to previous iteration
</code>```

What would be a pragmatic approach to the problem?

Test Data Range - N<=105

Source - INOI 2009 Q Paper

答:
with only adjacent swaps you are limited to a O(n^2) sorting algorithm, (with worst case being a reverse sorted set)

and since you only have to limit yourself to least amount of swaps you can compare everything as much as you like

one way to guarantee the least amount of swaps is to only swap 2 cartons when they are in reverse order

both bubble sort and insertion sort will do this

the way to compute this minimum is to find the desired location of each carton (with any sorting algo) and take the sum of the amount each carton is shifted and divide by 2

in psuedo code

```<code>sort arr
sum=0
foreach c in arr
   sum+= abs(oldIndexOf(c)-indexOf(c))
return sum/2
</code>```

Title: Rearranging Cartons Algorithm

Body:
with only adjacent swaps you are limited to a O(n^2) sorting algorithm, (with worst case being a reverse sorted set)

and since you only have to limit yourself to least amount of swaps you can compare everything as much as you like

one way to guarantee the least amount of swaps is to only swap 2 cartons when they are in reverse order

both bubble sort and insertion sort will do this

the way to compute this minimum is to find the desired location of each carton (with any sorting algo) and take the sum of the amount each carton is shifted and divide by 2

in psuedo code

sort arr
sum=0
foreach c in arr
   sum+= abs(oldIndexOf(c)-indexOf(c))
return sum/2


答:
Tcl, which was design to be  minimalist in the first place  </p>

<p>From there about page http://www.tcl.tk/about/features.html, one of the features is that it is very easy to learn and where casual programmers or even non programmers can use it. </p>

Title: Are there any programming languages that follow a minimalist development approach?

Body:
I find it that when languages are considered the same as commercial software, there is always a constant need to add new features to justify new releases.

Can there be or are there languages where version 1.0 is the final version? Of course bug fixes are exempt from this, but the feature set always remains the same?

This way every feature in the language fits together nicely and not seem like they are bolted on after the fact with obsolete features still around because of backwards compatibility.

I assume some academic languages are like this? But are there commercially successful languages that follows this idea? The accompanying library is also free to get new features too, but the language always remains constant.

One example I can give is, one of my favourite languages C#, which I use pretty often, more and more features are being added every release. To take advantages of these, I have to drop actual tasks in hand, and spend considerable time learning these instead of being able to pick up trivial concepts and combine those myself to solve more complex problems with ease.

So I guess I am looking for a minimalist approach where everything is consistent, makes sense, and is as orthogonal as possible.

Body:
Tcl, which was design to be  minimalist in the first place

From there about page http://www.tcl.tk/about/features.html, one of the features is that it is very easy to learn and where casual programmers or even non programmers can use it.


答:
There are several ways to manage that.

At the lowest level, you can let the database server take care of it. If all applications connect to the same database on the same server and you correctly use SQL transactions, the MySQL server will ensure everyone sees a consistent view of the database.

But if you already need the internet connection to reach the database, why not have there a single web-server that manages the business logic together with the database access and returns the results in a format digestible for the various front-ends (android app, ios app, windows program, website). That way you only have to write the business logic once and only the front-end specific presentation code has to be written for each supported platform.

Title: How can a single database work for website, mobile apps?

Body: We have developed a job-portal where users can view jobs and and also post jobs. We have used Php and MySQL. We hosted this on web faction. Now we want to develop the mobile app of the job portal for android, ios and windows. As the database should be synchronous and aligned dynamically with apps and website database. As the back-end code has to be changed to Java in android and c# in windows, how to manage a single synchronous database?</p>


答:
I just took a look at the Windows XP calculator.  While it's true that the number keys and the memory keys appear in the same general location in the standard and scientific view, I believe it is to create a consistent interface for the user.

Basically, a standard / scientific calculator presents two different views to the user.  The scientific view is a super set of the standard view.

One way to write a calculator application is to write the code for the scientific view.  A Strategy or Command pattern would prove useful in writing your calculator code.

You can then use the same code for the standard view, as the standard view is a subset of the scientific view.

Your application would switch views depending on the option the user selected.


问:
How to implement Scrum in a company with three similar web-based products
I am somewhat familiar with the concepts and benefits of Scrum. With that in mind, I am trying to improve the failing Scrum product management structure of a company I'm now working for that has three separate B2C products, catering to the same demographic and accessible on the same website. Each product has a product owner and a unique development team (5 - 9 people in each) behind it.

Given that the target audiences are similar (not sure if it should matter) and the 3 web products are similar in nature, what are the potential benefits/risks associated with merging the teams and having just one product owner/scrum master/dev team? Some questions that come to mind are: does it make sense to have 3 product owners and three distinct backlogs if your website has three distinct products? Also, if you only have one product owner, what is the best metric off which to choose who that will be?

答:
Mixing the teams is a probably not a good idea.  Restructuring may be in order if the teams aren't working well together.  Be sure the teams are small (7 plus or minus 2).  Also, keeping the teams cross-functional and product-oriented not component-oriented is also helpful.  Developing with the intent to deliver working software at the end of each sprint is paramount to success.

Given what you've said about the situation, I would first investigate if the teams are really doing Scrum effectively as it pertains to the culture of your organization and addressing issues as they appear.  Implementing Scrum exposes problems in your process; it does not fix those problems by itself.  Without a conscious effort to fix the existing problems in the way your organization develops its technology products, your projects will continue to fail whether you use Scrum or not.


问:
Installer or Portable
I feared programs that require installation a lot. They leave traces behind the registry even after un-installation, plus, some uninstallers are poorly-programmed (that means, some programs cannot be uninstalled).
That applies to Windows.

The good side of installers, they create shortcuts and file associations. However, the Komodo on Linux uses a shell script to setup and can be safely uninstalled by deleting the folder.

Do you think installers should be all abolished? Do you think the effect of installations should be replaced by shell scripts?
Do you think all computer games should be portable?

Should the "scan the /Applications/${AppName}/Information folder and list app icons" design should be used for future desktop environments?

答:
I'm pro-portable myself, because an application should never modify the system unless it is really necessary, and most of the time it's not.

If my machine was in state A when I installed something, I want it to go back to state A when that something is removed. Otherwise, you end up with tons of (now) useless crap on your system.

In this regard, Linux works better for me because the location of everything is much better "standardized" than on Windows, where, for example, you can find your settings almost anywhere: in Windows folder, in your home folder, in $App's install directory, in the registry etc..

Title: Installer or Portable


答:
TeX, the typesetting system, has been very stable since version 3.

Since version 3, TeX has used an idiosyncratic version numbering system, where updates have been indicated by adding an extra digit at the end of the decimal, so that the version number asymptotically approaches π. This is a reflection of the fact that TeX is now very stable, and only minor updates are anticipated. The current version of TeX is 3.1415926; it was last updated in March 2008. The design was frozen after version 3.0, and no new feature or fundamental change will be added, so all newer versions will contain only bug fixes. Even though Donald Knuth himself has suggested a few areas in which TeX could have been improved, he indicated that he firmly believes that having an unchanged system that will produce the same output now and in the future is more important than introducing new features. For this reason, he has stated that the "absolutely final change (to be made after my death)" will be to change the version number to π, at which point all remaining bugs will become features.

I won't claim that it fulfills your "So I guess I am looking for a minimalist approach where everything is consistent, makes sense, and is as orthogonal as possible." statement, but it meets most of your other criteria.


答:
C and Fortran are languages that spring to mind.  They are very stable and their syntax is easily contained in one's mind.  Other than writing bad code yourself, there are very few suprises when using these languages.  But I wouldn't hold them up as great languages for rapid application development.

I prefer the rapid advancement of languages with features that once I spend a little time on them, make my job considerably easier and the code less complex while maintaining expressiveness.


答:
There are few languages that have remained relatively unchanged since their inception outside of the esoteric one off languages which are unlikely to be what is desired (I would hate to try to write something meaningful in Befunge (though it has also been modified since its original 1.0 release)).

The languages that are most likely to fill the desire of not having to learn anything new are languages that specialize in 'glue' between other programs.  Languages such as jcl, bash, and the like.  Simple scripting languages may also fall into this - awk being one of the leaders.

Once one leaves this realm, development happens.  Either the language or the frameworks.  In some situations it is 'difficult' to code for the language without getting some of some framework that is reving quickly.

Many languages have some degree of backwards compatibility.  One can still write Java 1.4 today, though it probably isn't recommended - the frameworks people write for it are changing faster than the language.  One can still find f77 and f90 compilers out there for a language spec that hasn't changed in 20 or 40 years.  C, Objective C, C++ can still be coded to older specifications of the language - one doesn’t need to keep updating one's code because a new spec was released or a new framework is out there.

Some languages have a rather long unchanged history because the language itself is sufficiently powerful to do whatever one wants it to.  Lisp is the prime candidate in this area.  Forth also falls into the "it hasn't changed much" realm.

Going to more traditional scripting languages look at TCL, Perl and Python.  Avoid things that are currently in the 'fad' realm that are experiencing a burst of popularity for some reason or another (ruby and javascript, I'm looking at you).  TCL has changed over the years, though one of its goals is to try to maintain a consistency of design.  Modern Perl and Python both have some consistency of design, though admittedly new features can feel bolted on (though one doesn't need to use them).


问:
Designing a Web Application with Two Different Backend Databases
I'm working on a pretty standard LAMP based web application.  The server itself has a standard MySQL database and the application is written in PHP.  The kicker is, we also use SQL Server databases with this application.

The current data setup is this:

MySQL stores the user account information (Username, password,
privileges, etc.) and a "connection identifier".

The connection identifier links to another table that stores connection credentials for a SQL server database.

When a user logs in, a connection is made to a remote SQL Server database (these are hosted independently of the web application and not in my control).

Using that connection, the web application processes and outputs the data (only reads, no writes).

The application has evolved greatly and, while the organization and practices have improved, the design is still pretty messy and confusing.  I struggle to implement any kind of framework or ORM because most are designed with one database in mind.

I have stitched together a framework that works very well for reports (where only the SQL Server connection is needed) but it doesn't go well with things like account interaction (where SQL server is used for validation of data that goes into MySQL).

The setup doesn't look like it will change so I was wondering if there was any advice on designing and maintaining a web application with two different database backends at the same time.

On a side note, storing the credentials for remote SQL Server databases on our MySQL database makes me nervous.  I can only encrypt the passwords as I need them for connections and, as it currently stands, all the accounts used are admin accounts with full privileges.  Not something you want getting out especially when these databases are opened up for internet connections.  So any advice for that would be nice as well.

答:
Separate the data base code from the rest of the application so that the rest of the application gets it's data from one source, your separated (abstracted) data base code.

As far as your concern about the SQL Server credentials, I hope that the connection between your web software and SQL Sever is secure.  As far as storing the credentials, encrypt as you say, and name the table with the credentials something innocuous (like customer hobbies).  Lock down the privileges on the credentials table to read only by your application.


问:
What's a nice explanation for pointers?
In your own studies (on your own, or for a class) did you have an "ah ha" moment when you finally, really understood pointers? Do you have an explanation you use for beginner programmers that seems particularly effective?

For example, when beginners first encounter pointers in C, they might just add &s and *s until it compiles (as I myself once did). Maybe it was a picture, or a really well motivated example, that made pointers "click" for you or your student. What was it, and what did you try before that didn't seem to work? Were any topics prerequisites (e.g. structs, or arrays)?

In other words, what was necessary to understand the meaning of &s and *, when you could use them with confidence? Learning the syntax and terminology or the use cases isn't enough, at some point the idea needs to be internalized.

Update: I really like the answers so far; please keep them coming. There are a lot of great perspectives here, but I think many are good explanations/slogans for ourselves after we've internalized the concept. I'm looking for the detailed contexts and circumstances when it dawned on you.

For example:

I only somewhat understood pointers
  syntactically in C. I heard two of my
  friends explaining pointers to another
  friend, who asked why a struct was
  passed with a pointer. The first
  friend talked about how it needed to
  be referenced and modified, but it was
  just a short comment from the other
  friend where it hit me: "It's also
  more efficient." Passing 4 bytes
  instead of 16 bytes was the final
  conceptual shift I needed.

答:
I cant quite remember the circumstances around my pointers-aha-moment, but I have retroactively refitted the memory around my understanding of a c-style array. (i.e. arr[3] is the same as *(arr+3) )

For some reason I find it immensely helpful to view pointers as arrays whenever I happen upon a pointer-situation.

Title: What's a nice explanation for pointers?


答:
When a user logs in, a connection is made to a remote SQL Server database (these are hosted independently of the web application and not in my control).

I hope the connection to SQL server is not made and held when the user logs in arbitrarily. The connection should be taken from the pool only when needed, as late as possible, then returned to the pool as soon as possible.

Using that connection, the web application processes and outputs the data (only reads, no writes).

If the data is read only, then do not use admin accounts with full privileges. Only use what you need.

Advice:

The only issues I see are operations that span both databases, or keeping duplicate data in sync.

If data must be duplicated, try to restrict it to surrogate keys that NEVER change. Avoid duplicating data for performance reasons. This will make your life much easier and ironically could improve performance if there are massive updates.

Don't abstract the fact that there are 2 DB's in the data layer. Make that fact as loud and explicit as possible.

Do not make the closure of a connection dependent on the completion of an operation on the 2cd database. (except in the case of atomic transactions)

Joining sets between MySQL and SQLServer will be an issue. Retrieve the data sets from both DBs (filtered as finely as possible) then perform the "join" in your code. Functional style code would be very useful here, but imperative will get the job done.

Atomic transactions that span both DBs is an issue. (although not in your scenario) You must commit to 1 db before the other so you need to do a manual rollback if the commit fails on the 2cd DB. I don't see an easy way out there.

Title: Designing a Web Application with Two Different Backend Databases

Body:
I'm working on a pretty standard LAMP based web application.  The server itself has a standard MySQL database and the application is written in PHP.  The kicker is, we also use SQL Server databases with this application.

The current data setup is this:

MySQL stores the user account information (Username, password,
privileges, etc.) and a "connection identifier".

The connection identifier links to another table that stores connection credentials for a SQL server database.

When a user logs in, a connection is made to a remote SQL Server database (these are hosted independently of the web application and not in my control).

Using that connection, the web application processes and outputs the data (only reads, no writes).

The application has evolved greatly and, while the organization and practices have improved, the design is still pretty messy and confusing.  I struggle to implement any kind of framework or ORM because most are designed with one database in mind.

I have stitched together a framework that works very well for reports (where only the SQL Server connection is needed) but it doesn't go well with things like account interaction (where SQL server is used for validation of data that goes into MySQL).

The setup doesn't look like it will change so I was wondering if there was any advice on designing and maintaining a web application with two different database backends at the same time.

On a side note, storing the credentials for remote SQL Server databases on our MySQL database makes me nervous.  I can only encrypt the passwords as I need them for connections and, as it currently stands, all the accounts used are admin accounts with full privileges.  Not something you want getting out especially when these databases are opened up for internet connections.  So any advice for that would be nice as well.


问:
How do you convince the client their application's backend needs a rewrite?
I have been supporting a LOB winforms application for a client the last 3 years. The application is built with a simple monolithic architecture and uses .NET 2.0.

The application is a core part of their operations and its longevity is paramount. It needs to evolve with their evolving business processes, as well as implement improved functionality etc....this brings me to believe that this application needs an overhaul of sorts on the back-end.

The problem is changing a back-end is "invisible"...i.e. the user never actually sees it. It's a quality of the system that is changing (stability, maintainability, reliability, longevity), not some functional requirement that will be easily seen...i.e. the ROI is not obvious.

There is a lot of new functionality to be added to the front-end as well (user experience). I am considering a strategy of changing the back-end over time...i.e. when making a change or adding a feature to the front-end, change those components in the back-end that are affected, eventually you get to everything.

How do I convince the client that we need to rebuild the back-end?

答:
A rewrite is not the same as a reengineer.

I have posted this in other similar questions.

This chart could help sell the idea of a rewrite/replace/reengineer, it's a function of code base quality and business value of the application:


问:
How to make custom libraries accessible?
I am trying to compile and install every custom module under it's own designated folder. (ex: /myApps/myLinux/compiled_app)

I had luck with Python so far, where my Python is compiled from source and lives in:
/myApps/myLinux/python2.5 and "python2.5" -> /myApps/myLinux/python2.5.6-gcc463

So I can access this Python through a wrapper script that sets the right environment.

The question is recently I had to compile and add something called gperf3.0.4. So now it lives:
/myApps/myLinux/gperf3.0 and "gperf3.0" -> /myApps/myLinux/gperf3.0.4-gcc463

The question is: How will I point to this lib if some other app needs to access it? Is it done through the LD_LIBRARY_PATH variable?

答:
With gcc you can link to a lib in an arbitrary location by passing the full path to the linker just like any other object</p>

```<code>$ gcc -c somefile.c
$ gcc -c mainfile.c
$ gcc somefile.o mainfile.o /path/to/libsomelib.so
  or
  gcc somefile.o mainfile.o -L/path/to/ -lsomelib
$ LD_LIBRARY_PATH=/path/to/ ./a.out
</code>```

Body:
With gcc you can link to a lib in an arbitrary location by passing the full path to the linker just like any other object

$ gcc -c somefile.c
$ gcc -c mainfile.c
$ gcc somefile.o mainfile.o /path/to/libsomelib.so
  or
  gcc somefile.o mainfile.o -L/path/to/ -lsomelib
$ LD_LIBRARY_PATH=/path/to/ ./a.out


问:
When did the standard for packaging Linux source code become .tar.gz?
When browsing open-source projects that are primarily developed for Linux systems and downloading the latest packages, the source code is always stored in a .tar.gz or .tar.bz2 file.

Is there any reason for using .tar.gz or .tar.bz2 rather than something like .zip or .rar or some other compression algorithm (or even leaving it uncompressed if the project is small enough)?

答:
tar is traditional in unix, it combines files but doesn't necessarily compress them.
Compressing them with .g or .bz or .b2 is just as easy.

Zip and rar are propriety and more common in the Windows world


问:
What's the most absurd myth about programming issues?
To put it another way... What is the most commonly held and frustrating misunderstanding about programming, you have encountered?

Which widespread and longstanding myths/misconceptions do you find hard for programmers to dispel/correct.

Please, explain why this is a myth.

答:
Why don't you guys simply write it right the first time, rather than spending so much time typing in buggy code and then later reading the code trying to find the bugs?

:-) :-) :-) :-)