问:
When not to use Google Web Toolkit?
I'm considering use of GWT on a major in-house web app development project, namely it's major advantage in my eyes is the cross-compilation to Javascript which would (at least theoretically) help my team reduce the size of tech stack by one.

However, having been burnt before (like most devs), I would like to hear from programmers who did actually use it on any problems with GWT which would hamper, or limit, it's use within a certain problem domain.

What are the arguments against using GWT, and why?

答:
We use GWT for a big eGovernment web application (SOA in the backend) which has a heavy usage. The old UI was in DHTML but we had issues with browser compatibility, performance optimization and the development process, so we looked for alternatives.

Our requirements have been:

client side UI layer to minimize server load

browser compatibility

web based RIA

Easy performance optimizations

No client plugins installation necessary, should work with a plain windows installation

We choosed GWT and I never regret it. The new team had no or less DHMTL experience and therefore the Java dev process of GWT was very helpful. What you get  of the box is:

browser compatibility

Java based development process and code reuse

easy minimizing of requests (image bundle, ...)

easy agressive caching (new apps are completely cached at client side)

easy compression of all ressources (even with js on older buggy IEs)

and a lot more, to much to mention here

Our application issues only one request to the server on startup. On the negative side is that GWT (and also Android) have a poor design out of the box, but anyway if you apply your own look and feel you have to adapt the CSS. Alternatively you can use various component libraries for GWT which make it easy to apply proper styles and theming.

For me there is no point that maybe the HTML DOM is not as good as handcrafted, this was never an issue. When I develop in C++, I do not look at the generated assembler code. When I develop in GWT there was never a reason for me to look at the JS code and only once a reason to look at the DOM and do some refactoring.

For me GWT is the only choice when it comes to RIA development and I hope that GWT has a bright future. See the mission statement at:

[1] http://code.google.com/intl/de-DE/webtoolkit/makinggwtbetter.html#introduction

But it should not be unmentioned that Google don't use GWT on many of their internal projects and that at the moment there are some rumors around about the future of GWT, see

[2] http://googlewebtoolkit.blogspot.com/2011/11/gwt-and-dart.html

[3] https://plus.google.com/105933370793992913359/posts/bLfSagtziBC

Title: When not to use Google Web Toolkit?


问:
My Cassandra consultant left me and now I'm thinking about reverting to mysql
I run a middle size community and some time ago I started to develop social capabilities such as follow, status update, wall etc.

For some reason i thought that Cassandra was the right tool for the job so I looked online for a Cassandra developer and I found a very talented one.

Unluckily in the midst of the development the dev left (too much jobs) and so I'm here with a very nice class, a very nice demo, but a lot of fears that I won't be able to handle basic things such as compaction, scaling etc.

My biggest fear is to go online with all this coolness and then having a site inaccessible for hours or days.

The mysql consultant (very talented too) keeps saying me that I should stick with Mysql which I know rather well and in case something's wrong we can manage.

In that case I should take the class made for cassandra and abstract it for Mysql.

My question is this: Should I find another dev/consultant and stick with Cassandra because for social things it is definitely the best tool for the job, or should I listen to the Mysql consultant and revert to Mysql?

About 15k login each day
Average 20 actions per user
Avg 6 followers x user

