答:
The first thing you have to ask yourself is how much you care about the accuracy and correctness of the calculation as it is recorded in the database.

If money or statutory privacy requirements are on the line you simply cannot trust the application with the calculation. Either the database has to do the calculation, or preferably, some intermediate business logic tier running in a locked room under your control.

The problem is that you can't trust data coming from an external client! If somebody can make money by lying to your database there is a good chance they will. If I could arrange to get a $500,000 mortgage at 1% by simply reporting the wrong number to your database, then I have a strong motivation to do just that. For that kind of money it might be worth my while to run your application under a debugger while watching the traffic between the applications and the database with network sniffers. Eventually I'll learn how to impersonate your application, and send the database a number of my own choosing.

If you don't really care about the integrity of the calculation and nobody can gain any advantage by lying about calculation then you don't have to worry so much. You can decide based on the reasoning other folks have offered.

EDIT: Let me add a couple of specific example where you should not trust a calculation coming from the client.

Security validation. As silly as it sounds, this crops up on web sites from time to time. The password checking is done in embedded Javascript, or the user is validated once by checking with the database, and the result of the validation is stored in a cookie or as a parameter in the URL. I kid you not, there have been web sites that have been cracked simply by changing a URL parameter from ?isAuthenticated="F" to ?isAuthenticated="T".

Bonus/commission calculations. Suppose you have an application used by the sale force where they enter their sales, and their bonus is calculated. If the database simply records the bonus or commission as submitted by the application, then a sales person with a technical background could use a debugger to inflate his commissions. The database or the middle tier at least has to check the validity of the calculation, and then you are duplicating the code for the calculation in the database and the application.


问:
Developing BlackBerry app with 3rd party content
I'm working on a BlackBerry app, however I'm loading data from various 3rd party websites around the web. (E.g, posts from stackoverflow or currency rates off Yahoo.com) I'd like to know if this could cause any trouble, would it be allowed?

Thank you!

答: That's what those sites are for. If that was a problem, then the Firefox guys would be in serious trouble because Firefox does that too. Google couldn't release Chrome, since it does that too. (IANAL; this is not legal advice.)</p>

ContentLicense: CC BY-SA 3.0


问:
Has there been any formal work comparing ease of maintenance at the programming language level?
Is there any formal work attempting to measure ease of maintenance for complex programs, comparing at the programming language level? Are there any formal measures for ease of maintenance, at any level?

I'm looking for a method to obtain formal measurements of ease of maintenance (or any related work) for a pet project.

答: There appears to be some work on it in the form of analysis of Domain Specific Languages, the paper is rather old. Also some more work on C/C++. From a brief scan-through of each paper, it doesn't appear that there's a definite answer but it is being worked on.</p>


问:
terminology: Memory leak
When I hear the term memory leak by that I mean a bug in a program that doesn't cause any problems except that it doesn't free memory resource and if it continuously does that it can eat a lot of memory, hurting system performance and in the worst case crash the program (or an other program, if the OS decides to choose to kill that one).

But now in this comments section of this question the upvotes made me think whether that's the whole meaning of the term. I previously always saw used it in that meaning.

https://stackoverflow.com/questions/7451437/is-this-a-mem-leak-in-main

So, would you call something a simple memory leak that crashes a program by some other side-effect or causing a dead-lock by not freeing a lock?

Update - Note: unfortunately some admin deleted the comment section there so I cannot refer to that discussion anymore :/

Basically I said that a memory leak is harmless except that it eats up memory (and consequently on the long term in that respect can be harmful, crashing the app/system). They said that's not true, with C++ RAII it can cause serious problems. - Yes, if you don't delete an object with some important code in the destructor that can cause problems, but in my vocabulary that's a major bug and not a memory leak.

答:
Memory Leaks happen If you fail to delete dynamically allocated memory. Tracking
down memory leaks is one of the most time-consuming (and tedious) aspects of programming in
unmanaged environments.

A simple example of memory leak can be following.

```<code>int main(void)
{
    /* this is an infinite loop calling the malloc function which
     * allocates the memory but without saving the address of the
     * allocated place */
   while (malloc(50)); /* malloc will return NULL sooner or later, due to lack of memory */
   return 0;  /* free the allocated memory by operating system itself after program exits */
}
</code>```

Title: terminology: Memory leak

Body:
Memory Leaks happen If you fail to delete dynamically allocated memory. Tracking
down memory leaks is one of the most time-consuming (and tedious) aspects of programming in
unmanaged environments.

A simple example of memory leak can be following.

int main(void)
{
    /* this is an infinite loop calling the malloc function which
     * allocates the memory but without saving the address of the
     * allocated place */
   while (malloc(50)); /* malloc will return NULL sooner or later, due to lack of memory */
   return 0;  /* free the allocated memory by operating system itself after program exits */
}


问:
Are there any languages built to facilitate implementing design patterns?
Often it is not obvious how to implement a given design pattern in a language. Sometimes it is difficult or cumbersome. Are there any languages built to make using design patterns easy and effective?</p>

答: Design patterns (idioms) are usually a symptom of a programming languages short-commings. As languages improve, patterns will become intrinsic.</p>


问:
Should Professional Development occur on company time?
As a first-time part-time software developer at a small consulting company, I'm struggling to organise time to further my own software development knowledge - whether that's reading a book, keeping up with the popular questions on StackOverflow, researching a technology we're using in-depth, or following the front page of Hacker News. I can see results borne from my self-allocated study time, but listing and demonstrating the skills and knowledge gained through Professional Development is difficult.

The company does not have any defined PD policy, and there's a lot of pressure to get something deliverable done now! when working for consultants. I've checked what my coworkers do, and they don't appear to allocate any time to self-improvement; they just work at the problems they're given, looking up specific MSDN references, code samples, and the like as they need them.

I realise that PD policy is going to vary across companies of different size and culture, and a company like my own is probably a bit of an edge case. I'd love to hear views and experiences from more seasoned developers; especially those who have to make the PD policy choices in their team or company.

I'd also like to learn about the more radical approaches to PD, even if they're completely out there; it's always interesting to see what other people are trying.

Not quite a summary, but what I'm trying to ask:

Is it common or recommended for companies to allocate PD time?

Whose responsibility is it to ensure a developer's knowledge and skills are up to date?

Should a part-time work schedule inspire a lower ratio of PD time : work?

How can a developer show non-developer coworkers that reading blogs and books is net productive?

Is reading blogs and books actually net productive? (references welcomed)

Is writing blogs effective as a way of PD? (a recent theme on Hacker News)

This is sort of a broad question because I don't know exactly which questions I need to ask here, so any thoughts on relevant issues I haven't addressed are very welcome.

答: At my workplace we're responsible for keeping up to date ourselves, but if there's a class we want to take or a book we want to read we can ask the company to pay for it and (if a class) study on company time. I've also had a week's self-study time granted to start learning some Python (to be taken when there was little regular work for me to do). It has worked well for me so far, but it truly is a personal responsibility - if I hadn't requested the time to study no one would have pushed me to do it.</p>

ContentLicense: CC BY-SA 2.5


答:
I don't think it's the language feature to offer design pattern, infact no language does that. Developers themselves design patterns and makes use of the language in that. MVC, MVP, MVVC are design patterns which can be applied to any language. </p>

<p>Also, there are some IDE, that help you leverage the design patterns. Like in case of Visual Studio 2010, you can make use MVC design pattern by selecting the ASP.NET MVC template. </p>

Title: Are there any languages built to facilitate implementing design patterns?

Body: Often it is not obvious how to implement a given design pattern in a language. Sometimes it is difficult or cumbersome. Are there any languages built to make using design patterns easy and effective?</p>

Body:
I don't think it's the language feature to offer design pattern, infact no language does that. Developers themselves design patterns and makes use of the language in that. MVC, MVP, MVVC are design patterns which can be applied to any language.

Also, there are some IDE, that help you leverage the design patterns. Like in case of Visual Studio 2010, you can make use MVC design pattern by selecting the ASP.NET MVC template.


答:
Consider these points:

Design patterns indicate disconnect between the desired functionality and what the programming language provide

This disconnect can be easily created artificially by taking some concept from one language and trying to implement it in different language

Most of the existing design patterns have been found like that -- some nice smalltalk solution does not directly fit to c++, so it becomes a design pattern

Nice thing about design patterns is that it allows programmers to think more about how to solve the problem, and less about how the programming language features work

There really cannot be any language that helps implementing design patterns, since every language has different patterns that are common but still requires a pattern. So anything you do in language design, there is always a way to find a pattern which you didn't consider in the original design.


问:
How do you decide between putting the code in the database or putting the code in the application?
For the sake of argument:

Let's assume the application we are building is an amortization schedule.

Let's also assume that the database has a table called tblAmortizationPayments that stores the information about each monthly payment in a separate row.

Let's further assume that the database language can support the math calculations needed to perform the calculations.

