问:
How do people get rid of conditional branches in Functional Programming?
Long running switch cases or if-else-if constructs are avoided in OOP using polymorphism wherever it is applicable.

instead of branching by matching a value, branching is done at class-level itself.

How can similar approach be applied in Functional Programming paradigm, Clojure specifically ?

答:
In functional programming language, we can use functions and key params to get rid of conditional branches. That mean use functions with condition param instead of "if esle". See example 3.
As  computeSphereArea({radius:25.55})

Example 1: OOP
// in OOP(use java for example(sourceCode from: http: //developer.51cto.com/art/200907/136506.htm)):

```<code>public abstract class Shape {
    //    ...

    public abstract void computeArea();
    public abstract void computeVolume();
    public abstract double getArea();
    public abstract double getVolume();

}
public class Circle extends CircleShape2 {
    //    ...
    double volume = 0.0; //
    public void computeArea() { //
        area = Math.PI * radius * radius;
    }
    public double getArea() {
        return area;
    }
    public void computeVolume() {} //
    public double getVolume() {
        return volume;
    }

}
public class Sphere extends Circle {
    //    ...
    public void computeArea() { //
        super.computeArea(); //
        area = 4 * area;
    }
    public void computeVolume() { //
        super.computeArea(); //
        volume = 4.0 / 3 * radius * area;
    }
}
public class CircleShapeApp {
    public static void main(String[] args) {
        Circle circle = new Circle(12.98);
        Sphere sphere = new Sphere(25.55);

        Shape shape = circle; //
        //
        shape.computeArea();
        shape.computeVolume();
        System.out.println("circle area: " + shape.getArea());
        System.out.println("circle volume: " + shape.getVolume());
        //
        shape = sphere;
        shape.computeArea();
        shape.computeVolume();
        System.out.println("Sphere area: " + shape.getArea());
        System.out.println("Sphere volume: " + shape.getVolume());
    }
}
</code>```

Example 2: functional like oop.
//in functional programming(use javascript for example):

```<code>function initShape(v) {
    var shape = {};
    v = v || {};
    if (typeOf(v, 'object') === true) {
        shape.volumne = v.volumne || 0.0;
        shape.computeArea = v.computeArea || function() {};
        shape.computeVolume = v.computeVolume || function() {};
        shape.getArea = v.getArea || function() {};
        shape.getVolume = v.getVolume || function() {};
    }

    return shape;
}

function initCircle(v) {
    var circle = {};
    v = v || {};
    if (typeOf(v, 'object') === true) {
        circle.volume = 0.0;
        circle.radius = v.radius || 0.0;
        circle.computeArea = v.computeArea || function() {
            this.area = Math.PI * this.radius * this.radius;
        };
        circle.computeVolume = function() {};
        circle.getArea = v.getArea || function() {
            return this.area
        };
        circle.getVolume = v.getVolume || function() {
            return this.volume
        };
    }
    return initShape(circle);
}

function initSphere(v) {
    var sphere = {}
    v = v || {};
    if (typeOf(v, 'object') === true) {
        var circle = initCircle(v);
        sphere = circle;
        sphere.volume = v.volume;
        sphere.computeArea = function() {
            circle.computeArea();
            this.area = 4 * circle.area;
        }
        sphere.computeVolume = function() {
            circle.computeArea();
            this.volume = 4.0 / 3 * this.radius * circle.area;
        }
    }
    return initShape(sphere);
}
var circle = initCircle(12.98);
circle.computeArea();
circle.computeVolume();
console.log("circle area: " + circle.getArea());
console.log("circle volume: " + circle.getVolume());

var sphere = initShpere(25.55);
sphere.computeArea();
sphere.computeVolume();
console.log("sphere area: " + sphere.getArea());
console.log("sphere volume: " + sphere.getVolume());
</code>```

// Although, this is not pure functional program example, but with functional interface, like initCircle() initSphere().You can create more functions like computeCircleArea() computeSphereArea() makes it more functional.
// PS:typeOf() is here:https://github.com/will-v-king/javascript-showMe

Example3:
Ok, let's make it more funcitonal:

```<code>/** in functional code shape became meaningless.
function initShape(v) {
    var shape = {};
    v = v || {};
    if (typeOf(v, 'object') === true) {
        shape = v.object || v.shape || shape;
        shape.volumne = v.volumne || 0.0;
    }
    return shape;
}

function computeShapeArea(v){
}
function computeShapeVolume(v){
}
*/

function initCircle(v) {
    var circle = {};
    v = v || {};
    if (typeOf(v, 'object') === true) {
        circle = v.object || v.circle || circle;
        circle.volume = 0.0;
        circle.radius = v.radius || 0.0;
    }
    return initShape(circle);
}

function computeCircleArea(v){
  var area;
  v = v || {};
  if(typeOf(v) === 'Object'){
    var radius = v.radius || v.object.radius || v.circle.radius;
    if(!typeOf(v,'undefined')){
       area = Math.PI * radius * radius;
    }
  }
  return area;
}
function computeCircleVolume(v){
  return 0.0;
}
/**function initCircle and initSphere are not necessary. why? see the last line.*/
function initSphere(v) {
    var sphere = {}
    v = v || {};
    if (typeOf(v, 'object') === true) {
        var circle = initCircle(v);
        sphere = circle;
        sphere.volume = v.volume;
    }
    return initShape(sphere);
}

function computeSphereArea(v){
  var area;
  v = v || {};
  if(typeOf(v) === 'Object'){
    var radius = v.radius || v.object.radius || v.sphere.radius;
    if(!typeOf(v,'undefined')){
       area = 4 * computeCircleArea({radius:radius});  // **POINT** the same as :circle.computeArea();  this.area = 4 * circle.area;
    }
  }
  return area;
}
function computeSphereVolume(v){
  var volume;
  v = v || {};
  if(typeOf(v,'object') === ture){
    radius = v.radius || typeOf(v.object, 'object') === true ? v.object.radius : typeOf(v.sphere, 'Object') === true ? v.sphere.radius : 0.0;
    var circleArea = computeCircleArea({radius:radius});
    if(typeOf(circleArea,'number')=== true){
      volume = 4.0 / 3 * radius * computeCircleArea({radius:radius}); // **POINT** the same as:    circle.computeArea();  this.volume = 4.0 / 3 * this.radius * circle.area;
    }
  }
  return volume;
}

var circle = initCircle({radius:12.98});
console.log("circle area: " + computeCircleArea(circle) );
console.log("circle volume: " + computeCircleVolume(circle) );

var sphere = initShpere(25.55);
console.log("sphere area: " + computeSphereArea({radius:25.55}) );
console.log("sphere volume: " + computeSphereVolume({radius:25.55}) );
console.log("sphere object is unused.That means initSphere is also not necessary as initShape()");
</code>```

Body:
In functional programming language, we can use functions and key params to get rid of conditional branches. That mean use functions with condition param instead of "if esle". See example 3.
As  computeSphereArea({radius:25.55})

Example 1: OOP
// in OOP(use java for example(sourceCode from: http: //developer.51cto.com/art/200907/136506.htm)):

public abstract class Shape {
    //    ...

    public abstract void computeArea();
    public abstract void computeVolume();
    public abstract double getArea();
    public abstract double getVolume();

}
public class Circle extends CircleShape2 {
    //    ...
    double volume = 0.0; //
    public void computeArea() { //
        area = Math.PI * radius * radius;
    }
    public double getArea() {
        return area;
    }
    public void computeVolume() {} //
    public double getVolume() {
        return volume;
    }

}
public class Sphere extends Circle {
    //    ...
    public void computeArea() { //
        super.computeArea(); //
        area = 4 * area;
    }
    public void computeVolume() { //
        super.computeArea(); //
        volume = 4.0 / 3 * radius * area;
    }
}
public class CircleShapeApp {
    public static void main(String[] args) {
        Circle circle = new Circle(12.98);
        Sphere sphere = new Sphere(25.55);

        Shape shape = circle; //
        //
        shape.computeArea();
        shape.computeVolume();
        System.out.println("circle area: " + shape.getArea());
        System.out.println("circle volume: " + shape.getVolume());
        //
        shape = sphere;
        shape.computeArea();
        shape.computeVolume();
        System.out.println("Sphere area: " + shape.getArea());
        System.out.println("Sphere volume: " + shape.getVolume());
    }
}

Example 2: functional like oop.
//in functional programming(use javascript for example):

function initShape(v) {
    var shape = {};
    v = v || {};
    if (typeOf(v, 'object') === true) {
        shape.volumne = v.volumne || 0.0;
        shape.computeArea = v.computeArea || function() {};
        shape.computeVolume = v.computeVolume || function() {};
        shape.getArea = v.getArea || function() {};
        shape.getVolume = v.getVolume || function() {};
    }

    return shape;
}

function initCircle(v) {
    var circle = {};
    v = v || {};
    if (typeOf(v, 'object') === true) {
        circle.volume = 0.0;
        circle.radius = v.radius || 0.0;
        circle.computeArea = v.computeArea || function() {
            this.area = Math.PI * this.radius * this.radius;
        };
        circle.computeVolume = function() {};
        circle.getArea = v.getArea || function() {
            return this.area
        };
        circle.getVolume = v.getVolume || function() {
            return this.volume
        };
    }
    return initShape(circle);
}