(These are current statistics, but of course I'd like to increase them as much as possible.)

答:
If you are familiar with MySQL and your site isn't of incredibly huge magnitude, I'd stay with MySQL for now until there are more resources to look into hiring people well-versed with technologies like Cassandra.

MySQL is a great choice for different functionalities due to its pluggable engine architecture. There's a transactional engine using fractal trees for storing its index structure called TokuDB. It scales incredibly well compared to InnoDB for example and has great additional functionality such as specifying multiple clustered indexes. It isn't free but it isn't expensive to the point it's not worth thinking about it. AFAIK, it's free up to 50gb of data used in production.

I've been using that engine after trying out HandlerSocket and I must say it's really, really an impressive piece of software. Since it's a drop in replacement for InnoDB, there is no learning curve. My suggestion is sticking with MySQL for the moment. Stats you mentioned aren't something MySQL can't handle.

ContentLicense: CC BY-SA 3.0


问:
What are functional-programming ways of implementing Conway's Game of Life
I recently implemented for fun Conway's Game of Life in Javascript (actually coffeescript but same thing). Since javascript can be used as a functional language I was trying to stay to that end  of the spectrum. I was not happy with my results. I am a fairly good OO programmer and my solution smacked of same-old-same-old. So long question short: what is the (pseudocode) functional style of doing it?

Here is Pseudocode for my attempt:

```<code>class Node
  update: (board) ->
    get number_of_alive_neighbors from board
    get this_is_alive from board
    if this_is_alive and number_of_alive_neighbors < 2 then die
    if this_is_alive and number_of_alive_neighbors > 3 then die
    if not this_is_alive and number_of_alive_neighbors == 3 then alive

class NodeLocations
  at: (x, y) -> return node value at x,y
  of: (node) -> return x,y of node

class Board
  getNeighbors: (node) ->
   use node_locations to check 8 neighbors
   around node and return count

nodes = for 1..100 new Node
state = new NodeState(nodes)
locations = new NodeLocations(nodes)
board = new Board(locations, state)

executeRound:
  state = clone state
  accumulated_changes = for n in nodes n.update(board)
  apply accumulated_changes to state
  board = new Board(locations, state)
</code>```

答:
Here's a short purely functional version in Clojure. All credit goes to Christophe Grand who published this in his blog post: Conway’s Game of Life

```<code>(defn neighbours [[x y]]
  (for [dx [-1 0 1]
        dy (if (zero? dx) [-1 1] [-1 0 1])]
    [(+ dx x) (+ dy y)]))

(defn step [cells]
  (set (for [[loc n] (frequencies (mapcat neighbours cells))
             :when (or (= n 3) (and (= n 2) (cells loc)))]
         loc)))
</code>```

The game can then be played by repeatedly applying the "step" function to a set of cells, e.g.:

```<code>(step #{[1 0] [1 1] [1 2]})
=> #{[2 1] [1 1] [0 1]}
</code>```

The cleverness is the (mapcat neighbours cells) part - what this does is create a list of eight neighbours for each of the active cells and concatenates them all together. Then the number of times each cell appears in this list can be counted with (frequencies ....) and finally the ones that have the right frequency counts make it through to the next generation.

Body:
Here's a short purely functional version in Clojure. All credit goes to Christophe Grand who published this in his blog post: Conway’s Game of Life

(defn neighbours [[x y]]
  (for [dx [-1 0 1]
        dy (if (zero? dx) [-1 1] [-1 0 1])]
    [(+ dx x) (+ dy y)]))

(defn step [cells]
  (set (for [[loc n] (frequencies (mapcat neighbours cells))
             :when (or (= n 3) (and (= n 2) (cells loc)))]
         loc)))

The game can then be played by repeatedly applying the "step" function to a set of cells, e.g.:

(step #{[1 0] [1 1] [1 2]})
=> #{[2 1] [1 1] [0 1]}

The cleverness is the (mapcat neighbours cells) part - what this does is create a list of eight neighbours for each of the active cells and concatenates them all together. Then the number of times each cell appears in this list can be counted with (frequencies ....) and finally the ones that have the right frequency counts make it through to the next generation.


问:
Why is Conway's "Game of Life" used for code retreats?
Code Retreat is an all-day training event that focuses on the fundamentals of software development. There's a "global" code retreat day coming up, and I'm looking forward to it. That said, I've been to one before and have to say there was a huge amount of chaos... which is fine.

One thing that I still don't get is why the "Game of Life" is a good problem for TDD, and what good and bad TDD for it feels like.

Realize this is a pretty open ended question, so feel free to comment.

答:
Game of Life is in one hand a very simple set of rules, on the other contains some of the worst caveats of advanced programming, related to scalability. While the results are deterministic, there is the challenge of infinite playfield and infinite number of cells to process.

If the challenge specs include minimum performance and maximum memory footprint, then the tests include rapidly growing patterns, or patterns that travel in various directions far and wide, this may become a very frustrating challenge.

You got the known input and known output after X iterations, and you know all the steps to get there... except the steps take too much and too long. You must perform some pretty extreme optimizations to fit within specs. The trivial algorithm with scanning a fixed size double-buffered 2d array of bits becomes totally inadequate as its performance degrades with O(n^2) of the size. Treating filled blocks as new spawned objects suddenly eats up tons of memory and gets slow. Separating everything into limited size boards works sometimes, fails sometimes...

And since most of "global" tests will fail the performance standard, you need to develop smaller goals, smaller sub-tests that get the caveats ironed out...


问:
Piece of code for interview debugging abilities test?
May be someone has a piece of code, that would work as a test for debugging abilities? We will give ability to use Visual Studio, so it should be hardly solvable by doing manual tracing and show us, that candidate is really good at debugging.</p>

答:
The best thing I have seen is to give the candidate a test before the interview and let them bug fix the code at the interview.  Make the specs vague enough so that they will have to make judgement calls and the inputs to the problems can be vast -- say reading comma separated value data.  If you want to be evil, have them modify an already existing program.

It will show you how they fix their own mistakes.


问:
How do you learn to effectively use more than one framework
Someday, my leader told me that don't reinvent the wheels, use framework built-in classes. (with a serious mood) when I implement some algorithm has been supported by .NET fx. And seriously, I didn't know about these support before, cause this is the first time I work with .NET).

So I have this questions.
For example, for building an Web-App we have some ways:

C# with ASP.NET framework

Java with JavaEE (and friends like Struts, Spring v.v.) framework.

PHP with Zend framework.

...

It just takes about 1 months to learn language (C#, Java, PHP...), BUT learning to use a framework effectively takes you at least SOME YEARS working (to know every bit of code has been built-in).

So, how do you learn to use effectively 2 (or more)  frameworks? Any ideas are welcome!

答:
First of all, it shouldn't take years. It shouldn't really take anything. There's no good reason to spend your time pecking at every tiny detail in a framework. Mainly because they keep growing, and fast! It's better to just use your time to actually be productive.

Second of all - here's an easy way to solve your problem: when you want to accomplish something that's at least one of the following:

Not entirely trivial

Not very simple to implement most efficiently

You're not so sure about how to do it from scratch

You're not sure you're aware of all the edge-cases

You need a generic solution

Just Google for "MY FRAMEWORK - WHAT I WANT TO DO" and see what it has to say.


问:
A programming language that does not allow IO. Haskell is not a pure language
Are there any 100% pure languages (as I describe in the Stack Overflow post) out there already and if so, could they feasibly be used to actually do stuff? i.e. do they have an implementation? I'm not looking for raw maths on paper/Pure lambda calculus. However Pure lambda calculus with a compiler or a runtime system attached is something I'd be interested in hearing about.</p>

答:
It seems to me you're trying to reinvent Haskell.

The language doesn't need to have side effects at all. The run-time system does. The compiler/run-time system simply needs to search for the main function and treat it as an entry-point to the program as a whole.

Nice description of how IO is done in Haskell.

Hell, maybe you could execute until you need to prompt the user, wrap up the remainder of the code as a completely new program in the return type

You mean monads?

```<code>>>= :: M a -> (a -> M b)
</code>```

After the first half (M a) prompted the user to provide data (of type a), the second half (a -> M b) is the the "remainder" you describe.

If Haskell allowed you to introspect functions instead of just allowing you to run them, it would also be homoiconic.

Body:
It seems to me you're trying to reinvent Haskell.

The language doesn't need to have side effects at all. The run-time system does. The compiler/run-time system simply needs to search for the main function and treat it as an entry-point to the program as a whole.

Nice description of how IO is done in Haskell.

Hell, maybe you could execute until you need to prompt the user, wrap up the remainder of the code as a completely new program in the return type

You mean monads?

>>= :: M a -> (a -> M b)

After the first half (M a) prompted the user to provide data (of type a), the second half (a -> M b) is the the "remainder" you describe.

If Haskell allowed you to introspect functions instead of just allowing you to run them, it would also be homoiconic.


问:
UML Diagrams of Multi-Threaded Applications
For single-threaded applications I like to use class diagrams to get an overview of the architecture of that application. This type of diagram, however, hasn’t been very helpful when trying to understand heavily multi-threaded/concurrent applications, for instance because different instances of a class "live" on different threads (meaning accessing an instance is save only from the one thread it lives on). Consequently, associations between classes don’t necessarily mean that I can call methods on those objects, but instead I have to make that call on the target object's thread.

Most literature I have dug up on the topic such as Designing Concurrent, Distributed, and Real-Time Applications with UML by Hassan Gomaa  had some nice ideas, such as drawing thread boundaries into object diagrams, but overall seemed a bit too academic and wordy to be really useful.

I don’t want to use these diagrams as a high-level view of the problem domain, but rather as a detailed description of my classes/objects, their interactions and the limitations due to thread-boundaries I mentioned above.

I would therefore like to know:

What types of diagrams have you found to be most helpful in understanding multi-threaded applications?

Are there any extensions to classic UML that take into account the peculiarities of multi-threaded applications, e.g. through annotations illustrating that

some objects might live in a certain thread while others have no thread-affinity;

some fields of an object may be read from any thread, but written to only from one;

some methods are synchronous and return a result while others are asynchronous that get requests queued up and return results for instance via a callback on a different thread.

答:
The most important insight about how thread executions happen can be depicted by what is known as sequence diagram. Here is an example from wikipedia

This diagram essentially draws the list of events along with a direction over a vertical single line often called lifeline. In this case, each thread is an owner of it's own life line. The diagram allow representation all types of events such as synchronous, asynchronous etc.

The other most important thing in such systems is the state-charts or state-diagrams. Usually, this applies only if the model is represented as a state machine. However, in most multi threaded systems (where threads are non-trivial) it is best that they are designed to function with isolated algorithms for different states.

There are other diagram types like interaction diagram and communication diagram but i think trying to draw sequence diagram and state diagrams will put maximum clarity.


问:
Best algorithm to correlate similar articles
which is the best way to correlate and group similar articles?

I mean something like Google News, which groups under a single topic different articles from different sources.

I'm not interested in something much sophisticated, it is just important to be efficient in terms of speed and resources needed. I can live with a correlation only on short text like the titles of the articles, not the article itself.

I read a paper which talks about tuples of two or three words (best with three) to extract and use to produce a score to achieve the correlation, but it's way too much academic for me

答:
You can use Lucene Term Vectors.

Here is a blog post explaining it in detail.
http://sujitpal.blogspot.com/2011/10/computing-document-similarity-using.html

Lucene is an indexing library:
http://lucene.apache.org/java/docs/index.html


问:
What is jQuery and JavaScript's role in MVC?
I'm not sure I understand the role of jQuery/JavaScript in MVC. I've found an article about it on A List Apart, but it doesn't clear anything up for me.

Does it bridge the communication between the View and the Controller, or does it do something else?

答:
Your question contains a mismatch of two different levels of abstraction. MVC is a design pattern. JavaScript is a language, and libraries like jQuery are written in that language.

You might ask, what is the role of English in the telling of jokes? Jokes can happen in any language. English is one language in which a joke could be implemented.

Classic web MVC is a server-side thing and display-level technologies like JavaScript are part of the "View" layer, but there are also MVC frameworks that operate entirely on the client, entirely in JavaScript.


问:
What's your favourite quote about programming?
What's your favourite quote about programming?

One quote per answer, and please check for duplicates before posting!

答:
Just use string you G-- d---ed savages!

during debate about merits of  char[] vs string

LastEditorDisplayName: Roger Pate

ContentLicense: CC BY-SA 2.5


问:
Significance and role of Node.js in Web development
I have read that Node.js is a server-side javascript enviroment. This has put few thought and tinkers in my mind.

Can we develop a complete data-drivent web application utilizing just JavaScript (along with node.js), HTML5 and CSS? Do we still need to use some server-side scripting language (e.g. C#, PHP)?

In case we still need to use other scripting languages, what is node.js worth for, or useful?

NOTE: Pardon with my knowledge about node.js.

答:
Can we develop a complete data-drivent web application utilizing just the javascript(alongwith node.js) , HTML5 and CSS.

Yes, using node.js can mean that the only programming language you use is javascript, throughout the application stack.

In case, we still need to use other scripting language, then what node.js is worth for or useful ?

No need for another scripting language.

Even if you do use other scripting languages node is still useful - its non-blocking nature and fast response may make it ideal for some parts of your application.

Things to keep in mind about node.js:

The programming model uses callbacks. A lot. This takes time to get used to.

You can pass JSON between client and server and they will both be able to consume it natively.

node has no blocking (achieved by using all those callbacks), so responds very fast.


答:
You keep solving problems with the framework in question.

That's about it.

(IMO you don't really learn a language in a month, either, but that's a different issue.)

Title: How do you learn to effectively use more than one framework

Body:
Someday, my leader told me that don't reinvent the wheels, use framework built-in classes. (with a serious mood) when I implement some algorithm has been supported by .NET fx. And seriously, I didn't know about these support before, cause this is the first time I work with .NET).

So I have this questions.
For example, for building an Web-App we have some ways:

C# with ASP.NET framework

Java with JavaEE (and friends like Struts, Spring v.v.) framework.

PHP with Zend framework.

...

It just takes about 1 months to learn language (C#, Java, PHP...), BUT learning to use a framework effectively takes you at least SOME YEARS working (to know every bit of code has been built-in).

So, how do you learn to use effectively 2 (or more)  frameworks? Any ideas are welcome!


问:
RFC: Extending the MVC Design Pattern
I've been using the MVC pattern in my applications for years (with full separation of the controller from its views).

Having to implement several hundred views to represent a little over 100 model's for a potential contract, this time around I'd like to reduce the development time of my UI tasks and also add a few additional features (view decoration, etc).

I'm curious to find out if anyone has used or even implemented a design such as the one I'll explain bellow and if so, what were your pros and cons were.

Without getting into too much detail, I'm going to simply elaborate on an example of an API I have been juggling with in my head for a few days along with some explanations a bit later on, so here goes:

```<code>Model m = dao.getInstance(ID);  // ie: possibly fetch it from a database

VTextField text = new VTextField();  // simply 'extends' the Swing components

text.setModel(m);

Decorator deco = DecoratorFactory.getInstance();  // specific to a customer

text.setDecorator(deco);

Controller c = ControllerFactory.getInstance(m);

text.setController(c);

Validator v = ValidatorFactory.getInstance(m);  // get the current validator

c.setValidator(v, "validateText");
</code>```

So in the example above, the idea is that I will have the same application for several clients.  Although each have accepted the general usability, each want their branded L&F to it, some based on business rules (ie: a text field has errors, the background of text-field should be in yellow with red fonts... an other want the text in black and the background yellow with a red border).

What I was thinking was that on any event (on focus, loss focus, key typed, etc), the component would basically invoke the controller. In turn, the controller (through reflection) would invoke the validator.  If validation passes, the controller simply updates the model.  If validation fails, the controller does not update the model.

The controller would keep a state of all of this (viewing, editing, editing with error, etc) and would delegate to the decorator which would adjust the L&F of each component based on client demands.

This would avoid a ton of 'if/else' blocks directly in a single controller.  The controller, validator and decorator knows which concrete instance to load based on which client is running the application.  This way, I can separate the logic for each client and reuse when it is shared behavior.

The decorator doesn't overide the paintXXX() methods, but simply calls the 'setBackground(c)', 'setBorder(b)' and all of these setter methods already available in the Swing components.  The reason I extend each component is simply to add the 'setModel(m)' and 'setController(c)' methods along with any framework logic I'll need.  When the component is in 'view' mode, it usually doesn't paint the border and background and all that stuff (looks more like a traditional web page).  When it is in 'edit' mode then it looks more like a Swing component.

When I design application UI's I usually stick to only a few major components (JTextField, JTextArea, JPanel, etc).  So it wouldn't be too much work on that side.

I have not started to implement any of this stuff just yet, so if you know of existing libraries which does something similar, please point them out.

My only real issues I have at this time is how to handle cases where component depend on each other.  For example, two text fields having an int value.  If one field is odd then the other must also be odd and if one is even, then the other must be even.  When the validation occurs, the validator would need the value of the other text field to properly validate... so I still have not ironed out that part.

答:
This is a desktop UI, right?

This might be too far afield for you, but ages ago I came up with (out of necessity) a different way of programming UIs.
I've implemented it when I needed it in languages C, Lisp, C++, Visual Basic, and C#.
In the recent incarnations I called it dynamic dialogs, and it saves about an order of magnitude of code volume over MVC and other event-based patterns.

The basic idea is I need a domain-specific-language (DSL) to program the UI.
For example, in Windows there is a resource-compiler (RC) language used to describe dialogs.
It's a good DSL, but the problem with it is it's too "static". It lives outside the main programming language (MPL), and it doesn't have access to all the variables and control structure in the MPL.
As a result, it has to be surrounded by a lot of MPL code to handle events, move data in and out of controls, show and hide controls, or gray them, etc.
All that puffs up the code volume and makes it difficult to modify,
like adding a control takes several different coding steps in different places.
Tools can help with this, but removing a control also takes several coding steps you get no help with.
What's more, if you want any dynamic content, such as whole groups of controls appearing/disappearing dynamically, or varying numbers of them, it can be done but is relatively complicated to program.

In this DSL, I write a function (with sub-functions that it calls) in the MPL to paint the UI at any given point in time.
Then that function is executed under a control structure called differential execution which transforms the function into one for also doing incremental update, as well as erasing, of the UI.
So I don't have to write code to make dynamic changes to the UI.
I don't have to write code to move data in and out of controls.
That's all buried in the dynamic dialog implementation layer.
I don't have to write separate event handlers, or invent names for controls.
The event-handling code is embedded right in the code that paints the UI.
If I need the event-handling code to be separated from the paint code, it's simple enough to make it a separate function, but I don't have to.

It's a different pattern/paradigm (whatever you want to call it).
If I want to keep separate responsibility for appearance, model, activities, I can,
but very often I don't need to.
It does save about an order of magnitude of coding effort (and bugs), and it "just works".

So I don't know if that's any use to you, but if you want to move beyond MVC, I understand completely.

Title: RFC: Extending the MVC Design Pattern


答:
LDA is surely a way to get your job done - however it is complicated and involves the article.

"correlation only on short text like the titles of the articles", the information correlated in titles are too little to construct any model

Title: Best algorithm to correlate similar articles

Body:
which is the best way to correlate and group similar articles?

I mean something like Google News, which groups under a single topic different articles from different sources.

I'm not interested in something much sophisticated, it is just important to be efficient in terms of speed and resources needed. I can live with a correlation only on short text like the titles of the articles, not the article itself.

I read a paper which talks about tuples of two or three words (best with three) to extract and use to produce a score to achieve the correlation, but it's way too much academic for me


问:
Maintaining Regex in a .net application
I am sure everybody has had his/her share of regex woes.

We have a big application with around 30 developers working on a mvc3 web application , and the two fold regex validations (front-end and server side) is becoming a nightmare to maintain.

Is there a way to keep all the regexes in one place ? so that they can be used as attributes for entities and also be used for validations in the controller?

答:
What are you using for validation now? Generally, the default, built-in DataAnnotations do just what you are describing. Another option is FluentValidation which also works with client-side validation.

In any case this is a solved problem in general.

Title: Maintaining Regex in a .net application


答: you are talking about shared regex`s for JavaScript (ECMA) and C# (NET) correct? this is not possible because .NET and ECMA use different flavors, see Regular Expression Flavor Comparison for more info.</p>

Title: Maintaining Regex in a .net application

Body:
I am sure everybody has had his/her share of regex woes.

We have a big application with around 30 developers working on a mvc3 web application , and the two fold regex validations (front-end and server side) is becoming a nightmare to maintain.

Is there a way to keep all the regexes in one place ? so that they can be used as attributes for entities and also be used for validations in the controller?


答:
Do not mistake Node.js for a web development framework. It can be used that way, but so can Ruby without Rails. That doesn't mean you should.

Node.js is simply an event-driven library, written in Javascript. That is, it runs a script in a single thread, but using a system of queues and callbacks to free up that thread for other processing whenever it is doing something which takes time but not resources.

This replaces thread-based libraries, which tend to move the processor from thread to thread when they are all trying to work. This kind of context switching is costly so, generally, event-driven will be faster.

There are a couple of caveats to that though. Event-driven paradigms do not run over multiple processors so, if the load is fairly low, a thread-driven paradigm can be faster by sharing its work across cores (this is not an assumption you can make for certain with all frameworks though).

[Edit, ref Raynos's comment] It appears that the above is easily resolved by running a load-balanced cluster of node.js servers -- one for each core.

And code written to use event-driven paradigms must free up the thread whenever it can, otherwise all other requests will queue up behind it, making it considerably slower than a thread-based paradigm. Luckily most of the work there has been done for you and there are plenty of web development frameworks which sit on top of Node.js to make your life easier.

Pick the right one of those for your needs and yes, you will be able to use Javascript throughout your development stack.

Title: Significance and role of Node.js in Web development

Body:
I have read that Node.js is a server-side javascript enviroment. This has put few thought and tinkers in my mind.

Can we develop a complete data-drivent web application utilizing just JavaScript (along with node.js), HTML5 and CSS? Do we still need to use some server-side scripting language (e.g. C#, PHP)?

In case we still need to use other scripting languages, what is node.js worth for, or useful?

NOTE: Pardon with my knowledge about node.js.


问:
Stuff every programmer needs while working
I've been tasked with creating a fun and relaxing environment, one thing I know that I want is ergonomic mice and keyboards, others have suggested exercise balls and bands.

What is it that every programmer needs while working? What might not be necessary but would be nice to have anyway?

Note: this question was asked previously, but has been recommended to be posted here. See this link for the previous responses: https://stackoverflow.com/questions/3911911/stuff-every-programmer-needs-while-working-closed

答:
A great reference library

Google is great for many things, but it's no substitute for a good collection of books.  Searchable EBooks preferred, like the O'Reilly Safari collection.


答:
You could store the regexes in a table in your database, with a name a the key and then the two variants for front-end and back-end use, soemthing like:

```<code>regex_name | front_end                       | back end
-------------------------------------------------------------------------------
post_code  |"[a-zA-Z]\d[a-zA-Z] \d[a-zA-Z]\d"|"[a-zA-Z]\d[a-zA-Z] \d[a-zA-Z]\d"
</code>```

Of course, putting this in the database could make things difficult if you need a regex before you're connected to the database (probably won't happen in this case, but you never know) so you could implement a similar idea with a static class that just has a dictionary of names and the text for the regex versions.

Or you could store this in a CSV file and then load it into a cache at application startup. There are many ways to do this, I'm not sure what is the best for your team.

Title: Maintaining Regex in a .net application

Body:
You could store the regexes in a table in your database, with a name a the key and then the two variants for front-end and back-end use, soemthing like:

regex_name | front_end                       | back end
-------------------------------------------------------------------------------
post_code  |"[a-zA-Z]\d[a-zA-Z] \d[a-zA-Z]\d"|"[a-zA-Z]\d[a-zA-Z] \d[a-zA-Z]\d"

Of course, putting this in the database could make things difficult if you need a regex before you're connected to the database (probably won't happen in this case, but you never know) so you could implement a similar idea with a static class that just has a dictionary of names and the text for the regex versions.

Or you could store this in a CSV file and then load it into a cache at application startup. There are many ways to do this, I'm not sure what is the best for your team.


问:
What is the best way to design a table with an arbitrary id?
I have the need to create a table with a unique id as the PK.  The ID is a surrogate key.  Originally, I had a natural key, but requirement changes have undermined this idea.  Then, I considered adding an auto incrementing identity.  But, this presents problems.

A.  I can't specify my own ID.

B.  The ID's are difficult to reset.

Both of these together make it difficult to copy over this table with new data or move the table across domains, e.g. Dev to QA.  I need to refer to these ID's from the front end, JavaScript...so they must not change.

So, the only way I am aware of to meet all these challenges is to make a GUID ID.  This way, I can overwrite the ID's when I need to or I can generate a new one without concern for order (E.G. an int based id would require I know the last inserted ID).

Is a GUID the best way to accomplish my goals?  Considering that a GUID is a string and joining on a string is an expensive task, is there a better way?

答: Based on what you have told us, GUID is the best "built-in" way to meet your needs. trying to come up with a "roll-your-own" key that meets your needs sounds error prone, difficult, and like you would be reinventing the wheel.</p>


答:
GUID (the uniqueidentifier-data type in SQLServer) seems like the best option based on the information you provided. I work on a large application that has tables with 500000+ rows using GUID's as primary keys with some pretty large joins and the bottleneck is never in the joins of the primary keys.

Various other sources also seem to indicate that GUID's are a good choice, these are worth checking out:

http://www.informit.com/articles/printerfriendly.aspx?p=25862 talks about GUID performance and gives a clear indication with numbers as to the impact.

http://databases.aspfaq.com/database/what-should-i-choose-for-my-primary-key.html gives a decent pro/con analysis of the usage of GUID's versus integers.

Some of the bigger issues seem to be:

Loss of chronology (no way to know which row was inserted last and no ability to remove everything inserted after a certain point in time), can be fixed easily by using an 'insertdate'-column containing the date and time the row was added

Larger storage requirements but unless you deal with very large databases storage is pretty cheap

Harder to remember and work with in testing which is a valid issue but there are often alternatives to using a GUID to identify a row

I'm inclined to say that performance here would not be the issue and based on your requirements GUID are a very good - if not your only - choice.

Title: What is the best way to design a table with an arbitrary id?

Body:
I have the need to create a table with a unique id as the PK.  The ID is a surrogate key.  Originally, I had a natural key, but requirement changes have undermined this idea.  Then, I considered adding an auto incrementing identity.  But, this presents problems.

A.  I can't specify my own ID.

B.  The ID's are difficult to reset.

Both of these together make it difficult to copy over this table with new data or move the table across domains, e.g. Dev to QA.  I need to refer to these ID's from the front end, JavaScript...so they must not change.

So, the only way I am aware of to meet all these challenges is to make a GUID ID.  This way, I can overwrite the ID's when I need to or I can generate a new one without concern for order (E.G. an int based id would require I know the last inserted ID).

Is a GUID the best way to accomplish my goals?  Considering that a GUID is a string and joining on a string is an expensive task, is there a better way?


问:
Would refusing to use a PHP framework be a bad idea?

Possible Duplicate:

  When do I need to use a framework?

I feel fairly competent at creating a number of applications in PHP and thus far have not seen the need to use one of the popular frameworks (CakePHP, Zend, etc).

As a programmer it gives me comfort to know exactly what my code is doing and I suppose before now that has made sense since I've been learning the language.

Is it ignorant of me to not want to use one of these mainstream frameworks? Will it hurt my productivity? Why should I not just create me own code base that makes sense for me?

Other than possibly hindering later career choices where many roles might require framework experience, I'm not sure I'm missing out...

答:
Can you create your own code that is as feature-rich and extendable as your client wants, in the allotted time frame? If so, then go for it! But other developers who make use of frameworks may have an edge over you when they can get their systems built and running faster than you.

Also, if you decide one day to apply for a PHP job that uses some popular framework, which you have no related experience in (in the same framework or even a similar framework), it may hurt your chances of getting the job, if your equal to the other candidates in all other areas.

I agree with you that sometimes it's discomforting to not really know what's happening "under the hood", but honestly, there isn't always the time to build everything from scratch (fun though it may be).


答: You can put the regex strings in your web config and call they dynamically in your page and your code.  In this manner the strings will exist in a single location, will be able to be modified with out requiring a recompile, and will be available to your code through out your application.</p>

Title: Maintaining Regex in a .net application


答:
In this case it takes longer to develop something than to understand how something works.

If you want to know how things work, you can just read source code. On top of that, frameworks usually address some esoteric problems which you're probably unaware of in your personal code. And even if you are, the framework developers are committed to fixing any peculiarity that ever comes up, and fixing it well and tested.

Learn to use popular frameworks. Learn how they work inside and why. It'll only do you good.

Title: Would refusing to use a PHP framework be a bad idea?

Body:
Possible Duplicate:

  When do I need to use a framework?

I feel fairly competent at creating a number of applications in PHP and thus far have not seen the need to use one of the popular frameworks (CakePHP, Zend, etc).

As a programmer it gives me comfort to know exactly what my code is doing and I suppose before now that has made sense since I've been learning the language.

Is it ignorant of me to not want to use one of these mainstream frameworks? Will it hurt my productivity? Why should I not just create me own code base that makes sense for me?

Other than possibly hindering later career choices where many roles might require framework experience, I'm not sure I'm missing out...


答:
Refusing to use frameworks isn't always a bad idea.  However, at the same time I'd question if you are using your own web server software, PHP compiler or interpreter, and other tools so that you really know exactly what your code is doing as otherwise you are relying on other tools which is what a framework gives.

Be careful of approaching arrogance in terms of how you view those frameworks.  If you haven't thought about or even seen the frameworks, then you may have a prejudicial view that is worth remedying I'd consider.  While it may be nice to optimize your productivity, are you really prepared to have to create some set of metrics and experiments to determine what is and isn't working in your life?


答:
Note that while GUID sounds good, you must be careful about:

1-Your server must support it (Microsoft backend for example) so you can generate it automatically to guarantee its correctness and uniqueness.

2-Your database(s) must support it (Microsoft SQL Server for example), because if you move your data to another database, it may be cumbersome to generate it.

3-You must have a consistent way to generate the values (either from the Client or from the server) - This way you guarantee consistency (this is a personal guess).

4-The user must not have to enter it because it is very cumbersome.

5-It does not preserve sequence, so you can't 'reset' it and start over. but you can assume that it would be unique.


问:
I'm graduating with a Computer Science degree but I don't feel like I know how to program
I'm graduating with a Computer Science degree but I see websites like Stack Overflow and search engines like Google and don't know where I'd even begin to write something like that. During one summer I did have the opportunity to work as a iPhone developer, but I felt like I was mostly gluing together libraries that other people had written with little understanding of the mechanics happening beneath the hood.

I'm trying to improve my knowledge by studying algorithms, but it is a long and painful process. I find algorithms difficult and at the rate I am learning a decade will have passed before I will master the material in the book. Given my current situation, I've spent a month looking for work but my skills (C, Python, Objective-C) are relatively shallow and are not so desirable in the local market, where C#, Java, and web development are much higher in demand. That is not to say that C and Python opportunities do not exist but they tend to demand 3+ years of experience I do not have. My GPA is OK (3.0) but it's not high enough to apply to the large companies like IBM or return for graduate studies.

Basically I'm graduating with a Computer Science degree but I don't feel like I've learned how to program. I thought that joining a company and programming full-time would give me a chance to develop my skills and learn from those more experienced than myself, but I'm struggling to find work and am starting to get really frustrated.

I am going to cast my net wider and look beyond the city I've grown up in, but what have other people in similar situation tried to do? I've worked hard but don't have the confidence to go out on my own and write my own app. (That is, become an indie developer in the iPhone app market.) If nothing turns up I will need to consider upgrading and learning more popular skills or try something marginally related like IT, but given all the effort I've put in that feels like copping out.

答:
Graduating from school does not make us experts. It takes about a decade of good work (not just any type of work) for one to become an expert of sorts.

One of the great problems with CS schools nowadays is that they siphon students into a minimal curriculum of 60 credits. Unfortunately, a lot more has to happen for a student to get enough practice to develop a sound base of programming skills (before entering the work force.)

For me, it took me about 1.5 years longer to get my BS simply because I (and many of my peers back then) took a lot more programming courses. The typical student now simply takes Programming 101 and 102 (possibly in Java or C#) before going into data structures. Back then, I took Basic, Pascal I and II, C I and II, C++, x86 Assembly, expert systems, Delphi and Ada before setting foot on a data structures class. I wasn't alone in that.

It was the norm for many of us back then. That is we had 30 credit hours of programming before hitting data structures whereas now a student typically has a meager 6 to 9 credit hours.

This is not counting internships and part-time jobs at the labs (be it tutoring, teaching or programming small projects like reports for a local school department) that we were exposed to.

There was a great selection of programming courses and it was unthinkable not to take as many as possible. Now, all you see are a pair of meager Java courses and a half-ass course combining assembly and computer org (if you are lucky). To me, I don't see how an undergrad can have enough practicum by just following the bare-bone, minimal curriculum. Unless you land a really good job with a really good engineering-oriented, your job won't help you improve your programming skills.

In fact, and this is specially true in the enterprise/e-commerce arena, most jobs are crappy with people not recognizing what good programming habits are even if they landed on their laps and called them "momma". So the saying that one will learn more at work is half true. You learn something, but there is assurance that what you learn is good or bad (there is such a thing as bad learning.)

My advise to people in school boils down to the following:

Take as many programming courses as
possible (15-18 credits at
least beyond what a CS curriculum
requires you.)

Make sure to have more than 9
credits of programming hours before
taking data structures. Anything
less won't prepare you enough.

Take students loans and eat grass
and water if you have to, but do
take additional classes as outlined
above.

Aim to get internships. Do whatever
you have to to get internships on
your junior and senior years
(preferably with reputable
engineering firms and not sh*tty
e-sweat shops.)

Independently of whether you get
internships, always vie to get a
part-time job at a local computer
department, be it tutoring, but
preferably doing systems
administration and networking... or
if you are lucky, programming
reports or sysadmin utilities for
internal usage.

Network, network, network. As
professors for potential employers,
employers they can recommend.

Take Calc III and DEQ and/or take a
introductory course in EE/CE. It
will open a lot more doors beyond
what the enterprise has to offer.

If you already graduated and feel that you still have a lot to learn (and on-the-job training and work exposure are not cutting it), go back to school, get a MS or get professionally certified (.ie. Sun Certified). Engage local programming user groups. Read DDJ and the Pragmatic Book series; books on Architecture; on algorithms and concurrency; on security, e-commerce, distributed systems; on requirements analysis and engineering; on systems engineering (actual systems engineering as delineated by government agencies.)

Recognizing that you need to improve your skills after leaving school is 90% of the battle. Most people never recognize (or care). But you do. All you need is to sacrifice time outside of work to develop your career. Your job is never your career. Remember that.

ContentLicense: CC BY-SA 4.0


答:
If you aim for a clean codebase, you will have a framework. The only choice you can make is whether you want to develop (and maintain) your own framework, or whether you want to piggy-back on top of someone else's framework.

This is a set of problems that frameworks typically solve, and that you will end up solving yourself if you decide to build your own:

MVC separation of code, templating layer

Security best practices (avoiding SQL injection, mail header injection, character encoding issues, CSRF, XSS, session fixation, ...)

Unicode compatibility, translation

DB abstraction layer, cross-DB compatibility

Output caching for improved performance

From that perspective, a framework can save you a lot of time. But you should still understand how they solve all those problems.


答:
It is easy to both trivialize and overstate this problem. What you've discovered is a basic truth. Learning Java or C# or Ruby is not very much about learning that language syntax.

You also need to understand:

Platform characteristics and capabilities

Standard Library

Extended Library

Fashionable tools and frameworks

Style, conventions and idioms

Memorization is not important at all but you need a broad understanding of all these characteristics with pockets of specific or deep understanding to be considered a senior developer of that platform and it takes time to reach this level. Time spent developing but also reading other people's code, books, blog articles etc. You can't learn it all upfront and you can't Google it all as you go either.


答:
The only reasonable thing I could weigh in as being an advantage of writing your own is the knowledge gained in the experience. Reading a framework's source and writing your own are two entirely different experiences. Even in that situation though, it still comes down to how much you are willing to ignore pre-existing constructs and standards. I say reasonable, because there is the off chance that you might be a genius, or lucky, and come up with something amazing through your self imposed limits on influence. Your inventive potential stands to gain much from ignoring the status quo, should you even take it that far.

As for why you shouldn't just make something that makes sense to you, well: what if you spent some time making some pre-existing framework make sense to you? Could you perhaps save time in the long run, compared to your doing your own thing? Or if time isn't your concern, then insert whatever it is you are trying to get out of this into that question and think long and hard.

Basically, if writing your own framework is something you're seriously considering, you stand to become intimately familiar w/the material which is good if you are specializing in the field. If you feel your ingenuity is resilient enough to not miss out on any great ideas by immersing yourself in extant APIs. Alternatively, if you are unsure of your actual familiarity with a subject in the face of everything that is out there, taking Cake for a spin might do you a world of good and give you more ideas than you'd come up w/otherwise. Perhaps you may find that you can even improve upon one that already suits your tastes. :)


问:
Why is a linked list implementation considered linear?
Typically, computer memory is always linear. So is the term non linear used for a data structure in a logical sense? If so, to logically achieve non linearity in a linear computer memory, we use pointers. Is that right?

In that case, if pointers are virtual implementations for achieving non linearity, why would a data structure like linked list be considered linear, if in reality the nodes are never physically adjacent?

答:
Non-linear tends to imply a structure beyond a simple sequential pattern.  Pointers are one concept used to get past a simple array-like structures.  Relational databases could also be seen as a non-linear structure if you want another example.

A linked list can be considered linear if each node is pointing at another node in contrast to trees and other data structures where there may be multiple pointers within a node.  A binary tree for example, is much harder to imagine as a line.  Another point is how some algorithms like finding the maximum element in an unsorted list have linear time complexity.


问:
Can the customer be a SCRUM Product Owner in a project?
I just had a discussion with a colleague about the Product Owner role: In a project where a customer organization has brought in a sofware developing organization (supplier), can the role of Product Owner be successfully held by the customer organization, or should it always be held by the supplier?

I always imagined, that the PO was the supplier organizations guy. The guy that ensured that the customer is happy, and continously fed with new and high-businessvalue functionality, but still an integral part of the developer organization. However, maybe I have viewed the PO role too much like the waterfall project manager.

My colleague made me think: If the customer organization is mature and proffessional enough, why not let a person from their camp prioritize the backlog?? That would put the PO role much closer to the business, thus being (in theory) better to assess the business value of backlog items. To me, that is an intriguing thought. But what are the implication of such a setup???

I look forward to your input.

答:
I would recommend, whenever possible, having the Product Owner be a representative of the customer. The role of the PO is to be the voice of the customer, to ensure that what the team is producing adds business value, and write and prioritize user stories. Who better to perform these roles than a willing participant from the customer's organization? The key words are willing participant - they need to be willing and able to participate in the Scrum environment if that is the process methodology used by the team.

This isn't unique to Scrum, either. The concept of a customer representative (with an on-site representative often favored) is part of Extreme Programming, as well.


答:
I would suggest you come up with your own code with relevance to your company's job opening. This doubles as a benefit as you have the opportunity to also evaluate a candidate's learn new concepts before attempting to solve the actual bug.

You also don't want a candidate stumbling upon this question on the internet!

Title: Piece of code for interview debugging abilities test?

Body: May be someone has a piece of code, that would work as a test for debugging abilities? We will give ability to use Visual Studio, so it should be hardly solvable by doing manual tracing and show us, that candidate is really good at debugging.</p>


问:
Trial/Free & Full Version VS. Free App + In-app billing?
I'm just wondering what would be the best strategy to publish an application on the Android Market.

If you have a free and paid version you have two codes to update (I know it will be 99% the same but still) and besides all the popular paid apps are quite easy to find for "free" in "alternative" markets. Also if you have any stored data in the trial/free version you lose it when you buy the full version..

On the other hand if you put a free application but inside you allow the user to unlock options (remove ads/more settings/etc...) you only have to worry about one code. I don't know the drawbacks of that strategy and how easy/hard is to hack that to get all the options for "free".

答:
It's one code only in either case, you are just using either compile-time or run-time conditionals in it. Unfortunately Java lacks compile-time conditionals, so you have to be creative there (Java can optimize away if(static_final_variable), so you will just have two versions of one source defining that variable).

The chance that someone will crack your application is the same in either option and depends on the strength of the check that the user has valid license. Google provides interface to check license on the Market through the Market client, but it also depends on how tightly you integrate the checks in the application and therefore how hard you make it to disable them via disassembling.

The license can be obtained in two ways, either by purchasing the app on the market (separate APK) or by in-app billing (unlocking features). The later obviously involves some extra work, so that slightly favors the separate applications.

On the other hand you could do the billing in single package yourself and avoid giving 30% to Google, but that's a lot of work.

One package with unlocking features will be slightly more convenient for the user, because settings and content will be carried over. How much this favors single package depends on how much such content you expect average user to have.


答:
Some things to consider about allowing the customer to be the PO:

If they are not full committed you can find the whole development process screached to a halt.  The vast majority of customers don't want this kind of involvement, some think they do, but when it comes down to it, most actually don't want that committment.

You take a process that is in your control and give that control to the customer.  It has been my experience that not being in 100% control of a project for a client is more dangerous than the risk of not delivering exactly what they are asking for.  OTOH if a missed requirement occurs the blame lies entirely on the customer for missing this requirement, they can't fault you for that.

If you are developing a product that you or your organization has no interest or rights to turn around and use or sell to other customers then this can work.  Otherwise if you are developing a product for your company that you may want to customize and tailor to other customers in the future then you could be creating a catastrophe for yourself in the future.  The PO in this case should be somebody within YOUR company because you are developing a product that is intended to be reused for multiple customers.

Title: Can the customer be a SCRUM Product Owner in a project?

Body:
I just had a discussion with a colleague about the Product Owner role: In a project where a customer organization has brought in a sofware developing organization (supplier), can the role of Product Owner be successfully held by the customer organization, or should it always be held by the supplier?

I always imagined, that the PO was the supplier organizations guy. The guy that ensured that the customer is happy, and continously fed with new and high-businessvalue functionality, but still an integral part of the developer organization. However, maybe I have viewed the PO role too much like the waterfall project manager.

My colleague made me think: If the customer organization is mature and proffessional enough, why not let a person from their camp prioritize the backlog?? That would put the PO role much closer to the business, thus being (in theory) better to assess the business value of backlog items. To me, that is an intriguing thought. But what are the implication of such a setup???

I look forward to your input.


问:
Use the latest technology or use a mature technology as a developer?
I would like to develop an application for a group of people to use. I have decided to develop using python, but I am thinking of using python 2.X or python 3.X. If I use python 2.X, I need to upgrade it for the future... But it is more mature, and has many tools and libraries. If I develop using 3.X, I don't need to think of future integration, but currenttly it doesn't have many libraries, even a python to executable is not ready for all platforms.

Also, one of the considerations is that it is a brand new application, so I don't have the history burden to maintain the old libraries.

Any recommendation on this dilemma?

More information about this application:

Native application

Time for maintenance: 5 years+

Library/Tools must need: don't have idea, yet.

Must need feature that in 2.X: Convert to an executable for both Windows and Mac OS X

答:
It really depends on what your application does, and what kinds of libraries you want to leverage. The biggest downside of python 3.x is the lack of library/framework support. If you are building a web application, there is going to be very little downside to using 2.x, and you will have a much wider array of frameworks and libraries to choose from. Here's a good article on python 2.x vs 3.x.

Some general considerations when choosing a language/platform/framework:

lifespan of application. years? months? decades?

what's the cost to upgrade? what's the maintenance cost if you don't? many applications will happily run python 2.x in their own virtualenv for the next 20 years if you need them to.

What features of the language will your application take advantage of? many web applications will only use python in a fairly basic way, and it's more about the maintainability of the libraries you are using than the code you are writing.

hope this helps.


答:
Self Discipline

Like it or not, we're not all Pablo Picasos or Walt Whitmans who can code only if and when the muse strikes us.

Most programmers have likely already discovered they're asked to code things they're not personally enthused about all the time.  You also need to find a way to reach inside yourself and pull out good code even when the mood is wrong.

Title: Stuff every programmer needs while working

Body:
I've been tasked with creating a fun and relaxing environment, one thing I know that I want is ergonomic mice and keyboards, others have suggested exercise balls and bands.

What is it that every programmer needs while working? What might not be necessary but would be nice to have anyway?

Note: this question was asked previously, but has been recommended to be posted here. See this link for the previous responses: https://stackoverflow.com/questions/3911911/stuff-every-programmer-needs-while-working-closed


问:
How do you learn to effectively use more than one framework
Someday, my leader told me that don't reinvent the wheels, use framework built-in classes. (with a serious mood) when I implement some algorithm has been supported by .NET fx. And seriously, I didn't know about these support before, cause this is the first time I work with .NET).

So I have this questions.
For example, for building an Web-App we have some ways:

C# with ASP.NET framework

Java with JavaEE (and friends like Struts, Spring v.v.) framework.

PHP with Zend framework.

...

It just takes about 1 months to learn language (C#, Java, PHP...), BUT learning to use a framework effectively takes you at least SOME YEARS working (to know every bit of code has been built-in).

So, how do you learn to use effectively 2 (or more)  frameworks? Any ideas are welcome!

答:
Patterns.

How do you learn to play piano and guitar? How do you learn French and Spanish? How do you excel at football and soccer?

Anytime you're learning two distinct but related things, there are at least two important aspects to the process. The first is to learn and practice each thing on its own. The second is to look through that thing to the deeper, common body of knowledge, and to appreciate the thing's relationship to that knowledge. With piano and guitar, that knowledge is obviously music. Once you have a solid understanding of music the process of learning a third or fourth instrument becomes easier. The same is true for languages, sports, and even object oriented frameworks.

Most any object oriented application framework will have a set of data storage classes, a set of classes representing things that are drawn on the screen, and some way to make those two groups work together. There will be inheritance hierarchies, containment hierarchies, and command/control graphs. There may be classes for modifying other classes, communicating with the world beyond the framework, and so on.

These common features are called design patterns, and they are the deeper knowledge behind object frameworks. Each one has a name (sometimes several), and most of the well-known patterns are catalogued in the book Design Patterns. It can be difficult to learn about patterns in the abstract, just as it's more difficult to learn music theory without the concrete experience that comes from playing an instrument. Once you've gotten some experience with one or two frameworks, though, learning about design patterns leads to a string of "aha!" moments as you recognize the patterns you're reading about in the framework(s) that you already know.

So, keep at it, look for commonalities between the frameworks that you're learning, and at some point spend some time learning about the patterns behind the frameworks. That knowledge will give you a deeper understanding of what you already know, and it will also guide you and help you know what to look for or what you might be missing as you learn a new framework.


答:
First off, latest and mature are NOT always contrasting.

For example, in Python's case, you can't say 2.x is "more mature" than 3.x -- on the contrary, in some respects 3.x is more mature -- better classes, better Unicode support and of course bug fixes.

On the other hand, campare Node.JS with Python Twisted -- and you can say that Twisted is more mature than Node.JS which is sizzling latest.

Now, what you should go with is more about what you can handle in terms of maintainability, than about 2.x/3.x.

If you know it'll be not much pain to upgrade your app to 3.x later, you can go with 2.x right now, and leverage the 2.x eco-system.

On the other hand, if you think it'll be a maintenance nightmare to upgrade the app to 3.x, and are OK with developing the missing libraries and tools yourself, by all means go with 3.x then.

Title: Use the latest technology or use a mature technology as a developer?

Body:
I would like to develop an application for a group of people to use. I have decided to develop using python, but I am thinking of using python 2.X or python 3.X. If I use python 2.X, I need to upgrade it for the future... But it is more mature, and has many tools and libraries. If I develop using 3.X, I don't need to think of future integration, but currenttly it doesn't have many libraries, even a python to executable is not ready for all platforms.

Also, one of the considerations is that it is a brand new application, so I don't have the history burden to maintain the old libraries.

Any recommendation on this dilemma?

More information about this application:

Native application

Time for maintenance: 5 years+

Library/Tools must need: don't have idea, yet.

Must need feature that in 2.X: Convert to an executable for both Windows and Mac OS X


答:
Well, I know that if you need to make windows executables you may want to stick w/2.x since py2exe will be desirable.

See: http://www.py2exe.org/

There are other windows freezing tools, but the gurus I look up to swear by py2exe and it has always done right by me.

You may also want to consider the actual difficulty in porting things to new versions of python. For example, the current process (2.x to 3.x) isn't so bad and there are even tools that provide a degree of automation for such, like 2to3.

See: http://docs.python.org/release/3.0.1/library/2to3.html#to3-reference

You should also check out changes between major versions ("What's New" pages) of python and any other prospective APIs to get a feel for the potential scope of difference in revisions.

As for the matter of newer things being bigger/better, that may be true, but better to concern yourself with what is in the subset of all those improved items that you are, or would consider, using.


问:
Unit testing - getting started
I am just getting started with unit testing but I am not sure if I really understand the point of it all. I read tutorials and books on it all, but I just have two quick questions:

I thought the purpose of unit testing is to test code we actually wrote. However, to me it seems that in order to just be able to run the test, we have to alter the original code, at which point we are not really testing the code we wrote but rather the code we wrote for testing.

Most of our codes rely on external sources. Upon refactoring our code however, even it would break the original code, our tests still would run just fine, since the external sources are just muck-ups inside our test cases. Doesn't it defeat the purpose of unit testing?

Sorry if I sound dumb here, but I thought someone could enlighten me a bit.

Thanks in advance.

答:
It sounds like you have a monolithic app that does everything in void main(), from database access down to output generation.  There are several steps here before you can begin proper unit testing.

1) Find a piece of code that's been written / copy-pasted more than one time.  Even if it's just string fullName = firstName + " " + lastName.  Break that into a method, like:

```<code>private static string GetFullName (firstName, lastName)
{
    return firstName + " " + lastName;
}
</code>```

Now you have a unit-testable piece of code, however trivial it may be.  Write a unit test for it.  Rinse and repeat this process.  You'll eventually end up with a load of logically-grouped methods, and you're able to extract a number of classes out of it.  Most of these classes will be testable.

As a bonus, once you have multiple classes extracted, you can extract interfaces from them and update your program to talk to interfaces instead of the objects themselves.  At that point, you're able to use a mocking / stubbing framework (or even your own hand-rolled fakes) without changing the program at all.  This comes in very handy once you've extracted the database queries into a class (or many) because now you can fake up the data that the query should return.

OwnerDisplayName: higgenkreuz

Title: Unit testing - getting started

Body:
It sounds like you have a monolithic app that does everything in void main(), from database access down to output generation.  There are several steps here before you can begin proper unit testing.

1) Find a piece of code that's been written / copy-pasted more than one time.  Even if it's just string fullName = firstName + " " + lastName.  Break that into a method, like:

private static string GetFullName (firstName, lastName)
{
    return firstName + " " + lastName;
}

Now you have a unit-testable piece of code, however trivial it may be.  Write a unit test for it.  Rinse and repeat this process.  You'll eventually end up with a load of logically-grouped methods, and you're able to extract a number of classes out of it.  Most of these classes will be testable.

As a bonus, once you have multiple classes extracted, you can extract interfaces from them and update your program to talk to interfaces instead of the objects themselves.  At that point, you're able to use a mocking / stubbing framework (or even your own hand-rolled fakes) without changing the program at all.  This comes in very handy once you've extracted the database queries into a class (or many) because now you can fake up the data that the query should return.


答:
COBOL can be cured if caught early.

-- From Programming classes

Body:
What's your favourite quote about programming?

One quote per answer, and please check for duplicates before posting!


问:
When do I need to use a framework?
I am new to web programming and at this time I am learning about PHP. I would like to know when do I need to use a PHP framework such as CakePHP? What are things that this and other similar PHP frameworks offer for me?  And is it really important to use a framework to be a professional?

And can I create my own framework to provide the features I like into it?

答:
Use a framework when you know the underlying technologies well enough to know what the framework does for you, and why that's good (or bad).

A framework is sort of a meta-tool, which allows you to work with your tools (language, database) a bit faster without having to worry about some of the details of what you're doing, which is good if you really know your tools.

What you DON'T want to have happen is that you learn the framework instead of the tools, and become canalized into a certain way of doing things, and end up not really taking a mastery of the underlying languages and concepts - it should be a tool, not a crutch.

Title: When do I need to use a framework?


问:
What is the most compatible, widely used production language to export knowledge and skills gained from Haskell?
I like Haskell, plain and simple. While Haskell is used in production software, it's not especially widely deployed from what I've seen. What is the most similar and still widely used language in regards to production projects so that I might have a snowball's chance of using something similarly awesome in industry?

Also is the same language from the first part available on large numbers of platforms? If not, what is the best alternative that has wide platform deployment? I'd like a single language to put on my to-do list rather than a massive swarm or family. Hard evidence would be a plus.

答:
Clojure is increasingly widely used, and while it is does not look like Haskell at a superficial level, if you look a bit deeper it is clearly very much inspired by Haskell and encourages a very similar functional style.

Key Clojure features that Haskell users may find familiar and compelling:

The core language is purely functional - while side effects are possible they are buried away in specific places (e.g. STM references, IO functions, Java interoperability)

All data structures are immutable and persistent

Laziness - achieved largely through Clojure's ubiquitous lazy sequences, this will feel very familiar to Haskell users. Infinite lazy sequences are fine.

Software Transactional Memory - is the main way of handling mutable state in Clojure. Well worth watching this excellent video where Rich Hickey explains Clojure's approach to identity and state: http://www.infoq.com/presentations/Value-Identity-State-Rich-Hickey

Key differences (may be positive or a negative depending you your perspective):

It's impure - although my observation is that idiomatic Clojure style is to stick pure functions wherever possible.

Dynamic rather than static typing (although static type hints can be used optionally for performance optimisations)

It's a JVM langauage with easy access to the whole Java library ecosystem - this is in my opinion the biggest advantage in terms of real world applicability

Lisp syntax. So you get all the benefits of homoiconicity, at the cost of having to learn to see through all the parentheses :-)

Personal perspective: I learnt Haskell before Clojure, and loved Haskell for it's elegance and mathematical purity. Clojure draws a lot of inspiration and borrows many good features from Haskell, but is a much more pragmatic/practical langauge. Especially when you count the huge value of being able to leverage the Java library ecosystem then it's a great language for "getting stuff done".


问:
How does throwing an ArgumentNullException help?
Let's say I have a method:

```<code>public void DoSomething(ISomeInterface someObject)
{
    if(someObject == null) throw new ArgumentNullException("someObject");
    someObject.DoThisOrThat();
}
</code>```

I've been trained to believe that throwing the ArgumentNullException is "correct" but an  "Object reference not set to an instance of an object" error means I have a bug.

Why?

I know that if I was caching the reference to someObject and using it later, then it's better to check for nullity when passed in, and fail early.  However, if I'm dereferencing it on the next line, why are we supposed to do the check?  It's going to throw an exception one way or the other.

Edit:

It just occurred to me... does the fear of the dereferenced null come from a language like C++ that doesn't check for you (i.e. it just tries to execute some method at memory location zero + method offset)?

答:
I suppose if you are immediately dereferencing the variable, you could debate either way, but I would still prefer the ArgumentNullException.

It is much more explicit about what is going on.  The exception contains the name of the variable that was null, whereas a NullReferenceException does not. Particularly at the API level, an ArgumentNullException makes it clear that some caller did not honor the contract of a method, and the failure was not necessarily a random error or some deeper issue (though that may still be the case).  You should fail early.

In addition, what are later maintainers more likely to do?  Add the ArgumentNullException if they add code before the first dereference, or simply add the code and later on allow a NullReferenceException to be thrown?


答:
I believe it's only advantage is that you can provide better diagnostics in the exception. That is you know, that the caller of the function is passing null, while if you let the dereference throw it, you would not be sure whether the caller passes wrong data or there is a bug in the function itself.

I would do it if somebody else is going to call the function to make it easier to use (debug if something goes wrong) and not do it in my internal code, because the runtime will check it anyway.

Title: How does throwing an ArgumentNullException help?

Body:
Let's say I have a method:

```<code>public void DoSomething(ISomeInterface someObject)
{
    if(someObject == null) throw new ArgumentNullException("someObject");
    someObject.DoThisOrThat();
}
</code>```

I've been trained to believe that throwing the ArgumentNullException is "correct" but an  "Object reference not set to an instance of an object" error means I have a bug.

Why?

I know that if I was caching the reference to someObject and using it later, then it's better to check for nullity when passed in, and fail early.  However, if I'm dereferencing it on the next line, why are we supposed to do the check?  It's going to throw an exception one way or the other.

Edit:

It just occurred to me... does the fear of the dereferenced null come from a language like C++ that doesn't check for you (i.e. it just tries to execute some method at memory location zero + method offset)?


答:
I've been trained to believe that throwing the ArgumentNullException
  is "correct" but an "Object reference not set to an instance of an
  object" error means I have a bug.

You have a bug if the code does not work as designed.  An NullReferenceException is thrown by the system and that fact really makes more of a bug than a feature.  Not only because you did not define the specific exception to be handled.  Also because a developer reading your code may assume you did not account for the situation to occur.

For similar reasons that the ApplicationException belongs to your application vs a general Exception which belongs to the operating system.  The type of exception being thrown indicates where the exception originates.

If you have accounted for null, it's better that you handle it gracefully by throwing a specific exception or if it's an acceptable input, then do not throw an exception because they are expensive.  Handle it by performing operations with good defaults or no operation at all (e.g. no update required).

Finally, don't neglect the caller's ability to handle the situation.  By giving them a more specific exception, ArgumentException they can construct their try/catch in such a way to handle this error before the more general NullReferenceException which may be caused by any number of other reasons that occur elsewhere, like a failure to initialize a constructor variable.


答:
The point is, your code should do something meaningful.

A NullReferenceException is not particularly meaningful, because it could mean about everything. Without looking at where the exception was thrown (and the code might not be available to me) I cannot figure out, what went wrong.

An ArgumentNullException is meaningful, because it tells me: the operation failed because the argument someObject was null. I don't need to look at your code to figure that out.

Also raising this exception means, that you explicitly handle null, even though your only way to do it is to say, that you can't handle it, while just letting the code crash could potentially mean that, you might actually be able to handle null, but forgot to implement the case.

The point of exceptions is to communicate information in case of failure, which can be handled at runtime to recover from failure, or at debug time to better understand what went wrong.


问:
Modern programming language with intuitive concurrent programming abstractions
I am interested in learning concurrent programming, focusing on the application/user level (not system programming). I am looking for a modern high level programming language that provides intuitive abstractions for writing concurrent applications. I want to focus on languages that increase productivity and hide the complexity of concurrent programming.

To give some examples, I don't consider a good option writing multithreaded code in C, C++, or Java because IMHO my productivity is reduced and their programming model is not intuitive. On the other hand, languages that increase productivity and offer more intuitive abstractions such as Python and the multiprocessing module, Erlang, Clojure, Scala, etc. would be good options.

What would you recommend based on your experience and why?

EDIT: Thanks everybody for your interesting answers. It's hard to make a conclusion without actually trying since there are many good candidates: Erlang, Clojure, Scala, Groovy, and perhaps Haskell. I voted the answer with the most convincing arguments, but I'll try all the good candidates before deciding which one to pick :)

答:
Take a look at Microsoft's Parallel Programming for .net. It is very intuitive.

Many personal computers and workstations have two or four cores (that is, CPUs) that enable multiple threads to be executed simultaneously. Computers in the near future are expected to have significantly more cores. To take advantage of the hardware of today and tomorrow, you can parallelize your code to distribute work across multiple processors. In the past, parallelization required low-level manipulation of threads and locks. Visual Studio 2010 and the .NET Framework 4 enhance support for parallel programming by providing a new runtime, new class library types, and new diagnostic tools. These features simplify parallel development so that you can write efficient, fine-grained, and scalable parallel code in a natural idiom without having to work directly with threads or the thread pool. The following illustration provides a high-level overview of the parallel programming architecture in the .NET Framework 4...


答:
Both Erlang and Scala have actor-based concurrency, which I found very intuitive and easy to learn.

The Actor model in computer science is a mathematical model of concurrent computation that treats "actors" as the universal primitives of concurrent digital computation: in response to a message that it receives, an actor can make local decisions, create more actors, send more messages, and determine how to respond to the next message received... It has been used both as a framework for a theoretical understanding of computation, and as the theoretical basis for several practical implementations of concurrent systems.

Title: Modern programming language with intuitive concurrent programming abstractions

Body:
I am interested in learning concurrent programming, focusing on the application/user level (not system programming). I am looking for a modern high level programming language that provides intuitive abstractions for writing concurrent applications. I want to focus on languages that increase productivity and hide the complexity of concurrent programming.

To give some examples, I don't consider a good option writing multithreaded code in C, C++, or Java because IMHO my productivity is reduced and their programming model is not intuitive. On the other hand, languages that increase productivity and offer more intuitive abstractions such as Python and the multiprocessing module, Erlang, Clojure, Scala, etc. would be good options.

What would you recommend based on your experience and why?

EDIT: Thanks everybody for your interesting answers. It's hard to make a conclusion without actually trying since there are many good candidates: Erlang, Clojure, Scala, Groovy, and perhaps Haskell. I voted the answer with the most convincing arguments, but I'll try all the good candidates before deciding which one to pick :)


答: I think it depends on what it is you're building.  Desktop apps, or server?  I've heard that (but don't have personal experience) node.js great for concurrent programming for servers (both in terms of writing code and in performance).  If I wanted to write a new server app, I'd probably try that out.  Not sure about desktop apps... I've written a fair amount of stuff in C# and there are some tools that hide the complexity nicely, though for other cases you have to deal with it head-on.</p>


问:
Which tasks should a beginner, intermediate and advanced rails developer be able to complete?
I have been programming ROR for about a year now, and I think I am ready to start working on a project for someone else. The problem is that job postings for contractors don't really tell you which specific tasks you should be able to do at different experience levels (in rails and other technologies), so I don't know where to pitch myself. I think I am somewhere between junior and mid-level, but who knows? So my question is:

Which actual tasks should an junior programmer be able to do at, say, $35 an hour, which actual tasks should an intermediate programmer be able to do at, lets say, $75 an hour, and which actual tasks should an advanced programmer be able to do at, oh say, $140 an hour?

One or two examples should suffice.

答:
35$ developers can build up rails apps, not on high level.

70$ developers do this with a test-driven approach, and can also build his own gems and work nice dry.

More than 70$ developers know something about performance, scability, and should always find the best solution. He also needs to do a perfect database design etc.

the way to find the price for a project (if a customer asks me): how many hours? how much many can i arn in this timeframe with my own projects?

also a hint: how much money do you need for your life monthly. how many hours of work do you need to reach this at 35, 50, 70 bucks. is it realistic to have enough work? i know some people who works for 20€ per hour. so maybe they have 80 hours of work, thats ~1600€ per month. sounds good, but he needs to pay healt-insurance (250€), business-costs (150€), so after these costs he only have a little of 1200€. (and for this he need to pay tax at the end of the year). i told him, he needs to increase the hourly, he tried with new customers, but they dont want to pay 35-40€. so its not easy to calculate your hourly.

and at least: i think its way easier to calculate $$$ in projects-sizes not based on hourlys. obvious i would do an hour easy work (as writing textes, cause the customer is lazy) for less then if i would making some tests.

OwnerDisplayName: raouldeveloper

OwnerDisplayName: huan son


问:
How should a developer reject impossible requirements?
Here's the problem I'm facing:

Quote From Project Manager:

Hey Spark, I'm assigning you the task of developing a framework that could be used for many different iOS applications. Here are the requirements:

It should be able to detect the thickness of the thumb or fingers being used to manipulate the UI.

With this information, all elements of the UI should be arranged & sized automatically.

For a larger thumb, elements should be arranged nearer the center of the screen.

For a smaller thumb, elements should be arranged nearer the corners of the screen.

For a larger thumb, all fonts should be smaller. (We're assuming an adult in this case.)

For a smaller thumb, all fonts should be larger. (We're assuming a younger person in this case.)

Summary:

This framework is required for creating user-friendly user interfaces programmatically. The framework should be developed in such a way that we can use for as many projects as needed, so it must also be very developer-friendly.

I am the developer given this task, so my questions are as follows:

How can I explain that these requirements are a little ridiculous?

How can I explain that it would be better to concentrate on developing actual projects?

How can I explain that even if this were possible, I wouldn't recommended developing such a thing?

How do I say NO to this project politely, gently, and respectfully?

How can I explain that even for a developer with 3 years of experience, this might not be possible?

答: This sounds complex but not impossible at all; the point that the touch screen cannot distinguish between a thumb a middle finger or a stylus is moot; the user is asked at initialization (session startup, whatever) to place a thumb, then a middle finger, etc. to calibrate the sizes (make some statistical averages) using several movements, etc.</p>


答:
Erlang is definitely a great option, but something a little more practical might be Go, Google's new language.

It's not so far from other common languages, so it's typically easy to get if you already know other 'easy' languages.  Many people compare it with Python or even Lua in terms of how 'comfortable' is it to program.


答:
In the next version, C# makes it even easier than that diagram shows. There are two new keywords Async and Await.

Async is used as a function modifier and says "this operation performs its work on another thread.

Await is used within an Async function, and this is where the magic happens. Basically Await tells the compiler to run the operation following the keyword in a seperate thread and wait for the results. Any code after the await call runs after the operation.

ALSO, the operation synchronizes to the calling thread (so if you are doing an asynch operation in response to a button click, you don't have to manually post back to the UI thread). Two little keywords and you get a lot of concurrency power. Read more here


问:
How do you write straight to the point documentation without looking sloppy and informal?
I'm currently at a contract position and am looking to add to the documentation of the projects I worked on, to assist the next hiree taking over my projects.

The documentation I received was overly technical (i.e. references code right away, references replacing certain values on certain lines, no high level description at all)

How do I write documentation in simple plain English that is of actual benefit without looking sloppy? I find it difficult in areas such as outlining a system's flaws without coming off as judgmental, but still emphasize the severity of how detrimental some of the flaws are.

答:
Q: How do I write documentation in simple plain English that is of
  actual benefit without looking sloppy?

Documentation should be created for the readers. Important elements include

Content: The contents of the documentation should be aimed at the information the reader(s) need. Think about the types of tasks that readers will be using your documentation for. Make sure that the contents of your documentation are relevant to them, and provide all the necessary information. As you learn things about the system you are documenting, note items that took you longer than usual to understand, or that you feel are counter-intuitive. This is information that should be in the document as well.

Organization and Cohesiveness: The contents of your document should be organized in a manner that is logical. For instance, to support task-based activities, the activities should be arranged in the order that the reader will be performing them. To document a system, provide introductions that give an overview of the system and how the major components / subsystems interact before going into details about how individual pieces work. If the organization has a wiki or similar Content Management System, consider using this for the documentation. If not, lobby to get such a system started, and get support from the team you are working with.

Understandability: Only use terms that most of your readers will understand. Avoid jargon. If you do use it, provide your definition of the term. Define all acronyms and abbreviations when first used.

Readability: Use correct grammar. An interested non-technical person should be able to understand the material.

Context: As you have observed, detailed information that is not placed into a proper context can be difficult to understand. Provide introductory material that briefly identifies all the key components, layers, API, packages, etc. that comprise the system you are documenting.

Q: I find it difficult in areas such as outlining a system's flaws
  without coming off as judgmental, but still emphasize the severity of
  how detrimental some of the flaws are.

Practice egoless documentation. If there are awkward design elements in the system, you have a duty to highlight any extra information, care or steps a reader needs to know about, but do not judge the awkwardness itself. Avoid adjectives such as "idiotic". For instance, suppose there are several files that need to be changed in order to effect a simple configuration change. Do -- lay out the steps required. Don't -- waste text blaming the original designers for their lack of foresight and/or mental abilities.


答:
The check makes it more explicit what's going on, but the real problem comes with code like this (contrived) example:

```<code>public void DoSomething(Foo someOtherObject, ISomeInterface someObject)
{
    someOtherObject.DoThisOrThat(this, someObject);
}
</code>```

Here there's a call chain involved and with no null check you only see the error in someOtherObject and not where the problem first revealed itself - which instantly means time wasted debugging or interpreting call stacks.

In general it's better to be consistent with this sort of thing and always add the null check - which makes it easier to spot if one is missing rather than picking and choosing on a case-by-case basis (assuming that you know that null is always invalid).

Body:
The check makes it more explicit what's going on, but the real problem comes with code like this (contrived) example:

public void DoSomething(Foo someOtherObject, ISomeInterface someObject)
{
    someOtherObject.DoThisOrThat(this, someObject);
}

Here there's a call chain involved and with no null check you only see the error in someOtherObject and not where the problem first revealed itself - which instantly means time wasted debugging or interpreting call stacks.

In general it's better to be consistent with this sort of thing and always add the null check - which makes it easier to spot if one is missing rather than picking and choosing on a case-by-case basis (assuming that you know that null is always invalid).


答: You may also want to look at Groovy and the GPars library. GPars BTW is somewhat similar to .NET Parallel Extension mentioned in another answer, but Groovys flexible syntax makes it read better in some circumstances. </p>


问:
Agile (scrum) and UML round-trip tools
How effective are automated round-trip tools for UML modeling? Do they help in coding quick, clean, efficient code? In what ways do these tools fit into the Agile methodology?</p>

答:
Part of the Agile Manifesto states:

Individuals and interactions over processes and tools

  Working software over comprehensive documentation

It all boils down to the reason you're using UML.  Everywhere I've worked that used it, it was used as an artifact to "prove" you had completed the design phase, then classes were generated and it was never looked at again because it was too much work to keep the two in sync.  If that's how you're using it, that is decidedly non-agile.

On the other hand, if your team is that mythical creature who actually manages to keep their UML in sync, who constantly refers to it throughout the entire lifecycle, and would miss it when it's gone, that definitely fits with agile.  Remember that tools and documentation are fine, even encouraged under agile, as long as it doesn't interfere with interactions and working software.

Title: Agile (scrum) and UML round-trip tools