If you were to build this amortization schedule for a 30 year mortgage, how would you decide between placing the code for performing these 360 calculations inside the database (I'm assuming this would be a stored procedure) or inside the application?

I'm more interested in your thought process for making this type of decision or any similar scenario that might come along.

答:
Types of calculations.  In your example, I don't think databases do as good of a job at this type of task as a procedural program would.

Sharing Code. There may be limitations on how coding can be shared. If you're writing custom code for all applications, you have any reusable format you wish. Some third party applications or any app where you don't control the code and report writers may require you to use a stored procedure or some other type of database object.

Spreading the work among team members. Putting code in the same place and being consistent is great unless you have a two person staff and one of them is in the database area of expertise, it may make sense to split the work to utilize the man-hours.

Spreading the work among hardware. This really only makes sense if there are lenghtly batch processes going on. It would drive developers nuts trying to load balance random tasks between app and database servers. You're more likely to just increase the hardware on one or the other and put all your code there.

Developer Expertise Developers have preferences that are probably based on proficiency. You'll code it where you think it is easiest. Of course you're trying to work within the parameters of the application, but if given the choice...


问:
Source code and project documentation requirements for legal agreement

Question

What kind of documentation and other artifacts would you expect to get in case of taking over existing Java webapp (probably it uses JBoss Seam framework) made in-house?

I would expect to get:

Source code in form ready to open in specified IDE.

All external elements (i.e. DB schema as SQL scripts, installation scripts).

Configuration files (both for devel, testing and production environments).

All external libraries needed by project.

All external tools used in project or at least their description (i.e. make program, version control software).

Detailed info about:

How to compile project (IDE, libraries, their versions, compilers, OS),

How to setup development environment (database version, OS, DB schema),

How to install and run application -- server specification (OS, database, versions, minimal hardware, configuration both app and DB),

Probably it would be also nice to have:

Archive of the whole version control system (to make possible checking changes from the past).

UML diagrams or other form of big picture of application design.

DB schema.

What I miss?

Some background details

Friend works as a lawyer for a company which needs legal agreements with people who develop applications for them. Just in case something goes wrong.

In general -- the company wants to have source code deposited somewhere. But source code is not enough to maintain or even compile and run webapp, so they also needsome documentation which helps maintain the app.

I've never taken someone else's project in a similar case (no access to previous developers), and I am not Java developer, so I expect there are a lot of things to miss.

More details added after a few answers

The bosses of company (named it A, small corporation), which ordered and uses the app and company (named it B, a few people) which writes the app, are friends.

Development is in-house. No formal spec, no written specification. All features are discussed over mail or on meetings.

Everything, including hosting the app, is managed by B.

Friend (who is also one of heavy users of the app -- let's say she is product owner) doesn't trust developers from B at all.

Friend also doesn't believe in B competencies (believe me -- she should not).

So to protect A business friend wants written legal agreement with B in case B would go away with A data and app...

As MSalters wrote -- don't laugh -- it happens :(.

A already made B to make and provides backups.

答:
All the documents are important but I have a trick which works pretty well. Many developers just change the code and sometimes the static architecture. They are so involve in the job that usually just write a quick javadoc which makes it almost impossible to understand what has been done.

My trick is to ask the developer to reverse the package into a class diagrams each time he/she add/change something in the architecture which is used by other objects. I don't need a lot just a visual class diagram which is automatically made by the tools and a graphical note on class and on methods. If more is needed then I ask a detailed note directly in the UML object at model level. It means that if somebody else want to add new code to an existing code he/she will be able to open the package, see the structure and business methods in the IDE outline and navigate in the code with documentation available as class diagrams using the mouse to click on each class to have this class specific documentation. I mean that he/she can navigate in the code with the code, the outline, read the javadoc and then navigate in the object architecture using the diagrams and clicking on the class inside the diagram which will open a description menu in which information has been saved.

The result is impressive because class diagrams are really easy to be created, documentation is just two minutes to be written and new developer can start to code almost immediately in the project without breaking existing code.
This UML trick only works with java/jee projects for the class diagram. As soon as you introduce more than one diagram then the project get ctoo heavy for developers who will sooner or later refuse or forget to create diagrams. Class diagrams having the same object structure as code is easy, fast to create and read and really improve productivity. I have forgotten to say that you need to able to merge existing code with new model to have a full cycle. I would therefore recommend live code and model synchronization when the UML class diagram is open but you should also be able to close your diagrams to focus on code and just open it when you need it. This is the merge option.

My trick only work at code level with java annotations which are also reversed and manage by the tool. I usually use JBoss or Weblogic with Oracle or MySQL databases.


问:
Why python library APIs are more intutive than C++ STL library APIs?
I am not sure whether it is a personal perspective or just a common feeling. I think in most cases, python's API is much more intuitive than C++ STL library APIs.

If it is not a subjective judgement, could anyone explain why?

答:
It's absolutely subjective.

The C++ STL library will be much more intuitive to someone who's very comfortable with C++.

The Python libs will be much more intuitive to those well versed in Python.

The longer you spend with a language, the more you become comfortable with it and the more it makes sense. Or, the more you try to force it to make sense to refrain from losing your mind (depending on the language in question - think Javascript and scope chain for example, or just Brainf**k all on its own ;))


问:
Can GPL-licensed software be resold?
My research group is developing some software for research purposes. The project leader wants the software to be open source and likes the GPL, but wants to ensure that they software cannot be sold.

Are we reading the GPL correctly? The software can be freely modified, (re)distributed, and sold? If so, I see why it would be difficult to effectively sell the software; however, the GPL isn't quite strict enough for our needs.

Any suggestions?

答:
The official answer, from the GPL's own FAQ:  http://www.gnu.org/licenses/gpl-faq.html#DoesTheGPLAllowMoney

Does the GPL allow me to sell copies of the program for money?

Yes, the GPL allows everyone to do this. The right to sell copies is
  part of the definition of free software. Except in one special
  situation, there is no limit on what price you can charge. (The one
  exception is the required written offer to provide source code that
  must accompany binary-only release.)

If I distribute GPL'd software for a fee, am I required to also make
  it available to the public without a charge?

No. However, if someone pays your fee and gets a copy, the GPL gives
  them the freedom to release it to the public, with or without a fee.
  For example, someone could pay your fee, and then put her copy on a
  web site for the general public.

Title: Can GPL-licensed software be resold?


问:
A testing environment for JavaScript other than browser?
When I want to test something in JavaScript, I open up a new browser window (mostly Firefox) and start writing code in the provided console (mostly Firebug).

However, this tends to be really tedious and slow. Is there an environment, like an IDE with self-execution capability for example, in which we can test JavaScript?

Guide: I'm looking for something like jsfiddle, but not in the browser, and not online. I'd like to have an execution environment which is both off-line, and is not a browser.

All I'm asking is to have something like the Firebug Console as a separate applications (preferably Windows application) which can be opened by double-clicking, and in which, you can write JavaScript code and hit execute. That's all.

In simpler terms, all I want is Firebug's console, without Firefox. Do we have such a thing on the market?

答:
Have a look at JS-Test-Driver by Misko Hevery http://code.google.com/p/js-test-driver/wiki/GettingStarted

Javascript is a language that is implemented inside browsers, so in order to test it outside, you would need a complete implementation of it.

But JS-Test-Driver "captures" the browser, thus making the whole process a bit easier and more automatic.


答:
node.js is a popular server-side javascript platform.

It has a REPL that allows you to quickly test snippets. There are also other tools that can do this like the chrome console (I use it personally, responsive and fast) or the firefox6 scratchpad.

In combination with zombie or phantom, which are headless browsers, testing becomes a brease. You can easily write a suite of unit tests that interacts with your website.

Title: A testing environment for JavaScript other than browser?

Body:
When I want to test something in JavaScript, I open up a new browser window (mostly Firefox) and start writing code in the provided console (mostly Firebug).

However, this tends to be really tedious and slow. Is there an environment, like an IDE with self-execution capability for example, in which we can test JavaScript?

Guide: I'm looking for something like jsfiddle, but not in the browser, and not online. I'd like to have an execution environment which is both off-line, and is not a browser.

All I'm asking is to have something like the Firebug Console as a separate applications (preferably Windows application) which can be opened by double-clicking, and in which, you can write JavaScript code and hit execute. That's all.

In simpler terms, all I want is Firebug's console, without Firefox. Do we have such a thing on the market?


问:
How do you call a "Proxy" that delegates to *several* implementations?
In a traditional GoF Proxy, you have an Interface, an Implementation, that implements the Interface, and a Proxy that also implements the Interface, references an instance of Implementation, and delegates the calls on the Interface methods to the same methods in the Implementation instance.

Say you would call the Interface/Implementation pair a "Fragment", and you would have several different such pairs. Now imagine you create a Whole Interface that implemented all those Fragment interfaces, and a single Whole Proxy that implemented the Whole Interface, and delegated to the appropriate Fragment Implementation instance.

A code (Java) example:

```<code>// Fragment A:
interface FragmentA { ... }
class FragmentAImpl implements FragmentA { ... }
// Whole A. That is the interface that "clients use"
interfaces WholeA extends FragmentA { // EMPTY! }
// *automatically generated* Proxy:
class ProxyA implements WholeA {
    private FragmentA implA;
    // Implements FragmentA through delegation to implA
}

// Fragment B:
interface FragmentB { ... }
class FragmentBImpl implements FragmentB { ... }
// Whole B. That is the interface that "clients use"
interfaces WholeB extends WholeA, FragmentB { // EMPTY! }
// *automatically generated* Proxy:
class ProxyB extends ProxyA implements WholeB {
    private FragmentB implB;
    // Implements FragmentB through delegation to implB
}

// Fragment C: similar to Fragment B, but with different *added behavior*.
</code>```

Is this pattern at all (since Patterns must be common solution to common problems)? And if so, as it got a name? Or could it be cleanly defined as a combination of patterns?

Being able to clearly describe how this code works in terms of patterns would make it much easier to explain to others how create compatible code, and help to find a framework that already implements this pattern.

A Proxy normally delegates to a single instance.

A Facade normally offers a different interface to that multiple objects it hides.

A Bridge also offers a different interface to that the single instance it hides.

A Composite expects all components to share the same base interface.

A Decorator extends the interface of the wrapped object, like here, but normally implements the additional functionality itself, instead of delegating to another objects.

A Whole that implements a single Fragment is just a Proxy pattern, but a Whole that extends another Whole is closest to a Decorator pattern.

There are several reasons to do it this way. Firstly, client code should see WholeB as extending WholeA, although the implementer of FragmentB cannot extend FragmentA (which was implemented by someone else). Secondly, references to WholeX (ProxyX) stay valid, even if implementation of FragmentX is replaced a runtime. Thirdly, both ProxyB and ProxyC can share the same instance of FragmentAImpl.

答:
I'd still go with facade.

It offers a single port of call for clients needing the services of several interfaces. This is a facade. The fact that normally a facade declares a specific interface instead of re-using the ones from the classes/objects it aggregates is, to me, an implementation detail.

Update

From the GoF book:

Intent: Provide a unified interface to a set of interfaces in a
  subsystem. Facade defines a higher-level interface that makes the
  subsystems easier to use.

Especially when you then read

Motivation: Structuring a system into sybsystems helps reduce
  complexity. A common design goal it to minimize the communication and
  dependencies between subsysems. One way to achieve this goal is to
  introduce a facade object that provides a single, simplified
  interface to the more general facilities of a subsystem.

While the comment by @pdr would seem correct, I would argue differently.

The "simplified" interface can most certainly be the same as the interfaces put behind the facade. Its just a question of how simple those "facaded" interfaces are.

Plus, I don't take "simplifies" as a requirement for an object to be a facade.

The motivation to minimize communication and dependencies between subsystems is far more important and the main goal of the facade pattern. A facade object providing a single point of access to multiple (unchanged interfaces of) subsystems, still fulfills this goal regardless of whether it (also) simplifies the interface(s) offered by the subsystems it hides.


答:
Selenium automates browsers.

And htmlUnit provides javascript testing functionality  for Java.


答:
A mediator? Or inverse multiplexer?

Anyhow, there's no reason to dogmatically stick to the exact same patterns in GoF.
That book should expand your professional vocabulary and maybe even teach you some good ideas, but it's not the programmer's ten commandments.

I couldn't see a reason for you here to actually use the Proxy pattern, theoretically.

Having a separated interface/implementation is very good, but that doesn't mean it has to act as a proxy. If you want a name for it, just label it as "loosely coupled".

You can call it any name that makes sense. You don't have to try to dig up a standard name when it's not totally obvious.

In general, I find that the whole dogmatic way of creating clean code is sometimes deviant from the original purpose - to create code that's easy to read and understand.

If you can't find a completely standard name for what you're doing, don't try to turn it into an existing pattern or name. That only confuses fellow programmers.

Just give it a new one that makes sense to you and your fellow programmers. Consult, together, in your workplace - where it matters.

Title: How do you call a "Proxy" that delegates to *several* implementations?

Body:
In a traditional GoF Proxy, you have an Interface, an Implementation, that implements the Interface, and a Proxy that also implements the Interface, references an instance of Implementation, and delegates the calls on the Interface methods to the same methods in the Implementation instance.

Say you would call the Interface/Implementation pair a "Fragment", and you would have several different such pairs. Now imagine you create a Whole Interface that implemented all those Fragment interfaces, and a single Whole Proxy that implemented the Whole Interface, and delegated to the appropriate Fragment Implementation instance.

A code (Java) example:

```<code>// Fragment A:
interface FragmentA { ... }
class FragmentAImpl implements FragmentA { ... }
// Whole A. That is the interface that "clients use"
interfaces WholeA extends FragmentA { // EMPTY! }
// *automatically generated* Proxy:
class ProxyA implements WholeA {
    private FragmentA implA;
    // Implements FragmentA through delegation to implA
}

// Fragment B:
interface FragmentB { ... }
class FragmentBImpl implements FragmentB { ... }
// Whole B. That is the interface that "clients use"
interfaces WholeB extends WholeA, FragmentB { // EMPTY! }
// *automatically generated* Proxy:
class ProxyB extends ProxyA implements WholeB {
    private FragmentB implB;
    // Implements FragmentB through delegation to implB
}

// Fragment C: similar to Fragment B, but with different *added behavior*.
</code>```

Is this pattern at all (since Patterns must be common solution to common problems)? And if so, as it got a name? Or could it be cleanly defined as a combination of patterns?

Being able to clearly describe how this code works in terms of patterns would make it much easier to explain to others how create compatible code, and help to find a framework that already implements this pattern.

A Proxy normally delegates to a single instance.

A Facade normally offers a different interface to that multiple objects it hides.

A Bridge also offers a different interface to that the single instance it hides.

A Composite expects all components to share the same base interface.

A Decorator extends the interface of the wrapped object, like here, but normally implements the additional functionality itself, instead of delegating to another objects.

A Whole that implements a single Fragment is just a Proxy pattern, but a Whole that extends another Whole is closest to a Decorator pattern.

There are several reasons to do it this way. Firstly, client code should see WholeB as extending WholeA, although the implementer of FragmentB cannot extend FragmentA (which was implemented by someone else). Secondly, references to WholeX (ProxyX) stay valid, even if implementation of FragmentX is replaced a runtime. Thirdly, both ProxyB and ProxyC can share the same instance of FragmentAImpl.


答:
I find the STL pretty intuitive. It is extremely consistent, and the wording is clear. Of course consistency does not imply ease of discovery, however once you've discovered a given container or algorithms, you should be at ease with the others.

Some examples:

size, empty, clear are present on all containers, with the same signature. They have the same complexity (with an exception for std::list::size).

push_back is available on all containers that support insertion at the end: vector, deque, list, ... regardless of their internal implementation. The signature and complexity are nigh identical (from amortized O(1) to true O(1)) so there is no surprise.

copy takes a range of iterators as input, and a single iterator as output. The same applies to other algorithms: a range of iterators as input (+ another single iterator for a second input) and a single iterator as output.

I personally find it easy to use a "new" container (unordered_map ?) because I am in familiar hands.

Title: Why python library APIs are more intutive than C++ STL library APIs?

Body:
I am not sure whether it is a personal perspective or just a common feeling. I think in most cases, python's API is much more intuitive than C++ STL library APIs.

If it is not a subjective judgement, could anyone explain why?


问:
Are programmers who read programming-related books still rare?
Both in Code Complete by Steve McConnell and The Pragmatic Programmer by Andrew Hunt & David Thomas, they allege that most programmers don't read programming-related books as a habit, or at least not often enough. Does this still hold? Are programmers who do read such books still rare?

I must admit that only quite recently did I start reading (and now I can't stop; it's burning a whole in my wallet!). Before I was actually against it and argued that it's better to write programs than to waste time reading about it. Now I realize that the best outcome, for me at least, is to do both.

EDIT: I actually meant any kind of books that on way or another was related to programming; be it either on a particular language, technology, pattern, paradigm - anything as long as it may benefit you as a programmer. I was just referring to Code Complete and The Pragmatic Programmer because that's where I read that programmers don't usually read such books. It would have looked stranged if the title just read "Are programmers who read books still rare?"

答: The reason to read books is to improve your own knowledge and skills. That implies two things: (1) you have to recognize you have room to improve, and (2) you have to want to improve. Many of the programmers I've met had ego's the size of planets. A large chunk of the rest were happy to coast along.</p>


答: I haven't noticed any difference in intuitiveness, but C++ interfaces are naturally more complicated since they have to specify whether to pass objects by pointer, reference, value or move semantics, and who is responsible for deleting any objects involved.  Additionally C++ developers are very concerned with low-level efficiency, which can lead them to provide multiple different ways to access the same functionality.</p>


答:
Intuitiveness is pretty subjective, but there a few points that I can be objectively made.

1) Python's API have more stuff in them

