答:
A basic CMS is a pretty simple beast to create.  There's not a lot to them, conceptually.  You generally want some sort of user authorization system, and then the ability to enter and edit web page content, and of course store it all somewhere.  Mind you, what you'd make at first will be very bare bones - probably more resembling a 1996-era guest book than WordPress.  But it should be usable for basic web sites.

Out of the technologies you cite, HTML is the only one thats required since thats what you ultimately are producing.  The languages you use on the back end is just a matter of personal preference (along with any platform/hosting limitations).  If you like Java, use Java.  Or PHP, or Python, etc.  Same with the storage mechanism - sqlite, mysql, nosql, file system - use whichever you find appealing.  Or better, code your system in such a way that that storage systems can be switched.

One technology you will likely also need to understand is HTTP itself, as session information (and thus user authorization) is typically tracked in cookies.  Understanding how that works will be key to implementing authorization.  So if you dont understand how that all works, there's your starting point.

For managing content, take a look at one of the WYSIWYG javascript editors.  These will simplify entering content into your system, bypassing the need to use something like bbcode to apply font styles.

Title: web content management system

Body:
Quite a few of my friends want to have their own personal website to showcase their talents. However, they don't want to deal with such technical things as writing html and managing web server. Neither do I.

It would be nice that we go to our URL and view our pages and we edit and update our information when logging in. So basically the content displayed will be what we provide and at the same time we can choose from some provided templates for page layout and style.

It seems a typical content management system to me. If it is, I'd like to build a simple one myself because I'd like to have the experience of building a simple CMS. Since I have no previous experience for this, I need some help figuring out what is all I need for it. And, what are the most appropriate tools and technologies?

So far, I have html, css, JSP, Tomcat, SQLite in my mind. Is that enough? Are they the best combination?

Also, I have no idea how to approach the authorization and security aspects of building the system.