function initSphere(v) {
    var sphere = {}
    v = v || {};
    if (typeOf(v, 'object') === true) {
        var circle = initCircle(v);
        sphere = circle;
        sphere.volume = v.volume;
        sphere.computeArea = function() {
            circle.computeArea();
            this.area = 4 * circle.area;
        }
        sphere.computeVolume = function() {
            circle.computeArea();
            this.volume = 4.0 / 3 * this.radius * circle.area;
        }
    }
    return initShape(sphere);
}
var circle = initCircle(12.98);
circle.computeArea();
circle.computeVolume();
console.log("circle area: " + circle.getArea());
console.log("circle volume: " + circle.getVolume());

var sphere = initShpere(25.55);
sphere.computeArea();
sphere.computeVolume();
console.log("sphere area: " + sphere.getArea());
console.log("sphere volume: " + sphere.getVolume());

// Although, this is not pure functional program example, but with functional interface, like initCircle() initSphere().You can create more functions like computeCircleArea() computeSphereArea() makes it more functional.
// PS:typeOf() is here:https://github.com/will-v-king/javascript-showMe

Example3:
Ok, let's make it more funcitonal:

/** in functional code shape became meaningless.
function initShape(v) {
    var shape = {};
    v = v || {};
    if (typeOf(v, 'object') === true) {
        shape = v.object || v.shape || shape;
        shape.volumne = v.volumne || 0.0;
    }
    return shape;
}

function computeShapeArea(v){
}
function computeShapeVolume(v){
}
*/

function initCircle(v) {
    var circle = {};
    v = v || {};
    if (typeOf(v, 'object') === true) {
        circle = v.object || v.circle || circle;
        circle.volume = 0.0;
        circle.radius = v.radius || 0.0;
    }
    return initShape(circle);
}

function computeCircleArea(v){
  var area;
  v = v || {};
  if(typeOf(v) === 'Object'){
    var radius = v.radius || v.object.radius || v.circle.radius;
    if(!typeOf(v,'undefined')){
       area = Math.PI * radius * radius;
    }
  }
  return area;
}
function computeCircleVolume(v){
  return 0.0;
}
/**function initCircle and initSphere are not necessary. why? see the last line.*/
function initSphere(v) {
    var sphere = {}
    v = v || {};
    if (typeOf(v, 'object') === true) {
        var circle = initCircle(v);
        sphere = circle;
        sphere.volume = v.volume;
    }
    return initShape(sphere);
}

function computeSphereArea(v){
  var area;
  v = v || {};
  if(typeOf(v) === 'Object'){
    var radius = v.radius || v.object.radius || v.sphere.radius;
    if(!typeOf(v,'undefined')){
       area = 4 * computeCircleArea({radius:radius});  // **POINT** the same as :circle.computeArea();  this.area = 4 * circle.area;
    }
  }
  return area;
}
function computeSphereVolume(v){
  var volume;
  v = v || {};
  if(typeOf(v,'object') === ture){
    radius = v.radius || typeOf(v.object, 'object') === true ? v.object.radius : typeOf(v.sphere, 'Object') === true ? v.sphere.radius : 0.0;
    var circleArea = computeCircleArea({radius:radius});
    if(typeOf(circleArea,'number')=== true){
      volume = 4.0 / 3 * radius * computeCircleArea({radius:radius}); // **POINT** the same as:    circle.computeArea();  this.volume = 4.0 / 3 * this.radius * circle.area;
    }
  }
  return volume;
}

var circle = initCircle({radius:12.98});
console.log("circle area: " + computeCircleArea(circle) );
console.log("circle volume: " + computeCircleVolume(circle) );

var sphere = initShpere(25.55);
console.log("sphere area: " + computeSphereArea({radius:25.55}) );
console.log("sphere volume: " + computeSphereVolume({radius:25.55}) );
console.log("sphere object is unused.That means initSphere is also not necessary as initShape()");


问:
Would you re-design completely under .Net?
A very extensive application began as an Access-based system (for database storage). Forms were written in VB5 and/or VB6. As .Net became a fixture in the development community, certain modules have been rewritten. This seems very awkward and potentially costly just to maintain because of the cross-technologies and extra work to keep the two technologies happy with each other. Of course, the application uses a mix of ODBC OleDb and MySql.

Would you think spending the time and resources to completely re-develop the application under .Net would be more cost effective? In an effort to develop a more stable application, wouldn't it make sense to use .Net? Or continue chasing Access bugs, adding new features in .Net (which may or may not create new bugs between .Net and Access), and rewriting old Access modules into .Net modules under time constraints that prevent proper design and development?

Update
The application uses OleDb and MySql - I corrected my previous statement.

Also, to lend further support to rewriting: I have since found out that when the "porting" to .Net began, the VBA/VB6 code that existed was basically translated to the .Net equivalent. From my understanding, nothing was done to improve performance, or take advantage of new libraries or technologies.

In my opinion, this creates a very fragile and unstable application. With every new update, this becomes more and more visible. As a help desk technician, I have noticed an increase in problems reported. The customers using the software have noticed an increase in problems and are commenting on it.

答:
"Would you think spending the time and resources to completely re-develop the application under .Net would be more cost effective?"

This is not a question that can be answered here.

From the top of the requirement pyramid: someone made a decision which he hopefully can justify with a business plan. In that business plan it should state how many hours+extra costs it takes to convert the application and in that same business plan the benefits are stated also in terms on money.

That is the way to do it. If there is no business plan for it. then the answer is to first work on a business plan traceable to some high level use cases to make the impact analysis to verify the start of the project.

If the original driver of the business goal leading to the change is not even based on money then this person is probably the one paying for it all so it must be done.

If there is no business plan but "it just is done" then try to make one and present it to upper management. Include high level uses cases, costs, hours for redesign, build, extra cost for operations, new training for admin and endusers, project management and potential risks.

IMHO this is no technical question.

ContentLicense: CC BY-SA 2.5


问:
Randomization of biomes
You know how in Minecraft, the World is ever-expanding and all the biomes are randomized?

My generalized question is: In relation to a space simulation that is also ever-expanding as the player moves about the world, how would one go about programming this randomization in Java?

My real question is: Could I get a simplified example broken down into these example classes:

astroids (This would include how many astroids there are, their positioning in space, their size, how often the larger astroids occur, how close they are to each other, the limitations of how many of the large asteroids can be in one field, how often astroid fields are generated, etc.)

star-types (size, color, type, how often they occur, where hey occur, etc.)