Python's various objects have much more functionality. Compare what you can do with a python string and a C++ string. Or the python random functionality vs. c++ random functionality. A concrete example, selecting a random element from a list/vector.

```<code>items[rand() % items.size()]
</code>```

vs

```<code>random.choice(items)
</code>```

Python has move a lot more into the standard library which make it easier to use.

2) Invoking Python's functionality typically takes less verbiage.

For example, comparing sorting lists and vectors.

```<code>std::sort(items.begin(), items.end())
</code>```

vs

```<code>items.sort()
</code>```

What if you want to sort by custom criteria?

```<code>bool name_compare(std::string & left, std::string & right)
{
    return left.size() < right.size();
}
std::sort(items.begin(), items.end(), name_compare)
</code>```

vs

```<code>items.sort(key = len)
</code>```

3) Literals produces standard library values

In C++ string literals produces char arrays and array literals produces arrays. Neither produces the C++ object which would be useful. In contrast, Python provides literals for producing the most useful type of data structures.

Body:
Intuitiveness is pretty subjective, but there a few points that I can be objectively made.

1) Python's API have more stuff in them

Python's various objects have much more functionality. Compare what you can do with a python string and a C++ string. Or the python random functionality vs. c++ random functionality. A concrete example, selecting a random element from a list/vector.

