答:
For new development, especially Agile development:

"Perfection is achieved, not when there is nothing more to add, but
  when there is nothing left to take away."
  --  Antoine de Saint-Exuper

If you are estimating effort and time on fixing some nearly impossible to reproduce error(s) in a hideously overly complex system with very few to no developers with intimate domain knowledge of the system then the only correct answer is "When it is fixed."

Title: How to answer "When will it be done?"


问:
What is the proper way to write a setter?
I am am trying to learn JAVA on my own.  In one book I am reading the author says there is no convention for writing a correct setter.  His example would go something like this:

```<code>public void setUnitCost(double inUnitCost) {
     unitCost = inUnitCost;
}
</code>```

However, when using Eclipse, and tell it to create getters and setters it does this:

```<code>public void setUnitCost (double unitCost){
     this.unitCost = unitCost;
}
</code>```

My question is which way is better?  Does it make a difference in the programming world?  What exactly is the difference between the two?

答:
The most modern idiomatic code would be:

```<code>public void setUnitCost(final double unitCost)
{
     this.unitCost = unitCost;
}
</code>```

marking the argument final is important; using JSR305 @Nonnullable/@Nullable when working with object references is even better for self documenting the intentions of the code.

this. is self documenting that you are setting the current instance and not some variable in a super class, which should idiomatically use super.

ContentLicense: CC BY-SA 3.0

Body:
The most modern idiomatic code would be:

public void setUnitCost(final double unitCost)
{
     this.unitCost = unitCost;
}

marking the argument final is important; using JSR305 @Nonnullable/@Nullable when working with object references is even better for self documenting the intentions of the code.

this. is self documenting that you are setting the current instance and not some variable in a super class, which should idiomatically use super.


问:
How to answer "When will it be done?"
We all have it, problems that prove difficult to fix and working out a fix through obscure code and bizarre unexpected functionality. Slowly, logically working your way through trying to find patterns, errors, mistakes. This process takes time and the issues are often not easily understood by the client.

How does one answer when asked the question "When will it be done?", especially when the client may not understand the inherent complexities of software development?

答:
Typically, I would just tell them the truth.
I would tell them they I don't know right now, and I might have better insight in a week. I would then hand them a ball park with as many squiggles in front of it as you can fit on the paper to indicate that it is a gut feeling based guess.
If they start hard-balling you, just start every sentence with "It's possible ..."
Usually anyone I do anything for is happy with the "Check back in a week or so, but now all I can say is about 2 months" or something like that. </p>

OwnerDisplayName: Emdiesse

Title: How to answer "When will it be done?"