inhabitable-planets (size, positioning, how often they're generated, where they are generated, etc.)

This would be very helpful currently since I wish to make a simplified version of such a program.

答:
Minecraft Example

Biomes in minecraft are not directly determined; a biome is selected based on the local temperature and humidity (for example a hot dry biome ends up as desert, a hot wet biome ends up as rain forest, for the whole graph see http://www.minecraftwiki.net/wiki/File:BiomesGraph.png [Note this graph is outdated but the concept is still current]).

Now you could simply choose the temperature and humidity randomly; but that would lead to each block having a different biome (really really stupid) or you could still choose randomly but on a larger scale; this would lead to horrible sharp edges and biomes that shouldn't be next to each other. For example desert could be next to arctic tundra (still quite stupid).

Naive solutions i.e. don't do this

A method that would solve this problem would be to stop choosing the temperature and humidity randomly but start choosing the change in temperature and humidity randomly. Initially this seems really nice, but because the player can walk through the world in any manor you end up with problems when the world curves back around on itself; you get nasty joins. Even if you create rules such as the world is created outward from the origin irrespective of walk direction you still have to make parts of the world the player hasn't explored yet. I.e. walk 100m North, then 10,000m East, then 200m South. Suddenly and all at once you need the "other 10,000m East" that you didn't walk down to work out what the new block is going to be like.

Perlin Noise (and its more efficient cousin simplex noise)

Perlin noise takes the position co-ordinates as an input (as well as a main seed) and outputs a value between -1 and +1 that is both random and slowly changing as your co-ordinate changes. It achieves this by sampling random numbers on several length scales. For example, the point at (1100, 0) will sample:

(1088,0)[-16 (rounded)]

(1120,0)[+16 (rounded)]

(1096,0)[-8 (rounded)]

(1012,0)[+8 (rounded)]

...

(1100,0)[+0]

NB by rounded I mean that (for example) at the +-16 level the sampling point is moved to the nearest value divisible exactly by 16, so (1100, 0) (1101, 0) (1102, 0) and similar will all sample (1088,0) as their -16 point

And will sum them, the weighting will determine how quickly the value changes, high weighting for the large scale will create slow undulations, high weighting for small scales will create more jagged quickly changing values.

A point next to it (1101, 0) will sample the same higher level point but the lowest level point will be different so it changes only slowly (the weighting of the higher points will also change). (1109, 0) will only have the very high level points in common.

This means that to calculate (1100, 0) you don't need to know any other point, your can generate them as and when and they will just "end up" being gradually changing.

Note that simplex noise is considerable faster than perlin noise as well as better in several more technical ways; however the maths is considerably more complex (which is amusing given the name)

Conclusion

If you just want true randomness (i.e. looks like static) just use java's inbuild random functions. If you want random but slowly changing noise (i.e. looks like mountains) use Perlin or Simplex noise. Perlin and Simplex noises are available for any dimension but perlin noise gets very inefficient for high dimensions whereas simplex noise only slowly grows in complexity with dimension.

References:

Explanation of perlin noise

Java implimentation of perlin noise

ContentLicense: CC BY-SA 3.0

Title: Randomization of biomes


答:
They don't avoid them, they embrace them using the pattern match syntax.

But functional programming is largely orthogonal to object oriented programming, so absolute majority of "functional" languages are also object oriented¹, including clojure. In fact clojure's multi-methods are even better than plain virtual methods of Java, because they can dynamically dispatch on types of multiple arguments, not just the first one.

There is one purely functional language that does not have dynamic polymorphism, Haskell. In Haskell you can define multi-methods via type classes, but the types are resolved at compile time. To have varying types at runtime, you have to create a union type and you either have to write the function with pattern match (which is like the if chain, but with more convenient syntax) or ask the compiler to derive the method by composing the methods of the constituent types. Or use the GHC forall extension.

¹ By object-oriented I mean that the language has some form of dynamic polymorphism with dispatch based on actual runtime type. Many new languages only have “trait-based” polymorphism where only interfaces can be inherited; I count that as object-oriented and for purpose of this answer it is sufficient.

Title: How do people get rid of conditional branches in Functional Programming?

Body:
Long running switch cases or if-else-if constructs are avoided in OOP using polymorphism wherever it is applicable.

instead of branching by matching a value, branching is done at class-level itself.

How can similar approach be applied in Functional Programming paradigm, Clojure specifically ?


问:
At what size of data does it become beneficial to move from SQL to NoSQL?
As a relational database programmer (most of the time), I read articles about how relational databases don't scale, and NoSQL solutions such as MongoDB do.
As most of the databases I have developed so far have been small to mid scale, I have never had a problem that hasn't been solved by some indexing, query optimization or schema redesign.

What sort of size would I expect to see MySQL struggling with. How many rows?

(I know this is going to depend on the application, and type of data stored. the one that got me thing was basically a genetics database, so would have one main table, with 3 or 4 lookup tables. The main table will contain amongst other things, a chromosome reference, and a position coordinate. It will likely get queried for a number of entries between two potions on a chromosome, to see what is stored there).

答:
I don't think that the size of data is the only factor. "Data model" is also a very important part.

E-Commerce catalog pages (Solr, ElasticSearch), web analytics data (Riak, Cassandra), stock prices (Redis), relationships connections in Social Networks (Neo4J, FleetDB) are just some examples when a NoSQL solution really shines.

IMHO, data model has more important role than the size of data when considering a NoSQL solution or RDBMS.


问:
Agile bug fixing - what's the preferred process for testing?
When a bug is fixed, the dev set its status to "resolved" and the bug is reassigned back to the person that created it. In our case this is usually the product owner - we don't have dedicated testers.

But what's a good process for controlling how/when the PO tests the software? Should he be given the latest build after each bug is resolved/checked-in? Or what about every morning? Or should he only receive a build at (or close to) the end of the iteration, to include all of that iteration's new functionality and bug fixes?

We are using TFS by the way.

答:
In most agile environments that I've seen, a continuous integration environment exists. This produces new builds and executes a test suite on that build on a regular basis - after every check-in to the integration branch of the repository, every night, or every week. It depends on how long and complex the build/test cycles are - it may not be feasible to do it extremely frequently.

In terms of when a build should go to a person for user acceptance testing, after every bug fix seems a bit too much. You should have automated unit and system tests that are ensuring that your builds are fairly stable and to find any key issues. The exact time to carry out user acceptance testing depends on the number of bugs fixed and the length of your iteration. The earlier you get feedback on the work, the better, so that it's possible to resolve any issues with the fixes or new features.

My recommendation would be to make a build available for user acceptance testing as frequently as possible (preferably every morning). This build should have already undergone developer testing and automated testing. The user acceptance testing should happen as often as schedule permits, but it may not happen daily. You need to note the risks of waiting too late for user acceptance testing - feedback on new development or fixes may have to be put off until the next iteration.


答:
You may wish to consider having a separate QA role for this.  QA can dedicate themselves to following up and making sure new functions work, bugs are fixed as expected and regression suites still show everything else working.

Disclosure:  I am in a QA role that I basically created for myself to address these issues.

Title: Agile bug fixing - what's the preferred process for testing?

Body:
When a bug is fixed, the dev set its status to "resolved" and the bug is reassigned back to the person that created it. In our case this is usually the product owner - we don't have dedicated testers.

But what's a good process for controlling how/when the PO tests the software? Should he be given the latest build after each bug is resolved/checked-in? Or what about every morning? Or should he only receive a build at (or close to) the end of the iteration, to include all of that iteration's new functionality and bug fixes?

We are using TFS by the way.


问:
user's requirements verification, howto?
My question is: How can you verify the users' requirements early in the software creation process?

I show the user specifications, prototypes, demos... but still users forget to share some "insignificant details" about the process or business rules and data. Which pops up after the final test as some "really small and rare exceptions" - which are turned into change request and accumulate a lot of work.

So how do you prototype (or verify) users requirements early in the project?

答:
I think you must not forget the other side. For any user it is difficult to produce a complete list of details of what you want. Think of yourself, you think of new things all the time.

It is an incredible hard job to come up with all the requirements and details of something you only have a vague idea about. I don't think anyone can.

I have a book here from the 70's called "why software projects fail". When I read on blogs and get IT magazines I read on the cover "why software projects fail". And when I compare the book contents with the current listings.... nothing changed. Iterative development: yes lots of variations and it helps at some level. But after all this time the contents of the magazines have the same covers. If you don't believe me go digg up some magz from the way past and see how you can copy and paste the text to the now.

This problem is not solvable on the IT end. We have been inventing new tools, processes, checklists, requirements analysis schemes, (business) use cases, development frameworks, BPM, SOA, you call it and still the same problem exists...

You need to optimize this around 'the requirements specifier'. So you need to give those people the adequate tools, whatever to enable them to bring their level higher:

So e.g. for these persons: spec patterns out of the box, input from other projects and companies doing the same copy their end-result requirements and lessons, get people in there who have been through the dirt and can help this person to specifiy the things that caused the greatest problems and are not "trivial" but can only be learned after doing it (e.g. senior technical consultants doing the same stuff at other companies), give these people requirements composer tooling, for insurance, banks, telco etc...: dont invent your own processes buy the generic processes out of the box, etc...  they NEED tools just like developer need tools and patterns and frameworks.

Does not solve it but improves it significantly IMHO the improvement should be around that area and not later down the road.

Just like a developer these persons just try to do the best they can. But unlike developers for their field most of the stuff we take for granted after 30 years is not even present in that field. In general their tools are outlook, excel, word and a board. Their processes are brainstorm sessions. A lot of improvement can be done in this field.
Ofcourse the problem is mostly that they are sitting "outside" IT so even plans from the CIO to improve the situation in that field fall on deaf ears... but that is another question: how to "sell" this.


答:
I think the first reason to go to a NoSQL or Distributed solution isn't so much the size of all the data, but the size of the tables. What distributed solutions do well is split up tables to different nodes then when you need to query the tables, each node will process their piece of the table.

RDBMSs can do this, but the new wave of NoSQL databases have been built to do this. Oracle, MSSQL, MySQL took their centralized model and tweaked it to make it work in a distributed environment. However they still adhere to strict ACID rules while some of the new databases do not adhere to the strict rules such as by using eventual consistency.

There isn't a set amount of data where you should choose one over the other. What needs to be taken into account are the needs of the database and the amount of use it receives. NoSQL databases can process larger data-sets more quickly while relational databases give you the confidence your data is correct with the ACID principles.

Title: At what size of data does it become beneficial to move from SQL to NoSQL?

Body:
As a relational database programmer (most of the time), I read articles about how relational databases don't scale, and NoSQL solutions such as MongoDB do.
As most of the databases I have developed so far have been small to mid scale, I have never had a problem that hasn't been solved by some indexing, query optimization or schema redesign.

What sort of size would I expect to see MySQL struggling with. How many rows?

(I know this is going to depend on the application, and type of data stored. the one that got me thing was basically a genetics database, so would have one main table, with 3 or 4 lookup tables. The main table will contain amongst other things, a chromosome reference, and a position coordinate. It will likely get queried for a number of entries between two potions on a chromosome, to see what is stored there).


问:
Pair programming business logic with a non-IT person
Have you had any experience in which a non-IT person works with a programmer during the coding process?

It's like pair programming, but one person is a non-IT person that knows a lot about the business, maybe a process engineer with math background who knows how things are calculated and can understand non-idiomatic, procedural code.

I've found that some procedural, domain-specific languages like PL/SQL are quite understandable by non-IT engineers. These persons end up being co-authors of the code and guarantee the correctness of formulas, factors, etc.

I've found this kind of pair programming quite productive, this kind of engineering-type users feel they are also "owners" and "authors" of the code and help minimize misunderstandings in the communication process. They even help design test cases.

Is this practice common?

Does it have a name?

Have you had any similar experiences?

答:
Yes. Where I work I do the hardcore programming type stuff, while strategists work on uhm strategy. That is to say I write the programs that implement their trading models.

The key to this is sitting right next to them and understanding exactly what the ideas are, and asking lots of questions about things which may be incidental to them, but important to the execution side. For instance I'd ask about how fast a trade needs to be executed, whether that affects their model. This has a huge impact on how I'll be writing the code. In fact I tend to spray questions into the room as we're sitting there working every day.

There's a two-way feedback. If I tell them some trading scheme is not going to be easy to build, they go back and have a think about which tradeoffs can be made on the decision making side. If they decide their new strategy needs some new feature, I have a chat with them about how long it would take to build and what the potential pitfalls are.

They do code modules that encapsulate some aspect of the trading strategy from time to time, but I massage the pieces together into an architecture that allows us to keep track of all the different strategies as well as backend operational stuff. That way they don't need to know the nitty-gritty of the system.


问:
Is it correct to fix bugs without adding new features when releasing software for system testing?
This question is to experienced testers or test leads.
This is a scenario from a software project:

Say the dev team have completed the first iteration of 10 features and released it to system testing. The test team has created test cases for these 10 features and estimated 5 days for testing. The dev team of course cannot sit idle for 5 days and they start creating 10 new features for next iteration. During this time the test team found defects and raised some bugs. The bugs are prioritised and some of them have to be fixed before next iteration. The catch is that they would not accept the new release with any new features or changes to existing features until all those bugs fixed. The test team says that's how can we guarantee a stable release for testing if we also introduce new features along with the bug fix. They also cannot do regression tests of all their test cases each iteration. Apparently this is proper testing process according to ISQTB.

This means the dev team has to create a branch of code solely for bug fixing and another branch where they continue development. There is more merging overhead specially with refactoring and architectural changes.

Can you agree if this is a common testing principle. Is the test team's concern valid. Have you encountered this in practice in your project.

答:
"Can you agree if this is a common testing principle.

```<code>Yes
</code>```

Is the test team's concern valid

```<code>Yes
</code>```

Have you encountered this in practice in your project."

```<code>Yes
</code>```

:

```<code>and Yes Merging is the downside of it
</code>```

You did not ask who's responsibility it is but it is the Configuration Manager's responsibility. This stream strategy should be in his CMP. Otherwise fire him/her.
I think the response from Pierre 303 is also very good but ofcourse where possible
technically (e.g. thinking of a Siebel release...) and organizationally.

Body:
"Can you agree if this is a common testing principle.

Yes

Is the test team's concern valid

Yes

Have you encountered this in practice in your project."

Yes

:

and Yes Merging is the downside of it

You did not ask who's responsibility it is but it is the Configuration Manager's responsibility. This stream strategy should be in his CMP. Otherwise fire him/her.
I think the response from Pierre 303 is also very good but ofcourse where possible
technically (e.g. thinking of a Siebel release...) and organizationally.


问:
Should I write an integration test that verifies rate limits?
This test would call a web service over and over for about a minute to confirm that a particular response code is returned, notifying us of our rate limit being reached. Not only is it a very slow test, it doesn't confirm much of anything, and wastes resources.

I feel that this is like confirming that chugging a bottle of vodka will kill a human. Do we really need a test for it?

答: If it's not increasing your confidence in some aspect of the system, drop it. (Also, +1 for "confirming that chugging a bottle of vodka will kill a human.")</p>


问:
Why is Quicksort called "Quicksort"?
The point of this question is not to debate the merits of this over any other sorting algorithm - certainly there are many other questions that do this.  This question is about the name.  Why is Quicksort called "Quicksort"?  Sure, it's "quick", most of the time, but not always.  The possibility of degenerating to O(N^2) is well known.  There are various modifications to Quicksort that mitigate this problem, but the ones which bring the worst case down to a guaranteed O(n log n) aren't generally called Quicksort anymore.  (e.g. Introsort).

I just wonder why of all the well-known sorting algorithms, this is the only one deserving of the name "quick", which describes not how the algorithm works, but how fast it (usually) is.  Mergesort is called that because it merges the data.  Heapsort is called that because it uses a heap.  Introsort gets its name from "Introspective", since it monitors its own performance to decide when to switch from Quicksort to Heapsort.  Similarly for all the slower ones - Bubblesort, Insertion sort, Selection sort, etc.  They're all named for how they work.  The only other exception I can think of is "Bogosort", which is really just a joke that nobody ever actually uses in practice.  Why isn't Quicksort called something more descriptive, like "Partition sort" or "Pivot sort", which describe what it actually does?  It's not even a case of "got here first".  Mergesort was developed 15 years before Quicksort.  (1945 and 1960 respectively according to Wikipedia)

I guess this is really more of a history question than a programming one.  I'm just curious how it got the name - was it just good marketing?

答:
I believe it's because, at the time it was invented, it was very much quicker than all (or, rather, most, as speed also depends heavily on the kind of data and in some cases other algorithm become much faster than quicksort) of the algorithms out there.

So yes, it's historical (I don't know precisely that history, however...)

But I agree that its name should instead contain a hint of the algorithm...

Title: Why is Quicksort called "Quicksort"?


答:
In 1962 research on sorting algorithms wasn't as far advanced as today and the computer scientist Tony Hoare found a new algorithm which was quicker than the other so he published a paper called Quicksort and as the paper was quoted the title stayed.

Quoting the abstract:

A description is given of a new method of sorting in the random-access store of a computer. The method compares very favourably with other known methods in speed, in economy of storage, and in ease of programming. Certain refinements of the method, which may be useful in the optimization of inner loops, are described in the second part of the paper.

Title: Why is Quicksort called "Quicksort"?

Body:
The point of this question is not to debate the merits of this over any other sorting algorithm - certainly there are many other questions that do this.  This question is about the name.  Why is Quicksort called "Quicksort"?  Sure, it's "quick", most of the time, but not always.  The possibility of degenerating to O(N^2) is well known.  There are various modifications to Quicksort that mitigate this problem, but the ones which bring the worst case down to a guaranteed O(n log n) aren't generally called Quicksort anymore.  (e.g. Introsort).

I just wonder why of all the well-known sorting algorithms, this is the only one deserving of the name "quick", which describes not how the algorithm works, but how fast it (usually) is.  Mergesort is called that because it merges the data.  Heapsort is called that because it uses a heap.  Introsort gets its name from "Introspective", since it monitors its own performance to decide when to switch from Quicksort to Heapsort.  Similarly for all the slower ones - Bubblesort, Insertion sort, Selection sort, etc.  They're all named for how they work.  The only other exception I can think of is "Bogosort", which is really just a joke that nobody ever actually uses in practice.  Why isn't Quicksort called something more descriptive, like "Partition sort" or "Pivot sort", which describe what it actually does?  It's not even a case of "got here first".  Mergesort was developed 15 years before Quicksort.  (1945 and 1960 respectively according to Wikipedia)

I guess this is really more of a history question than a programming one.  I'm just curious how it got the name - was it just good marketing?


答:
Part of why we test is to verify our assumptions that the code is working as designed. If you don't care about the results that this test is returning, it's not useful and you should throw it away.

Conversely, if you do care, and the results of the test help you to develop the best software you can, keep it.

The point of testing is to help deliver high quality code. If a particular test activity gets you closer to that goal, do it. If it doesn't, don't.

Title: Should I write an integration test that verifies rate limits?

Body:
This test would call a web service over and over for about a minute to confirm that a particular response code is returned, notifying us of our rate limit being reached. Not only is it a very slow test, it doesn't confirm much of anything, and wastes resources.

I feel that this is like confirming that chugging a bottle of vodka will kill a human. Do we really need a test for it?


问:
php templating with codeigniter
I am currently develop a website application in codeigniter, and I'd like to do something in PHP / CodeIgniter where I can make a common template for separate sections of the website.  I was thinking that I would keep the header / footer in a separate php files & include them separately.

The thing I'm not sure about is the content beneath the header and above the footer.  This website application will contain a lot of different pages, so I'm having a hard time figuring how what's the best way to do this.

答:
I always used to create systems with CodeIgniter and this template library: http://www.williamsconcepts.com/ci/codeigniter/libraries/template/

It's very simple to use and it can do a better job than yours used techniques like using only $this->load->view() method.

Title: php templating with codeigniter


答:
In this situation (assuming a 3rd party web service), I don't write the test that actually gets the service to return a rate-limited response.  Instead, I have a test that verifies the expected behavior when receiving the response.

Save a rate-limiting response from the service, and pass that response back rather than calling the actual web service.  Not only does the test run much faster, it can also run offline and will probably lead to a better code design.

In Java/Mockito-ish pseudo code it would look something like:

```<code>// pretend we are rate limited
when(client.callService()).thenReturn(RATE_LIMITED_RESPONSE);
// call the service
response = getResponse(client);
// decision based on rate limited response is correct
assertEquals(Status.RATE_LIMITED, response.getStatus());
</code>```

where getResponse() calls client.callService() and subsequently handles all of the logic based on the content of the response.

If you've already got a test like this, then the integration test is really only testing that the web service returns a rate-limited response in a format that you expect.

Body:
In this situation (assuming a 3rd party web service), I don't write the test that actually gets the service to return a rate-limited response.  Instead, I have a test that verifies the expected behavior when receiving the response.

Save a rate-limiting response from the service, and pass that response back rather than calling the actual web service.  Not only does the test run much faster, it can also run offline and will probably lead to a better code design.

In Java/Mockito-ish pseudo code it would look something like:

// pretend we are rate limited
when(client.callService()).thenReturn(RATE_LIMITED_RESPONSE);
// call the service
response = getResponse(client);
// decision based on rate limited response is correct
assertEquals(Status.RATE_LIMITED, response.getStatus());

where getResponse() calls client.callService() and subsequently handles all of the logic based on the content of the response.

If you've already got a test like this, then the integration test is really only testing that the web service returns a rate-limited response in a format that you expect.


答:
Something I use most of the time, is just three (or more) views in the controller, like this:

```<code>class Mycontroller extends CI_Controller {
    public function index() {
        $headerData['title'] = 'Title of the page';
        $yourData['content'] = 'Everything you want to do inside your controller';

        $this->load->view('template/header',$headerData);
        $this->load->view('template/page',$yourData);
        $this->load->view('template/footer');
    }
}
</code>```

This way you can also set, for example, a title in your header file.

edit: you can extend this with, for example, menu views or something to keep things even more seperated. Just make sure that you load the views in correct order.

Title: php templating with codeigniter

Body:
I am currently develop a website application in codeigniter, and I'd like to do something in PHP / CodeIgniter where I can make a common template for separate sections of the website.  I was thinking that I would keep the header / footer in a separate php files & include them separately.

The thing I'm not sure about is the content beneath the header and above the footer.  This website application will contain a lot of different pages, so I'm having a hard time figuring how what's the best way to do this.

Body:
Something I use most of the time, is just three (or more) views in the controller, like this:

class Mycontroller extends CI_Controller {
    public function index() {
        $headerData['title'] = 'Title of the page';
        $yourData['content'] = 'Everything you want to do inside your controller';

        $this->load->view('template/header',$headerData);
        $this->load->view('template/page',$yourData);
        $this->load->view('template/footer');
    }
}

This way you can also set, for example, a title in your header file.

edit: you can extend this with, for example, menu views or something to keep things even more seperated. Just make sure that you load the views in correct order.


问:
Why not have a High Level Language based OS? Are Low Level Languages more efficient?
Without being presumptuous, I would like you to consider the possibility of this.
Most OS today are based on pretty low level languages (mainly C/C++)
Even the new ones such as Android uses JNI & underlying implementation is in C

In fact, (this is a personal observation) many programs written in C run a lot faster than their high level counterparts (eg: Transmission (a bittorrent client on Ubuntu) is a whole lot faster than Vuze(Java) or Deluge(Python)). Even python compilers are written in C, although PyPy is an exception.

So is there a particular reason for this? Why is it that all our so called "High Level Languages" with the great "OOP" concepts can't be used in making a solid OS?

So I have 2 questions basically.

Why are applications written in low level languages more efficient than their HLL counterparts? Do low level languages perform better for the simple reason that they are low level and are translated to machine code easier?

Why do we not have a full fledged OS based entirely on a High Level Language?

答:
First, there are some bootstrap issues.  Most of the features that make high level languages easier are based on abstractions that a kernel must provide itself.  How do you write a memory manager in a language that requires a memory manager?  How do you write I/O drivers without using the nice I/O standard libraries of your language?  How do you create threading and synchronization primitives without using the language's libraries?

Second, it's extremely useful and much more readable when writing operating systems to be able to assign a variable to a specific memory location.  This is easy in C, and every single C programmer knows how to do it.  If it's even possible in higher level languages, it's so rare that only gurus know how to do it.

In other words, when you account for all the limitations and modifications you would have to accept, C and C++ start looking a lot easier.


问:
HTML Canvas: Should my app x, y values be global?
I have a large file of functions. Each of these functions is responsible for drawing a particular part of the application. My app has x and y parameters that I use in the setup function to move the whole app around in order to try different placements. So, naturally, I need to use these x and y values to anchor each function's component rendering so that everything moves in unison if the global x,y values ever change.

My question is, is it bad practice/architecture to have these x,y values in the global namespace and having the each function directly access them like so?

```<code>function renderFace() {
   var x = App.x;
   var y = App.y;

   // drawing here
}
</code>```

is there a better way i'm missing?

答:
...is it bad practice/architecture to have these x,y values in the global namespace... like so?

In your code, your x and y aren't in the global namespace; they're properties of App. That's a good start: you're using App.x instead of window.x.

That said, App and renderFace are coupled: you can't apply the functional behavior of renderFace to anything but the values of App.x/y. If you want to reduce coupling to make renderFace more general, it might be better to have renderFace accept x and y as arguments:

```<code>function renderFace(x, y) {
   // drawing here
}
</code>```

and have some invoking code call renderFace(App.x, App.y) instead of just renderFace().

Alternatively, make your render functions actual methods of App and refer to the properties using this.

```<code>var App = {
    x: 0,
    y: 0,

    renderFace: function() {
        var x = this.x;
        var y = this.y;

        // drawing here
    }
}
</code>```

By having App "own" renderFace as a method, it indicates logically that renderFace is a behavior of App.

When someone reading your code sees renderFace(), they might not know it depends on the state of App. When they see App.renderFace() or renderFace(App.x, App.y) the relationship is explicitly clear. Furthermore, by moving the identifer App out of your function, it's easy to re-use renderFace in other non-App contexts later.

Body:
...is it bad practice/architecture to have these x,y values in the global namespace... like so?

In your code, your x and y aren't in the global namespace; they're properties of App. That's a good start: you're using App.x instead of window.x.

That said, App and renderFace are coupled: you can't apply the functional behavior of renderFace to anything but the values of App.x/y. If you want to reduce coupling to make renderFace more general, it might be better to have renderFace accept x and y as arguments:

function renderFace(x, y) {
   // drawing here
}

and have some invoking code call renderFace(App.x, App.y) instead of just renderFace().

Alternatively, make your render functions actual methods of App and refer to the properties using this.

var App = {
    x: 0,
    y: 0,

    renderFace: function() {
        var x = this.x;
        var y = this.y;

        // drawing here
    }
}

By having App "own" renderFace as a method, it indicates logically that renderFace is a behavior of App.

When someone reading your code sees renderFace(), they might not know it depends on the state of App. When they see App.renderFace() or renderFace(App.x, App.y) the relationship is explicitly clear. Furthermore, by moving the identifer App out of your function, it's easy to re-use renderFace in other non-App contexts later.


问:
How should modules access data outside their scope?
I run into this same problem quite often. First, I create a namespace and then add modules to this namespace. Then issue I always run into is how best to initialize the application? Naturally, each module has its own startup procedure so should this data(not code in some cases, just a list of items to run) stay with the module? Or should there be a startup procedure in the global namespace which has the startup data for ALL the modules.

Which is the more robust way of organizing this situation? Should some things be made centralized or should there be strict adherence to modules encapsulating everything about themselves?

Though this is a general architecture questions, Javascript centric answers would be really appreciated!

答:
Some data/scope is always given for any module, because they all run as part of the same application. It doesn't make sense to let every module load this for itself.

But if you distribute aliases for the data between modules, you can get into trouble. (Race conditions etc.). So be careful.


答:
My approach would be to make the rate limit configurable on the fly through some mechanism. And now your integration test can test both behaviors by lowering the rate substantially, and then exceeding it.

Configurable rate limits may or may not prove to be independently useful.  But I think it is important to be able to sanely test that the safeguards you are depending on are actually there.


答: I believe that it was originally called Hoare Sort after the inventor but the name got changed  fairly early due to Hoare sounding a little to close to whore in English. As to why they chose "quick" instead of something else, I'm not sure.</p>

Title: Why is Quicksort called "Quicksort"?


答:
First of all, bootstrapping requires at least a small part to be written in Assembly or equivalent.

Second, there was a OS written in an indisputably HLL - Lisp Machine.
(The fact that it failed commercially had more to do with other hardware becoming cheaper faster and the triumph of Worse is Better than with deficiencies of its philosophy or design).

Third, C++ is quite object-oriented and high level, so, as others pointed out, Symbian OS is another example.

Fourth, there is little need for new OSes at this time. We already have quite a few linux and bsd flavors which run on just about any hardware, and creating a brand new OS from scratch is quite expensive.

Title: Why not have a High Level Language based OS? Are Low Level Languages more efficient?

Body:
Without being presumptuous, I would like you to consider the possibility of this.
Most OS today are based on pretty low level languages (mainly C/C++)
Even the new ones such as Android uses JNI & underlying implementation is in C

In fact, (this is a personal observation) many programs written in C run a lot faster than their high level counterparts (eg: Transmission (a bittorrent client on Ubuntu) is a whole lot faster than Vuze(Java) or Deluge(Python)). Even python compilers are written in C, although PyPy is an exception.

So is there a particular reason for this? Why is it that all our so called "High Level Languages" with the great "OOP" concepts can't be used in making a solid OS?

So I have 2 questions basically.

Why are applications written in low level languages more efficient than their HLL counterparts? Do low level languages perform better for the simple reason that they are low level and are translated to machine code easier?

Why do we not have a full fledged OS based entirely on a High Level Language?


问:
should I create a new class for a specific piece of business logic?
I have a Request class based on the same Entity in my Domain.   It currently only has property definitions.  I'd like to add a method for checking a duplicate Request which I'll call from my controller.  Should I add a method called CheckDuplicate in the Request class?  Would I be violating the SRP?  The method will need to access a database context to check already existing requests.  I'm thinking creating another class altogether for this logic that accepts a datacontext as part of its constructor.  But creating a whole new class for just one method seems like a waste too.  Any advice?</p>

答: As per the question, you just need to validate if the entry is a duplicate? If thats the case that is like validation, so you can go ahead and create a method isValid() or isDuplicate() which would return a boolean value on checking the validations that you have.</p>


问:
Why is an anemic domain model considered bad in C#/OOP, but very important in F#/FP?
In a blog post on F# for fun and profit, it says:

In a functional design, it is very important to separate behavior from
  data. The data types are simple and "dumb". And then separately, you
  have a number of functions that act on those data types.

This is the exact opposite of an object-oriented design, where
  behavior and data are meant to be combined. After all, that's exactly
  what a class is. In a truly object-oriented design in fact, you should
  have nothing but behavior -- the data is private and can only be
  accessed via methods.

In fact, in OOD, not having enough behavior around a data type is
  considered a Bad Thing, and even has a name: the "anemic domain
  model".

Given that in C# we seem to keep borrowing from F#, and trying to write more functional-style code; how come we're not borrowing the idea of separating data/behavior, and even consider it bad? Is it simply that the definition doesn't with with OOP, or is there a concrete reason that it's bad in C# that for some reason doesn't apply in F# (and in fact, is reversed)?

(Note: I'm specifically interested in the differences in C#/F# that could change the opinion of what is good/bad, rather than individuals that may disagree with either opinion in the blog post).

答:
The main reason FP aims for this and C# OOP does not is that in FP the focus is on referential transparency; that is, data goes into a function and data comes out, but the original data is not changed.

In C# OOP there's a concept of delegation of responsibility where you delegate an object's management to it, and therefore you want it to change its own internals.

In FP you never want to change the values in an object, therefore having your functions embedded in your object doesn't make sense.

Further in FP you have higher kinded polymorphism allowing your functions to be far more generalized than C# OOP allows. In this way you may write a function that works for any a, and therefore having it embedded in a block of data doesn't make sense; that would tightly couple the method so that it only works with that particular kind of a. Behaviour like that is all well and common in C# OOP because you don't have the ability to abstract functions so generally anyway, but in FP it's a tradeoff.

The biggest problem I've seen in anemic domain models in C# OOP is that you end up with duplicate code because you have DTO x, and 4 different functions that commits activity f to DTO x because 4 different people didn't see the other implementation. When you put the method directly on DTO x, then those 4 people all see the implementation of f and reuse it.

Anemic data models in C# OOP hinder code reuse, but this isn't the case in FP because a single function is generalized across so many different types that you get greater code reuse since that function is usable in so many more scenarios than a function you would write for a single DTO in C#.

As pointed out in comments, type inference is one of the benefits FP relies on to allow such significant polymorphism, and specifically you can trace this back to the Hindley Milner type system with Algorithm W type inference; such type inference in the C# OOP type system was avoided because the compilation time when constraint-based inference is added becomes extremely long due to the exhaustive search necessary, details here: https://stackoverflow.com/questions/3968834/generics-why-cant-the-compiler-infer-the-type-arguments-in-this-case


答:
Most of the higher-level languages that you mention have a feature that doesn't fit well with operating systems: Automatic memory management. You can't rely on a garbage collector when writing a real-time system -- either soft (which is what an operating system is) or even worst hard. To quote Tanenbaum [i]:

Some things that C does not have include built-in strings, threads, packages, classes, objects, type safety, and garbage collection. The last one is a show stopper for operating systems. All storage in C is either static or explicitly allocated and released by the programmer, usually with the library function malloc and free. It is the latter property -- total programmer control over memory -- along with explicit pointers that makes C attractive for writing operating systems. Operating systems are basically real-time systems to some extent, even general purpose ones. When an interrupt occurs, the operating system may have only a few microseconds to perform some action or lose critical information. Having the garbage collection kick in at an arbitrary moment is intolerable.

Now, you might argue that C++ is also a good candidate since it offers manual memory management. C++ has already been used in some operating systems such as Symbian (mentioned by Bart) and BeOS. But IMHO C is still the fastest language that can be ported in many architectures without a huge effort (in contrast to assembly of a specific architecture).

[i]: Modern Operating Systems 3rd edition, page 73


问:
Version control and personal configuration file
Our project uses a user-specific configuration file. This file is currently not in version control, since it is different for each user. The problem is, whenever a developer adds a new module that requires configuration, or changes the name of an existing modules, the other developers get errors because their private configuration files are not updated.

To solve the problem, we thought of working with two configuration files: a default/global configuration file that will be in version control and will be updated regularly by each developer that adds a new module, and a private configuration file that will be kept out of version control and will contain only the user-specific changes.

However, this still seems like an ad-hoc solution.

Can you propose a better solution?

What do the professionals do?

答:
This is a useful solution based on the post: Keeping passwords in source control

In summary the strategy is to "keep an encrypted version of the configuration file in source control and then provide a means through which the user can encrypt and decrypt that data."

Create a dummy comfig file and .gitignore it.

Create a makefile that can encrypt and decrypt the config file

Store the makefile and the encrypted config file in the repository

The makefile asks for a password, and how to contact the author for the password.

When building the project, if the makefile has not run, advise the user with
console.error("Config file [conf/settings.json] missing! Did you forget to run make decrypt_conf?");

A check is described to ensure the config file is up to date.


答:
If relational databases don't scale, nothing does.  Don't worry about scaling problems.

SQL has problems with some sorts of analysis, but it doesn't take much data to trigger the problem.  For example, consider a single table with a column that references other rows based on a unique key.  Typically, this might be used to create a tree structure.  You can write fast SQL statements that reference the related row.  Or the related row's related row.  In fact you can make any specific number of jumps.  But if, for each row, you want to select a field on the first related row in the chain that meets some criterion, then it gets complicated.

Consider a table of office locations at nation, province/state, county, town, and village levels, with each office referencing the office it reports to.  There is no guarantee that each office's reporting office is only one level up.  For a selected set of offices, not all on one level, you want to list each one's associated national office.  This requires loops of SQL statments and will take a long time even today.  (I used to get 30 seconds on a selection of 30 offices, but that was a long time ago--and switching to stored procedures helped a bit.)

So the alternative is to put the whole structure into one big block of data, label it, and store it.  When you want to analyze the data, read all of it into memory at one go, setting up pointers to track the structure, and you can process a couple million offices in the blink of an eye.

None of this has much to do with the amount of data.  The key is the nature of the data's organization.  If a relational layout helps, then a RDBMS is what you want.  If not, some kind of bulk storage is going to be anything from slightly to a quadrillion times faster.

Note that if one of these sets of data becomes too big to fit into memory, your non-SQL database doesn't work any more.  Another problem is when you need data from more than one block at a time; you can do this if, and only if, all the blocks fit in memory at once.  And the user has to wait while you load them up.

If your relational database is going to cause you problems, it will do so before you've put much data into it.  The only scaling problem you might have is with your program when the block of data you are assembling for a nosql DB--if you have to use one--becomes too big for it.  (Do read up on out-of-memory errors.  The newer languages sometimes do strange things with memory.)


答:
As others have pointed out, several operating systems have been written in high level languages. Perhaps what you mean is that all the successful, mass market, general purpose OS have been written in some combination of assembly, C, and C++?

Most high level languages have tons of helpful features that carry an associated performance cost. Automated memory management is an obvious example, bounds checking of arrays is another. If you are writing a general purpose OS you are likely to run into situations where the performance penalty of these helpful features is more than you are willing to pay. At that point you'd like to be able to turn them off. Languages like Python, C#, and Java vary in which features you can turn off, but none of them are as versatile as C or C++ in this regard.

In this aspect C and C++ are almost as versatile as pure assembly. If you decide that you need ten different memory managers covering ten different memory allocation scenarios you can implement them all in C and C++, and load and unload them as you see fit. Heck, you don't even have to link to the standard C runtime libraries or startup code if you don't want to.


问:
Naming conventions used for variables and functions in C
While coding a large project in C I came upon a problem. If I keep on writing more code then there will be a time when it will be difficult for me to organize the code. I mean that the naming for functions and variables for different parts of the program may seem to be mixed up.

So I was thinking whether there are useful naming conventions that I can use for C variables and functions?

Most languages suggest a naming convention. But for C the only thing I have read so far is the names should be descriptive for code readability.

EDIT:

Examples of some examples of suggested naming conventions:

Python's PEP 8

Java Tutorial

I read some more naming conventions for java somewhere but couldn't remember where.

答:
In my opinion 90% of the naming problem is solved if you keep three things in mind: a) make your variable and function names as descriptive as possible,  b) be consistent throughout your code (i.e., if a function is named addNumbers, a second function should be named multiplyNumbers and not numbersMul) and c) try to make the names short if possible, as we need to type them.