items[rand() % items.size()]

vs

random.choice(items)

Python has move a lot more into the standard library which make it easier to use.

2) Invoking Python's functionality typically takes less verbiage.

For example, comparing sorting lists and vectors.

std::sort(items.begin(), items.end())

vs

items.sort()

What if you want to sort by custom criteria?

bool name_compare(std::string & left, std::string & right)
{
    return left.size() < right.size();
}
std::sort(items.begin(), items.end(), name_compare)

vs

items.sort(key = len)

3) Literals produces standard library values

In C++ string literals produces char arrays and array literals produces arrays. Neither produces the C++ object which would be useful. In contrast, Python provides literals for producing the most useful type of data structures.


问:
Should you document everything or just most?
It seems a bit of a controversial subject to document everything, including the "JavaBean" syntax of getters and setters for fields: People say its needlessly long and repetitive breaking DRY (don't repeat yourself), that the naming convention should explain everything, and it clutters code/documentation. Sometimes those arguments work. But other times, you end up with this:

Above is common to open source projects that do boldly follow those principles. You're left with entirely useless documentation. That doesn't explain anything about what's going on underneath, the possible effects, or even what the expected value is (could it be null or never null? I don't know; the Javadoc doesn't tell me).

So when should I document? Do I document everything even if it occasionally clutters code? Or do I document nothing since in my eyes it's "obvious"?

答: Keep documenting until you can watch someone else read it without feeling the need to explain anything.</p>


问:
How to use a 3rd party web API
I am trying to understand the concept of using 3rd party web API.
From what I understand so far, web API look like regular URLs with some parameters etc. Will the client program need to download and install any package/bundle etc from the website/server etc providing APIs and include it with their product or no bundle is needed to download from service provider. the client program just uses the web API URLs (like how we do it in browser)

What are the variants in common use?

Does it boil down to how much we want to do on client side and how much we want to do on server side? like not downloading anything from web API service provider means everything happens on web API provider side..

答:
A web API (Application Programming Interface) is typically a defined set of HTTP request messages along with a definition of the structure of response messages, typically expressed in JSON or XML. You can consider Web API as a Web service but they have moved from SOAP to REST.

For further information you can visit this wiki LINK for REST. If you want to easily understand what Web API, think of facebook API, they allow anyone to connect with the facebook and use its services and database for their own use.

Title: How to use a 3rd party web API


答:
Will the client program need to download and install any
  package/bundle etc from the website/server etc providing APIs and
  include it with their product or no bundle is needed to download from
  service provider.

It depends. Generally, when you use a webservice, you make a request and you get a response. How you handle that is your choice. You needn't necessarily download anything but the responses from the service.

Most of the times, though, you want to generate an interface to the webservices which handles the communication part for your client, so you needn't write it yourself. You mostly do so by downloading WSDL files for the service which can be used to generate such a client interface. This client does not contain any logic of the WebAPI, it's purpose is to let you to call the logic on the serverside. The generation of such a client interface is just for your convenience, so you don't have to parse the responses or deal with the underlying protocol.

What are the variants in common use?

SOAP and REST with responses in JSON or XML are the most common forms of such services.

Does it boil down to how much we want to do on client side and how
  much we want to do on server side? like not downloading anything from
  web API service provider means everything happens on web API provider
  side..

Well, I don't know how to answer that part of your question as I don't understand it. When you make a call to a WebAPI, the request is processed on the server and a response is sent back to you. Even if you generate client stubs from WSDL, this just provides an interface and handles communication for you. There's no domain logic clientside in such a case.

Title: How to use a 3rd party web API

Body:
I am trying to understand the concept of using 3rd party web API.
From what I understand so far, web API look like regular URLs with some parameters etc. Will the client program need to download and install any package/bundle etc from the website/server etc providing APIs and include it with their product or no bundle is needed to download from service provider. the client program just uses the web API URLs (like how we do it in browser)

What are the variants in common use?

Does it boil down to how much we want to do on client side and how much we want to do on server side? like not downloading anything from web API service provider means everything happens on web API provider side..


问:
What should take precedence: YAGNI or Good Design?
At which point should YAGNI take precedence against good coding practices and vice versa?  I'm working on a project at work and want to slowly introduce good code standards to my co-workers (currently there are none and everything is just kind of hacked together without rhyme or reason), but after creating a series of classes (we don't do TDD, or sadly any kind of unit testing at all) I took a step back and thought it's violating YAGNI because I pretty much know with certainty that we don't require the need to extend some of these classes.

Here's a concrete example of what I mean: I have a data access layer wrapping a set of stored procedures, which uses a rudimentary Repository-style pattern with basic CRUD functions.  Since there are a handful of methods that all my repository classes need, I created a generic interface for my repositories, called IRepository.  However, I then created a "marker" interface (i.e. interface that doesn't add any new functionality) for each type of repository (e.g. ICustomerRepository) and the concrete class implements that.  I've done the same thing with a Factory implementation to build the business objects from DataReaders/DataSets returned by the Stored Procedure; the signature of my repository class tends to look something like this:

```<code>public class CustomerRepository : ICustomerRepository
{
    ICustomerFactory factory = null;

    public CustomerRepository() : this(new CustomerFactory() { }

    public CustomerRepository(ICustomerFactory factory) {
        this.factory = factory;
    }

    public Customer Find(int customerID)
    {
        // data access stuff here
        return factory.Build(ds.Tables[0].Rows[0]);
    }
}
</code>```

My concern here is that I'm violating YAGNI because I know with 99% certainty that there is never going to be a reason to give anything other than a concrete CustomerFactory to this repository; since we don't have unit tests I don't need a MockCustomerFactory or similar things, and having so many interfaces might confuse my co-workers.  On the other hand, using a concrete implementation of the factory seems like a design smell.

Is there a good way to come to a compromise between proper software design and not overarchitecting the solution?  I'm questioning if I need to have all of the "single implemenation interfaces" or if I could sacrifice a bit of good design and just have, for example, the base interface and then the single concrete, and not worry about programming to the interface if the implementation is that will ever be used.

答:
The question presents a false dilemma. Proper application of the YAGNI principle isn't some unrelated thing. It's one aspect of good design. Each of the SOLID principles are aspects of good design as well. You can't always fully apply every principle in any discipline. Real-world problems put a lot of forces on your code, and some of those push in opposing directions. Principles of design have to account for all of those, but no handful of principles can fit all situations.

Now, let's take a look at each principle with the understanding that while they may sometimes pull in different directions, they are by no means inherently in conflict.

YAGNI was conceived to help developers avoid a particular kind of rework: that which comes from building the wrong thing. It does this by guiding us to avoid making errant decisions too early based on assumptions or predictions about what we think will change or be needed in the future. Collective experience tells us that when we do this, we are usually wrong. For example, YAGNI would tell you not to create an interface for the purpose of reusability, unless you know right now that you need multiple implementers. Similarly YAGNI would say don't create a "ScreenManager" to manage the single form in an application unless you know right now that you're going to have more than one screen.

Contrary to what many people think, SOLID is not about reusability, genericity, or even abstraction. SOLID is intended to help you write code that is prepared for change, without saying anything about what that specific change might be. The five principles of SOLID create a strategy for building code that is flexible without being overly generic, and simple without being naive. Proper application of SOLID code produces small, focused classes with well-defined roles and boundaries. The practical result is that for any needed requirements change, a minimum number of classes need to be touched. And similarly, for any code change, there is a minimized amount of "ripple" through to other classes.

Looking at the example situation you have, let's see what YAGNI and SOLID might have to say. You are considering a common repository interface due to the fact that all the repositories look the same from the outside. But the value of a common, generic interface is the ability to use any of the implementers without needing to know which one it is in particular. Unless there is somewhere in your app where this would be necessary or useful, YAGNI says don't do it.

There are 5 SOLID principles to look at. S is Single Responsibility. This says nothing about the interface, but it might say something about your concrete classes. It could be argued that handling the data access itself might best be made a responsibility of one or more other classes, while the repositories' responsibility is to translate from an implicit context (CustomerRepository is a repository implicitly for Customer entities) into explicit calls to the generalized data access API specifying the Customer entity type.

O is Open-Closed. This is mostly about inheritance. It would apply if you were trying to derive your repositories from a common base implementing common functionality, or if you expected to derive further from the different repositories. But you're not, so it doesn't.

L is Liskov Substitutability. This applies if you intended to use the repositories through the common repository interface. It places restrictions on the interface and implementations to ensure consistency and avoid special handling for different impelementers. The reason for this is that such special handling undermines the purpose of an interface. It might be useful to consider this principle, because it may warn you away from using the common repository interface. This coincides with YAGNI's guidance.

I is Interface Segregation. This may apply if you start to add different query operations to your repositories. Interface segregation applies where you can divide the members of a class into two subsets where one will be used by certain consumers and the other by others, but no consumer will likely use both subsets. The guidance is to create two separate interfaces, rather than one common one. In your case, it's unlikely that fetching and saving individual instances would be consumed by the same code that would do general querying, so it might be useful to separate those into two interfaces.

D is Dependency Injection. Here we come back to the same point as the S. If you separated your consumption of the data access API into a separate object, this principle says that rather than just newing up an instance of that object, you should pass it in when you create a repository. This makes it easier to control the lifetime of the data access component, opening up the possibility of sharing references to it between your repositories, without having to go the route of making it a singleton.