(PS: I'm not sure what tags are proper for my question. Feel free to edit them for me)


问:
Self-Executing Anonymous Function vs Prototype
In Javascript there are a few clearly prominent techniques for create and manage classes/namespaces in javascript.

I am curious what situations warrant using one technique vs. the other. I want to pick one and stick with it moving forward.

I write enterprise code that is maintained and shared across multiple teams, and I want to know what is the best practice when writing maintainable javascript ?

I tend to prefer Self-Executing Anonymous Functions however I am curious what the community vote is on these techniques.

Prototype :

```<code>function obj()
{
}

obj.prototype.test = function() { alert('Hello?'); };
var obj2 = new obj();
obj2.test();
</code>```

Self-Closing Anonymous Function :

```<code>//Self-Executing Anonymous Function
(function( skillet, $, undefined ) {
    //Private Property
    var isHot = true;

    //Public Property
    skillet.ingredient = "Bacon Strips";

    //Public Method
    skillet.fry = function() {
        var oliveOil;

        addItem( "\t\n Butter \n\t" );
        addItem( oliveOil );
        console.log( "Frying " + skillet.ingredient );
    };

    //Private Method
    function addItem( item ) {
        if ( item !== undefined ) {
            console.log( "Adding " + $.trim(item) );
        }
    }
}( window.skillet = window.skillet || {}, jQuery ));
//Public Properties
console.log( skillet.ingredient ); //Bacon Strips

//Public Methods
skillet.fry(); //Adding Butter & Fraying Bacon Strips

//Adding a Public Property
skillet.quantity = "12"; console.log( skillet.quantity ); //12

//Adding New Functionality to the Skillet
(function( skillet, $, undefined ) {
    //Private Property
    var amountOfGrease = "1 Cup";

    //Public Method
    skillet.toString = function() {
        console.log( skillet.quantity + " " +
                     skillet.ingredient + " & " +
                     amountOfGrease + " of Grease" );
        console.log( isHot ? "Hot" : "Cold" );
     };

}( window.skillet = window.skillet || {}, jQuery ));
//end of skillet definition

try {
    //12 Bacon Strips & 1 Cup of Grease
    skillet.toString(); //Throws Exception
} catch( e ) {
    console.log( e.message ); //isHot is not defined
}
</code>```

I feel that I should mention that the Self-Executing Anonymous Function is the pattern used by the jQuery team.

Update
When I asked this question I didn't truly see the importance of what I was trying to understand. The real issue at hand is whether or not to use new to create instances of your objects or to use patterns which do not require constructors/use of the new keyword.

I added my own answer, because in my opinion we should make use of patterns which don't use the new keyword.

For more information please see my answer.

答:
I use prototypes because they are cleaner and follow standard inheritance patterns. Self-invoking functions are great for browser development or a situation where you don't know where the code is being executed, but otherwise it's just noise.

Example:

```<code>var me;

function MyObject () {
    this.name = "Something";
}

MyObject.prototype.speak = function speak () {
    return "Hello, my name is " + this.name;
};

me = new MyObject();
me.name = "Joshua";
alert(me.speak());
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I use prototypes because they are cleaner and follow standard inheritance patterns. Self-invoking functions are great for browser development or a situation where you don't know where the code is being executed, but otherwise it's just noise.

Example:

var me;

function MyObject () {
    this.name = "Something";
}

MyObject.prototype.speak = function speak () {
    return "Hello, my name is " + this.name;
};

me = new MyObject();
me.name = "Joshua";
alert(me.speak());


问:
Does using new techniques hurt productivity?
It seems that as experience with the specific set of tools you have to work with grows, the incentive to try out new things weakens.

When I was new at this programming job, trying out new things, researching online, made me more productive, because I often found a way (or library) that made the task easier that the code framework already in place. So using something new -- to me as well as in the context of the given codebase -- made me more productive.

Now I noticed, that there are more and more instances where, for a given problem, I know that there probably is a better solution "out there", and finding it would -- presumably -- improve the code. However, given my now intimate knowledge of the code base, it is by far easier to use the suboptimal tools we have, and get a solution (including tests) running than find someting new and "better" and "improve" the codebase.

So there is this tension: "do it properly" vs. "get the job decently done".

Is this something that happens to a lot of developers? Is this a known specific problem? (Is it a real problem after all?) Does it actually have to do with increasing levels of experience?

Oh, and note: I still like my job and like to keep it. It's just that it seems the -- always interesting! -- research part get's smaller as I learn the code base and problem sets we face with our app.

答:
Yes, new things hurt productivity

Yes of course.  Even for the best case scenario new things require additional time because they are unfamiliar. It can often cost alot more time.

No, new techniques can improve productivity

Any new technique which allows you to more easily express solution will improve your productivity.  This can be as simple as moving from large if-elseif conditions to a dispatch table.


问:
Are there any frameworks available for drawing with CSS?
I realize this sounds silly.  Let me explain:

I just came across this page about using CSS elements to create shapes- square, circle, triangle, star, yin-yang (yin-yang!), etc. using pseudo elements.

Having struggled with HTML5 Canvas drawing in the past, I immediately thought that some combination of JavaScript and CSS pseudo-elements should be able to draw just about anything.

So I first googled "CSS Fractals".  No dice.  Then "JS Fractals".  Some dice, but not what I was looking for.

Am I crazy, or is there potential here?  jQuery can add and remove elements from the DOM by the thousands all day long.  It seems to me that--given the existence of triangles via pure CSS--there is potential for a nice drawing mechanism (2D and 3D) sans Canvas.

Any thoughts, frameworks, tutorials, white papers, etc would be appreciated!

答:
Donatello

This is what I think you have been looking for.


问:
Why is there such limited support for Design by Contract in most modern programming languages?
I recently discovered Design by Contract (DbC) and I find it an extremely interesting way to write code. Among other things, it would seem to offer:

Better documentation. Since the contract is the documentation, it's impossible for one to be out of date. Additionally, because the contract specifies exactly what a routine does, it helps to support reuse.

Simpler debugging. Since program execution stops the moment a contract fails, errors can't propagate, and the specific assertion violated will presumably be highlighted. This offers support during development and during maintenance.

Better static analysis. DbC is basically just an implementation of Hoare logic, and the same principles should apply.

The costs, in comparison seem to be rather small:

Extra finger-typing. Since the contracts have to be spelled out.

Takes some amount of training to get comfortable with writing contracts.

Now, being familiar with Python primarily, I realize that it is in fact possible to write up preconditions (just throwing exceptions for inappropriate input) and it's even possible to use assertions to test again certain postconditions. But it's not possible to simulate certain features such as 'old' or 'result' without some extra magic that would ultimately be considered un-Pythonic. (In addition, there are a few libraries that offer support, but ultimately I get the vibe it would be wrong to use them, as most developers don't.) I assume that it's a similar problem for all other languages (except of course, Eiffel).

My intuition tells me that the lack of support must be a result of some kind of rejection of the practice, but searching online has not been fruitful. I'm wondering if someone can clarify why most modern languages seem to offer so little support? Is DbC flawed or overly expensive? Or is it just obsolete due to Extreme Programming and other methodologies?

答: Just guessing. Maybe part of the reason that it isn't so popular is becuase "Design by Contract" is trademarked by Eiffel.</p>


问:
When is it appropriate to develop a gui application, as opposed to a web application?
I've been thinking about an application that I want to develop for a while now. In short, I want this application to perform some crud operations. The application will be for a law firm so overall security is going to be very important. My primary programming language is php but I wouldn't mind learning some Java or possibly Objective C to make my application os-x and iOS native. Back to my question, what are the pros and cons to developing a gui application as opposed to just developing an app for the browser? The reason I ask is because if there are some benefits to developing an gui app in, say, objective c, then I guess I need to start focussing on learning the language.

Important considerations about the application I want to develop:

Database connectivity

Security(Very important)

答: One pro that you might want to consider is accessibility. With web apps, your users can access it anywhere through the internet (that is of course this app is not constrained to the intranet). Although accessibility will entail more security considerations...</p>


问:
Are null references really a bad thing?
I've heard it said that the inclusion of null references in programming languages is the "billion dollar mistake".  But why?  Sure, they can cause NullReferenceExceptions, but so what?  Any element of the language can be a source of errors if used improperly.

And what's the alternative?  I suppose instead of saying this:

Customer c = Customer.GetByLastName("Goodman"); // returns null if not found
if (c != null)
{
    Console.WriteLine(c.FirstName + " " + c.LastName + " is awesome!");
}
else { Console.WriteLine("There was no customer named Goodman.  How lame!"); }
```

<p>You could say this:</p>

<pre class="lang-cs prettyprint-override"><code>if (Customer.ExistsWithLastName("Goodman"))
{
    Customer c = Customer.GetByLastName("Goodman") // throws error if not found
    Console.WriteLine(c.FirstName + " " + c.LastName + " is awesome!");
}
else { Console.WriteLine("There was no customer named Goodman.  How lame!"); }
</code>```

But how is that better?  Either way, if you forget to check that the customer exists, you get an exception.

I suppose that a CustomerNotFoundException is a bit easier to debug than a NullReferenceException by virtue of being more descriptive.  Is that all there is to it?

答: The issue to what degree your programming language attempts to prove your program's correctness before it runs it. In a statically typed language you prove that you have the correct types. By moving to default of non-nullable references (with optional nullable references) you can eliminate many of the cases where null is passed and it shouldn't be. The question is whether the extra effort in handling non-nullable references is worth the benefit in terms of program correctness.</p>

Title: Are null references really a bad thing?

ContentLicense: CC BY-SA 2.5


问:
How to prove an application is built on a bad codebase?
I'm currently reviewing a system built by some developers that previously worked at my job. The system works pretty well from a user's point of view, but when delving into code review it's a utter mess. I'm more than convinced that the way the application is built won't hold up for future updates, let alone high increases in usage.

The problem is that I know how bad it is, but my superiors don't. How can I prove it to my manager so he actually sees the problem and can be convinced to do minimal triage on the current codebase, and in the near future start a new line of development for the next version of the application?

答:
'But it works now' is the standard management response to the legitimate frustrations of software engineers. The first thing I would do would be to compile the documentation (if any) and use that to demonstrate contradictions between the code and the documentation.

If you can, put together a comprehensive suite of unit tests. Run these with every change so you can document regressions which can be blamed on the existing codebase.

Lastly, if you can pull in a developer from another department whose work you trust, get a second pair of eyes on the code. One developer saying 'this is crap' is easier to dismiss, than when a senior developer who has been around a while vouches for him and says, 'No, Jim, he's right. This is crap on a crap cracker.'

Of course, it all depends on your environment, company size, etc.

I always recommend taking a look at The Pragmatic Programmer If you haven't read it. Not only should it be required reading for every software professional, but it has some good suggestions for dealing with management, co-workers, users, etc. who don't view software engineering as a craft.


答: A big con with native applications is the deployment. Installing and updating a native application is much more hassle for you as developer and for your users. With a web application, that becomes a lot easier. I wouldn't go native unless there are OS features I really need.</p>

Title: When is it appropriate to develop a gui application, as opposed to a web application?

Body:
I've been thinking about an application that I want to develop for a while now. In short, I want this application to perform some crud operations. The application will be for a law firm so overall security is going to be very important. My primary programming language is php but I wouldn't mind learning some Java or possibly Objective C to make my application os-x and iOS native. Back to my question, what are the pros and cons to developing a gui application as opposed to just developing an app for the browser? The reason I ask is because if there are some benefits to developing an gui app in, say, objective c, then I guess I need to start focussing on learning the language.

Important considerations about the application I want to develop:

Database connectivity

Security(Very important)


答:
Having a web app has a few major pluses

It is easy to upgrade (just push a new version to the server)

It is cross platform (Windows, mac, tablets etc)

You already know how to do a web app

It is possible to make sure all the data is in one place for security and backups

On the minus side there are some limitations, but with HTML5 those are less and less each year.


答:
There are various tools available which can do code coverage and code review. Google tools suitable for your technology, these are normally industry standard tools.
I would suggest you use these tools and come up with code-quality report and present it to Manager. Make sure your criticism is contructive and non-political.</p>

Title: How to prove an application is built on a bad codebase?

Body:
I'm currently reviewing a system built by some developers that previously worked at my job. The system works pretty well from a user's point of view, but when delving into code review it's a utter mess. I'm more than convinced that the way the application is built won't hold up for future updates, let alone high increases in usage.

The problem is that I know how bad it is, but my superiors don't. How can I prove it to my manager so he actually sees the problem and can be convinced to do minimal triage on the current codebase, and in the near future start a new line of development for the next version of the application?


答:
Donatello, as the above answer suggests, is a great answer, especially if you're looking for graphs. If you want to do more general drawing, Donatello is built on Raphael.js, and it's more generalized. Raphael can do most anything you want when it comes to 2-D (and even simulated 3-D) graphics. Everything from charts to 3-D shaded spheres... it's pretty much amazing. If you want to do fractals and more computationally complex imaging, you might want to look at specialized libs that utilize web workers, for instance Fractaljs.

The combination of HTML5 Canvas, CSS3, and JavaScript (especially jQuery) is definitely the answer. Finding the right tolls and frameworks on top of those technologies is the next step. The ones listed here are a great place to start.

Title: Are there any frameworks available for drawing with CSS?

Body:
I realize this sounds silly.  Let me explain:

I just came across this page about using CSS elements to create shapes- square, circle, triangle, star, yin-yang (yin-yang!), etc. using pseudo elements.

Having struggled with HTML5 Canvas drawing in the past, I immediately thought that some combination of JavaScript and CSS pseudo-elements should be able to draw just about anything.

So I first googled "CSS Fractals".  No dice.  Then "JS Fractals".  Some dice, but not what I was looking for.

Am I crazy, or is there potential here?  jQuery can add and remove elements from the DOM by the thousands all day long.  It seems to me that--given the existence of triangles via pure CSS--there is potential for a nice drawing mechanism (2D and 3D) sans Canvas.

Any thoughts, frameworks, tutorials, white papers, etc would be appreciated!


答:
You have answered your own question in a way.

The way to convince them to spend money on the system is to wait until it doesn't function well for the user. If you think it won't scale, either wait for that to happen or do a load test to prove it.

It's then a simple proposal of cleaning this to scale will cost X hours.


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

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

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

答:
It depends on the language, but it's usually a bad idea...

In C, never do this.  It's too easy to find a situation where the value you are testing is not false (non-zero), but also not equal to the single value defined as "true".

In Ruby, do this only if you are absolutely certain that you want to fail on everything except Boolean true.

In C++ and other static languages with a bool type,  it's redundant, and can lead to programming errors when you mis-type = instead of ==, or promotion errors as mentioned in the comments.

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


问:
web content management system
Quite a few of my friends want to have their own personal website to showcase their talents. However, they don't want to deal with such technical things as writing html and managing web server. Neither do I.

It would be nice that we go to our URL and view our pages and we edit and update our information when logging in. So basically the content displayed will be what we provide and at the same time we can choose from some provided templates for page layout and style.

It seems a typical content management system to me. If it is, I'd like to build a simple one myself because I'd like to have the experience of building a simple CMS. Since I have no previous experience for this, I need some help figuring out what is all I need for it. And, what are the most appropriate tools and technologies?

So far, I have html, css, JSP, Tomcat, SQLite in my mind. Is that enough? Are they the best combination?

Also, I have no idea how to approach the authorization and security aspects of building the system.

(PS: I'm not sure what tags are proper for my question. Feel free to edit them for me)

答:
As a fervent Rubyist, I'm biased, but I would suggest Ruby on Rails for learning to build a CMS. The barriers to entry are pretty low, there are great tutorials to get you bootstrapped,  adherence to standards such as REST, HTML5, CSS3, etc. is a top priority, the list goes on and on.

One really nice thing about getting started with Rails is Ryan Bates' series Railscasts. You can watch an expert code similar exercises and adapt it to what you're trying t accomplish. In addition, Github is chock full of both build-a-blog-or-cms code-along tutorials, as well as full-fledged, open source Rails-based CMS applications you can go to as examples. One of the best CMSes I've ever played with is Alchemy, which is built on Rails 3.

I'm not insisting that you MUST become a Ruby programmer, or that other languages/frameworks are wrong. But once you try it... this is the framework that skyrocketed to popularity when DHH built a blog engine in 15 minutes, on stage. So even just for rapid prototyping, it's a great tool.

Give it a try... there are excellent gems (OmniAuth, Devise) for handling security and authentication, and many of the hairy issues like CSRF are handled by the framework itself. You can concentrate on the project, rather than the incidental issues. And as it's database-agnostic, you can start with SQLite if you like, and move to PostgreSQL or even Mongo or Couch later if you fancy.

So... yeah. Enjoy. Programming should be fun.

Title: web content management system


答: First determine the accumulated technical debt in your codebase. Then take a look at this question and answers, where it is explained how to convince management to pay off the technical debt before proceeding further.</p>


问:
How to verify/prove orthogonality of a programming language?
I know the concept of orthogonality, but from a programming language point of view, is there a way to verify/prove it?

For instance in C#, one can use public or static for a method signature. You can use either or both and they wouldn't interfere with each other, so they are orthogonal to each other, right?

My question is, how do I go about the rest of features, particularly features that are not related to each other?

Do all the features have to coexist/stack together?

Is there a programming language that is 100% orthogonal?

答:
The list of unorthogonal features is indeed long in most programming languages, e.g.

anonyous classes conflict with java reflection

generic and type erasure conflict with java reflection

arrays are somewhat different to other objects, because of their special type, even though they are objects.

static vs. instance methods are not the same, e.g. you can't override a static method

nested class are an after-thought

impact of dynamic vs. static typing on the message dispatch strategy (see e.g. this edge case in C#)

etc.

Those a just a few that comes to my mind, but there are many others, and also in other languages.

It's hard to ensure that there are not subtle interference between language features. As C.A.R. Hoare indicates in his paper "Hints on Programming Language Design":

Part of language design consists of innovation. This activity leads to
  new language features in isolation. The most difficult part of
  language design lies in integration: selecting a limited set of
  language features and polishing them until the result is a consistent
  simple framework that has no more rough edges.

Probably, a good move to increase orthogonality is to unify concepts (that goes in the direction of @karl-bielfeld answer). If everything is, say a list or an object, chances are that there will be less conflicts. Or instead of having nested class an after thought, make it a core features.

Most programming languages papers prove certain properties of the language (e.g. type soundness) on a subset (a "core") of the language that is formalized. Here we should do the opposite, prove that all features compose safely. Also, that means one should define what it means to "compose". Does it mean to "run"? (In this case, the link above about the edge case with dynamic and static typing is safe). Does it mean to be "safe"? Does it mean to be predictable from a developer point of view?

All that is very interesting--but also very challenging.

OwnerDisplayName: Joan Venge


问:
Software licenses in practice
Almost all questions and information on both SO and "Google" describes how different licenses works and what license to choose for your work?

But how do they work in reality.

Almost everyone I have spoken to have vastly different thoughts of how they work, including hard core open source developers that gladly share their libs and consultants who is only interested in money and would never reveal their libs.

First I will give my impression of how they work in practice with three questions / statements and you can agree or disagree with me on those.

Lets say I make a large application and have a small portion of that from GPL code, then the copyright holder can't do much about it as it's deemed non essential code for my application and thereby the "law" rules over the GPL?

If the code is generic the copyright doesn't hold. For example if I make a tutorial on how to set up a chess engine no one have to care about my license. That's because my code is mechanical in nature.

If I use a lot of GPL code that is essential for my application and don't disclose it and someone finds out, my "punishment" will be to release all my source code, large companies are terrified by this.

But for a small hobby developer this isn't much of an issue as the software wouldn't be written at all or would be open sourced from the start anyway? I don't like this approach personally because I find it unethical and disrespectful to the original author.

EDIT: Clarified as a comment made was that I din't ask a question. My question is are the 3 statements correct.

答:
In my view, your question is really about how effectively the copyright holder can enforce their copyright and licensing terms on the internet.

Whilst the actual wording of copyright laws do vary around the world, there are international treaties signed by many countries that define the basic copyright protection that signatories have to enact in their countries laws. That said, implementation and enforcement of the laws does vary considerably expecially around "fair use" exemptions.

In case (1), the probability is that the copyright holder probably does not know that you have copied their code, and are attempting to profit from it. The likely outcome is that they do nothing because they do not know.  However, should they find out and then choose the legal approach, then the outcome is likely to be that you have to pay a substantial sum of money to lawyers, you have to pay them damages for the copies of their code that you have shipped, and you are not allowed to continue to distribute your product.  In the mean time, your reputation with your customers is destroyed.

In case (2) The person who created the site is expecting people to follow their example to write their own programs. If they cared about their intellectual property rights on that example code, it would have remained private, and not published. If this kind of copying did end up in court, a significant issue here is likely to be whether copying actually took place, or did you actually create similar code (either independently or based on the teachings from their site). Even on a "balance of probability" legal test this may be a significant challenge for the copyright holder to show that you copied rather than learned.

In case (3), as you say, this does scare companies. In this scenario the company faces a choice of testing the license terms in court, and facing the court sanctions, which are likely to prevent them from continuing to distribute their product, to start complying with the license terms and to give away their source code too. It is probably too late to just rewrite the code removing the copied source. If this scenario occurred as described, then it would be symptomatic of a complete loss of control by the directors of their employees actions, and you would have to wonder how long before the company collapses anyway.  However, a milder version does occur where one aspect of a companies product is compromised, and to protect their reputation, companies do tend to outsource their associated code.

Title: Software licenses in practice


问:
How do existential types differ from interfaces?
Given the existential type

```<code>T = ∃X.{op₁:X, op₂:X→boolean}
</code>```

and this generic Java interface:

```<code>interface T<X> {
    X op₁();
    boolean op₂(X something);
}
</code>```

What are the fundamental differences between the existential type and the Java interface?

Obviously there are syntactical differences, and Java's object-orientation (which also includes details such as hidden this parameters etc.). I'm not so much interested in these as in conceptual and semantic differences — though if someone would like to shed light on some finer points (such as the notational difference between T vs. T<X>), that would be appreciated too.

答:
The 2 presented types are very different from each other. The interface definition you've written is an universal type (Java generics in general fall in this category).

An existential type hides a type within its implementation from the consumer. Intuitively, for X to be existential in T, X's identity cannot be known from any consumer; all that should be known is the set of operations provided at definition. There exists one type T for some type X.

In contrast, an universal type defines operations applicable to all types, from which the consumer is free to choose. The interface type T is exactly that. X is instantiated by the consumer, who'll know exactly which type X is. There exists a type T for every type X in the universe.

Existentials aren't actually present in Java as a language construct, except for in the limited case of wildcards (List<?>). But yes, they can be emulated with interfaces. The problem then becomes more of design.

As ony pointed out, in an object-oriented setting, existentials become tricky to implement because the way you usually encode the type information of X (what you can do with it) is to have member functions in an interface type which X implements. In short, interfaces can buy some type abstraction capabilities, but require the elimination of the existential to some extent.


答:
Self executing anonymous functions are used to automate script execution without hooking into external events (i.e. window.onload).

In this example it is used to form the classic Module pattern, the primary purpose of which is to introduce a namespace into the global environment, and provide encapsulation for any internal properties that are not "exported" or attached to the namespace.

Modifying an objects prototype, on the other hand, is used to establish inheritance (or extend natives). This pattern is used to produce 1:n objects with common methods or properties.

You should not choose one pattern in preference to the other, since they perform different tasks. In terms of namespacing, the Self Executing Function is an appropriate choice.

Title: Self-Executing Anonymous Function vs Prototype

Body:
In Javascript there are a few clearly prominent techniques for create and manage classes/namespaces in javascript.

I am curious what situations warrant using one technique vs. the other. I want to pick one and stick with it moving forward.

I write enterprise code that is maintained and shared across multiple teams, and I want to know what is the best practice when writing maintainable javascript ?

I tend to prefer Self-Executing Anonymous Functions however I am curious what the community vote is on these techniques.

Prototype :

```<code>function obj()
{
}

obj.prototype.test = function() { alert('Hello?'); };
var obj2 = new obj();
obj2.test();
</code>```

Self-Closing Anonymous Function :

```<code>//Self-Executing Anonymous Function
(function( skillet, $, undefined ) {
    //Private Property
    var isHot = true;

    //Public Property
    skillet.ingredient = "Bacon Strips";

    //Public Method
    skillet.fry = function() {
        var oliveOil;

        addItem( "\t\n Butter \n\t" );
        addItem( oliveOil );
        console.log( "Frying " + skillet.ingredient );
    };

    //Private Method
    function addItem( item ) {
        if ( item !== undefined ) {
            console.log( "Adding " + $.trim(item) );
        }
    }
}( window.skillet = window.skillet || {}, jQuery ));
//Public Properties
console.log( skillet.ingredient ); //Bacon Strips

//Public Methods
skillet.fry(); //Adding Butter & Fraying Bacon Strips

//Adding a Public Property
skillet.quantity = "12"; console.log( skillet.quantity ); //12

//Adding New Functionality to the Skillet
(function( skillet, $, undefined ) {
    //Private Property
    var amountOfGrease = "1 Cup";

    //Public Method
    skillet.toString = function() {
        console.log( skillet.quantity + " " +
                     skillet.ingredient + " & " +
                     amountOfGrease + " of Grease" );
        console.log( isHot ? "Hot" : "Cold" );
     };

}( window.skillet = window.skillet || {}, jQuery ));
//end of skillet definition

try {
    //12 Bacon Strips & 1 Cup of Grease
    skillet.toString(); //Throws Exception
} catch( e ) {
    console.log( e.message ); //isHot is not defined
}
</code>```

I feel that I should mention that the Self-Executing Anonymous Function is the pattern used by the jQuery team.

Update
When I asked this question I didn't truly see the importance of what I was trying to understand. The real issue at hand is whether or not to use new to create instances of your objects or to use patterns which do not require constructors/use of the new keyword.

I added my own answer, because in my opinion we should make use of patterns which don't use the new keyword.

For more information please see my answer.


问:
Programmers' concerns about export restrictions from the United States
Which aspects do I need to consider when designing and publishing software that must meet the US export restrictions for cryptographic software?

Wikipedia says that there are various categories which you can assign to cryptographic software. And the export destination (e.g. China, Russia) does play a major role as well. But I didn't really understand those restrictions and their effect on my work.

Can anybody explain that to me?

I'm asking because if you try to publish your application (e.g. on Apple's App Store or Android's Market) you have to assure that your application meets the US export restrictions. And there are lots of applications who offer secure information storage, e.g. for passwords.

Have they all notified the government and asked for a review? Of course, you cannot know if they did. But do they need to do this?

答:
A slightly different answer, but why write the encryption code in the USA? Even if you write the rest of the product in the USA, it makes a lot of sense to do the encryption parts elsewhere.  You can still sell your product in the USA, but you import into the USA, rather than export from the USA.

As an aside, in the early PGP days, the export rules were sidestepped by printing a book containing the source code, and exporting the book.

OwnerDisplayName: Marco W.


答:
My intuition tells me that the lack of support must be a result of some kind of rejection of the practice,...

False.

It's a design practice.  It can be embodied explicitly in code (Eiffel style) or implicitly in code (most languages) or in unit tests.  The design practice exists and works well.  The language support is all over the map.  It is, however, present in many languages in the unit test framework.

I'm wondering if someone can clarify why most modern languages seem to offer so little support?
  Is DbC flawed or overly expensive?

It's expensive.  And.  More importantly, there are some things which cannot be proven in a given language.  Loop termination, for example, cannot be proven in a programming language, it requires a "higher-order" proof capability.  So so some kinds of contracts are technically inexpressible.

Or is it just obsolete due to Extreme Programming and other methodologies?

No.

We mostly use unit tests to demonstrate that DbC is fulfilled.

For Python, as you noted, the DbC goes in several places.

The docstring and the docstring test results.

Assertions to validate inputs and outputs.

Unit tests.

Further.

You can adopt literate programming-style tools so that you write a document which includes your DbC information and which generates clean Python plus unit test scripts.  The literate programming approach allows you to write a nice piece of literature which includes the contracts and the complete source.

Title: Why is there such limited support for Design by Contract in most modern programming languages?

Body:
I recently discovered Design by Contract (DbC) and I find it an extremely interesting way to write code. Among other things, it would seem to offer:

Better documentation. Since the contract is the documentation, it's impossible for one to be out of date. Additionally, because the contract specifies exactly what a routine does, it helps to support reuse.

Simpler debugging. Since program execution stops the moment a contract fails, errors can't propagate, and the specific assertion violated will presumably be highlighted. This offers support during development and during maintenance.

Better static analysis. DbC is basically just an implementation of Hoare logic, and the same principles should apply.

The costs, in comparison seem to be rather small:

Extra finger-typing. Since the contracts have to be spelled out.

Takes some amount of training to get comfortable with writing contracts.

Now, being familiar with Python primarily, I realize that it is in fact possible to write up preconditions (just throwing exceptions for inappropriate input) and it's even possible to use assertions to test again certain postconditions. But it's not possible to simulate certain features such as 'old' or 'result' without some extra magic that would ultimately be considered un-Pythonic. (In addition, there are a few libraries that offer support, but ultimately I get the vibe it would be wrong to use them, as most developers don't.) I assume that it's a similar problem for all other languages (except of course, Eiffel).

My intuition tells me that the lack of support must be a result of some kind of rejection of the practice, but searching online has not been fruitful. I'm wondering if someone can clarify why most modern languages seem to offer so little support? Is DbC flawed or overly expensive? Or is it just obsolete due to Extreme Programming and other methodologies?


问:
Distributed transactions and queues, ruby, erlang
I have a problem that involves several machines, message queues, and transactions.  So for example a user clicks on a web page, the click sends a message to another machine which adds a payment to the user's account. There may be many thousands of clicks per second. All aspects of the transaction should be fault tolerant.

I've never had to deal with anything like this before, but a bit of reading suggests this is a well known problem.

So to my questions. Am I correct in assuming that secure way of doing this is with a two phase commit, but the protocol is blocking and so I won't get the required performance?  It appears that DBs like redis and message queuing system like Rescue, RabbitMQ etc don't really help me a lot - even if I implement some sort of two phase commit, the data will be lost if redis crashes because it is essentially memory-only.

All of this has led me to look at erlang - but before I wade in and start learning a new language, I would really like to understand better if this is worth the effort.  Specifically, am I right in thinking that because of its parallel processing capabilities, erlang is a better choice for implementing a blocking protocol like two phase commit, or am I confused?

答:
As long as your message queue middleware is restartable and can guarantee Exactly Once processing, you will be fine. Your apps should drop their requests onto the queue, and the middleware tool will take care of persisting that and managing the retry activity. At the "data layer" end, you just need to make sure that your transaction to the DB and your acknowledgement to the middleware occurs correctly.

This can be handled by a proper XA 2 phase commit tool, or you can work around it.

For example, perhaps, save the unique message ID to the DB when you record the payment, and before you write a payment you do a check that the unique message Id has not been seen before.


答:
I'd go with the self-executing function, but with a slight difference:

```<code>MyClass = (function() {
     var methodOne = function () {};
     var methodTwo = function () {};
     var privateProperty = "private";
     var publicProperty = "public";

     return function MyClass() {
         this.methodOne = methodOne;
         this.methodTwo = methodTwo;
         this.publicProperty = publicProperty;
     };
})();
</code>```

If find this approach much cleaner, as I separate the returned global variable from any input parameters (such as jQuery) (the way you wrote it is equivalent to returning void and using a ref parameter in C#, which I find a bit off, or passing in a pointer to a  pointer and re-assigning it in C++). If I were then going to attach additional methods or properties to the class I would use prototypal inheritance (example with jQuery's $.extend method, but it's easy enough to roll your own extend()):

```<code>var additionalClassMethods = (function () {
    var additionalMethod = function () { alert('Test Method'); };
    return { additionalMethod: additionalMethod };
})();

$.extend(MyClass.prototype, additionalClassMethods);

var m = new MyClass();
m.additionalMethod(); // Pops out "Test Method"
</code>```

This way you have a clear distinction between the added methods and the original ones.

Body:
I'd go with the self-executing function, but with a slight difference:

MyClass = (function() {
     var methodOne = function () {};
     var methodTwo = function () {};
     var privateProperty = "private";
     var publicProperty = "public";

     return function MyClass() {
         this.methodOne = methodOne;
         this.methodTwo = methodTwo;
         this.publicProperty = publicProperty;
     };
})();

If find this approach much cleaner, as I separate the returned global variable from any input parameters (such as jQuery) (the way you wrote it is equivalent to returning void and using a ref parameter in C#, which I find a bit off, or passing in a pointer to a  pointer and re-assigning it in C++). If I were then going to attach additional methods or properties to the class I would use prototypal inheritance (example with jQuery's $.extend method, but it's easy enough to roll your own extend()):

var additionalClassMethods = (function () {
    var additionalMethod = function () { alert('Test Method'); };
    return { additionalMethod: additionalMethod };
})();

$.extend(MyClass.prototype, additionalClassMethods);

var m = new MyClass();
m.additionalMethod(); // Pops out "Test Method"

This way you have a clear distinction between the added methods and the original ones.


问:
Using Memcached: is it good practice to update the cache when updating the database?
This question is about best practices in architecture.

Our Current Architecture

I have a PHP class that accesses MySQL for user info.  Let's call it User.  User is accessed many times, so we have implemented layers of caching to reduce load.

The first layer is what we call the "per request" cache.  After the data has been retrieved from MySQL, we store the data in a private property of User.  Any subsequent requests for the data returns the property instead of re-requesting the data from MySQL.

Since the web request lives and dies on a per-request basis, this cache only prevents the application from accessing MySQL more than once in a single request.

Our second layer is Memcached.  When the private property is empty, we first check Memcached for the data.  If Memcached is empty we query MySQL for the data, update Memcached, and update the private property of User.

The Question

Our application is a game, and sometimes it is imperative that some data be as up-to-date as possible.  In the span of about five minutes, a read request for the user data may happen 10 or 11 times; then an update may occur.  Subsequent read requests need to be up to date or game mechanics fail.

So, what we've done is implement a piece of code that is executed when a database update happens.  This code sets the key in Memcached with the updated data, so all subsequent requests to Memcached are up to date.

Is this optimal?  Are there any performance concerns or other "gotchas" we should be aware of when trying to maintain a sort of "living cache" like this?

答:
My recommendation is to look at your usage profile and your requirements for the cache.

I can see no reason why you would leave stale data in memcached. I think you have picked the right approach ie: update the DB.

In any case, you're going to need a wrapper on your DB update (which you've done). Your code to update the User in the DB and in-RAM should also do a push to memcached, OR an expiry in memcached.

For example - If your users normally do an update once per session as part of log off, there's not much point updating the data in cache (eg high score total) - you should expire it straight away.

IF however they are going to update the data (eg current game state) and then 0.2 seconds later you'll have an immediate PHP page hit that is going to request the data, you'd want it fresh in the cache.


问:
Sort algorithms that work on large amount of data
I am looking for sorting algorithms that can work on a large amount of data, i.e. that can work even when the whole data set cannot be held in main memory at once.

The only candidate that I have found up to now is merge sort: you can implement the algorithm in such a way that it scans your data set at each merge without holding all the data in main memory at once. The variation of merge sort I have in mind is described in this article in section Use with tape drives.

I think this is a good solution (with complexity O(n x log(n)) but I am curious to know if there are other (possibly faster) sorting algorithms that can work on large data sets that do not fit in main memory.

EDIT

Here are some more details, as required by the answers:

The data needs to be sorted periodically, e.g. once in a month. I do not need to insert a few records and have the data sorted incrementally.

My example text file is about 1 GB UTF-8 text, but I wanted to solve the problem in general, even if the file were, say, 20 GB.

It is not in a database and, due to other constraints, it cannot be.

The data is dumped by others as a text file, I have my own code to read this text file.

The format of the data is a text file: new line characters are record separators.

One possible improvement I had in mind was to split the file into files that are small enough to be sorted in memory, and finally merge all these files using the algorithm I have described above.

答:
Use external merge sort algorithm (if your data are continuos), or a bucket sort with counting sort as a implementation of sorting for buckets (if your data are discrete and uniformly distributed).

Probably the best approach is to build your own index/mapping file if the increment is small.

Somehow order your "database"

Assign an integer to every entry (1, 2, 3, 4, ..., n) (better: use some sparse indexes)

When adding an increment just find a gap where the left number is less or equal and the right number is greater or equal (it should not be difficult with some modified version of a binary search)

Insert, while the gaps are sufficietly big, if not: just reindex (never sort again) :-)


答:
I wouldn't go about it quite like you outlined. What you need to do is decide whether you actually NEED completely up-to-date data. Then, if you do need it, decide which parts of the data need to be up-to-date at all times and separate them from things that can be cached in your architecture.

For example, you probably want to update your user's email address as soon as they change it, so you don't send out mails to the wrong address, but it's unlikely that the user's date of birth or surname is going to need to be completely up-to-date to provide a decent user experience. (N.B. I'm not using a game-architecture example as I don't know what kind of game to aim it at, and I think this one is fairly easy to understand).

This way you have two clear sets of data: short- and long-term cacheable data. You can probably get away with a cache duration of a minute or so on the short-term data, just to relieve load on the DB, but the long-term data can be left in the cache on a sliding duration for as long as it's used.

Then you need to deal with updates. I'd first look at using a DB trigger to simply remove items from the cache once they're out of date. That will force your business layer to trigger a cache refresh on the next time it requests the data, freeing up some space in the cache if the data isn't being used (for example if a user changes their email address then logs out immediately). If this is going to cause performance issues in the UI (i.e. introduce too much lag while waiting for cache refreshes) then you can look at simply triggering the cache call once the item is removed from the cache. I'd also look at optimising the DB read times for this small set of data, to ensure that any lag induced in refreshing the cache is minimal (this should be easier as you only need to load data you really need).

What I would not do, in any circumstance, is add an additional method of filling the cache, as then you will need to maintain the call (and API hooks etc.) in two places.

As for gotchas, the main thing you need to be careful of if you're writing directly to the cache is synchronisation. If many threads try to read while you're doing your silent update you might have some serious invalid data issues, which will defeat the point of trying to keep the data up-to-date in the first place.

Title: Using Memcached: is it good practice to update the cache when updating the database?

Body:
This question is about best practices in architecture.

Our Current Architecture

I have a PHP class that accesses MySQL for user info.  Let's call it User.  User is accessed many times, so we have implemented layers of caching to reduce load.

The first layer is what we call the "per request" cache.  After the data has been retrieved from MySQL, we store the data in a private property of User.  Any subsequent requests for the data returns the property instead of re-requesting the data from MySQL.

Since the web request lives and dies on a per-request basis, this cache only prevents the application from accessing MySQL more than once in a single request.

Our second layer is Memcached.  When the private property is empty, we first check Memcached for the data.  If Memcached is empty we query MySQL for the data, update Memcached, and update the private property of User.

The Question

Our application is a game, and sometimes it is imperative that some data be as up-to-date as possible.  In the span of about five minutes, a read request for the user data may happen 10 or 11 times; then an update may occur.  Subsequent read requests need to be up to date or game mechanics fail.

So, what we've done is implement a piece of code that is executed when a database update happens.  This code sets the key in Memcached with the updated data, so all subsequent requests to Memcached are up to date.

Is this optimal?  Are there any performance concerns or other "gotchas" we should be aware of when trying to maintain a sort of "living cache" like this?


答:
Live Example

```<code>(function _anonymouswrapper(undefined) {

    var Skillet = {
        constructor: function (options) {
            options && extend(this, options);
            return this;
        },
        ingredient: "Bacon Strips",
        _isHot: true,
        fry: function fry(oliveOil) {
            this._addItem("\t\n Butter \n\t");
            this._addItem(oliveOil);
            this._addItem(this.ingredient);
            console.log("Frying " + this.ingredient);
        },
        _addItem: function addItem(item) {
            console.log("Adding " + item.toString().trim());
        }
    };

    var skillet = Object.create(Skillet).constructor();

    console.log(skillet.ingredient);
    skillet.fry("olive oil");

    var PrintableSkillet = extend(Object.create(Skillet), {
        constructor: function constructor(options) {
            options && extend(this, options);
            return this;
        },
        _amountOfGrease: "1 Cup",
        quantity: 12,
        toString: function toString() {
            console.log(this.quantity + " " +
                        this.ingredient + " & " +
                        this._amountOfGrease + " of Grease");
            console.log(this._isHot ? "Hot" : "Cold");
        }
    });

    var skillet = Object.create(PrintableSkillet).constructor();

    skillet.toString();

    function extend(target, source) {
        Object.getOwnPropertyNames(source).forEach(function (name) {
            var pd = Object.getOwnPropertyDescriptor(source, name);
            Object.defineProperty(target, name, pd);
        });
        return target;
    }
}());
</code>```

You can use a IIFE to emulate "module scope" around your code. Then you can just use objects as you normally do.

Don't "emulate" private state using closures as that has a large memory penalty.

If your writing an enterprise application and want to keep your memory usage under 1GB avoid unnecessarily using closures to store state.

Body:
Live Example

(function _anonymouswrapper(undefined) {

    var Skillet = {
        constructor: function (options) {
            options && extend(this, options);
            return this;
        },
        ingredient: "Bacon Strips",
        _isHot: true,
        fry: function fry(oliveOil) {
            this._addItem("\t\n Butter \n\t");
            this._addItem(oliveOil);
            this._addItem(this.ingredient);
            console.log("Frying " + this.ingredient);
        },
        _addItem: function addItem(item) {
            console.log("Adding " + item.toString().trim());
        }
    };

    var skillet = Object.create(Skillet).constructor();

    console.log(skillet.ingredient);
    skillet.fry("olive oil");

    var PrintableSkillet = extend(Object.create(Skillet), {
        constructor: function constructor(options) {
            options && extend(this, options);
            return this;
        },
        _amountOfGrease: "1 Cup",
        quantity: 12,
        toString: function toString() {
            console.log(this.quantity + " " +
                        this.ingredient + " & " +
                        this._amountOfGrease + " of Grease");
            console.log(this._isHot ? "Hot" : "Cold");
        }
    });

    var skillet = Object.create(PrintableSkillet).constructor();

    skillet.toString();

    function extend(target, source) {
        Object.getOwnPropertyNames(source).forEach(function (name) {
            var pd = Object.getOwnPropertyDescriptor(source, name);
            Object.defineProperty(target, name, pd);
        });
        return target;
    }
}());

You can use a IIFE to emulate "module scope" around your code. Then you can just use objects as you normally do.

Don't "emulate" private state using closures as that has a large memory penalty.

If your writing an enterprise application and want to keep your memory usage under 1GB avoid unnecessarily using closures to store state.


答:
Personally, I agree with both Steve Job's and Bill Gate's view on this: http://vimeo.com/25043022

In short: native apps will always be around, and in times are preferable, over that the experience that they can provide can often at times be far superior than a non-native (web) app, however the cloud, or the web infrastructure should definitely be there supporting the native app. When you think about it, this is more or less every apple product these days - iOS, iTunes, OSX, MobileMe, iCloud, iTV - in theory, they could all be pure web applications, but the experience would not be the same.

Here are the full interviews http://www.youtube.com/watch?v=LrS7JQv-zgY and another http://www.youtube.com/watch?v=zmInRZ2d-bI - well worth a listen.


问:
Why should I use reflection?
I am new to Java; through my studies, I read that reflection is used to invoke classes and methods, and to know which methods are implemented or not.

When should I use reflection, and what is the difference between using reflection and instantiating objects and calling methods the traditional way?

答:
Reflection allows a program to work with code that may not be present and do so in a reliable way.

"Normal code" have snippets like URLConnection c = null which by its sheer presence cause the class loader to load the URLConnection class as part of loading this class, throwing a ClassNotFound exception and exiting.

Reflection allow you to load classes based on their names in string form and test them for various properties (useful for multiple versions outside your control) before launching actual classes that depend on them.  A typical example is the OS X specific code used to make Java programs look native under OS X, which are not present on other platforms.

Title: Why should I use reflection?


问:
Steps required to start programming in C++ to develop native applications
I am dealing around with C# .Net for almost around a year now. I got lots of experience (I owe most of it to guys at stackoverflow).

Now I am thinking to start working with C++ as well. Mainly because I would like to be able write codes resulting in applications that are not .Net dependent so they can be executed in most of environments also having cross-platform in mind. Although I have to confess, writing code in .Net with C# and Visual Studio can not be easier nowadays.

Of my other reasons I can name, since I am studying electrical engineering, who knows maybe I later need to write drivers for hardwares!

My questions are:
1- Am I right with the idea of learning C++ I mean is it add to my value if say I am going to work as a developer later?
2- What tools will I need to start programming in native C++ that is perhaps compilers and IDE

答:
Learning nearly anything new adds value. If you've got a spare time for it - just do it, without questioning the reasons.

As for this specific case, C++ is quite an interesting language, its numerous pitfalls and ill design decisions contributed more into the modern languages design than any other language. Learning from the mistakes is always a good idea. But do not forget to pay enough attention to the other languages too.


问:
version control workflow for environment with shared code
I work at a company that is looking into "upgrading" our version control system. We have about 200 websites that operate in their own directories. However, all of these websites use the same shared code. We basically use the 200 directories for the display code (html/css) and then the shared code for the processing and database queries. Its a little more detailed but I'll leave it at that for now. We also have a backend system that primarily uses shared code only.

We currently have multiple programmers and multiple coders/designers that all need access to the code on a regular basis. Unfortunately our shared code isn't exactly modular, so it is hard to split something off into a "project" when something needs done since so many files are hit. I am basically looking for suggestions on the best workflow available for a version control system. As far as we can tell from research, git seems to be the way to go. But being the version control newbies that we are, we still have concerns on general workflow. Can anyone give me any advice on this topic?

Edit:
I'm trying to be a little more detailed, hopefully I answer some questions from the comments. Pretty much anyone is allowed to change any code at any time. If a change is made to shared code then it is immediately applied to the central code base. We don't really have a versioning scheme. We used to in the past but it was never enforced when new developers were brought on board. The shared code is clearly separated from the rest of the code. There are a few files in our system that get edited a lot. We are constantly "stepping on each other's toes" with these files. These files are very important to our system. I'll be the first one to say this is not an ideal work situation. We are well aware these files need to go. We are in the planning process of modularizing them but we would still need to consider them when choosing a versioning system. I guess another good thing to mention is the fact that we have a large number of files. This isn't ideal either but its happened primarily from not having a sound version control system put in place. Many developers over the years would just save a back up of a file if making a significant change. This is another reason we want to move away from the current scheme. Thanks for your responses already.

答:
when we migrated from SVN to GIT we have based our repository usage model on gitflow - http://nvie.com/posts/a-successful-git-branching-model/

This branching model really helped us in our situation of 5 million lines of copy-paste legacy nightmare code and 3 scrum teams keeping application alive in 1 week iterations

We also use gerrit - http://code.google.com/p/gerrit/ for code review and access control, but it's not perfect tool for beginners (it adds a lot of complexity in day-to-day usage of your repositories, though it prohibits non administrators from breaking anything)


答: for some of the basics you could use visual studio to learn c++, but visual c++ is different than regular c++, so you may want to branch out into something different after a while, but all the basic stuff is the same in visual c++ and if you fee comfortable with visual studio its less to overcome in  learning a language.</p>

Title: Steps required to start programming in C++ to develop native applications

Body:
I am dealing around with C# .Net for almost around a year now. I got lots of experience (I owe most of it to guys at stackoverflow).

Now I am thinking to start working with C++ as well. Mainly because I would like to be able write codes resulting in applications that are not .Net dependent so they can be executed in most of environments also having cross-platform in mind. Although I have to confess, writing code in .Net with C# and Visual Studio can not be easier nowadays.

Of my other reasons I can name, since I am studying electrical engineering, who knows maybe I later need to write drivers for hardwares!

My questions are:
1- Am I right with the idea of learning C++ I mean is it add to my value if say I am going to work as a developer later?
2- What tools will I need to start programming in native C++ that is perhaps compilers and IDE


问:
How to get the most out of an annoying project
I was recently assigned a task of managing a small project.

The project has some technological aspects but the job is mainly doing managerial things: scheduling, making sure people do what they are suppose to, going to a lot of meetings, etc. Basically, it's not how the average programmer or even a team leader would like to spend his time.

Since I am not going to sneak out of this, I have found myself wishing I could teleport myself to some point of time after the project has ended. After pondering about it some more, I reached the conclusion that I hate working like that and I can't allow myself to work on a project that makes me think this way. I have to make the most out of this project.

So my goal is to make the most out of this unwanted project. How do I do that?

I thought about writing every day a "What I have learned today" list, that will help me see clearly that I am learning from this and not wasting my skills.

Do you have any recommendations on what can I do?

答:
I like your suggestion of making a list of "what I have learned today", but I would also say that it might be a good idea to create certain goals and objectives for your self that you can track your progress with during this project. That way you keep your eye on the goals instead of the frustrating aspects that are demotivating you at the moment. These goals could be things like fixing x number of issues per week, reaching project mile stones, your team completing x number of y per day, etc.

Another thing you could do is try to think of technology solutions that will make your management work easier. For instance work on a really cool Excel spreadsheet that manages and tracks certain variables about the project and reports on it in fancy graphs. This will give you a technological distraction while adding value to your management work and impress your superiors all at the same time. You could also perhaps think of new and innovative ways to slice and dice management data that you have / make use of in this project, or present feedback reports in an innovative new way that perhaps sheds new light on something. I know this is a bit vague but its very difficult to be specific if I don't know enough about the job or the project.

Lastly I think that developers are problem solvers by nature and we (usually) get satisfaction out of solving problems. So talk to your team and ask them to make a list of their top 3 frustrations in this particular project or in the team that YOU could help them with. Sure some will be outside of your control so forget about those, but try to put some focus on making changes or doing things different that will solve problems for your team. I'm sure that will bring a good amount of satisfaction.

Hope that helps.


问:
Is Java to Linux what .NET is to Windows?
Is Java becoming the de facto standard from Linux application development in the same way .NET is the standard for Windows application development?  If not why not?  </p>

答:
Not really, though perhaps it should (from the perspective of making the Linux desktop successful).

While you can use Java on Linux as a platform in a similar way to .Net on Windows there are two substantial differences:

.Net is fundamentally tied to the Windows platform, but Java is portable across pretty much all platforms. So Java isn't really "native" to Linux.

The Linux platform is much more heterogeneous, with substantial (some might say fragmented) communities around many different programming languages and toolkits. There's the python folks, the C++ folks, the C folks, Perl people etc.

Having said all that, I think the failure of the Linux community to properly embrace Java on the Desktop is the main reason why Linux hasn't yet been successful in the desktop space. Java and it's huge library/tool ecosystem is the only open source platform that can realistically compete and win with .Net for general purpose application development. And if more people developed Java applications (which can run identically on Windows and Linux) then the Microsoft desktop monopoly would be substantially weakened.


答:
I have never used Visual C or windows environment, so my answer will be biased. I feel if you want to learn c++, you should do it in on Linux. As Linux is open source platform, and used extensively on heterogeneous environments such as server, mobile, desktop, you will find lot more support when you run into problems as opposed to windows.

Next, you would do much better if you begin with plain c++ as opposed to Visual C++ as standard c++ can run on multiple devices. Also it is good time to jump into C++ as the new standard C++0x introduces lot more capabilities. Here is what the creator of C++ has to say about the new standard

“C++11 feels like a new language.” – Bjarne Stroustrup

Lastly, C++ is not a small language and will require at least a year of continuous learning and coding to get familiar with it. So sooner you start, the better it is. Also, if you decide to jump into Linux environment, you will sooner or later feel the urge to learn C, which looks similar to C++ on the skin, but is a very different beast under the skin.


答:
Take the opportunity to be the kind of manager you would like to work for. You have a chance to be involved in all those decisions that affect the development. Try and mentor some of the other programmers. If you find one that is really good, try and learn something from her.

Now's the time to see if you are cut out for this. Be careful, you might like it.

Title: How to get the most out of an annoying project

Body:
I was recently assigned a task of managing a small project.

The project has some technological aspects but the job is mainly doing managerial things: scheduling, making sure people do what they are suppose to, going to a lot of meetings, etc. Basically, it's not how the average programmer or even a team leader would like to spend his time.

Since I am not going to sneak out of this, I have found myself wishing I could teleport myself to some point of time after the project has ended. After pondering about it some more, I reached the conclusion that I hate working like that and I can't allow myself to work on a project that makes me think this way. I have to make the most out of this project.

So my goal is to make the most out of this unwanted project. How do I do that?

I thought about writing every day a "What I have learned today" list, that will help me see clearly that I am learning from this and not wasting my skills.

Do you have any recommendations on what can I do?


问:
What are your initial three steps when you are first presented with a software problem?
I am curious about the very early steps that a programmer's mind takes when it first encounters a problem that it is supposed to solve. How do you start reasoning about it ? What are the first questions you ask yourself ??.

Ok, let me make it more concrete for those of you who think the question is too vague or entirely situation dependent. Pick any of the following   requirements and think out loud about your very first hunches/impressions/tendencies about how to solve it.

1) build a simple word processor with about as much functionality as MS Word Pad

 2) design a single person card game (e.g. Solitaire)

 3) build a scientific calculator

 4) Any  problem of your choosing with similar scale/complexity as the above three

答:
Mentally I do the following, very quickly and abstractly

1) Requirements Gathering - I quickly create a mental list of functionality and how it may be implemented

2) Methodology - I try to figure out which technologies are best suited for the job

3) Identify Problems - Before even starting the project I try to identify any problems that may arise and how to avoid them from the get-go

In Process I do the following:

1) Requirements Gathering - I'll almost always create a Project Specification which lists all of the features, how the features work, what they do, what they don't do and which user groups will be using them. I think this is key, as it clearly defines goals for all parties and can aid in testing & Q.A. as well as provide an outline for development.

For paid projects, it also ensures clients have no unmet expectations, however I do this for Internal projects as well.

2) Development - Development for me includes setting up a development environment separate from the production environment, setting up Version Control (Git for me), and getting each feature done, doing some testing along the way.

3) User Experience - The UX phase involves having a Graphic Designer style all elements on the site/application as I'm a programmer and shouldn't be allowed to make any design decisions :P

It also involves testing the application and making any required tweaks. At the end of this phase the application/software/website should be ready for an initial release.

OwnerDisplayName: mumtaz

LastEditorDisplayName: mumtaz


答:
I have been criticized as being horribly depressing for this viewpoint but in my eyes I feel better about doing less than satisfactory work by looking at the results of how bad things could really be for me right now if I didn't catch X number of breaks, and also how thinking, how is the work I am doing right now going to pay off in my long term security.

What I mean by this is, if I get depressed about managerial discussions, scheduling in an awful tool that I have no choice over, writing drab reports to other people who will write drab reports, then I have to think to myself how fortunate I am that I live in the once great country of the USA, a pathetic vampiric crumbling empire that seems to do everything in its power to make life as difficult as possible for vast majority of the population.  The fact that I even have a job that affords me a wife, a nice house, an active social life, the ability to give to charity and the ability for modest savings makes me feel so unbelievably fortunate in the face of so much human despair that I see around myself everyday.

I live every day of my career not only thinking about how I can get ahead, but who I should suck up to, who I should avoid being seen with, and what do I have to do to ensure I will not be replaced by someone younger or someone offshore who is more desperate than myself.  I am only 28 so that is not a huge concern just yet, but I still actively look at everything I am doing day to day as slowly working to a position where I can jump into being a project manager, a business analyst, a software architect, or really anything technical at all that increases my versatility in quite possibly the most unforgiving and cutthroat job market that any of us have ever seen.  I am winning now, but what about tomorrow?  The day after?  How can I be certain that I won't be destitute when I am 50 and nobody will want to take a chance on me anymore?

Welcome the opportunity to learn project management skills, it is a window of opportunity that you are lucky if it opens to you once in your entire life, and you will only be stronger for learning it.


问:
n-layers architecture design, really worth the effort?
I was building an application in .Net for almost a year (almost alone), I took the decision to build it with a 3-layer design. Recently when finished the project, I analyzed if the effort of creating this application with layer design in mind really compensate for the "benefits" obtained implementing such design.

Out of port the desktop application to web without any major code rewrite and to be almost database-agnostic; I don't see any further benefits of this.

Any experiences, and thoughts?

答:
If your application does indeed have these separate layers (I am assuming UI, BLL and DAL), then:

You can write other UIs (desktop, mobile) without changes to other layers

You can make changes to your BLL and not effect the UI or DAL (and with several different UIs the changes will just happen automatically)

You can migrate to a different data store without the need to change the UI or BLL (so, sharding, NOSQL and clustering can be options)

Testing each layer in isolation is much easier

When you have such separation, you can also scale the different layers separately (need more power to the UI bit? You can add a web server to the farm. Need more DB power? Shard, cluster or whatever else makes sense, though normally such a change will require changing the architecture).

Of course, if you have developed a site that doesn't need this scale and will not needs to be changes in the above ways, then such an architecture can be over engineering.


答:
Databases get superceeded and vendors stop supporting old versions. UI's beccome out of date (it's very hard to support older version of ASP/ASP.net). There are new requirements for UI's these days with the advent of smart phones. If you need to replace either of these, you don't want to replace all the business logic. The business logic is the element that is likely to endure the longest (just think of 30 year old Cobol applications that are still running!). You may also at some point want to service orientate the application, and this will be easier if you can access the business logic directly.

Also, layering makes it much more maintainable and scalable, but also it makes it much more logically structured and readable. You know exactly where everthing needs to go, and when you come back to it, you know where it is. For example, I have worked on many 'forms over stored procedure' applications (This being a common alternative to an n-layered application) and I find the business logic strewn between the UI and the stored procedures. If there is a BLL, there is no excuse for it to be anywhere else other than the BLL (OK, except in very exceptional circumstances).

Also, I dispute the fact that an n-layered application really requires that much more effort to develop? I certainly think the development overhead is massively paid off by the maintainability.

Not all application warrant an n-layer architecture but I would imagine anything that took a year to develop would.

Title: n-layers architecture design, really worth the effort?

Body:
I was building an application in .Net for almost a year (almost alone), I took the decision to build it with a 3-layer design. Recently when finished the project, I analyzed if the effort of creating this application with layer design in mind really compensate for the "benefits" obtained implementing such design.

Out of port the desktop application to web without any major code rewrite and to be almost database-agnostic; I don't see any further benefits of this.

Any experiences, and thoughts?


问:
How many developers before continuous integration becomes effective for us?
There is an overhead associated with continuous integration, e.g., set up, re-training, awareness activities, stoppage to fix "bugs" that turn out to be data issues, enforced separation of concerns programming styles, etc.

At what point does continuous integration pay for itself?

EDIT: These were my findings

The set-up was CruiseControl.Net with Nant, reading from VSS or TFS.

Here are a few reasons for failure, which have nothing to do with the setup:

Cost of investigation: The time spent investigating whether a red light is due a genuine logical inconsistency in the code, data quality, or another source such as an infrastructure problem (e.g., a network issue, a timeout reading from source control, third party server is down, etc., etc.)

Political costs over infrastructure: I considered performing an "infrastructure" check for each method in the test run. I had no solution to the timeout except to replace the build server. Red tape got in the way and there was no server replacement.

Cost of fixing unit tests: A red light due to a data quality issue could be an indicator of a badly written unit test. So, data dependent unit tests were re-written to reduce the likelihood of a red light due to bad data. In many cases, necessary data was inserted into the test environment to be able to accurately run its unit tests. It makes sense to say that by making the data more robust then the test becomes more robust if it is dependent on this data. Of course, this worked well!

Cost of coverage, i.e., writing unit tests for already existing code: There was the problem of unit test coverage. There were thousands of methods that had no unit tests. So, a sizeable amount of man days would be needed to create those. As this would be too difficult to provide a business case, it was decided that unit tests would be used for any new public method going forward. Those that did not have a unit test were termed 'potentially infra red'. An intestesting point here is that static methods were a moot point in how it would be possible to uniquely determine how a specific static method had failed.

Cost of bespoke releases: Nant scripts only go so far. They are not that useful for, say, CMS dependent builds for EPiServer, CMS, or any UI oriented database deployment.

These are the types of issues that occured on the build server for hourly test runs and overnight QA builds. I entertain that these to be unnecessary as a build master can perform these tasks manually at the time of release, esp., with a one man band and a small build. So, single step builds have not justified use of CI in my experience. What about the more complex, multistep builds? These can be a pain to build, especially without a Nant script. So, even having created one, these were no more successful. The costs of fixing the red light issues outweighed the benefits. Eventually, developers lost interest and questioned the validity of the red light.

Having given it a fair try, I believe that CI is expensive and there is a lot of working around the edges instead of just getting the job done. It's more cost effective to employ experienced developers who do not make a mess of large projects than introduce and maintain an alarm system.

This is the case even if those developers leave. It doesn't matter if a good developer leaves because processes that he follows would ensure that he writes requirement specs, design specs, sticks to the coding guidelines, and comments his code so that it is readable. All this is reviewed. If this is not happening then his team leader is not doing his job, which should be picked up by his manager and so on.

For CI to work, it is not enough to just write unit tests, attempt to maintain full coverage, and ensure a working infrastructure for sizable systems.

The bottom line: One might question whether fixing as many bugs before release is even desirable from a business prespective. CI involves a lot of work to capture a handful of bugs that the customer could identify in UAT or the company could get paid for fixing as part of a client service agreement when the warranty period expires anyway.

答: CI is always always always worth it: The sense of security it gives you enables you to work at a faster rate than would be possible otherwise. The problem that you have seems to revolve around unit tests. I agree that unit tests are very expensive, but also think that (for many things) they are the least worst option that we have. Personally, and for the sorts of systems that I tend to work on, I swear by system-level tests operating on a combination of real-world and (possibly synthetic) pathological cases; It is cheaper than unit tests, and gets into those hard-to-reach corners of your conceptual universe: Donald Rumsfeld's "Unknown Unknowns".</p>


问:
How to prove an application is built on a bad codebase?
I'm currently reviewing a system built by some developers that previously worked at my job. The system works pretty well from a user's point of view, but when delving into code review it's a utter mess. I'm more than convinced that the way the application is built won't hold up for future updates, let alone high increases in usage.

The problem is that I know how bad it is, but my superiors don't. How can I prove it to my manager so he actually sees the problem and can be convinced to do minimal triage on the current codebase, and in the near future start a new line of development for the next version of the application?

答:
This is a tough situation to be in because from the user's perspective everything is at an acceptable and stable point now.  Primarily with non-technical managers, there is nothing to be concerned about at the moment, but asking to rewrite the codebase is an enormous decision and one that should not be taken lightly, especially on the opinion and efforts of a single man (yourself).

So you are in a tough spot of trying to make a case for a rewrite because of overwhelming technical debt (in your opinion, we don't have any examples and have to take your word for it) as well as being in the tough spot of having the difficulty of maintaining and adding features into this system.

Your estimates for new features will be high, justify these high numbers with facts, proving that these things will indeed take a great deal of time.  If you don't convey this properly then your manager may just assume you incompetent and you certainly don't want that.  When he questions the high estimates then explain why you feel the accumulated technical debt is hindering the ability to quickly and cheaply add features to the current software.  If your manager has two brain cells to rub together he will start to understand very quickly.

The point is that you should not try to convince your manager, but steer your manager with appropriate (and carefully selected) information that he/she can convince themselves that a rewrite is an acceptable course.  You have to make the manager think it was his/her idea all along.


问:
Tags or specify revision?
At my company, we have your typical svn structure.  Each project has branches, tags and trunk.

```<code>repo
-Project A
 * trunk
 * branches
 * tags
-Project B
 * trunk
 * branches
 * tags
-Project C
 * trunk
 * branches
 * tags
-Project D
 * trunk
 * branches
 * tags
-Application 1
 * trunk
 * branches
 * tags
</code>```

So Project A is core functionality pretty much all of our other projects use.  D may depend on C & B as well, and application 1 uses them all.  Note that we have many more libraries and applications than I've illistrated above, but its all done the same way.  The assemblies generated by building project A are included in needed library or application projects as externals.  We've got quite a few libraries like this.

What we've been doing after a release is tagging the RC branches we created for each project used by the application, and then these then become tags.

Obviously this is a fair amount of work as we ensure that tags only point to other tags, and you start by creating the tag for Project A, making the other stuff point to that, etc.,  the idea being we want to branch from the tags should a patch release be required before our next feature release.

Given the amount of effort that can be involved getting this all together, one proposal is to tag only the application's RC and for all the externals point to a specific revision.  If we need to create a branch to fix one of the libraries, branch from that revision and do the work then.

I'm not against this, as I would like to not have to spend the time getting all the tags for all the projects setup, but I wanted to ask, can anyone think of any pitfalls of this approach?  Is there any reason to create these tags over just pinning to a specific revision?

答:
The only advantage I can see to create the tags rather than pinning to a specific revision is that it allows for more description.  For example, tag/1.0.2-RC1 is a bit more descriptive than r12345.

My suggestion would be to tag the application's RC and then point all of the externals to specific tags on Project A, B, C, etc. for the verbosity reason noted above.

(But personally, I'm with Karpie and would split all of these projects into their own repos)

Title: Tags or specify revision?


答:
It depends on how cleanly all these elements are separated.

In order to put clarification on how exactly i see things - i am trying to put general

As you highlighted you can deal with this in two ways -

A. Single Product Approach

The entire space is one projects and while they are fairly independent - the repo doesn't recognize it.

In this case few things can be observed.

The same release number of any RC is applied to all object products. So if the repo moves from 1.2 to 1.3 via 1.2.1 and 1.2.3 - there is a corresponding revision of each element i.e. project1.1.2.1.so as well as project2.1.2.1.so.

Version number of tags of all projects and application has the same tag.

Between two versions of a particular singular repo, whether the projectA or projectB has any changes or not, the tag keeps advancing as per total progress.

In such case, when you take a branch from any point in trunk, the entire trunk must be mirrored.

Assuming that testing has been good, all projects and application with same version/tag are always perfectly compatible with each other.

B. Independent Product approach

Here each project is an independent product -

They must have different repo (or at least separate trunks for themselves).

The tagging is limited to the projects individually each part of repo will produce end product like - projectA.1.2.1.so OR projectB.1.5.lib

In such cases - when you branch - the branch is always only for the given project and any tags before/after the merge only applies to those projects.

Each project can have independent number of tags depending on the actual number of bugs within it.

In this case each different project advances with different amount - you always need to find which set of tags - for each other works compatibly with other projects. For example - projectA-1.2 works for projectB-1.2 all the way upto projectB-2.3 but breaks after projectB-2.5 or higher. Such nested dependencies is what you need to now manage through explicitly integration testing.

So what are the pros and cons?

In a simple terms - the single product approach is clumsy because all elements are copied when a branch is created. Now if before committing if someone changes something on another person's module it becomes a conflict and that too after some significant time in future when other person decides to commit/merge. This problem essentially grows as the number of people grow in the team.

One of the primary reason why single product approach helps is the simplicity. Ideally if you have a single authority for release management - every full release is not only tested to see that pieces work individually but also that all versions work together. The integration testing is always more painful when independent products grow and you need to keep a tab on multiple versions of each different products that works together and that is the job by itself.

Support cost increases in case of multiple product situation. This is understood in this way - suppose projectB-1.2 and projectB-1.7 depends on different compatible versions of projectA-0.8 and projectA-0.9. Now, if the projectA has got a bug which could have been affecting all its' clients (irrespective of compatibility) it has to be fixed twice - both in projectA-0.8 and projectA-0.9. This doubles the effort on bug support for projectA.

Further suppose if implementations in projectA-0.8 is found to be a bug (say already solved in projectA-0.9) but you realize that solution to this bug under 0.8 will help part of its clients, but break others; in this case projectA-0.8 needs to be further branched out separately to see that now both groups are supported.

Last but most important - when people work in independent systems the communication between them reduces. They establish their work based on their individual tests; later on when the application folk needs to put in all the modules together, they have to put effort to bring pieces together, you realize a lot of issues of integration and further, if the responsibility of the bugs are not appropriately fixed based on root cause, system will tend to accumulate tech debt over time.

In a nutshell the more break-up you do in terms of a projects/modules, more of the nesting dependencies issues arise.

However this complexity is worth it if the size of the repo is too large. In a single repo, everyday people may end-up stuck dealing with conflicts or mergers.

One of the practical solution

In our place this has been a long time debate with all of us.

A simple approach we try to follow is as follows. Initially we all start with a single product approach. As we realize that as APIs become more stable, and certain key objects becomes fairly stable, we remove them slowly to another repo so that it becomes black-box for everyone. This approaches balances the initial need to remain in close communication and integration, and longer term need to keep repo manageable.

Sorry, i wrote too much?

NOTE:
From your question - i felt that your current practice and proposed one are both slightly different from how i described; however, i have used the above scenarios since they are well outlined methods so easier to follow.

Title: Tags or specify revision?

Body:
At my company, we have your typical svn structure.  Each project has branches, tags and trunk.

```<code>repo
-Project A
 * trunk
 * branches
 * tags
-Project B
 * trunk
 * branches
 * tags
-Project C
 * trunk
 * branches
 * tags
-Project D
 * trunk
 * branches
 * tags
-Application 1
 * trunk
 * branches
 * tags
</code>```

So Project A is core functionality pretty much all of our other projects use.  D may depend on C & B as well, and application 1 uses them all.  Note that we have many more libraries and applications than I've illistrated above, but its all done the same way.  The assemblies generated by building project A are included in needed library or application projects as externals.  We've got quite a few libraries like this.

What we've been doing after a release is tagging the RC branches we created for each project used by the application, and then these then become tags.

Obviously this is a fair amount of work as we ensure that tags only point to other tags, and you start by creating the tag for Project A, making the other stuff point to that, etc.,  the idea being we want to branch from the tags should a patch release be required before our next feature release.

Given the amount of effort that can be involved getting this all together, one proposal is to tag only the application's RC and for all the externals point to a specific revision.  If we need to create a branch to fix one of the libraries, branch from that revision and do the work then.

I'm not against this, as I would like to not have to spend the time getting all the tags for all the projects setup, but I wanted to ask, can anyone think of any pitfalls of this approach?  Is there any reason to create these tags over just pinning to a specific revision?


答:
If you have just finished your application then you have not seen the benefits of this approach. You will find most of the benefit of doing this as you begin to make changes to the existing application. Think about how easy it will be to move items around in the UI as you change the application. Or how easy it will be to performance tune a specific portion of the data storage functionality without changing any other code. It is the separation of concerns that is important in the n-tier architecture. You will learn a lot from this experience only if you continue to maintain the code base. Everyone always uses the examples of "write a new UI", or "swap out the database examples". Theses cases are rare, if at all. What does happen is that you will need to add new features or modify existing ones. That is when you will reap the benefits of having your concerns separated into different layers.

With that having been said. An inappropriately written n-tier application can be just as difficult to maintain as an ad-hoc version. The key point of n-tier is separation of concerns. You have to look at every method you write, and ask yourself: How easy will it be to change this existing functionality without affecting other parts of the application? This is the reasoning behind both n-tier and SaaS development. They are just two different versions of the same thing: separation of concerns.