That being said if you want to take a look at other aspects on this topic the Wikipedia page on Naming Conventions has a good list of things you should keep in mind. It also has a secion on C and C++:

In C and C++, keywords and standard library identifiers are mostly
lowercase. In the C standard library, abbreviated names are the most
common (e.g. isalnum for a function testing whether a character is
alphanumeric), while the C++ standard library often uses an underscore
as a word separator (e.g. out_of_range). Identifiers representing
macros are, by convention, written using only upper case letters and
underscores (this is related to the convention in many programming
languages of using all-upper-case identifiers for constants). Names
containing double underscore or beginning with an underscore and a
capital letter are reserved for implementation (compiler, standard
library) and should not be used (e.g. reserved__ or _Reserved).[5][6]
This is superficially similar to stropping, but the semantics differ:
the underscores are part of the value of the identifier, rather than
being quoting characters (as is stropping): the value of __foo is
__foo (which is reserved), not foo (but in a different namespace).


答:
I'd go ahead and create it.

As you mentioned, adding a new responsibility to what's currently a DTO would violate the SRP.  The question arises, what happens when the next requirement comes along?  Would you add another method?  What happens when you add a new attribute to the DTO?  Would that necessary change add the risk of messing up your duplicate checking logic?  Part of the idea of the SRP is that there should only be one reason to modify your class.