It's important to note that most of the SOLID principles don't necessarily apply at this particular stage of your app's development. For example, whether you should break out data access depends on how complicated it is, and whether you want to test your repository logic without hitting the database. It sounds like this is unlikely (unfortunately, in my opinion), so it's probably not necessary.

So after all that consideration, we find that YAGNI and SOLID actually do provide one common piece of solid, immediately-relevant advice: It's probably not necessary to create a common generic repository interface.

All this careful thought is extremely useful as a learning exercise. It's time consuming as you learn, but over time you develop intuition and becomes very quick. You'll know the right thing to do, but don't need to think all these words unless someone asks you to explain why.


答:
Don't try to separate design patterns by their implementation details. Doing so will cause great confusion when you come to Strategy and State, or cause you to overcomplicate things to avoid having arguments on the Execute method of a Command.

Separate design patterns by their intent. To take your five examples:

A Proxy is a class which creates an interface to something expensive, which is not eaily duplicated, like a network connection or a large chunk of memory. * see comments

A Facade is a simplification of an overcomplicated API. Reducing the surface area, as they say; making it simpler to use.

A Bridge is where an abstraction is decoupled from the implementation, so that when the implementation changes, the calling code doesn't have to. Initially, the interface doesn't have to be different, as you suggested, you just can't insist on them remaining the same.

A Composite is for taking multiple objects and wrapping them in a single abstraction.

A Decorator allows objects to get wrapped in objects with the same interface, so that they add functionality without changing the calling code.

It's hard to tell from your example which you are trying to implement, because you've described the implementation and not the intent. But I'm guessing that the Proxy pattern is appropriate.


答:
This past week there was a great article regarding documentation over at The Daily WTF. I think it says everything, so I'll just leave the link:

http://thedailywtf.com/Articles/Documentation-Done-Right.aspx

Basically it says that you shouldn't document something if it's not going to be useful (some documentation is just left to rot in a drawer) and document the least amount of information that is needed to understand a certain part of the project. Too much documentation just confuses the reader.

Title: Should you document everything or just most?

Body:
It seems a bit of a controversial subject to document everything, including the "JavaBean" syntax of getters and setters for fields: People say its needlessly long and repetitive breaking DRY (don't repeat yourself), that the naming convention should explain everything, and it clutters code/documentation. Sometimes those arguments work. But other times, you end up with this:

Above is common to open source projects that do boldly follow those principles. You're left with entirely useless documentation. That doesn't explain anything about what's going on underneath, the possible effects, or even what the expected value is (could it be null or never null? I don't know; the Javadoc doesn't tell me).

So when should I document? Do I document everything even if it occasionally clutters code? Or do I document nothing since in my eyes it's "obvious"?


问:
What does a company typically expect from a Perl developer?
Are there any common expectations from perspective employers when they hire a Perl developer?

For a student who likes Perl and Linux and would like to get a job as Perl developer, what would you recommend to learn?

I am looking for things that are generic and applicable to most/all Perl positions, as opposed to specific details of a given company's requirements.

In other words, what are the things I should be able to to/know to become more attractive to ANY company looking for a Perl developer.

答:
I think you're pretty much right. It completely depends on what the specifics of a company needs, what the level of experience is of the people already working there, and what their client base is (i.e. what is the set of problems they solve to generate revenue). You would probably best be served by just reading through job postings and figuring out what problems Perl developers are utilized to solve. Try to find a company that gives you a balance of growth/experience that you want, culture, and compensation that jives with what you're looking for.

For me, I need to be involved in solving coding problems that are interesting, and in that realm, not all places are equal. For example, I have interests in web development, automation, large data sets, and user experience. Because of that, I like places that have web applications that have a large and diverse user base with which I can interact to get feedback on what they want, so I can build it for them. It's a plus if the data set I work on is large/complex (because that's fun for me), and if there are opportunities to write automation scripts (e.g. batch processing for sending out email notifications, periodic DB cleanup and massaging tasks, automated reports, etc.).

What kind of code do you write in your spare time when you're not coding for class? Try to find a place that writes the same kind of code.


答:
Really depends on how readable the code is to the audience reading it. Figure out who the audience is for reading your code, and have someone that meets that profile read your code.

Another approach would be to review your own code after a week and see if you still understand what you did, if you don't, document it and review the code in two weeks or so.


答:
You seem to believe that 'good design' means following some sort of idealogy and formal set of rules that must always be applied, even when useless.

IMO that's bad design. YAGNI is a component of good design, never a contradiction to it.

Title: What should take precedence: YAGNI or Good Design?

Body:
At which point should YAGNI take precedence against good coding practices and vice versa?  I'm working on a project at work and want to slowly introduce good code standards to my co-workers (currently there are none and everything is just kind of hacked together without rhyme or reason), but after creating a series of classes (we don't do TDD, or sadly any kind of unit testing at all) I took a step back and thought it's violating YAGNI because I pretty much know with certainty that we don't require the need to extend some of these classes.

Here's a concrete example of what I mean: I have a data access layer wrapping a set of stored procedures, which uses a rudimentary Repository-style pattern with basic CRUD functions.  Since there are a handful of methods that all my repository classes need, I created a generic interface for my repositories, called IRepository.  However, I then created a "marker" interface (i.e. interface that doesn't add any new functionality) for each type of repository (e.g. ICustomerRepository) and the concrete class implements that.  I've done the same thing with a Factory implementation to build the business objects from DataReaders/DataSets returned by the Stored Procedure; the signature of my repository class tends to look something like this:

```<code>public class CustomerRepository : ICustomerRepository
{
    ICustomerFactory factory = null;

    public CustomerRepository() : this(new CustomerFactory() { }

    public CustomerRepository(ICustomerFactory factory) {
        this.factory = factory;
    }

    public Customer Find(int customerID)
    {
        // data access stuff here
        return factory.Build(ds.Tables[0].Rows[0]);
    }
}
</code>```

My concern here is that I'm violating YAGNI because I know with 99% certainty that there is never going to be a reason to give anything other than a concrete CustomerFactory to this repository; since we don't have unit tests I don't need a MockCustomerFactory or similar things, and having so many interfaces might confuse my co-workers.  On the other hand, using a concrete implementation of the factory seems like a design smell.

Is there a good way to come to a compromise between proper software design and not overarchitecting the solution?  I'm questioning if I need to have all of the "single implemenation interfaces" or if I could sacrifice a bit of good design and just have, for example, the base interface and then the single concrete, and not worry about programming to the interface if the implementation is that will ever be used.


答:
Some points:

As a Perl developer, pretty much any company will expect you to know MORE than Perl. Even in pure Perl shop, you need to know (ideally) JavaScript/overall web development; and SQL for back-end work.

And most companies have a mix of languages, so you should be prepared to be Perl/C++ or Perl/Java or whatever else is needed. Much as the fact grates on me, there aren't all that many good "Perl-only" shops I'm aware of.

As with any language, a company would expect you to use the language effectively. This has several facets, some are more important in Perl

Available libraries. This is a MAJOR point for Perl, of course. Great familiarity with CPAN and knowing which libraries are considered "state of the art"/"most common" for specific common tasks is a must.

Can you rattle off - without asking SO - the "standard" library for loading a CSV file? For parsing data out of HTML document? For writing unit tests? For mocking objects? For generating JSON data? For reading simple XML config files? For dealing with ordered hashes? For exception handling (try/catch logic)?

Ditto for frameworks. Do you know how to construct unit tests for Perl modules and integration tests for Perl code? Do you know at least one web templating framework or better yet an MVC web development framework (hint: Catalist :) ? Do you know how to use database connectivity libraries?

Do you know the internals of Perl? Can you work with XS modules, or at least be able to read the code?

Do you know the features that make Perl a unique language in terms of expressiveness and how to use them? Can you easily use map, grep, Regular Expressions, nested data structures, subroutine references? Do you know what autovivification is and how it lets you write 1 line of Perl code that is equivalent to a page worth of Java code?

Do you know advanced Perl features? Have you read Higher-Order Perl and can effectively use all the techniques in it? Remember that one of Perl's strengths is that it's "almost Lisp" :)  - so you need to be able to leverage the Lispy strengths into your productivity.

Do you know that Perl community is considered one of its major assets? Do you know which two main places to go to to ask Perl questions?

Have you participated in Perl tag on StackOverflow - both asking intelligent questions and trying to answer questions (even if you don't know the perfect answer, and even if it's already answered - the PRACTICE of trying to answer will make you a much better Perl developer).

As a Perl developer, the company would likely expect you be able to deal with either legacy (5.8 and before) Perl, or, if you're lucky, with Modern Perl. Meaning, know both how to construct the object the old way (in detail - do you know how to work with inside out objects? How to implement standard OO patterns?) - and how to do Moose based OO; Catalyst MVC web development and DBIx ORM data access. For the latter, reading chromatic's Modern Perl is a must.

A company will expect you to know language independent stuff. Algorithms, data structures, networking, concurrent programming, GUI design, Unit testing, OS internals (or externals  - sometimes you can spend 30 seconds building a Unix shell pipe tool that would take even a seasoned Perl developer 1-2 hours to polish off - and sometimes a good boss would note that :) )