问:
Does programming in general become easier to read, write and understand as you gain experience?
I'm a beginner in programming and I've been reading books, studying, reading articles, and whatnot. I'm getting great results since I've started learning programming, and when I was a beginner I used to think I knew everything about programming, but as I learned more I realized how difficult this field is (In fact all fields are difficult, but that's not the point).

Nowadays, I've written functional software and I've learned the BASICS of 3 languages and I'm intermediate in just one language. When I look at advanced things like MYSQL, or OpenGL programming, or even visual studio C++ code it gives me headaches, and even when visualising HTML source code of many websites (Most source codes on websites, seen by google chrome seem very messy and unorganized) it makes me confused to the very limit of my brain. It all seems simple at first, yet when looking at these advanced things it just makes me wonder how can one learn so much.

The question, in a nutshell, is if these things become clearer to a programmer as he advances in his career. Do complicated topics as the ones listed above (OpenGL, MySQL, advanced html sites) become easier to read, write and understand as you learn more, or does it just get more complicated as you go by? How can you combat this feeling that you're an ant in the programming world and this stuff is the foot about to squash you?

答:
It gets easier and more complicated at the same time!

Knowing others is wisdom;

  Knowing the self is enlightenment.

  Mastering others requires force;

  Mastering the self requires
  strength;

  He who knows he has enough is rich.

  Perseverance is a
  sign of will power.

  He who stays where he is endures.

  To die but
  not to perish is to be eternally present.

translated to Software Development

Knowing lots of technologies is wisdom. ( Everything descends from ALGOL )

  Knowing what you don't know is enlightenment. ( LISP )

  Mastering lots of languages, frameworks and platforms requires lots of effort. ( Java )

  Mastering only what you need to know and only that requires strength. ( and Google or stackoverflow.com )

  Knowing when to stop coding and deliver something is when you know good enough. ( No Analysis Paralysis or Gold Plating )

  Keep working at what you are trying to achieve, it requires focus and will power.  ( Everything constantly changes, you are never finished )

  Stick with one or two technologies and you will endure. ( COBOL still pays well, as does C )

  To quit programming and move into management is to be eternally present. ( or leave a legacy of FOSS software that everyone will continue to use well after you are dead ).


答: Whatever you estimate don't forget to include Hofstadter's law: It always takes longer than you expect, even when you take into account Hofstadter’s law.</p>

Title: How to answer "When will it be done?"

Body:
We all have it, problems that prove difficult to fix and working out a fix through obscure code and bizarre unexpected functionality. Slowly, logically working your way through trying to find patterns, errors, mistakes. This process takes time and the issues are often not easily understood by the client.

How does one answer when asked the question "When will it be done?", especially when the client may not understand the inherent complexities of software development?


问:
Learning Asynchronous programming
Asynchronous non-blocking event driven programming seems to be all the rage. I have a basic conceptual understanding of what this all means. However what I'm not sure is when and where my code can benefit from being asynchronous, or how to make blocking IO, non-blocking. I'm sure that I can simply use a library to do this, but I'm more interested in more in depth concepts, and the various ways to implement it myself.

Are there any comprehensive/definitive books, or other resources on this subject (like GoF for Design Patterns, or K&R for C, tldp for things like bash)?

(Note: I'm not sure if this is actually functionally an identical question to my question on Learning event driven programming)

答:
Asynchronous programming is much more of a philosophy than just another programming trick.  While, your last question attracted answers mainly  about programming aspects and my answer was a disconnected loner for being mostly theoretical, I am trying to give you a fresh perspective building on the same line but explanations rather than just references.

This one is about some fundamentals of why and how of Asynchronous Programming.

Let's suppose you go to a bakery shop (and assuming the cake will be prepared after the order) - you have two choices, either you choose to wait till the cake is ready or you give the order and head-back to home and pick up later when it is ready. The first one (wait) is a synchronous method and later is asynchronous method. Needless to say this example provides a good reference why should you use asynchronous methods over synchronous.

Event based programming is only one of the ways the asynchronous systems can be built and it is not just a useful design pattern but rather it is an architectural pattern. I am listing down cases where this theory is used in a practically useful way - hoping that it would bring some clarity

One of the first example of Asynchronous systems are Unix system IO.
While we know read(), write() and even select() calls blocks the program flow, but inside the OS, they are asynchronous, i.e. the kernel generally knows that the block device (aka hard disk) will take some time to fill buffer, till such a time CPU is free from that respective thread and hence the thread is parked as (not ready).
Refer 1. Moris Bach "The design of Unix Operating system"

Another most common example is majority of UI frameworks. Here, all user clicks are first dispatched through a controller which in turn call backs respective application. Important thing is such call backs should not keep call-backs waiting else the system will freeze. The call back from UI controller to back-ends are usually asynchronous if they involve heavy processing.

Another good example of asynchronous programming (as a pure design pattern) is Active Object. An active object is one which has it's own private thread such that one can keep many requests in a queue and execute one-by-one.
Refer to this Paper : Active Object. This pattern is heavily used right from Enterprise software to mobile frameworks. The popular platforms Java/EJB and .NET allows Local or Remote asynchronous method invocation which essentially allows normal objects to become active objects. Active objects were present way back in Symbian : Active objects in Symbian OS by Aapo Haapanen (see this also: Active Objects in Symbian). This is now also present in Android).

Apart from Active object, the same author Douglas C. Schmidt, has produced number of other works which are other parallels to Active object and are also the asynchronous patterns. See this Event Handling Patterns and a full account is available on his book Pattern-Oriented Software Architecture: Patterns for Concurrent and Networked Objects - V2

When a given object needs to return the API, while working in the background to actually accomplish the work, the usual methodology is to have a multi-threaded system to achieve this. Threaded systems are present everywhere from C (posix), C++ (boost)  to Java, C# and so on. Active Object is essentially only an abstraction which can hide this. See why Active object implementations are preferable over naked threads. Another good read.

But this concept goes beyond threads or objects inside an application to become asynchronous.  One of the best usage is in Distributed systems where two applications doesn't necessarily need to wait for each other for co-ordinations. Good old (or not so good, whichever way you look at it) RPC was synchronous. [of course, there are other asynchronous RPCs as well]. But the modern alternatives like Message Oriented Middleware is truly asynchronous for good reasons.

Last but could be most interesting one, is the Agents programming which can benefit from Asynchronous model of communication.

While asynchronous programming does look sexy but it creates its' own complexity including:

framework for return value passing

additional overhead of communication

additional need for synchronizing constructs

possibility of deadlocks, racing etc. if things not done right.

... and so on.

It should always be used only for a genuine reasons.

So when should one use Asynchronous model? When should you put a background thread and allow caller to go asynchronous?Here are some good thumb rules when it applies (but not complete)

When system wants to apply strict serious resource conversation: for example, you want to keep an absolute fixed number of threads. Asynchronous pattern forces the system to implement queue.

When caller's need to do "other useful things to do" indeed is genuine. So many times, the other thread even if made unblocking, will not do anything useful and hangs around polling for results. This indeed can be more CPU consuming than basic synchronous model.

When you need higher levels of reliability in distributed systems. (see Message Oriented Middleware).

Title: Learning Asynchronous programming


问:
Using PHP's ternary operator with only two arguments
I was recently reviewing some of my code and noticed that in a fit of absent-mindedness, I'd left a structure like the following:

```<code>$guid = empty($subscription->guid) ?  : $subscription->guid;
</code>```

Now, this wasn't doing what it's supposed to and is wrong, but since that property is always set now it was working fine, and there's no syntax error since 5.3 because of the following change:

Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

I wasn't aware of this change, and now I'm curious if I should be using it or not. This is something I was sorely missing from languages like ruby where you can do eg, a = b || c to get either b or c rather than a 'real' boolean. However, the syntax they've chosen for the ternary operator seems a little counter intuitive to me. Should I be using this in production code? It definitely threw myself when I saw it by accident.

答:
I think it's a very useful operator and should definitely be used since the language standard explicitly defines it.

Note that it's officially called the Elvis Operator in Grooy (why? just look at it closely!), and had been proposed to be introduced in Java 7.


答:
There's no difference between them. as long as it fulfills it task in an efficient way it is fine. I do write my Setters(sometimes)  this way

```<code>public void setFoo(String fooName){
  this.fooName = fooName;
}
</code>```

The reason I used this is that I lack the idea of proper naming of variables. but nonetheless you can write a setter what suits you.

But I prefer the first setter, since there might errors occur on the second one

Title: What is the proper way to write a setter?

Body:
I am am trying to learn JAVA on my own.  In one book I am reading the author says there is no convention for writing a correct setter.  His example would go something like this:

```<code>public void setUnitCost(double inUnitCost) {
     unitCost = inUnitCost;
}
</code>```

However, when using Eclipse, and tell it to create getters and setters it does this:

```<code>public void setUnitCost (double unitCost){
     this.unitCost = unitCost;
}
</code>```

My question is which way is better?  Does it make a difference in the programming world?  What exactly is the difference between the two?

Body:
There's no difference between them. as long as it fulfills it task in an efficient way it is fine. I do write my Setters(sometimes)  this way

public void setFoo(String fooName){
  this.fooName = fooName;
}

The reason I used this is that I lack the idea of proper naming of variables. but nonetheless you can write a setter what suits you.

But I prefer the first setter, since there might errors occur on the second one


答:
This might rub a few people the wrong way, but I'd say do not write (or generate) code that merely gets or sets a variable, as it leads to clutter and more lines of code to read / scan to understand what your class does. This clutter can take attention away from code that does actually have specific implementation details other than merely getting or setting a variable.

The Lombok library provides @Getter & @Setter annotations to alleviate you from having to write (and others to read) 'dumb' getter and setter methods. At compile time Lombok will generate these methods for you, and their IDE integration means you won't notice the difference when developing.

(There is even a de-lombok option to generate source code with the appropriate getters and setters in place, without any dependency on Lombok, but I wouldn't recommend it unless you have to meet some really weird requirements.)


答: The Personal Software Process (PSP) focuses on improving estimates. This is achieved by disciplined logging of tasks. This, in essence somewhat "accelerates" the "experience" part of estimating since you will have actual data about typical tasks. Of course, this profession still requires unique solutions to many problems but in my experience, estimates are better after using PSP.</p>

Title: How to answer "When will it be done?"


问:
exclamation points in error messages
What do you think about using exclamation points in error messages?  i.e. "The address is not valid!".

Personally, I think it adds nothing, insults the user, and makes the product look like it was written in TRS-80 BASIC by a 12-year-old.

答: Well, if it's a standard Windows dialog box, it may already have an exclamation point in a red triangle or blue circle, depending on the parameters passed to the Win32 API method that displays it.  So why duplicate the urgency?</p>

ContentLicense: CC BY-SA 2.5

Title: exclamation points in error messages


问:
What is a "wrapper" program?
Where I work, employees use a third-party desktop program for their clients. This program saves data to a flat file. My colleague wants to write a Java program that uploads that flat file to a remote server, opens the desktop program when the flat file is downloaded from a Web site, and checks if the desktop program is running or not by looking at the Windows processes.

He keeps calling this helper/utility program a "wrapper." But it doesn't wrap anything! I tried to clear it up with him, but he said, "Well, I call it a wrapper." He now has everyone in the company calling it a "wrapper." What would you call it? I say that it's a helper program or utility program.

答: If he cannot explain why he calls this a "wrapper program", then he used this word intuitively without thinking to much about the name. Names are sound and smoke - do not argue about the names of things.</p>

Title: What is a "wrapper" program?


问:
Why is it so difficult to make C less prone to buffer overflows?
I'm doing a course in college, where one of the labs is to perform buffer overflow exploits on code they give us. This ranges from simple exploits like changing the return address for a function on a stack to return to a different function, all the way up to code that changes a programs register/memory state but then returns to the function that you called, meaning that the function you called is completely oblivious to the exploit.

I did some research into this, and these kinds of exploits are used pretty much everywhere even now, in things like running homebrew on the Wii, and the untethered jailbreak for iOS 4.3.1

My question is why is this problem so difficult to fix? It's obvious this is one major exploit used to hack hundreds of things, but seems like it would be pretty easy to fix by simply
truncating any input past the allowed length, and simply sanitizing all input that you take.

EDIT: Another perspective that I'd like answers to consider - why do the creators of C not fix these issues by reimplementing the libraries?

答:
why do the creators of C not fix these issues by reimplementing the
  libraries?

Probably because C++ already did this, and is backward compatible with C code. So if you want a safe string type in your C code, you just use std::string and write your C code using a C++ compiler.

The underlying memory subsystem can help to prevent buffer overflows by introducing guard blocks and validity checking of them - so all allocations have 4 bytes of 'fefefefe' added, when these blocks are written to, the system can throw a wobbler. Its not guaranteed to prevent a memory write, but it will show that something has gone wrong and needs to be fixed.

I think the problem is that the old strcpy etc routines are still present. If they were removed in favour of strncpy etc then that would help.


问:
Best example for mixins in .NET
I want to present the concept of mixins and their implementation in .NET.

The way they work in .NET is you add extension methods on an interface and decorate classes with said interface.

What would be the best examples for this pattern (other than linq)?

答:
As far as I know, "mixin" is a Ruby concept for handling multiple inheritance limitations, and does not have a built-in comparable way of doing it in C#, VB.NET, or Java.

Your suggestion of adding extension methods to an interface is an interesting one, and would provide much of the benefit of a mixin. I've never actually seen anyone do it that way before, so I'll have to put that in my bag of tricks...

As far as an example, I think the one you put in your comment above isn't a bad one; demonstrating that a Bat is a mammal that can fly.  Without making your own contrived example like that, I can't think of anyplace where this just "occurs" in any of the core .NET libraries, other than Linq (sort of, though even IEnumerable requires that you define the GetEnumerator method in the implementing class, so it isn't a purely "empty" interface with only extension methods.)

Is there a problem with presenting your own contrived example?

Title: Best example for mixins in .NET


问:
Is specializing beneficial in IT industry?
For the past few years I started wondering if it makes sense to learn advanced techniques in some fields of IT, or is it better to be just good at everything, and use the simplest code possible everywhere.

I will use C++ as a language for comparisons, since I'm a C++ developer.

As a C++ developer you can write truly interesting code, ranging from code that looks like C with simple functions all around, to template meta-programming stuff, sometimes intermixed with pure abstract classes.

I've started noticing that I'm leaning towards the later lately.

The problem is, that with larger solutions programmers are rarely working alone, and most likely skills don't overlap that much either. So some parts of code I write might be confusing to other team members, and the other way around.

I might like STL and templates, while other people might prefer pure abstract classes everywhere, others will rely on dynamic_casting, or code generated by VC wizards. While some just enjoy everything written in a very simple, C like manner.

This also backfires with the fact that people who haven't worked with, say, with virtual classes, might not even know why the new class they've derived is broken because of simple missing virtual destructor. So the code you write paves a way toward memory leak if some other people decide to reuse your code later on.

Do you have experience working in environments with multiple developers with different skill-sets? Do you try to find a common dominator in your environments? Does using the skill-sets of every person even works in larger projects?

答:
There's a short term answer, and a long term answer, and neither is absolute.

In the short term there tends to be a better return on investment in specialized skills.  If two people are applying for a job doing C++ (or Python or Oracle...) and one is more clearly more competent at the job at hand, they will generally get picked for it.  Some companies look for broader skills, but that's usually in strategic hiring (after school, management training programs, etc.) rather than specific tasks.  If I really need someone to help me get my databases straight over 6 months, I want an SQL rock star, not someone who has a little bit of everything, and also played high school baseball and speaks Latin.

In the long term things flip.  A good CIO/CTO/CEO/Entrepreneur/Leader needs to be able to converse on many levels and many topics.  Specializing may have gotten them there, but being a generalist tends to be more important.  It isn't until later that learning things above and beyond the job (spending 3 months is support, learning test automation, a lateral assignment in South America) start to pay off.

Of course there's a more tactical bit of advice, which is learn what interests you.  :-)


问:
Best practice/Patterns for two way data synchronisation
Quite often in my work the idea of 2-way data synchronisation between database systems crops up. The classic example is two slightly different CRM systems (say, Raiser's Edge and Salesforce) and the need to have a two-way sync of Contact data between them.

API considerations aside, assuming you have a shared key to sync on, and purely thinking of the algorithm/pattern to be employed, this is a task that is often underestimated by non-techies.

For example, you have to watch out for:

Can you easily detect which records have changed in both systems (or will you have to compare all records between the systems to detect changes)

If you're going for a once-every-N-hours sync, how to deal with conflicts where the same record changes at more-or-less the same time in both systems

If you're going for a real-time sync (ie an update in one system immediately triggers an update to the other system) how to handle divergence over time due to bugs or system crashes

Personally I can think of ways to tackle all this but I'm wondering if there are any well known patterns, literature or best practices that I could refer to.

答: Yes, a hard problem, easily underestimated. And could be a lot of work. If you are on Microsoft technologies, you may want to have a look at Microsoft Sync Framework here and here. </p>


问:
Are High Level Design and Low Level Design documents needed to follow Agile development process?
Our team is developing a project using an Agile development process. All of our requirements are converted into product backlog items and task are broken down based on that. One of my team member suggested to maintain the High Level Document (HLD) and Low Level Document (LLD) for the requirement.

Do we need to have these documents to follow the Agile process?

答:
I believe It depends on some factors like :

The business domain of the project if we are talking about medical application or similar then you'd definitely want to keep track of these type of documentation for FDA or equivalent Approval.

Expected lifetime of the project to release if we are looking to a 2~3 years then its better to keep as minimum and effective level of documentation as possible maintained to keep track of the critical changes through life time of the project.

And I believe there can be more factors that can affect such decision so it is better to define the pros and cons of creating & keeping such type of documentation maintained and deiced.


问:
Why is Perl 5's smart-match operator considered broken?
I've seen a number of comments across the web Perl's smart-match operator is broken.
I know it originally was part of Perl 6, then was implemented in Perl 5.10 off of an old version of the spec, and was then corrected in 5.10.1 to match the current Perl 6 spec.

Is the problem fixed in 5.10.1+, or are there other problems with the smart-match operator that make it troublesome in practice?

What are the problems?

Is there a yet-more-updated version (Perl 6, perhaps) that fixes the problems?

Edit: To clarify, I'm not asking about bugs, but rather the opinion that the intended behavior of ~~ is bad.

答:
People often confuse the issues that arise with the smartmatch operator with those that arise with the given/when construct, such as the problem of lexical $_.

I’ve come to the opinion that if you use the smartmatch operator only on literals, that you will not go insane.  I can make no promises about any other situation.  Trying to figure out what $a ~~ $b is doing is enough to drive any decent human being to run screaming in madness, and to take up another programming language altogether.

Or at least, that’s the take I got from Larry when he was editing the smartmatch section of the 4th edition of Programming Perl.


答: Usability guru Jakob Nielsen discourages their use. Most usability advise is based on research. That's why i tend to prefer those advice over personal opinions.</p>

Title: exclamation points in error messages

Body:
What do you think about using exclamation points in error messages?  i.e. "The address is not valid!".

Personally, I think it adds nothing, insults the user, and makes the product look like it was written in TRS-80 BASIC by a 12-year-old.


问:
How DEP and ASLR play role in security?
Lines from CLR via C#:

A managed module is a standard
32-bit Microsoft Windows portable executable (PE32) file or a standard 64-bit Windows
portable executable (PE32+) file that requires the CLR to execute. By the way, managed
assemblies always take advantage of Data Execution Prevention (DEP) and Address Space
Layout Randomization (ASLR) in Windows; these two features improve the security of your
whole system.

Que: I want to know the Security in which context here and what DEP and ASLR does here??

答:
Rather well-documented here:

DEP

ASLR

The long and short is DEP keeps data from being executed as code, such as buffer overflow attacks and ASLR keeps malicious code from knowing where other bits of code and data will be located at in memory, so it can't be easily attacked.

Title: How DEP and ASLR play role in security?


问:
GPL copying copyright notices
The "GPL How to" has the following to say about applying copyright notices of code copied from other programs:

If you have copied code from other programs covered by the same
  license, copy their copyright notices too. Put all the copyright
  notices together, right near the top of each file.

I did a total refactoring of a C# library, which itself was a port from Visual Basic (VB) code. The original VB code is currently released under the Microsoft Public License (Ms-PL), but originally under GPL. The C# library is GPL, continuing work on the older VB library. Basically I only used the same 'technique' they used.

I don't care making the library GPL, so that's not the issue. (From this answer I gather my library might be considered a derivative work.) I do however find it cumbersome having to copy the previous copyright notices in every source file. I would rather only reference them in the README file. This question discusses the need to add notices to every source file, but there's no consensus between the answers. Therefore I'd like to add the license to every file as a safety measure.

Do I have to include copyright notices of the projects on which my library was based in all source files as well?

答:
MS-PL (definition) is much more liberal compared to GPL. Not very identical, but MS-PL more like Apache license, where in the code is given as-is. MS-PL original software doesn't mind whether a derived software is distributed as source or binary or even commercial. Hence, if you take MS-PL code, modify (whether trivial or with refactoring) you can publish it through GPL

However, it is clear that you cannot remove MS-PL license notice. And hence, the GPL license granted by you essentially becomes a dual license. Since MS-PL already permits other people to include your work in commerical, GPL's provided protection will no longer hold! Yes, your license will no longer be any stronger than the weakest of all - the MS-PL.

One more ref: http://www.cmswire.com/cms/web-development/taking-a-closer-look-at-microsofts-mspl-open-source-license-004248.php

There is a general opinion, [ Is it possible to rewrite every line of an open source project in a slightly different way, and use it in a closed source project? ] that even if you modify every line of code, it is still a derived work; hence you cannot really rule out MS-PL terms.

EDIT

Oops! I just got off the tangent to read the question properly.

Basically, assuming that GPL is common across all three generations. This is simple. What GPL requires is that for every file copyright claim needs to be included with mention of GPL. See GPL Howto it reads following:

Whichever license you plan to use, the process involves adding two
  elements to each source file of your program: a copyright notice (such
  as “Copyright 1999 Terry Jones”), and a statement of copying
  permission, saying that the program is distributed under the terms of
  the GNU General Public License (or the Lesser GPL).

So there needs to be at least one copyright claim attached to every source file without which you cannot attach GPL (or any license) to it!

Now, the real question in your case is,

if you have really modified a file heavily or almost re-written but do
  not include original author's name, are you violating copyright law?
  (by not copy pasting the original author's name).

This is determined by the common notion of whether new author deserves copyright over determined works. See this wiki page for primary introduction:
When does derivative-work copyright exist?

The simple answer is: when the change is significant. This is quite ambiguous given that it is a statement underlaw, but it is true. Even copying only rythm but not words and making remixes in music comes in severe gray area because of this; and this notion of significant change varies between laws of different countries.

Having said that, it would be suffice to notice that had you almost started with a new file and re-wrote the program, the new file will typically deserve your name rather than old author. In general, if you simply copy a file and simply change author's copyright notice to put your name, you will be violating copyright.

So as a practical advice if you have started out with new set of
  files, put your name, if you have kept original files, keep the
  original names (you can add your name in addition).

Title: GPL copying copyright notices


答:
There are some really good answers here already but I thought I might add a couple more short points:

when I was a beginner I used to think I knew everything about programming, but as I learned more I realized how difficult this field is

This is called the Dunning-Kruger effect. It is extremely common amongst beginner programmers, and in fact, beginners in many fields.

Most source codes on websites, seen by google chrome seem very messy and unorganized

Did the people who wrote those web sites want you to be able to understand them? Probably not. It is in their interests to have code that is difficult to understand.

it just makes me wonder how can one learn so much.

By specializing. I am an expert in an extraordinarily narrow field: the design and implementation of C# compiler semantic analyzers. If I'd spent fifteen years studying OpenGL or XML or HTML or whatever, I'd be an expert on that and mystified by semantic analyzers. But I didn't, and thus I have only a very basic understanding of OpenGL, XML and HTML.

The question, in a nutshell, is if these things become clearer to a programmer as he advances in his career.

Yes, because you start to see the larger patterns. Take OpenGL for example. You've probably seen a bunch of "API libraries" -- big pieces of related code where the way you interface with the code is by calling a bunch of named functions with particular arguments. And you can get a basic understanding of OpenGL merely from understanding that it is an API.

When you've gotten more experience and seen a bunch of different programming techniques, you realize that seemingly unrelated technologies -- say, OpenGL and LINQ in C# -- have commonalities. Both are APIs where you build workflows that pipe data around, and that you can run optimizers and other transformation on the workflow in rich and interesting ways. Once you have that concept in your box of tools, suddenly it becomes much easier to tap into the full power of any API that uses that pattern.

Do complicated topics as the ones listed above (OpenGL, MySQL, advanced html sites) become easier to read, write and understand as you learn more, or does it just get more complicated as you go by?

They become both easier and more complicated. Easier because, like I said, you start to recognize the larger patterns of thought that underly the design of the system, which enables you to use the system more effectively. More complicated because now you can use the system to solve more complicated problems, and you then start to run into the limitations of the system.

How can you combat this feeling that you're an ant in the programming world and this stuff is the foot about to squash you?

You're an ant; we're all ants. But the stuff isn't the foot that squashes you; it's the world that you get to explore, live in, benefit from, and improve. You, ant, only get to explore a tiny, tiny part of it. Pick a part you like where you can add real value and become an expert in it.

Title: Does programming in general become easier to read, write and understand as you gain experience?

Body:
I'm a beginner in programming and I've been reading books, studying, reading articles, and whatnot. I'm getting great results since I've started learning programming, and when I was a beginner I used to think I knew everything about programming, but as I learned more I realized how difficult this field is (In fact all fields are difficult, but that's not the point).

Nowadays, I've written functional software and I've learned the BASICS of 3 languages and I'm intermediate in just one language. When I look at advanced things like MYSQL, or OpenGL programming, or even visual studio C++ code it gives me headaches, and even when visualising HTML source code of many websites (Most source codes on websites, seen by google chrome seem very messy and unorganized) it makes me confused to the very limit of my brain. It all seems simple at first, yet when looking at these advanced things it just makes me wonder how can one learn so much.

The question, in a nutshell, is if these things become clearer to a programmer as he advances in his career. Do complicated topics as the ones listed above (OpenGL, MySQL, advanced html sites) become easier to read, write and understand as you learn more, or does it just get more complicated as you go by? How can you combat this feeling that you're an ant in the programming world and this stuff is the foot about to squash you?


问:
When to refactor
I've read through most of Fowler's Refactoring book and have refactored many applications in my past big and small.

One of the harder things I find to teach is "when" to refactor.  I tend to do this based on a gut feel which has served me remarkably well in the past.  However, when getting into discussions with people about whether a piece of code should be left alone or refactored right now it is hard to stand by the "gut check".

I feel like there should be more rigorous approaches to this, but am not sure what they are.

I understand "code-smells", red-green-refactor and other thoughts, but often I feel that the best time to refactor is not the first time you write the code, but the second or third time you are using the code and realize that it is actually a problem and is in actual use.

答:
I think your question can be answered differently by each developer and even the management in charge of the programming.

My personal preference is, whenever I learn something new, or improve my best practices, I refactor the code that I can - I like to keep my code up to standard as soon as I learn what the best standard to use for that situation was. I am allowed to do this though because it is a smaller company that uses the same software for long periods of time.

In a bigger software development company where time is money, it may be to just start designing with the better practices you learned from this point forward, do not worry about refactoring until verison 2 of that specific software?

I feel teaching when to refactor really depends on the company you are currently in.

Title: When to refactor


答:
When your gut is telling you that you should probably do some refactoring, It's likely it's your instincts telling you a little late that you've been putting something important off for too long.

I understand "code-smells", red-green-refactor and other thoughts, but often I feel that the best time to refactor is not the first time you write the code, but the second or third time you are using the code and realize that it is actually a problem and is in actual use.

There are effectively two levels to refactoring.  The first is the obvious issues that appear when you first code.  These are the little optimizations that cost you very little to do up front. Things like keeping your methods and classes small, and adhering to DRY and SRP. Then you have the additional stage of dealing with major flaws in your design, which may not be immediately apparent until your code has a couple of miles under it. It's this second level that you are talking about, and yet in order to ensure that later refactoring isn't too costly, you need to have already written your code in such a way that the effort you later envisage is made easier and less costly, which means doing an early refactoring.

As Jeff mentioned in his answer, "time is money", particularly in companies where the workload is high and the risks even higher.  Time spent up front making sure the code is in its best possible state is time saved later, when teasing out what should have been an easy refactoring turns out to be a major operation.

When writing software, every moment spent improving your code up front is time saved later, when you're really going to need it. The earlier you refactor, the clearer your later changes will be.  It's like making a down payment in today's dollars against future technical debt which will be in tomorrows inflated dollars.

In any case, refactoring shouldn't be a task that you put off until some mysterious future when the software is already complete and stable, as it increases your risks later when the stakes are much higher and the product much more difficult to change.  Refactoring should be a part of your daily activities, and this is the essence of the Red-Green-Refactor philosophy that you mentioned.

Title: When to refactor

Body:
I've read through most of Fowler's Refactoring book and have refactored many applications in my past big and small.

One of the harder things I find to teach is "when" to refactor.  I tend to do this based on a gut feel which has served me remarkably well in the past.  However, when getting into discussions with people about whether a piece of code should be left alone or refactored right now it is hard to stand by the "gut check".

I feel like there should be more rigorous approaches to this, but am not sure what they are.

I understand "code-smells", red-green-refactor and other thoughts, but often I feel that the best time to refactor is not the first time you write the code, but the second or third time you are using the code and realize that it is actually a problem and is in actual use.


问:
How would you use Redis for Exception Handling?
I was reading this transcript of an interview with a GitHub developer and he was describing how they use Redis:

Q: You mentioned using Redis. How do you use that?

  A: We use Redis for
  exception handling and for our queue. We tried a lot of Ruby-based
  queuing mechanisms. Chris wrote an abstraction to the queuing
  mechanism. We used to use BJ and DJ and in the super early days we
  tried out Amazon SQS and a lot of queuing mechanisms and they all fell
  over at one point or another with the amount of traffic that we were
  doing on them and the types of queries that we were trying to get from
  them. Eventually we moved to a Redis space that Chris also wrote,
  called Resque.

Can anyone guess to what that means to use Redis for exception handling? Does it mean the logging of exceptions or something else?

You can see the video of him saying it here.

答:
Yes, he meant logging.
Redis is actually classical for logging - it's volatile data; writes should be extremely fast in order to not create an unnecessary load on the system/database; you are usually interested in only the last logs so you can easily run:

```<code>LPUSH log error_message
LTRIM log 0 1000
</code>```

and always keep only the latest logs.
Of course, this example is highly simplified, but this is the main idea.

See:

http://redis.io/commands/ltrim

http://simonwillison.net/static/2010/redis-tutorial/ - the slide that begins with Capped Collections

Body:
Yes, he meant logging.
Redis is actually classical for logging - it's volatile data; writes should be extremely fast in order to not create an unnecessary load on the system/database; you are usually interested in only the last logs so you can easily run:

LPUSH log error_message
LTRIM log 0 1000

and always keep only the latest logs.
Of course, this example is highly simplified, but this is the main idea.

See:

http://redis.io/commands/ltrim

http://simonwillison.net/static/2010/redis-tutorial/ - the slide that begins with Capped Collections


问:
What exactly is distributed computing?
What exactly constitutes distributed computing, and how does it differ from parallelized / concurrent computing?

Does the use of mutexes and semaphores in multiple parallel threads trying to synchronize for access to a resource constitute a problem in the domain of distributed computing?

答: Distributed computing the the "non-marketting" term for enterprise computing which you may hear a lot more in real life.  However, the general idea as pointed out by others is "you are using more than one computer to do work"</p>

ContentLicense: CC BY-SA 4.0

Title: What exactly is distributed computing?


答:
When I was first learning about refactoring, my mentor told me: "Do it twice, hold your nose. Do it three times. refactor."  (Thanks, Josh!) To be specific, what he was saying was that when you are about to write the same block of code for the third time (or even a similar code pattern), that is the time to refactor. I have followed that for the past 10 years, and found it to be a sound enough rule of thumb.

Using Eclipse, or similar IDE which has strong refactoring support, reduces the effort to do the refactoring. The IDE support makes it more likely you will refactor as soon as you hit the "third time" (or see the need), instead of seeing it as additional effort.

Also - TDD is a big help here too, since you can keep running your tests as your refactor, and know that you haven't broken anything.

Title: When to refactor


问:
What advantages does developing applications for smartphones have over developing the same application as a web application?
Let's take the Facebook application as an example. Why did they develop an application when the users could just access to their page and do the same? For me that represents more maintenance and more cost because for each feature added to the web application that feature will have to be added to the smartphone application as well.

So why would I want to develop more than once (for each patform iOS, Android, etc) when I could just have one web application? What benefits do I get? The only one that comes to my mind is GPS feature.

EDIT:

My question is more oriented towards business applications that are going to be used only by some members of the company, it's not about selling the application (private use). So contrary to what some answers say about that by developing as a smartphone application it will benefit from more sells because of the "smartphone stores" for me this point is not important because the application is for private use.

By developing the application as a web application it means that it can be accessed through smartphone browser and also in a PC (any capable browser), but developing as a native application would limit this to only some kind of smartphone so we would be limiting  the use.  On the other hand developing it as a web application means that in order to access the application an Internet connection must be available.

So keeping this in mind how would you convince your boss to write the application for a given smartphone platform (iOS/Android) vs developing it as a web application?

答:
Biggest benefit of Smartphone application verses web based application is offline functionality.  Depending on how the app is written you can still get work done regardless of web connection.

If a Smartphone app needs to report events to a web service, it can always queue them up, then sync the next time the app has access to the web.

There have been many times I've needed information when web was not available.  The apps that shine are those that don't rely on the web.


答:
I think, that depends on the demands of the project owner and the guy that answers for the quality of the code. You simply can't decide it alone, when the money of somebody else are under question.

As for technical reasons, there are several.

If you have a bug in the code, that means that this place is misunderstood and it is VERY probable that more errors could be hidden here and surely there will be great problems with any attempt to develop the connected parts of code. So, this place should be checked for possible refactoring.

Another reason is when you add or change a feature and the old code is very inconvenient for changing/adding and the later changes/addings are highly possible. Of course, you should balance the cost.

Maybe the most serious reason is when you are changing the code and it is untestable.

Title: When to refactor


答:
Refactoring by its definition is a process. This implies that you should not strive to find spare time to do the rafactoring task, instead you should keep refactoring all the time when you come across code code that could be written better.

Personally I like writing evolutionary prototypes, saying it more simply: code that just works, and then refactoring those until they will meet expected coding standards. Another good example is adding additional functionality and refactoring existing code to enable its reuse.

Title: When to refactor


问:
Calculate statistics for web application
I'm planning to add a couple of usage statistics to my web application. Some common things like: registered users, amount of comments/posts, etc. over time (last 24 hours / last week / last month / last year) which I want to display graphically to all admins.

I know that I can retrieve all information from database queries, but I have a bad feeling going over "old data" over and over again.

Example: Yesterday, I requested the amount of users who registered for an account the last year. Admin XYZ requests the same statistic today. A simple select-all-users-reg-date-last-year query would be redundant and cause much database traffic, right?

What is the best approach of calculating statistical data like this?

答: You can get arbitrarily fancy with things like this, but it's probably not worth it. Unless you've observed that you're actually causing too much database traffic with the straightforward way, just do that and move on to something else. If you are, then for the query you've described, you could precompute each day's new users and then just sum one year worth of totals at query time. You can go further than that, even, but it's really not likely to be worthwhile.</p>


问:
Is writing comments inside methods not a good practice?
A friend told me that writing comments inside methods is not good. He said that we should have comments only for the method definitions(javadocs) but not inside the method body. It seems he read in a book that having comments inside the code means there is a problem in the code. I don't quite understand his reasoning. I think writing comments inside the method body is good and it helps other developers to understand it better and faster. Please provide your comments.</p>

答:
The problem with inline comments is that they have to be maintained along with the code (also true for function/method/module/class-level comments, but not to as great a degree); God knows how much source code is still out there where the comments have absolutely nothing to do with the code they document anymore, which IMO is just as bad or worse than not having any comments at all.

Ideally, inline documentation should be limited to the following situations:

Explaining code that's heavily optimized or "tricky", along with a justification for why the code is so heavily optimized or "tricky" ("we were missing performance requirement X and profiling showed the bottleneck to be in this section; the optimizations below gained Y% performance");

Referring to a standard or requirement ("DTED 0 post spacing is 30 arc seconds");

Identify code that needs further analysis/development ("TODO");

First law of code docmentation - don't document the obvious.  Corollary to the first law of code documentation - write code that's obvious to the greatest extent possible.

OwnerDisplayName: Srini Kandula


问:
How useful are Lisp macros?
Common Lisp allows you to write macros that do whatever source transformation you want.

Scheme gives you a hygienic pattern-matching system that lets you perform transformations as well.  How useful are macros in practice?  Paul Graham said in Beating the Averages that:

The source code of the Viaweb editor was probably about 20-25% macros.

What sorts of things do people actually end up doing with macros?

答:
I mostly use macros for adding time-saving new language constructs, that would otherwise require a bunch of boilerplate code.

For example, I recently found myself wanting an imperative for-loop similar to C++/Java. However, being a functional language, Clojure didn't come with one out of the box. So I just implemented it as a macro:

```<code>(defmacro for-loop [[sym init check change :as params] & steps]
  `(loop [~sym ~init value# nil]
     (if ~check
       (let [new-value# (do ~@steps)]
         (recur ~change new-value#))
       value#)))
</code>```

And now I can do:

```<code> (for-loop [i 0 , (< i 10) , (inc i)]
   (println i))
</code>```

And there you have it - a new general-purpose compile-time language construct in six lines of code.

Title: How useful are Lisp macros?

Body:
I mostly use macros for adding time-saving new language constructs, that would otherwise require a bunch of boilerplate code.

For example, I recently found myself wanting an imperative for-loop similar to C++/Java. However, being a functional language, Clojure didn't come with one out of the box. So I just implemented it as a macro:

(defmacro for-loop [[sym init check change :as params] & steps]
  `(loop [~sym ~init value# nil]
     (if ~check
       (let [new-value# (do ~@steps)]
         (recur ~change new-value#))
       value#)))

And now I can do:

 (for-loop [i 0 , (< i 10) , (inc i)]
   (println i))

And there you have it - a new general-purpose compile-time language construct in six lines of code.


问:
How can I bootstrap a software development community at my school?
I'm a student at the University of South Florida who's frustrated with the educational environment in the Computer Science program. Right now, I'm taking "Program Design." I should be learning how to organize my source code into functions and modules in order to make my programs readable and maintainable; instead, I'm learning about arrays and recursion in C. Next semester, I have to take "Object-Oriented Design," which is taught through C++ (shudder.)

Two years ago, I fell in love with programming, and I've been learning as much as I could since then. The prospect of taking another C++ class bores me almost to tears. For that reason, I thought I would start a programming club in order to meet similarly ambitious students, learn new languages, discuss software development topics, and work with other students developers.

However, I'm beginning to realize that there may not be any other students who share my software development experience. It's not because of a lack of motivation but a lack of opportunity: I know of only one other programming class ("Programming Languages") and no classes on real-world software development. Everybody else only has experience writing trivial scripts in C and C++.

I've realized that if I want to work with other student software developers, I'm going to have to train them myself. Now, I'm planning to make the club a software development bootcamp, teaching members how to develop software with modern tools and languages. Obviously, starting an unofficial software development course is a monumental task with many possible approaches. My question to you, dear reader, is

What's my plan of attack?

Should I

lecture the club myself, trying to balance club work with homework?

ask the CS faculty to teach on topics within their expertise which may be less than relevant to members?

try to find a sympathetic, experienced developer inside or outside the school who can share my workload?

show video lectures (from MIT OpenCourseWare, Google Tech Talks, etc)?

hold hands-on programming workshops?

assign homework?

do something else?

答:
Frankly your whole attitude concerns me. You haven't even gotten the group together and already you assume you will be only one who has any knowledge to impart and the one who should decide what the group will do.

The best bet is to get the intial group together and, as a group, brainstorm what they want to do. What you personally want to do is irrelevant in terms of what the group wants to do. Deciding what to do without the input of the other group members before the first meeting,  you will come across as an arrogant idiot that I wouldn't want to work with voluntarily. Thus you would kill the group before it got started.


问:
What language is the CLR written in?
Just out of curiosity, what language is the CLR written in? I read on the Java Virtual Machine wikipedia entry that it is programmed in C++; is this the same for the CLR?

Sorry if this is off-topic, I didn't feel that this question was technical enough to go on Stack Overflow.

答:
Could be Java! Okay, maybe not...

Actually, the CLR is written mostly in C++ and a little garnish of assembly language according to this: http://social.msdn.microsoft.com/forums/en-US/netfxbcl/thread/e7ca66a9-aac5-47b7-b41f-01b1f1543f38/

C++ is a good language for this since it is at once portable, fast, and expressive.

You didn't ask, but FYI, the Framework Class Library (FCL) is C#. Makes sense too - a good dog fooding exercise.

Title: What language is the CLR written in?


答:
Refactor when the cost of refactoring is less than the cost of not refactoring.

Measure "cost" however you can. For example, is the code so poorly implemented that trivial bugs cost hours or days to fix? Will refactoring allow you to gain more customers, or increase capacity, or improve performance and thus make your existing customers happier?

Title: When to refactor


问:
How do you create interest in your projects?

Possible Duplicate:

  Ideas to get you programming mojo back?

Its almost 10 years for me working in Java based applications (mainly on Web). Sometimes I feel really bored of the regular work...same old problems, similar challanges etc. Since I work for a company that provides services to different customers, I change my domain from time to time, I get to know about some new things, but ultimately all are web applications and I really find nothing interesting after 6-8 months in a new project.

I would like to know from experts, how do you make working in same technology interesting?

答:
Well, I am not an expert but I think that you can keep interest but associating your current job with something else you like.

Let's say you like some sport like Baseball, then you could participate in a project that creates a fantasy baseball site or something like that.

It's also possible to try some new languages, or learn new stuff, like a new methodology, design patterns, new frameworks and so on.


答:
Usually, when working on a project there is a limited scope and you barely get a taste for how deeply you can dive into a domain. In most domains, there is a lot beneath the surface waiting to be uncovered by an adventurous developer. If you're bored with the mundane, take some time to explore the challenges of the domain and mull over what a solution to those challenges would look like. Perhaps mention it during a requirements gathering session (or if you don't participate in those, mention it to a lead developer who is). But be ready to back it up, because you just might get called to do it.

Other opportunities abound...find a common pattern for your development and see if you can extract it into something that can be scaffolded. When you find yourself doing the same thing repeatedly, use the computer for what it's designed so you can focus on what's different about the specific piece of functionality you're working on.

Title: How do you create interest in your projects?

Body:
Possible Duplicate:

  Ideas to get you programming mojo back?

Its almost 10 years for me working in Java based applications (mainly on Web). Sometimes I feel really bored of the regular work...same old problems, similar challanges etc. Since I work for a company that provides services to different customers, I change my domain from time to time, I get to know about some new things, but ultimately all are web applications and I really find nothing interesting after 6-8 months in a new project.

I would like to know from experts, how do you make working in same technology interesting?


答:
Be proactive, look for new technologies and how they could fit in the projects you're working on. If you'll reach your supervisor with new ideas and even display a "proof of concept", telling him/her something like:

"look, I checked out hibernate and I managed to accomplish stuff that would take a day of work in less than an hour - plus, it has built in security etc etc" - not only they'll appreciate your "out of the box" thinking, but you'll also build yourself a reputation as a technology leader/expert, people will come to you for advice and you'll maintain the level of interest in your projects as well as in your field.
To sum up in one word: be proactive! ("be" is not considered as a "real" world... ;)


问:
How do programmers quit a job?
I'm thinking about leaving my current employer and wondering how one goes about that process in the programming world. We have a lot of projects on the go at the moment and I'm the only developer. We have 4-5 projects that are fairly big and need to be done in the next few months and even a few longer than that.

I'm leaving because I'm the only employee and that's doing me no good. I'm young and want to learn, so a team would be nice. It's also too much work and the company is managed horribly.

I have no contract to worry about so I could theoretically quit and just not come back without notice. Just wondering how this is normally handled.

Should I write a resignation letter

How much notice should I give

Should I give a reason for leaving

Should I go to my boss who is the main reason I'm leaving or go to his boss?

Overview of replies

From the feedback here, it looks as though it's best to give 2-4 weeks of notice, and present a written resignation. Don't go into detail explaining why you're leaving in most cases. Don't burn bridges. Be professional.

答:
I was actually in your position fairly recently. I was working as a programmer in an engineering lab. I was the only developer, so, like you, I wasn't learning a whole lot. I also didn't like the location (I got the job at the nadir of the recession, so I didn't have much choice at the time). Plus, I spent more time doing IT support ("Hey, my printer's broken, can you fix it?" "How do you do this in Outlook?"), which wasn't a part of the job description.

Should I write a resignation letter?

I did. It was just a brief "Hey, I'm leaving by this date" sort of letter. HR likes to have something in writing, I guess. :) (Actually, I sent an email, but same difference in modern times, right?)

How much notice should I give?

I gave four weeks. Two weeks is the absolute minimum, but...I feel that for a more "professional" job like a programmer, you want to give extra time. Six weeks might be even better, if you can swing that, but I think four is enough. (For what it's worth, my predecessor at my old job gave less than two weeks' notice.)

Should I give a reason for leaving?

You're not obligated to give a reason for leaving. If you get along well with your boss, it may be nice to outline your reasons ("I found something that offered better prospects" or whatever), but I wouldn't formally give your reasons in your resignation notice. Judging by your next question, I'm guessing you don't get along well with your boss, so a simple "I found another job" would probably suffice.

Should I go to my boss who is the main reason I'm leaving or go to his boss?

I'd go to your boss. I mean, look, you don't have to criticize him excessively when you quit, you just have to say you're leaving. If the next guy and the next next guy quit quickly, even a mediocre boss should start to notice there're management issues. ;)

Should I leave all of my emails nice and organized to help the next guy/gal (They are organized now) or possibly erase them as the last several people did?

I left all of my emails. I had a separate work account that I accessed via IMAP, so after ensuring I hadn't accidentally mingled personal correspondence with the work account, I left it all on the server, and gave the server admin permission to let the new guy access the emails. Most of them weren't important, but I figured it would help him out. Like your situation, the guy before me left no emails, and very little documentation, so I thought I'd be nicer to the next person. :)

Should I leave all of the documents I worked hard to create (All of the FTP info for our different sites and what not that wasn't being kept before I got here), or should I delete them?

Leave 'em, they'll help out the new guy and it's the right thing to do anyway, since you (presumably) created them at work. Sounds like your predecessor wasn't nearly as helpful, but there's no need to be vindictive towards your replacement. :) And if you already created the documentation, it'll take less time to not delete the files.

Title: How do programmers quit a job?


问:
If Instance is for Class, what's for Template?
I am not able to find the right technical term to mention child or instance of a template.

What's the right one, child or instance or something else I am not aware of?
Sorry for my unclear original question.

Its not related to any language. The Template I am talking about is a business concept in my application.
Say for example, I have a "chair" template. I would set a few property values to it to create it's usable instances.
I need this for naming and documentation stuff.

Shortlisted 3 terms: Instance, Definition, Child. Whats suits better?

答: I'd use "view" to describe an instance of a template.</p>


答:
a definition?

You can explicitly tell the compiler when it should generate a
  definition from a template. This is called explicit instantiation.

but I think an 'instantiation' is more usual terminology, so 'instance' is just as good for templates too.

Title: If Instance is for Class, what's for Template?

Body:
I am not able to find the right technical term to mention child or instance of a template.

What's the right one, child or instance or something else I am not aware of?
Sorry for my unclear original question.

Its not related to any language. The Template I am talking about is a business concept in my application.
Say for example, I have a "chair" template. I would set a few property values to it to create it's usable instances.
I need this for naming and documentation stuff.

Shortlisted 3 terms: Instance, Definition, Child. Whats suits better?


答:
In C++, the instantiation of template is done like vector<int> testVector; in this case testVector is just like any other ordinary object.

BONUS:

In many other languages, (Not C++ to my knowledge) there is a concept called metaclass who's instances are classes.


答:
In my humble opinion, constantly challenging yourself with new projects either in your professional environment or in your free time can be the real motivator to programming.

You can take up any area of your interest and start to develop an application. Once you begin to complete it, you will begin to realize that these challenges start to take a meaningful shift to boost your interests.

In my personal experience, my interest starts to grow when I implement a new technology or a new way of implementing what I have already done already.


问:
How can I unit test audio?
I have inherited a small project and want to extend it and stabilize it at the same time by writing Unit Tests for all the new code I am adding. The first class, TypedAudioCreator, creates audio files and this turned out to be very easy to test first and write code for second.

However, when it came time to write TypedAudioPlayer, I had no idea how I could test it. It's a very small class focusing on the very basics of playing sound:

```<code>public class TypedAudioFilePlayer
{
    public event StartedPlayingHandler StartedPlaying;
    public event StoppedPlayingHandler StoppedPlaying;

    public readonly int TimeBetweenPlays;

    private Queue<TypedAudioFile> _playlist = new Queue<TypedAudioFile>();

    public TypedAudioFilePlayer(int timeBetweenPlays)
    {
        TimeBetweenPlays = timeBetweenPlays;
    }

    public void AddFile(TypedAudioFile file)
    {
        _playlist.Enqueue(file);
    }

    public void StartPlaying()
    {
        ThreadPool.QueueUserWorkItem(ignoredState =>
        {
            while (_playlist.Count > 0)
            {
                var audioFile = _playlist.Dequeue();

                if (StartedPlaying != null)
                    StartedPlaying(audioFile);

                audioFile.SoundPlayer.PlaySync();
                audioFile.SoundPlayer.Dispose();

                if (StoppedPlaying != null)
                    StoppedPlaying(audioFile);
            }
        });
    }

    public void StopPlaying()
    {
        if (StoppedPlaying != null)
            StoppedPlaying(null);
    }
}
</code>```

I'm still very new at TDD, but I realize the benefits of the practice and would like to try and get better at it. I have written Code first, no tests here, but that was just me being too lazy to properly think of the TDD way of solving it.  The question I have is, how should/could I test this class?

答:
There are many things "on the edges" of most systems that cannot adequately be unit tested. For example, anything that produces graphics or sound. For these kinds of systems, you are probably best off with manual testing. Even given an automated solution, these outputs are meant for human perception. The only way to know that you are producing the desired effect is to have a human interact with them.

It may be possible to perform a manual test, then record the output of that manual test and create an automated test that ensures that the output does not change. Be warned though that tests like these are incredibly fragile: any change to the underlying code may require a repeat of the manual test and then creating a new recording for the automated test.

Title: How can I unit test audio?


问:
Best example for mixins in .NET
I want to present the concept of mixins and their implementation in .NET.

The way they work in .NET is you add extension methods on an interface and decorate classes with said interface.

What would be the best examples for this pattern (other than linq)?

答:
Don't know if it's the best example, but I've got an example of using extension methods to approximate mixins on my blog: http://horsdal.blogspot.com/2009/05/dci-in-c.html?m=0

Please note that you don't really get mixins by doing this, just something that sort of like mixins from the client codes perspective.

Title: Best example for mixins in .NET


问:
Where can I locate business data to use in my application?
This question talks about any and all free public raw data which appeared to have valuable pieces but nothing that really provides what I am looking for.

Instead of using a socially defined listing of businesses (foursquare), I would like a business listing data set of registered businesses and associated addresses that could then be searchable based on location (coordinates). The critical need is that the data set should be filterable based on varying criteria (give me all restaurants, coffee shops, etc...).

If the data is free that is great but anywhere that sells this type of data would also suffice. Infochimps looked like a possibility but perhaps something a bit more extensive exists.

Where can I find a free or for fee data set of registered business that is filterable based on type of business and location?

答:
There are some relevant (though not free) data sources on the Azure DataMarket here:

https://datamarket.azure.com/browse/Data?Query=Company

And this web service from StrikeIron might help (also not free):

http://www.strikeiron.com/Catalog/ProductDetail.aspx?pv=2.0.0&pn=Cortera+Business+Vitals


问:
Getting and maintaining data from a large number of sources on the web
For the sake of an exercice I want to aggregate price listings with prices coming from a series of web sites in a structured form (XML, JSON...). If I have control on both sides how can I go about making price updates the most efficient possible?

Edit: To clarify, I'm looking for a more efficient approach then having a script or application pull in price lists in their entirety from all sources for updates.

答:
Gathering Data:

One approach is to ask all of the sites to publish an RSS feed with prices in a specific format. Could use ATOM format. Part of ATOM RSS feed is that it specifies metadata inside that says, essentially, "don't check back more frequently than hourly" (or whatever) which may help handle knowing how often to poll each without having to manage that data centrally (assuming price volatility may vary by source). This is basically how an RSS aggregator works (like Google Reader).

Could also look into making the data formats OData (see www.odata.org).

You could alternatively have all the sites call a central API, but that will be harder to manage and likely more complex for the partner sites - and more error prone.

Maintaining Data:

A database! Simple pricing tables may suffice: shred the data as it comes in and store in form that allows easy aggregation. Consider keeping all history (might have other value in trend analysis or otherwise). Recalc aggregates on a schedule or on demand. Consider how to handle "corrections" to prices (maybe a source site can ping the central site with a "correction" hint do the RSS grab can be scheduled sooner than otherwise to pick up the corrections).

You did not mention volume. Very large data sets may require more consideration, but this set up ought to get you pretty far.


问:
What's the worst question you were ever asked at interview?
It doesn't have to be programming or software development related, but just asked during an interview for an IT related job.

I know some "left field" questions are meant to see how the candidate copes with unexpected and novel situations, but here I'm looking for a question that appeared to be completely unrelated to the job they were interviewing you for, or something that made you think "what useful information could they possibly get from my answer to that question?".

答:
In rapid succession:

What's your biggest strength?

What's your biggest weakness?

What's your weakest strength?

last one really threw me for a loop.


问:
Why is it so difficult to make C less prone to buffer overflows?
I'm doing a course in college, where one of the labs is to perform buffer overflow exploits on code they give us. This ranges from simple exploits like changing the return address for a function on a stack to return to a different function, all the way up to code that changes a programs register/memory state but then returns to the function that you called, meaning that the function you called is completely oblivious to the exploit.

I did some research into this, and these kinds of exploits are used pretty much everywhere even now, in things like running homebrew on the Wii, and the untethered jailbreak for iOS 4.3.1

My question is why is this problem so difficult to fix? It's obvious this is one major exploit used to hack hundreds of things, but seems like it would be pretty easy to fix by simply
truncating any input past the allowed length, and simply sanitizing all input that you take.

EDIT: Another perspective that I'd like answers to consider - why do the creators of C not fix these issues by reimplementing the libraries?

答:
One of the great powers of using C is that it lets you manipulate memory in whatever way you see fit.

One of the great weaknesses of using C is that it lets you manipulate memory in whatever way you see fit.

There are safe versions of any unsafe functions.  However, programmers and compiler do not strictly enforce their use.


答:
It's obviously difficult to automatically test that the audioplayer really plays audio, but you can create useful unit tests anyway. For example, you can test that StartPlaying() causes the StartedPlaying event, and StopPlaying() causes the StoppedPlaying event. You can test the behavour when trying to play an empty playlist, or a null playlist. You can test that AddFile really adds the file to the playlist. You can test that after playing an audio file, it is removed from the playlist (if that is desired). Maybe there are cornercases for broken audio files etc. too that deserve testing.

Having unit tests for those things, you can be sure that the class behaves well, i.e. meets its contracts. If it does, but still plays no sound, that's relatively easy to catch in manual tests.

Title: How can I unit test audio?

Body:
I have inherited a small project and want to extend it and stabilize it at the same time by writing Unit Tests for all the new code I am adding. The first class, TypedAudioCreator, creates audio files and this turned out to be very easy to test first and write code for second.

However, when it came time to write TypedAudioPlayer, I had no idea how I could test it. It's a very small class focusing on the very basics of playing sound:

```<code>public class TypedAudioFilePlayer
{
    public event StartedPlayingHandler StartedPlaying;
    public event StoppedPlayingHandler StoppedPlaying;

    public readonly int TimeBetweenPlays;

    private Queue<TypedAudioFile> _playlist = new Queue<TypedAudioFile>();

    public TypedAudioFilePlayer(int timeBetweenPlays)
    {
        TimeBetweenPlays = timeBetweenPlays;
    }

    public void AddFile(TypedAudioFile file)
    {
        _playlist.Enqueue(file);
    }

    public void StartPlaying()
    {
        ThreadPool.QueueUserWorkItem(ignoredState =>
        {
            while (_playlist.Count > 0)
            {
                var audioFile = _playlist.Dequeue();

                if (StartedPlaying != null)
                    StartedPlaying(audioFile);

                audioFile.SoundPlayer.PlaySync();
                audioFile.SoundPlayer.Dispose();

                if (StoppedPlaying != null)
                    StoppedPlaying(audioFile);
            }
        });
    }

    public void StopPlaying()
    {
        if (StoppedPlaying != null)
            StoppedPlaying(null);
    }
}
</code>```

I'm still very new at TDD, but I realize the benefits of the practice and would like to try and get better at it. I have written Code first, no tests here, but that was just me being too lazy to properly think of the TDD way of solving it.  The question I have is, how should/could I test this class?


问:
Legal ramifications of use of the JavaScript trademark?
It's widely known that the name "JavaScript" is trademarked by Oracle (formerly a trademark of Sun, formerly a trademark of Netscape).

However, others seem to have no problem using the JavaScript trademark. Google uses it in reference to V8, Mozilla uses it in reference to SpiderMonkey and in various other places, etc. Mozilla is the only one that seems to try to attribute the trademark to its owner (bottom of this page), although at the time of this writing it's incorrectly attributed to Sun rather than Oracle.

For a long time, Microsoft used "JScript" as the name of their ECMAScript implementation rather than "JavaScript," presumably to avoid infringing on the trademark. Recently (I'm not sure when), Microsoft appears to have switched from the "JScript" name to "JavaScript."

My understanding based on the version history is that they've written a new ECMAScript implementation and named it "JavaScript," leaving the old one named "JScript" (rather than retroactively renaming "JScript" to "JavaScript").

My question is this: Since JavaScript is trademarked, isn't it an infringement to use it in connection with the name of a product or technology (such as "Microsoft JavaScript") without permission? If so, where can I find records of agreements with Oracle/Sun/Netscape allowing third-party use of the trademark? I assume these documents would be publicly listed somewhere, but I don't know where to find them. And finally, if the trademark changes hands again, would previously-made agreements still be valid, or would they need to be re-forged with the current trademark holder?

The reason I ask is because I want to know whether I can use the word "JavaScript" in the title of a product, for example a JavaScript library, without explicit permission, and whether I need to provide a disclaimer stating that JavaScript is Oracle's trademark.

答:
Trademarks are not like copyright or patents. Anyone may use them, but only for "nominative" purposes. That is to say, you may use the trademark "JavaScript" to describe something that's indeed Javascript. A "Javascript library" would mean a library that works with Oracle's Javascript.

You don't need to mention trademarks yourself. Oracle does, of course, since it's their trademark. But if you do note that Javascript is a trademark, you must make clear whose trademark it is (so you don't suggest it's yours).

Microsoft's JScript was not a real Javascript, so the "nominative use" rule didn't apply to them.


问:
How to implement smart card authentication with a .NET Fat client?
I know very little about smart card authentication in general so please point out or correct me if anything below doesn't make sense.

Lets say i have:

A Certificate Authority "X"-s smart card (non-exportable private key)

Drivers for that smart card written in C

A smart card reader

CA-s authentication OCSP web service

A requirement to  implement user authentication in a .NET fat client application via a smart card, that was given out by the CA "X".

I tried searching info on the web but no prevail. What would the steps be ? My first thought was:

Set up a web service, that would allow saving of (for example) scores of a ping pong game for each user.
Each time someone tries to submit a score via the client application, he can only do so by inserting the smart card into the reader.

Then the public key is read from the smart card by native c calls through .NET and sent to my custom web service, which in return uses the CA-s authentication OCSP web service to prove the validity of the public key/public certificate (?). If the public key is okay and valid, encrypt a random sequence of bytes with the public key and send it to the client application.
If the client application sends back the correctly decrypted random sequence of bytes along with the score of the ping pong game, then the score is saved in the database for the given user.

My question is, is this the correct way to do it ? What else should i know about smart card authentication ?

答:
That sounds far too complex, and heading in the complete wrong direction.

For starters, "A requirement to implement user authentication in a .NET client application". .Net applications run in user sessions, which implies that the user authentication already happened. It's too late.

But Smart Card logins are already supported out of the box. That's done by SCardSvr.exe (Smart Card Service) in conjunction with WinLogon. As a service, it's not limited in that way. But WinLogon isn't going to cooperate with your service in that way, obviously. That wouldn't be exactly secure.

The proper solution is to implement a "Smart Card Cryptographic Service Provider" (CSP). This is a highly non-trivial solution, if you're faced with such impossible requirements as you have.


问:
How to explain your non-programmer boss you need to refactor a whole site?
First of all, is not a programming matter, is a programmer afair.

I'm the new web programmer in my company.

I'm here just for 2 weeks. And they want me to teach Wordpress, configure & install it, and things like that.

But they have a intranet too to make all the compatibility stuff, tracking clients, ordering event, auto-emailing.

Well, the intranet is very nice, and they spent 1 or 2 years with a programmer to do that.

But the problem is:

The intranet is great for the user (a bad UI experience but works well).

They have it from 4 or 5 years now.

But if you go to the code, it is annoying.

Seriously, it's really really really heavy, code duplicated, insecure. All works ok, but all is wrong in code view.

Some points:

The site keeps 4GB of disk space (without DB!)

There where thousands of files, folders, with no order

A lot of files are duplicated

There were, at least, 20-40 files you have to configure to change the database source

Some config files are in .ini, so i can download from anywhere

The sites was coded for 4.0 or 3.x, miraculously it works on 5.x with some warnings.

The site was coded without any kind of scalability, they just copy and paste files and keep working, no includes, nothing.

For example: I see, at least 40 files called check_in.php in different folders.

Functions called: paste() paste_2()...

What points you will use to convince your boss to take care of that and refactor all the whole site?

It's a pain in the ass. I know refactor all gonna be hard, but I think it's the better way to continue my work.

Because they want me to make modifications on that and I have to spent 3 hours just to understand from where comes that **** function called paste() and what exactly do.

Ah, one more good point.

There's no documentation at all.

答:
The amount of change one should effect is contentious. What happens if you decide on a 'big bang' approach, estimate that it should take two months to refactor completely, and end up taking six? I'm not questioning your competence - it's just that projects like these can easily spiral out of control.

You could make a case for a gentle, iterative refactoring. So maybe you take a day to centralise the configuration files, and then move to other projects. Then two weeks later, you add autoloading. Get small changes live each time, and then wait for a bit for them to bed in. This way you remain productive on new projects, whilst slowly improving your codebase.

You should do these things on a separate branch, and if there are other tech people that your changes will touch (programmers, dbas, etc) then get them to buy into your changes before you do them.

OwnerDisplayName: nax


答:
Explain the cost benefit: Every time they want to make a change you will spend 3 hours figuring out the code, and only then will you be able to make the change, which will probably take less than 3 hours. On a neat, well-structured site with good documentation most changes and additions can start immediately without delay. In your case you have a 3 hour prep session before anything can happen (based on what you have described)

Also, try to find a real-world analogy that your boss can understand. Explain how working on undocumented code is like trying to find something in a cupboard full of non-glass jars that all have no labels.

Generally doing a complete overhaul of a site is never (financially) viable. I have almost always had to compromise to make changes to a poor solutions as and when I touched on the code-base to avoid loosing too much productivity time to re-factoring. Code Clean-up is hardly ever allowed for from a costing point of view, it generally happens as a passive side-effect of touching on something else that needs to be improved.

Title: How to explain your non-programmer boss you need to refactor a whole site?

Body:
First of all, is not a programming matter, is a programmer afair.

I'm the new web programmer in my company.

I'm here just for 2 weeks. And they want me to teach Wordpress, configure & install it, and things like that.

But they have a intranet too to make all the compatibility stuff, tracking clients, ordering event, auto-emailing.

Well, the intranet is very nice, and they spent 1 or 2 years with a programmer to do that.

But the problem is:

The intranet is great for the user (a bad UI experience but works well).

They have it from 4 or 5 years now.

But if you go to the code, it is annoying.

Seriously, it's really really really heavy, code duplicated, insecure. All works ok, but all is wrong in code view.

Some points:

The site keeps 4GB of disk space (without DB!)

There where thousands of files, folders, with no order

A lot of files are duplicated

There were, at least, 20-40 files you have to configure to change the database source

Some config files are in .ini, so i can download from anywhere

The sites was coded for 4.0 or 3.x, miraculously it works on 5.x with some warnings.

The site was coded without any kind of scalability, they just copy and paste files and keep working, no includes, nothing.

For example: I see, at least 40 files called check_in.php in different folders.

Functions called: paste() paste_2()...

What points you will use to convince your boss to take care of that and refactor all the whole site?

It's a pain in the ass. I know refactor all gonna be hard, but I think it's the better way to continue my work.

Because they want me to make modifications on that and I have to spent 3 hours just to understand from where comes that **** function called paste() and what exactly do.

Ah, one more good point.

There's no documentation at all.


问:
Why was dependency injection pattern not included in the Gang of four?
Why was the dependency injection pattern not incluided in the gang of four? Did GOF pre-date widespread automated testing? Is dependency injection now considered a core pattern?</p>

答:
They called it Strategy.

Their Strategy seems to have all the features of dependency injection without the complex-sounding name.


问:
Adding conditional toggles into methods for running tests
We've recently started to write tests for our fairly large PHP code base - using PHPUnit we are writing unit and integration test for our models and controllers.

What's the concensus in setting a boolean toggle that states whether a class is in TEST_MODE that alters the behaviour of a method?

ie: An email helper function - we don't need to send out an email during a test and we're not testing the mail server, just that that method has been called.

```<code>if (self::TEST_MODE) {
    return true;
}
</code>```

I'm already going off this idea - I don't think adding extra checks throughout the codebase for testing is an elegant solution.

But in this example for instance - what would be a good way to check the email has been sent?

答:
what would be a good way to check the email has been sent?

That is why folks invent mocks.

Start reading about PHP Mock Libraries.  For example: http://code.google.com/p/yaymock/.

I'm sure there are a dozen more.


答:
It will help your case when you show some sort of transition path. Evolution not Revolution.

This way the decision becomes less risky.


问:
How easy it is to update Entity Model from database when enough code has already been written?
I am new to Entity Framework.

I know there is an option to update model from the database, but I want to know how easy and successful is this task. I may need to update my model in a few weeks but till that time many lines of code has already been pushed inside.

Is it difficult to track changes and make code work?

答:
EntityFramework was originally designed with the "Model-First" approach as the preferred approach to building your Data Access layer, however many software shops still seem to live in the Dark Ages where they prefer to design the schema first and then the model to accomodate it.  Okay, I may be a little unfair, if you have database intensive processing where stored procedures benefit performance then it can make sense to start at the database and work your way up.

Regardless, when I played with the early release of EntityFramwork, support for refreshing the model from the database existed, however it was somewhat buggy at first.  This was years ago however and I remember reading that a lot of those issues have been worked out since.  I hear nothing by great things about EntityFramework being used in this way.

Is it difficult to track changes and make code work?

This all depends if you are following an appropriately layered architecture with loose coupling.  Ideally if the EntityFramework model changes then changes in the Data Access and Business Logic layers should be constrained to the layers that use the EntityFramework model.

Ideally if you are practicing TDD then your unit tests should fail and indicate which areas need refactored after a model change.


答: Instantiation. That's it..

Body: Instantiation. That's it..


答:
Code generators are a double-edged sword.  You can build lots of complex code quickly and easily but you have to be prepared to live with the code you've generated.  You can't (don't want to) customize this code because your customizations will be wiped out if you ever regenerate.

In my experience, recent versions of EF (say 4.x) are perfectly capable of regenerating from changes to a database.

As long as you've avoided the temptation to customize the generated code, you will be fine.

There is a caveat, of course.  If your DB-side changes include modifications or deletions to previously existing items then any code that touches the ORM for those items will potentially be broken.  This means any business logic or presentation layer code which uses modified database objects could be broken after updating your model.

You will need to do a thorough regression test of your existing code if any of your DB changes touch items that were already in your model as of your previous generation.

Title: How easy it is to update Entity Model from database when enough code has already been written?

Body:
I am new to Entity Framework.

I know there is an option to update model from the database, but I want to know how easy and successful is this task. I may need to update my model in a few weeks but till that time many lines of code has already been pushed inside.

Is it difficult to track changes and make code work?


答:
I've been doing some testing/learning projects with this recently and I've found that the update Entity from DB goes smoothly for the most part. You have to be careful to pick the right choice of tab and not screw everything up by using add rather than update. One of the downsides is that if you generate something wrong it's sometimes easier just to delete and start over than to try and correct problems.

I found the Entity to DB process to be less smooth, particularly when dealing with a Compact SQL DB. Sometimes weird errors would cause me to have to shut down VS and restart it and, after doing that, the generated scripts would work. However, sometimes the scripts weren't entirely correct and left out an index. This required a manual fix to the DB.

As Joel Brown mentioned, you want to avoid making changes to the generated code. However, you can use partial classes to add in functionality if you need to. I used this to implement IEquatable for some Entities since I needed it for a business layer routine.


问:
Sprint planning and accommodating slack
After reading Tom DeMarco's Slack, I'm wondering how to factor slack into sprints.

For those who haven't read the book, TDM describes 'slack' as providing time for innovation and other good things.

Scrum leans towards eliminating slack and resisting change within the sprint. Allowing stories to be re-prioritised between sprints. I appreciate the purpose of a sprint, and am not trying to ask how to respond to change within them.

My initial thought about adding slack to sprints would be to plan a sprint with 8/9 days of work for a two week sprint. If you're conscious of this decision, can still calculate your velocity accurately? Based on story points completed in your 8/9 day window (vs 10).

Conversely, these are two competing ideas and don't belong together... ?

gnat's focus factor link is interesting.

答:
In SCRUM, it's generally referred to as velocity.

Velocity incorporates all the concepts you mentioned - focus factor, "slack", etc. Point is that you should not artificially tweak your estimates or block off days as "slack". You try to estimate as consistently as possible and at the end of each sprint, you modify the velocity based on what you accomplished.

Title: Sprint planning and accommodating slack


问:
When to refactor
I've read through most of Fowler's Refactoring book and have refactored many applications in my past big and small.

One of the harder things I find to teach is "when" to refactor.  I tend to do this based on a gut feel which has served me remarkably well in the past.  However, when getting into discussions with people about whether a piece of code should be left alone or refactored right now it is hard to stand by the "gut check".

I feel like there should be more rigorous approaches to this, but am not sure what they are.

I understand "code-smells", red-green-refactor and other thoughts, but often I feel that the best time to refactor is not the first time you write the code, but the second or third time you are using the code and realize that it is actually a problem and is in actual use.

答:
"When to refactor ?"

Short answer : every time you come across code that smells bad or could be improved (Boy Scout Rule)

Practically, this happens :

If you practice TDD, systematically during the Refactor step of the TDD cycle, that is, once your test is green and before you start writing a new test.

As a result of a code review

When taking over legacy code

When consuming code that seems awkwardly designed

etc.

Title: When to refactor