Moreover, a DuplicateChecker may turn out to be useful for other domain classes as you move forward.

It's not like classes are particularly expensive.

Title: should I create a new class for a specific piece of business logic?

Body: I have a Request class based on the same Entity in my Domain.   It currently only has property definitions.  I'd like to add a method for checking a duplicate Request which I'll call from my controller.  Should I add a method called CheckDuplicate in the Request class?  Would I be violating the SRP?  The method will need to access a database context to check already existing requests.  I'm thinking creating another class altogether for this logic that accepts a datacontext as part of its constructor.  But creating a whole new class for just one method seems like a waste too.  Any advice?</p>


问:
Tabs versus spaces—what is the proper indentation character for everything, in every situation, ever?
The coding standards for the code hosted in drupal.org suggest to use two spaces to indent the code; other sites suggest to use tabs to indent the code.

What is the proper indentation character for everything, and in every situation? Please explain the answer you give.

答:
Why can't someone implement this:

code is stored in a compact format beneficial to the system in question

as each dev opens the code, it is formatted exactly how they want it

when they have finished with it, back to the compact format

Everyone is happy as they all see their 'own' format

Is that so difficult?


答:
Few important things to be considered while naming would be;

Look upon the actionObject or ObjectAction type.(Object Not for C. But in general when you go to other Object Oriented Languages)
This should help