A company would expect you to be more than a Perl code monkey. Do you have communications skills? Can you effectively communicate to users and other developers? Can you write clear code/comments/documentation? Do you write your code as if the next developer maintaining it is a raging psycho who knows where you live? And most importantly, are your prepared to learn the business that your code supports? A value of developer increases by an order of magnitude when they understand what their users do and how and why they do it and can translate that into "how can I make their work more efficient with my product".

Title: What does a company typically expect from a Perl developer?

Body:
Are there any common expectations from perspective employers when they hire a Perl developer?

For a student who likes Perl and Linux and would like to get a job as Perl developer, what would you recommend to learn?

I am looking for things that are generic and applicable to most/all Perl positions, as opposed to specific details of a given company's requirements.

In other words, what are the things I should be able to to/know to become more attractive to ANY company looking for a Perl developer.


问:
How can a maintenance-only programmer get a raise?
I have been working as a maintenance programmer for a couple of years and am wondering if there is such a thing as a raise for maintenance programmer?  I ask because responsibilities don't get wider, you're still doing almost the same things, maybe a little faster as time passes. If it's possible, then what would be the path to get it?</p>

答:
The rule is the same for all jobs: you'll always get a bigger raise by moving to another company.

Why? In part, because you can keep turning down offers that are 2% over your current salary, or 4% over your current salary.  In part, because the incentives are different for the two employers--one wants to pay the least that will keep you from leaving, the other who wants to pay you enough to make you switch.


问:
Explanation of the Google Gravity trick
I am not much of a JS developer, but I stumbled upon this site called Google Gravity (those who haven't used it, try doing a search there - you'll be amazed), which is a remastered Google homepage. From then on, I've been thinking and wondering about learning more on how the guy implemented it. I tried googling, but could not find a good explanation of the implementation.

All the JS/CSS Gurus, can you point me to a location where I can learn more? I already know the basics of working with jQuery and AJAX.

答:
Have you looked at the javascript source code?