Rest would be BE CONSISTENT, short and descriptive for sure.

Also, have a sole purpose of every variable and function defined,
Eg: If its to store a value temporarily, name it as nTempVal for int

Variables should be noun and Methods should be verb.

Title: Naming conventions used for variables and functions in C

Body:
While coding a large project in C I came upon a problem. If I keep on writing more code then there will be a time when it will be difficult for me to organize the code. I mean that the naming for functions and variables for different parts of the program may seem to be mixed up.

So I was thinking whether there are useful naming conventions that I can use for C variables and functions?

Most languages suggest a naming convention. But for C the only thing I have read so far is the names should be descriptive for code readability.

EDIT:

Examples of some examples of suggested naming conventions:

Python's PEP 8

Java Tutorial

I read some more naming conventions for java somewhere but couldn't remember where.


答:
The only hard constraint in C is that there are no namespaces. Therefore, you have to find a way to make the rename() function of your filesystem library distinct from the rename() function of your media library. The usual solution is a prefix, such as: filesystem_rename() and media_rename().

The other general advice is: stay consistent within a project or a team. Readability will be improved.


问:
Best alternative of Property file in Java
Hey I an working on the product which is live at multiple portals. The product is developed in GWT, JAVA, Hibernate.

My question is : Whether there is any alternative of using property file in java.

My Requirement :

For one property key there are multiple values in live portal for each different portal.

Each time I change property file, I need to make the war again.

The loading of any of the property should not be time-consuming.

Any help or suggession would be apprecialble !!!

答:
One option is store your configuration in a data base. This way you can change properties on the fly.

You don't actually have to install something like MySQL or PostgreSQL, you can use something really minimal such as SQLite or H2.

You can also employ a JMX bean and you can modify it also on the fly.


答:
I find that JSON files mapped to my own classes does wonders.  A few annotations are usually all that's needed to tell the JSON libs how to serialize the class.  Outside of this you pretty much live in your code for the rest of the time and get all the benefits of it (refactors, compiler checks, code complete etc).

If you require more strict format and validation of the files then I go for XML by first creating an XSD.  Then through JAXB generate the classes, from then on it's the same deal as JSON above.  Bit more involved though, only go this route if you require exchanging the data in these files with system that naturally "speak" XML or if you need a strict validation but dont want to spend the time doing it manually.

Yaml can make a pretty good candidate for config.  I tried it recently in a python project and I must say it was really nice !  Not sure what the Java yaml work is like though but I would be very surprised if one could not find a good resource to deal with the yaml format.

Title: Best alternative of Property file in Java

Body:
Hey I an working on the product which is live at multiple portals. The product is developed in GWT, JAVA, Hibernate.

My question is : Whether there is any alternative of using property file in java.

My Requirement :

For one property key there are multiple values in live portal for each different portal.

Each time I change property file, I need to make the war again.

The loading of any of the property should not be time-consuming.

Any help or suggession would be apprecialble !!!


问:
Why can't `main` return a double or String rather than int or void?
In many languages such as C, C++, and Java, the main method/function has a return type of void or int, but not double or String.   What might be the reasons behind that?

I know a little bit that we can't do that because main is called by runtime library and it expects some syntax  like int main() or int main(int,char**) so we have to stick to that.

So my question is:  why does main have the type signature that it has, and not a different one?

答:
The return value of main is to be passed to the operating system (any operating system) in a single, consistent way.  The information that the operating system needs to know is "did the program terminate successfully, or was there an error?"

If this is a string, the response becomes difficult in different languages.  The internals of a Pascal string (first byte is length) and a FORTRAN string (fixed, padded to some value) and a C string (null terminated) are all different.  This would make returning a consistent value to the operating system challenging.  Assuming that this was solved, what would you do to answer the question the OS had of the program?  String comparisons are fraught with errors ("success" vs "Success"), and while the error may be more useful to a human, it is more difficult for the operating system or another program (shell) to deal with.  There also were significant differences even in the strings themselves -- EBCDIC (with all of its code pages) vs. ASCII.

Floats and doubles provide no additional value over the integer for communicating back data to the OS (and shell).  For the most part, neither of these parts of the computer deal with floating point numbers.  Doubles are also not enumerable making comparisons difficult.  Not being enumerable, they make reporting what the error was (assuming you have picked a particular value for success).  Again, floating points are not consistent - a float on an 8 bit machine was different than the float on a 16 bit and a 32 bit machine (and those are just the 'normal' ones - even within IBM, floating point wasn't standardized between machines by the same manufacturer until the 1980's).  And then you've got decimal vs. binary computers.  Floating point values aren't consistent and don't provide meaningful data back.

That really leaves us with the byte and integer as options.  The convention that was established was '0' was success, and anything else was an error.  An integer gives more room than a byte for reporting the error.  It can be enumerated (return of 1 means XYZ, return of 2 means ABC, return of 3, means DEF, etc..) or used as flags (0x0001 means this failed, 0x0002 means that failed, 0x0003 means both this and that failed).  Limiting this to just a byte could easily run out of flags (only 8), so the decision was probably to use an integer.


答: The value returned by the main method is an "exit code". It's used by the caller application (normally bash) to test if the program ended as expected. Returning an integer is the easiest way to do it on the OS level. Double makes no sense for error code and a String is hard to maintain in OS level (there is no GC).</p>

Title: Why can't `main` return a double or String rather than int or void?

Body:
In many languages such as C, C++, and Java, the main method/function has a return type of void or int, but not double or String.   What might be the reasons behind that?

I know a little bit that we can't do that because main is called by runtime library and it expects some syntax  like int main() or int main(int,char**) so we have to stick to that.

So my question is:  why does main have the type signature that it has, and not a different one?


问:
How do you deal with over-the-head APIs/technology
I guess most people have been in this situation.

The initial project planning begins. The requirements are outlined. After architectural review and sorting through APIs/Frameworks the fitting technology is picked. The development starts.

And then it starts. As soon as you need to do some supposedly simple supporting things, framework/API start to backfire, and instead of doing any work you end up fighting against the technology. The research time skyrockets, forums are silent, nothing seems to be done, and even when you get something to work, you're not really sure it's done right.

How do you manage in these situations? Do you go for hacks, do you research further, what do you say to management?

答:
"How do you manage in these situations?". What I have seen / experienced:

the number 1 point I agree with Ptolemy: be honest:

If it is really a problem: go to that room, tell the problem, sit back to await the anger response and then ... work towards a new plan/solution. (the guy is not angry at you personally).

There are IT courses which deal only with this situation. You are placed with actors and they place the angry client who hears this news. You get a lot of tips around it. Sounds stupid but probably only after doing it you notice the value of it. I left with a sheet with 80 points to remember in those situations... (and practice).

This situation is typical probably even more so today where budgets are tight, sales are done on "lowest offer", the planning you gave is trimmed 5 times before it is accepted by the customer... (including that prototype since "he is hiring you because you are the expert and otherwise it is 10 others waiting") etc...

--
Another thing might be lateral thinking: if it can not be done in this way try to propose something completely different that provides the same value for the customer. If the technology does not work AT ALL / is broke / jumps out of the deal / etc... If the customer buys in to this it can deliver the same value at the end. But bringing it is also pretty hard. (for some and totally not for others). You need the really experienced guys for this. A likewise situation is that the Technology is NOT YET up to it... it takes some months... So you need to convince to customer to replan and accept the replanning and impact on his organization...

-- Another 'lesson learned' is to invoke the senior senior guys as soon as you notice that it goes in this direction. They often have dealt with troubled projects and are really helpful in these situations. Often they only travel from troubled project to troubled project.

-- Another lesson learned is to let your architectural stuff go through verification channels especially on the bigger projects. A signature can cover your ass. (save all your e-mails LOL)


答:
We use XML and save configuration files in external resources (out of war/jar).

The configuration loading should not be a problem (even if you save it in database), because you don't load it frequently (don't you?). If you need update the configuration runtime, you can use file monitor API to get notified when file changed, or just a timer loop to pull data.


答:
If I keep on writing more code then there will be a time when it will be difficult for me to organize the code.

This is your problem: get the organisation right, and the style should flow more easily.

Don't wait to organise your code: keep your code organised as you go. Although the language doesn't do it for you, code should still be organised into modules with low coupling and high cohesion.

These modules then naturally provide a namespace. Abbreviate the module name (if it is long) and prefix function names with their module to avoid collisions.

At the level of individual identifiers, these are roughly in increasing order of subjectivity:

pick a convention and stick with it

eg, function_like_this(struct TypeLikeThis variable) is common

definitely avoid Hungarian notation (sorry JNL)

unless you're willing to use it as originally intended, which means Simonyi's apps notation rather than the terrible systems version