I just took a very quick look (and it's far from my cup of tea) but it looks like the page is broken up into 2d boxes and a simulation of those boxes free falling under gravity is ran.  Then the mouse events are handled to allow those boxes to be interactively manipulated.

Title: Explanation of the Google Gravity trick


问:
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!

答:
Skill Appreciates Skill

(Or, It Takes One to Know One)

I have often felt that programming is an art form,

whose real value can only be appreciated

by another versed in the same arcane art;

there are lovely gems and brilliant coups

hidden from human view and admiration, sometimes forever,

by the very nature of the process.

You can learn a lot about an individual

just by reading through his code, even in hexadecimal.

From The Story of Mel, a Real Programmer (free verse version)

I had no idea there was actually a short Wikipedia article with links to both prose and verse versions of the story, along with other information.

LastEditorDisplayName: Roger Pate


答:
What it does, besides using mathematical formulas (for which, you have to be good at math), is using the native technologies of web coming under HTML5 and CSS3.

I recommend that you read these items:

CSS Transitions

CSS Animation

Timing Control for Script-Based Animations

Title: Explanation of the Google Gravity trick

Body:
I am not much of a JS developer, but I stumbled upon this site called Google Gravity (those who haven't used it, try doing a search there - you'll be amazed), which is a remastered Google homepage. From then on, I've been thinking and wondering about learning more on how the guy implemented it. I tried googling, but could not find a good explanation of the implementation.

All the JS/CSS Gurus, can you point me to a location where I can learn more? I already know the basics of working with jQuery and AJAX.


问:
Tutoring students who are struggling with the basics in C++
I am tutoring a few students who are having significant trouble learning the basics of their first programming language: C++. I have known many excellent and bright students who have failed or dropped their first CS course. Everyone I am tutoring gives a similar account of his or her experience in class: the instructor moves along too quickly, nothing in the lectures make any sense, et al. Prior to this CS class, most of these struggling students had not expressed any interest in computers as anything more than word processors, web browsers, or some other form of entertainment. The computer is a blackbox that works, so why mess with it?

My best guess is that they are having trouble connecting the abstractions of computer science with familiar concepts. That is to say, these student might know how to learn math, biology, or physics, but those techniques are not working when it come to programming.

Does anyone have any suggestions or advice?  The students I am helping do not deserve to fail this class. It is clear that the instructor is not taking into account the learning style of these students. That is to say, the instructor is failing not his students.

答:
Here's what I would advice:

Give them all the details they need to figure it out

Encourage them to try to understand the details

Make sure they have the details stored in compact form whenever they need them

Basically I would advice you to create single a4 paper which has all necessary details required. Some kind of reference manual which has all the details. Some books can also help, for example "The C programming language" -book helped tremendously because it had all the necessary details available in compact form. The compression of information is necessary part in creating the a4 paper which contains all the details.


答:
In my opinion C++ is an overkill as a first language.

If I were you, and had sufficient time at hand, I'd go about introducing concepts of programming and CS using Python (or similar).

When the concepts are clear, i.e., when they are comfortable with basic data structures, indirection, basic algorithms etc, I'd slowly introduce C++ and they will very quickly be able to relate to what they already would have learnt.

Title: Tutoring students who are struggling with the basics in C++

Body:
I am tutoring a few students who are having significant trouble learning the basics of their first programming language: C++. I have known many excellent and bright students who have failed or dropped their first CS course. Everyone I am tutoring gives a similar account of his or her experience in class: the instructor moves along too quickly, nothing in the lectures make any sense, et al. Prior to this CS class, most of these struggling students had not expressed any interest in computers as anything more than word processors, web browsers, or some other form of entertainment. The computer is a blackbox that works, so why mess with it?

My best guess is that they are having trouble connecting the abstractions of computer science with familiar concepts. That is to say, these student might know how to learn math, biology, or physics, but those techniques are not working when it come to programming.

Does anyone have any suggestions or advice?  The students I am helping do not deserve to fail this class. It is clear that the instructor is not taking into account the learning style of these students. That is to say, the instructor is failing not his students.


问:
How do you know if you've split your domain correctly
In DDD i struggle to understand whether or not my domain is split correctly into aggregate roots and then those aggregate roots are grouped correctly into bounded contexts. is there a way - like a set of rules/guidance i can use to decide whether or not i am placing things in the right AR/BC</p>

答: My suggestion: don't design the aggregation roots, keeping refactoring the model and the aggregation roots will show themselves. When developing the system, you'll notice that some related entities are always being changed together, then you know they belongs to the same aggregation root.</p>


答:
There are a few things that practically every beginner struggles with. Students need to know how to read code before they can learn how to write code.

The sequential nature of imperative languages. People have trouble understanding that functions are executed in sequence, one item at a time, like a recipe. One way to overcome this is to show some code working through a debugger.

The assignment operator (=) in C-style languages is extremely misleading. You need to explain very carefully that a = 5 means "assign 5 to variable a, not "a is equal to 5".

For beginners, it's safe to describe functions as structured blocks of code that other functions can jump to. Also, beginners have trouble understanding that in C++, function arguments are identified by order, not by name.

Most imperative programming languages have some declarative components and some procedural components, and C++ is no exception. Make sure the student understands that some parts of the code describe the structure of the program, and other parts (functions) describe what the program should do.

Stepping through a program with the debugger is an extremely important and often-neglected teaching tool.

Expressions have types. 3+3 is an integer, 3.5 + 3 is a double, "3" + "3" (in C#) is a string, x == 5 * 3 + 25 is a boolean (or integer in C++). Spend a lot of time to make sure the student is completely comfortable with this notion.

Variable scope is something that beginners get confused all the time. Explain to the student how scope works, and make sure they know that an x defined in one scope is different from an x defined in another scope.

Every variable is referenced at least three times in its lifetime: declaration, assignment (often done on the same line as declaration), consumption. If any of these is missing, then there's a conceptual mistake somewhere. For the same reason, if you're analyzing a working program, you can always look for these three things in the code to figure out the purpose of a variable.

for loops shouldn't be taught until adequate examples of iteration using while loops is given. The shorthand syntax is confusing, and it leaves students wondering why they can't just use while loops. Having a cheat sheet that describes a for loop in terms of a while loop can be helpful.

Arrays and pointers are fairly easy to teach, but a nightmare to learn. In other words, until it clicks, practice is important.

The idea that code is text and that a compiled program is in fact a file is elusive to some beginners. Be sure to show them the .cpp, .h and binary files in the shell.

The OOP components of C++ are a whole different beast entirely, and I kind of hope the instructor doesn't get there -- because OOP is best taught using languages that were designed from the ground up to be OOP. In my experience, teaching OOP through C++ has never gone well.


答:
Programming is substantially different from the other common domains a student encounters.  Many students before college have succeeded by merely paying attention in class and perhaps doing a few homework assignments with easy problems and the answers in the back of the book.  It's more about memorizing processes, then creating them.  It's also the first time for a lot of students to get the wrong answer repeatedly (syntax errors, logic errors, seg faults, etc).  This can drain student motivation when working on programs.

To truly know what's going on with programming, they'll need to PRACTICE a LOT.  An often overlooked technique is to have them write out psuedo code in whatever their native language is first. Ask them to keep expanding that until they have a fairly detailed solution to the problem.  Then its a matter of translating that into real code.


答:
Have you taught programming before?

I taught programming to CS and non-CS majors for four years.
The first semester, my experience was like yours, until I learned a few things.

What seemed vacuously simple to me was not at all simple to the beginners.

Regardless of language, you need to put a mental framework in place - things so obvious you don't even realize you know them, such as:

Computers only do one thing at a time. (Anybody who says they have parallelism and pipelining, go away. Come back when the students know something.) Computers can only do a small number of different things, and they can't begin to do one step until the previous one is finished. I'm only saying this, because computers seem to do so many things, and do them instantaneously, that to a beginner it looks like they do everything at once, and read your mind as well.

Variables are important. It is essential to understand that the name of a variable, and its contents at run time, are two entirely different things. Beginners struggle with this. If I say "Write a program to input your name and then say Hello to you", they need to figure out that they need a variable to hold their name, and they have to think up a name for the variable, and they are tempted to name it after themselves and wonder what "input" means.

There is a huge difference between the time at which you write/edit the program, and the time at which it executes. During their first exercises, they need to be reminded of this fairly often.

The language I used was BASIC, because it is very simple for beginners.
It's not hard to move on to other languages after they've built up a set of basic programming abilities.

We would often write a program on the board, and then "play computer". That is, put an X next to the current statement, manually do it, then move the X to the next statement. Variables were rectangles on the board, where we would write the current contents. When an assignment happened, we would erase it and put in the new value.

One trick I developed was a simulated decimal computer, with 1000 memory locations, each capable of holding a 4-digit number. There was a small set of "opcodes" like load the accumulator, add, store, jump, etc.
I would have them write little programs in this "machine language" and then single-step it to see it working.
Then later, concepts like variables, jumping, and so on are much easier to explain.

Hope that helps.


答:
If you just want the JavaScript language, either Rhino or V8 work as command-line environments, complete with a REPL.  Most developer editors allow you to send the text content to a command-line process.

If, on the other hand, you want to test a browser-like environment, complete with a DOM tree, you can try env.js, originally by John Resig (yes, the jQuery guy).


答:
Of all the wonderful choices for programming languages out there, this college uses C++ as its intro CS class for non-CS majors?? In the hands of talented instructor, it might be remotely conceivable-- but why make it so hard?

When I learned "Pascal" in my college intro-CS class, we spent the first 3 weeks working with "Karel the robot". This was a very simple sandbox Logo-like programming environment where all the basic concepts (including recursion) were explored thoroughly before doing it in Pascal. In "Karel the robot", you control a robot in 2D space using a small set of simple commands. This gives students a useful concrete grounding that they can draw upon for what happens next.

Perhaps there are now more modern instructional programming languages that fill the role of "Karel the Robot"? Probably too late for your students now, however.


答: As others have mentioned, node.js is fantastic for testing Javascript. I just want to add that testing in Firebug may have unexpected results. Actually, the Firebug input is evaled, which is not exactly the same as executing the code as it is. For instance, all variables are created without the [[DontDelete]] flag. This post explains the matter in more detail.


答:
In addition to what was said, I assume that as beginners they only need to scratch the surface, so tailor your curriculum accordingly to avoid complex stuff.

0-give them a simple problem (say evaluate an expression).

1-give them time to figure it out.

2-give them the answer.

3-go through the answer line by line

4-ask them to compare your answer with their attmpt

5-ask them to derive the lesson from this problem

6-add a further step to the SAME problem, say a condition requiring an IF statement

7-repeat the above task on several problems. By then they would have grasped the basics of the language and how to use the environment. The would be ready for what comes next.

Also,

-have a bonus simple problem for them to try at home every 2 classes or so

-engage with each student to see what is the point that is stopping him from going further

-provide easy reference material, forget complex topics and complex books

-get their feedback frequently and use it

-ask them to prepare for the next topic before they come to class


问:
Why do interrupts need to be turned off when inside other interrupt code?
Simple question that will help me understand my OS class... thanks!

Basically, why is it unsafe to have an interrupt within an interrupt? (or exception within exception)

答:
There are two types of interaction between the CPU and the rest of the
  computer's hardware. The first type is when the CPU gives orders to
  the hardware, the other is when the hardware needs to tell the CPU
  something. The second, called interrupts, is much harder to implement
  because it has to be dealt with when convenient for the hardware, not
  the CPU. Hardware devices typically have a very small amount of RAM,
  and if you don't read their information when available, it is lost.

Under Linux, hardware interrupts are called IRQ's (InterruptRe
  quests). There are two types of IRQ's, short and long. A short IRQ
  is one which is expected to take a very short period of time, during
  which the rest of the machine will be blocked and no other interrupts
  will be handled. A long IRQ is one which can take longer, and during
  which other interrupts may occur (but not interrupts from the same
  device). If at all possible, it's better to declare an interrupt
  handler to be long.

When the CPU receives an interrupt, it stops whatever it's doing
  (unless it's processing a more important interrupt, in which case it
  will deal with this one only when the more important one is done),
  saves certain parameters on the stack and calls the interrupt handler.
  This means that certain things are not allowed in the interrupt
  handler itself, because the system is in an unknown state.

The solution to this problem is for the interrupt handler to do what
  needs to be done immediately, usually read something from the hardware
  or send something to the hardware, and then schedule the handling of
  the new information at a later time (this is called the "bottom half")
  and return. The kernel is then guaranteed to call the bottom half as
  soon as possible -- and when it does, everything allowed in kernel
  modules will be allowed.

http://tldp.org/LDP/lkmpg/2.6/html/x1256.html


问:
Automating Unit Test Creation
What are some strategies that could be used to automate the creation of unit test cases? What aspects would you need to look at in each class to be able to generate at least a decent test case skeleton?

I realize a comprehensive automatic solution isn't practical, but I'd like to speed up the test creation a little at least by creating a skeleton. I'm not looking for code examples, just perhaps some suggestions for where to start or examples of where something like this has been done so that I can see how they approached it and what might be possible.

I'm particularly interested in methods for creating unit test skeletons in PHP, which doesn't provide all of the tools that other languages afford, like complete type hinting, for example.

答:
I haven't had a chance to use it on an application of a meaningful size or complexity yet, but there are tools, including Google's CodePro AnalytiX, that automate the generation of unit tests for Java applications. I also found a commercial product, Parasoft's C++Test, that appears to allow for the generation of C++ unit tests

These applications used heuristics to generate test cases. I'm not sure that there's a single framework that you can use to produce a skeleton, but there are constructs that you can look for. I tend to focus on loops, conditional statements (if blocks, switch/case statements), and exceptions, and create test cases that force different execution paths to be carried out.

I wouldn't focus on speeding up the writing of tests by trying to create a skeleton or template, but rather by improving analysis of the specification and/or implementation and writing high quality tests. Being able to identify what tests add the most value early, writing those, and then filling in holes later would have a greater impact on productivity and quality.

Just to provide some more publicity, Falcon tried out CodePro on a project and wrote a little blurb about his experiences.

Title: Automating Unit Test Creation


问:
Using Visual Foxpro DBF with ASP.NET as opposed to SQL Server
I work in a small software company where my boss is a great fan of Visual Foxpro. We are working on an ASP.NET project but my boss is insisting to use Visual Foxpro DBF instead of SQL Server.

I want to know what may be the advantages and disadvantages of using a Foxpro database file with ASP.NET 3.5.

答:
I can only think of one advantage to using Foxpro data with ASP.NET 3.5:

Your boss can manipulate the data using Foxpro

The disadvantages include poor performance and/or unexplained errors and even data corruption.

There is a VERY active community of people who mix and match Visual FoxPro (VFP) and .NET quite a bit that I think could provide a lot of useful information for you:

http://www.west-wind.com

In fact, if you ask this same question there you'll get much more detailed answers.

The owner of that site has written many articles on the subject of FoxPro and .NET and has even written a wrapper for communication between the two, wwDotNetBridge, part of the West Wind Internet Client Tools for VFP:

http://www.west-wind.com/WestwindClientTools.aspx

However, that tool is for accessing .NET from VFP. Oddly absent from his site that spans many years is a detailed explanation on accessing VFP data from .NET. The reason for this is, he doesn't recommend it (from what I've gathered from talking to him in person). The OBDC driver is woefully out-of-date and the OLE DB Driver can have serious issues unless it is only used for reads.

Here's a post on his forum from a very respected FoxPro expert, Doug Hennig, about the various ways of connecting to VFP data:

https://support.west-wind.com/Thread2DJ149KLZ.wwt

Here's a post on his forum about issues with the OLE DB:

https://support.west-wind.com/Thread2IN0TBQQ5.wwt

You are bound to run into the same problems and more if you proceed down the path your boss wants.

A much better solution, IMO, is to either stick with native FoxPro for web development (for now at least) and use Rick's excellent West Wind Web Connection product:

http://www.west-wind.com/webconnection/

Or just do straight ASP.NET development and tell your boss to use FoxPro's ability to access SQL data and bring it into a cursor where he can use FoxPro commands all he wants to manipulate the data.

For what it's worth, we've been using West Wind Web Connection for over 10 years for our ecommerce website. It works great and since all our in-house data/programming is VFP, it was the right choice back in 2000. And for everyone here who might chuckle at a VFP backend for a website, last year our website processed over 150,000 orders (sometimes 2,000+ per day) with a total value in the mid-eight figures. We are a leader (if not the leader) in our industry.

Having said that, I would highly recommend you stick with ASP.NET MVC and just do exporting or data mining processes to get the data into FoxPro for your boss' needs. We are in the process of converting to ASP.NET MVC right now.


问:
For what common problems is functional programming not a good fit?
Functional programming is a declarative paradigm. One of the strenghts with FP is that side-effects are avoided. It's said that for some problems FP isn't a good fit.

For what common problems isn't functional programming a good fit?

答: Real-time embedded programming is all about the side effects.  Interacting with digital and analog io, timers, serial and parallel ports, everything interesting is done by calling functions with side efffects.  </p>


答: The general issue is that an interrupt handler will typically manipulate data structures and it would corrupt those data structures if that same code was reentered in mid-update.  However, there are many ways to organize interrupt systems and many of those ways allow nested interrupts at different priority levels.  Interrupt controllers can mask off interrupts that have not yet been acknowledged by the interrupt handling code, so it is too broad a statement to say that it is "unsafe to have an interrupt within an interrupt".  It will depend on the design of the interrupt controller (hardware) and the interrupt handlers (software), as well as the characteristics of the interrupting device and the meaning of the interrupt.</p>

Title: Why do interrupts need to be turned off when inside other interrupt code?

Body:
Simple question that will help me understand my OS class... thanks!

Basically, why is it unsafe to have an interrupt within an interrupt? (or exception within exception)


答:
Your strategy and skeleton depends, non-trivially, on what kinds of tests you're looking to generate, what kind of coverage you're looking for, and the language/environment you're working in.

It's fairly straight forward to write a test generator which, for languages like C or Java, reads class signatures and automatically generates tests for standard corner cases (passing in 0, 2 random values, MAX_INT, MIN_INT, to an integer argument, nulls for nullables, etc...). You could then run the generated tests, record the results for each test, and manually filter through them to remove irrelevant ones, approve acceptable results for tests which pass (so they can automatically pass from then on), and mark as invalid ones which fail.

You can augment this with tagging/commenting/refactoring of classes to help your generator with extra hints. You might have a tag which lists all the possible exceptions that a method call is allowed to raise, or which gives a reduced range of valid integers for an integer argument. Look at these as short-hand for having to write the tests yourself.

So, here are some components you'll want to look at:

A component to automatically parse source code/function signatures/manual annotations, producing standard test cases, or outlines/signatures for test cases which wait for your input to be completed.

A perpetually growing/changing language of tags/annotations/comments which may go to any level of granularity (method/class/signature/while loops/etc...) representing hints to the automated test builder. Ideally you should be able to play with this language without having to recode your framework or any chunks in it

Automated test runner, with the ability to identify new/old tests and record/test against "acceptable" answers for each test. Ideally this runner will build a database of test runs, results accepted/declined, and current acceptable results for each test.

Automated "object faker" which, given a class name and map of names->values, can generate an object mimicking the class, returning customizable data for function calls, accessors, public data slots, etc...

There are lots of test frameworks out there which already include chunks of this functionality for various languages and platforms. While it's fairly easy to start doing this work yourself and grow this kind of framework organically in-house, it's also an endless long-term project which will probably be duplicating existing work. I'd recommend taking significant time to look at what's available first, and then decide whether it's worth the time to dive in.

Title: Automating Unit Test Creation

Body:
What are some strategies that could be used to automate the creation of unit test cases? What aspects would you need to look at in each class to be able to generate at least a decent test case skeleton?

I realize a comprehensive automatic solution isn't practical, but I'd like to speed up the test creation a little at least by creating a skeleton. I'm not looking for code examples, just perhaps some suggestions for where to start or examples of where something like this has been done so that I can see how they approached it and what might be possible.

I'm particularly interested in methods for creating unit test skeletons in PHP, which doesn't provide all of the tools that other languages afford, like complete type hinting, for example.


问:
What are questions to test a programmers knowledge of SQL?
What are questions to test a programmers knowledge of SQL? What is the answer to the question? And what would a lack of an correct answer mean in terms of time likely to understand the concept(s) related to the question?

GOOGLED: sql challenge

答:
I would ask "Why and how should you sanitize input values given from the user which will be used in an SQL query?"

This is needed to prevent SQL injections, and being able to answer this requires good knowledge about SQL syntax and commands (such as SELECT, UPDATE, DROP, DELETE, etc.), as well how those can be circumvented by use of SQL comments to break a query and inject what the malignant user may wish to do.


答:
What helped me when I went through CS 101 was learning the logic before even looking at code. We went through truth tables and prepositional calculus just so we would start thinking "this is true or false" and not "this equals this or that".

That right there was when everything clicked for me. Once I figured out that programming is basically just manipulating true/false values at its core, then it all became relatively simple.

And this made it so it didn't matter what language I was using, logic is the same everywhere. Syntax might be confusing, but I can say things like "Ok, in Obj C I send messages to classes like this and in C++ messages were sent like this other way. But the algorithm hasn't changed at all." etc.


问:
Should I start developing code before planning out the interface?
I'm starting a gaming project on the side of my normal school/work projects and I'm wondering if I should start planning out the user interface before starting an actual project in code.

I see some pros/cons to doing both first and was wondering what advice some seasoned developers could suggest.

答:
I believe it was at his Dev Days talk a couple of years ago, but Joel Spolsky once pointed out that the best designs come from when the UI is something which has been considered from the beginning.

He then showed a browser which had been "skinned" (something which was supposed to have a generic interface which was supposed to be easy to update and customize), it looked nice enough. Then he contrasted it with Chrome and made the point that the majority of the features simply could not have been possible had UI been ignored until later in the game.


答:
If you're going with a test-first kind of approach, then start by planning the UI and what you want from the game, and then go through the cycle of test-implement-refactor-update_design-test.

In general, though, I look at the two processes as parallel, and interacting. Design the UI without paying attention to the technology, early on, and work on the code in parallel, also early on. The UI design will help shape your target, your "user stories" and inspire your coding. Your coding, on the other hand, will impose limits on what you can hope to accomplish reasonably, based on the complexity of the program and your skills/abilities. Take turns thinking of each independently, and then take time to integrate your ideas and discuss them with others.

Title: Should I start developing code before planning out the interface?

Body:
I'm starting a gaming project on the side of my normal school/work projects and I'm wondering if I should start planning out the user interface before starting an actual project in code.

I see some pros/cons to doing both first and was wondering what advice some seasoned developers could suggest.


答:
There's an ACM or IEEE article somewhere that goes into some of the details of why beginners (even CS graduates starting in the field) need to sit behind a senior programmer and watch them code a problem.

Professionals often pair for difficult problems.  Students are too often told not to.
Advantages of pairing (taking turns at keyboard):
1. The student gets told what he is doing wrong immediately.  Instant feedback.
2. When the learner watches the teacher the learner picks up on things the teacher would have never thought to point out.

Rather than let a student develop bad practices, they are nipped in the bud. (I would flip #1 with #2 here and let the student watch the Instructor/TA FIRST)

Teaching CS with a static set of powerpoint slides doesn't lend well to the temporal process of writing a program.  (Granted there are tricks you can do with growing functions line by line, but they're usually awkward.)

Learners need to know where to start writing, and where to stop and compile.  Our brains are mostly wired to read left to right top to bottom, but a program is like a whole choose your own adventure book crammed into a single page!

Too often a beginner will copy a whole program and then compile.  Even a professional might give a first crack at it that way, before realizing they should have left all of the functions empty, and compiled the program, then iteratively added into a working skeleton.

Also, related is the ridiculous idea that CS should be taught without a computer and just pencil and paper.  I wonder how many employed programming professionals really think this is the best way, or if it's just what CS instructors do because they themselves don't like working with computers?  Any attempt to remove a computer from the picture is a mean one.  Doing so makes programming less fun and less interactive than it should be.  We are long past the days of entering data into a punch card and patiently waiting.  Today's professional developers are fans of instant gratification.  Luckily most students are too.

Obviously the drawing of pretty designs with pencil and paper before and during the development process is a powerful tool for both professional and beginner programmers.  This like the "hands on keyboard" time should be also be spent pairing!  Maybe here it might make sense to let the student attempt the first round before watching the teacher, although even with this it's probably worth seeing the teacher's real thought process.

Lastly, The hot keys and editing tricks that the professional developer employs aren't "noise" to the student's learning.  Most importantly, they engage and interest the student.  Second, they raise awareness to common development needs.  Furthermore the most basic of these practices are often easy to execute but not obvious initially.  A young wood shop student can easily learn how to remove a nail with the claw of a hammer, but in most cases must first be told that's what the claw is for.  Some extremely easy to do things are just not trivial to learn without being taught.  Even professional developers forget about these "tricks" all the time, and benefit from refactoring tools like resharper to remove redundant or unreached code etc.


问:
Which technology stack to use for car pooling over web and mobile
I want to start working on a project where I want to build a intranet website and mobile app for people working in my office for car pooling. The basic idea is that if anyone is interested in looking for someone to carpool with should make a posting of going from A to B at time X.People can then reply to it.

I've narrowed down my option to Scala+Lift+MongoDB or Node.JS+Redis/MongoDB+HTML5. I don't know which one is better or worse for the problem I have mentioned. Also looking at developing mobile apps for the same application where people can send carpool request over their phones.Looking for a stack which can complement the mobile development also.

I know there are various solutions for this, but I'm looking to learn something new and exciting and have fun while developing it.

答: Use whichever you like the best. The 'stack' is rarely what defines success or failure of a project.</p>