Why? I could write an essay about this, but I'll instead suggest you read this article by Joel Spolsky, and then hunt around some more if you're interested. There's a link to Simonyi's original paper at the bottom.

avoid pointer typedefs unless they're genuinely opaque cookie types - they only confuse things

```<code>struct Type *ok;
typedef struct Type *TypePtr;
TypePtr yuck;
</code>```

What do I mean by an opaque cookie type? I mean something used inside a module (or library, or whatever) which has to be passed out to client code, but that client code can't use directly. It just passes it back to the library.

For example, a database library might expose an interface like

```<code>/* Lots of buffering, IPC and metadata magic held in here.
   No, you don't get to look inside. */
struct DBContextT;
/* In fact, you only ever get a pointer, so let's give it a nice name */
typedef struct DBContexT *DBContext;

DBContext db_allocate_context(/*maybe some optional flags?*/);
void db_release_context(DBContext);
int db_connect(DBContext, const char *connect);
int db_disconnect(DBContext);
int db_execute(DBContext, const char *sql);
</code>```

Now, the context is opaque to the client code, because you can't look inside. You just pass it back to the library. Something like FILE is also opaque, and an integer file descriptor is also a cookie, but isn't opaque.

A note on design

I used the phrase low coupling and high cohesion above without explanation, and I feel a bit bad about that. You can search for it, and probably find some good results, but I'll try to address it briefly (again, I could write an essay but will try not to).

The DB library sketched above shows low coupling because it exposes a small interface to the outside world. By hiding its implementation details (partly with the opaque cookie trick), it prevents client code coming to depend on those details.

Imagine instead of the opaque cookie, we declare the context struct so its contents are visible, and that includes a socket file descriptor for a TCP connection to the database. If we subsequently change the implementation to support using a shared memory segment when the DB is running on the same machine, the client needs to be re-compiled rather than just re-linked. Even worse, the client could have started using the file descriptor, for example calling setsockopt to change the default buffer size, and now it needs a code change as well. All these details should be hidden inside our module where practical, and this gives low coupling between modules.

The example also shows high cohesion, in that all the methods in the module are concerned with the same task (DB access). This means that only the code that needs to know about the implementation details (that is, the contents of our cookie) actually have access to them, which simplifies debugging.

You can also see that having a single concern made it easy to choose a prefix to group these functions together.

Now, saying this example is good is easy (especially since it isn't even complete), but doesn't immediately help you. The trick is to watch, as you write and extend your code, for functions that do similar things or operate on the same types (which might be candidates for their own module), and also for functions that do lots of separate things that aren't really related, and might be candidates for splitting up.

Body:
If I keep on writing more code then there will be a time when it will be difficult for me to organize the code.

This is your problem: get the organisation right, and the style should flow more easily.

Don't wait to organise your code: keep your code organised as you go. Although the language doesn't do it for you, code should still be organised into modules with low coupling and high cohesion.

These modules then naturally provide a namespace. Abbreviate the module name (if it is long) and prefix function names with their module to avoid collisions.

At the level of individual identifiers, these are roughly in increasing order of subjectivity:

pick a convention and stick with it

eg, function_like_this(struct TypeLikeThis variable) is common

definitely avoid Hungarian notation (sorry JNL)

unless you're willing to use it as originally intended, which means Simonyi's apps notation rather than the terrible systems version

Why? I could write an essay about this, but I'll instead suggest you read this article by Joel Spolsky, and then hunt around some more if you're interested. There's a link to Simonyi's original paper at the bottom.

avoid pointer typedefs unless they're genuinely opaque cookie types - they only confuse things

struct Type *ok;
typedef struct Type *TypePtr;
TypePtr yuck;

What do I mean by an opaque cookie type? I mean something used inside a module (or library, or whatever) which has to be passed out to client code, but that client code can't use directly. It just passes it back to the library.

For example, a database library might expose an interface like

/* Lots of buffering, IPC and metadata magic held in here.
   No, you don't get to look inside. */
struct DBContextT;
/* In fact, you only ever get a pointer, so let's give it a nice name */
typedef struct DBContexT *DBContext;

DBContext db_allocate_context(/*maybe some optional flags?*/);
void db_release_context(DBContext);
int db_connect(DBContext, const char *connect);
int db_disconnect(DBContext);
int db_execute(DBContext, const char *sql);

Now, the context is opaque to the client code, because you can't look inside. You just pass it back to the library. Something like FILE is also opaque, and an integer file descriptor is also a cookie, but isn't opaque.

A note on design

I used the phrase low coupling and high cohesion above without explanation, and I feel a bit bad about that. You can search for it, and probably find some good results, but I'll try to address it briefly (again, I could write an essay but will try not to).

The DB library sketched above shows low coupling because it exposes a small interface to the outside world. By hiding its implementation details (partly with the opaque cookie trick), it prevents client code coming to depend on those details.

Imagine instead of the opaque cookie, we declare the context struct so its contents are visible, and that includes a socket file descriptor for a TCP connection to the database. If we subsequently change the implementation to support using a shared memory segment when the DB is running on the same machine, the client needs to be re-compiled rather than just re-linked. Even worse, the client could have started using the file descriptor, for example calling setsockopt to change the default buffer size, and now it needs a code change as well. All these details should be hidden inside our module where practical, and this gives low coupling between modules.

The example also shows high cohesion, in that all the methods in the module are concerned with the same task (DB access). This means that only the code that needs to know about the implementation details (that is, the contents of our cookie) actually have access to them, which simplifies debugging.

You can also see that having a single concern made it easy to choose a prefix to group these functions together.

Now, saying this example is good is easy (especially since it isn't even complete), but doesn't immediately help you. The trick is to watch, as you write and extend your code, for functions that do similar things or operate on the same types (which might be candidates for their own module), and also for functions that do lots of separate things that aren't really related, and might be candidates for splitting up.


问:
Concept of bit fields
Whenever I read a code like this:

```<code>  struct node
  {
          int x : 2;
          int p : 4;
   }n;
</code>```

with bit fields involved, I get really confused, as to how they are represented in memory, what is sizeof(n) etc., how does it differ with normal members of structures? I tried referring K&R and http://en.wikipedia.org/wiki/Bit_field but they little to remove my confusion. What concepts of bit fields am I failing to grasp?

答:
sizeof reports in units of bytes, so it is not well behaved for bit fields.

C doesn't have a clear standard how bit fields have to be laid out, and in general, you should be extremely cautious about any assumptions, especially if different platforms or
different compilers may come into play.

I usually use manual packing/unpacking schemes, but hide the details in acessor
functions, in those rare circumstances where packing information into integers
at the level of bits is appropriate.  The only case where the layout of bit fields
absolutely does matter is writing drivers for hardware.

Title: Concept of bit fields


答:
Well, it could.

For example, in the dialect of C used in the Plan 9 operating system main is normally declared as a void function, but the exit status is returned to the calling environment by passing a string pointer to the exits() function. The empty string denotes success, and any non-empty string denotes some kind of failure. This could have been implemented by having main return a char* result.

And it would certainly be possible to implement a system with a float or double exit status.

So why int? It's just a matter of convention -- and there's a tremendous value in having operating systems and programs that run under them obey a common convention.

The Unix convention is to use an integer status code, with 0 denoting success and non-zero denoting failure (because typically there's only one way to succeed, but multiple ways to fail). I don't know whether that convention originated with Unix; I suspect it came from earlier operating systems.

Floating-point would be a more difficult convention, because (a) floating-point support is not universal, (b) it's more difficult to define a mapping between floating-point values and error conditions, (c) different systems use different floating-point representations, and (d) just imagine the fun of tracking down a rounding error in your program's exit status. Integers, on the other hand, lend themselves very well to enumerating error codes.

Plan 9, as I mentioned, uses strings, but that imposes some complexity for memory management, character encoding, etc. It was, as far as I know, a new idea when Plan 9 implemented it, and it didn't replace the existing widespread convention.

(Incidentally, in C++ main can only return int, and in C void main is permitted only if the compiler specifically supports it. Many compilers don't complain very loudly if you write void main, but it's only a slight exaggeration to say that it's wrong.)


问:
user's requirements verification, howto?
My question is: How can you verify the users' requirements early in the software creation process?

I show the user specifications, prototypes, demos... but still users forget to share some "insignificant details" about the process or business rules and data. Which pops up after the final test as some "really small and rare exceptions" - which are turned into change request and accumulate a lot of work.

So how do you prototype (or verify) users requirements early in the project?

答:
If you really want to do the job right, before you start working on code or designing an architecture, sit down with some of the people who will be the users of your code ( not their management or any other higher level stakeholder ) and get them to show you how to do their job. Ideally actually do the job for a day or two. That will give you an understanding of the way the current system works and the type of people who are doing it. It will also show you the frustrations they have with the current system and the things that are hitting their productivity. You need to hear all the daily gripes and annoyances too, which may mean you have to do what is necessary to make sure their feedback stops with you or your design team, if the idea of passing their views on to other members of their organisation is likely to inhibit that.

For each group of users you need to have someone who will be working on the development of that part of the software do the same thing. Then you can all meet up and discuss what you have learned in the roles you have shadowed to see whether there are areas of crossover and how you can make things easiest for everyone involved.

I don't suggest this replaces other requirements gathering processes, but it is a supplement that lets you understand what the real users need from your system. Whatever managment thinks they need, it is likely that the managers and business analysts will not be the actual users of the system, but if you can make the system work well for those users it's going to make them more productive, making the managers happy and making your company look good.