问:
What are the advantages of Scala's companion objects vs static methods?
Scala has no static-keyword, but instead has similar functionality through companion objects. Behind the scenes the companion objects are compiled to classes that have static methods, so all this is syntactic sugar. What are the advantages of this design choice? Disadvantages? Do other languanges have similar constructs?

答:
Here are a few reasons, which might be more or less compelling for you, depending on your own preferences:

Do not simply discount it for being "syntactic sugar". While you may say that something is just syntactic sugar, it is after all the sugar that sweetens your life - as a programmer just as well as a coffee or tea drinker.

Singletons - every Scala object is inherently a singleton. Considering that in the Java world people are implementing singletons in all sorts of different ways and more often than not end up making some mistake in their implementation, you cannot make an error as simple like that in Scala. Writing object instead of class makes it a singleton and you're done.

Access to static methods: The static methods in Java can be accessed from objects. For example, suppose you have a class C with a static method f and an object c of type C. Then you should call C.f, but Java allows you (albeit with a warning) to use c.f, which when you come from the Scala background doesn't really make any sense, because objects do not have a method f really.

Clear separation: In Java you can mix static and non-static attributes and methods in a class. If you work disciplined, this doesn't become a problem, however, if you (or someone else for that matter) do not, then you end up with static and non-static parts interleaved and it is hard to tell at a quick glance what's static and what's not. In Scala, everything that's located inside the companion object is cleary not part of the corresponding class's runtime objects, but is available from a static context. Vice versa, if it is written inside a class, it is available to instances of that class, but not from a static context. This becomes especially burdensome in Java, once you start adding static and non-static initializer blocks to your class. This can end up to be very hard to comprehend in terms of dynamic execution order. It's a lot clearer in Scala, where you initialize the companion object from top to bottom and then do the same for the class in case of a runtime object being created.

Less code: You don't need to add the word static to each and every attribute or method in an object, thus keeping the code more concise (indeed, not a prominent advantage really).

Disadvantages are much harder to find. One might argue, that the static and non-static parts should belong together, but are separated by the Scala concept of companion objects. For example, it may appear strange to have a class diagram, but then end up having to create two things in the code and dissect which attribute goes where.


问:
Review tests first
I am going to adopt TDD in our team and one of the ideas I have is to review tests first. So one would write interfaces, mocks, and tests first, submit them for a code review and once interfaces and tests (think specification) are approved an actual implementation can be written (theoretically, can be done by another developer). I wonder how viable this idea is?</p>

答:
I would strongly suggest you DO NOT take this approach.

Writing unit tests on top of production code is a lot of overhead for many people.  No matter how you slice it, with unit tests, you end up writing double if not triple the amount of code you would have had otherwise.

Unit tests are great and they have a huge number of benefits, but a lot of those benefits are long term and they don't start paying back until later (when people need to reference on how to use API, when next co-op breaks existing code... etc).

However, unit tests have huge short term benefit in that, when people write code (with or without TDD), people need to exercise that code at least once before checking it in.  In non-TDD environment, they would try to run the code within the context of a larger application, or they might write some throw-away utilities just to invoke the functions they just wrote.  Unit tests are awesome because while you are writing them, you get to see your code run and fix it on the spot.

When a person gets into the flow (what is referred to as red/green/refactor cycle), TDD overhead, IMO based on very limited experience (but a lot of research) becomes much smaller than 2x because even though you are producing more code, that code is instantly helping you write your production software that much faster by providing feedback on an order of magnitude sooner than with manual testing.

So ideally to get the benefit with TDD with least amount of overhead, you want to think about next function you want to add to production, write a test, write the function, make sure it passes, cleanup, go on to the next function.... ship it.

What you are proposing will directly kill that short-term benefit I just described. Instead of writing one test and then functionality, you'll end up writing many tests and feedback is much slower since between reviews/approvals it could take hours if not days.  And instead of writing the test for exactly the next piece of production code you will work on, you'll end up writing preemptive tests for things you "might" introduce in production.

ContentLicense: CC BY-SA 3.0

Title: Review tests first


答:
This idea doesn't sound viable at all.  It seems that more focus is spent on verifying the tests as opposed to the actual code - which doesn't make sense.  Tests can pass, but at the same time, the code it's testing may run for 12 hours in production, which makes the code review on the tests worthless.

It's also the case that the programmer just doesn't know everything about the requirements of the code.  It's tough to write tests for something that you're not entirely sure how it should behave, so "happy path" tests are a bit of smoke and mirrors, too.

Adhere more to fail/pass/refactor instead - let your developers write smaller bites of the code, code review the quality of the production-caliber code, then let them continue with the smaller bites of code.  Do feel encouraged to review the tests to see if they're actually testing anything, but don't let it interrupt the TDD flow.

Title: Review tests first

Body: I am going to adopt TDD in our team and one of the ideas I have is to review tests first. So one would write interfaces, mocks, and tests first, submit them for a code review and once interfaces and tests (think specification) are approved an actual implementation can be written (theoretically, can be done by another developer). I wonder how viable this idea is?</p>


问:
Open Source License that prevents re-selling
I have an open source project that is a add-in to TFS (ie it is for developers and those using TFS.)

It is currently using the GPL.  But it occurs to me that the GPL does not really represent what I am trying to do with my license.

I want my code to be free to everyone who wants to use it.  And if you modify it and use it then that is great too.  You should not have to open source your modifications.

But I would like to block someone from building my code and selling it.  Or modifying it and selling it. (Anyone that wants to do that should have to negotiate a separate license with me.)

Is there an open source license that prevents re-selling, but allows full non-vending use for a person/company that downloads it?

答: No, there is no such license. And there cannot be. The ability to sell the software is a crucial part of the Open Source Definition. Any license that prohibits selling is by definition not Open Source.


问:
What are the things you put on an impact analysis document?
So you're fixing bugs, then you encountered one that could affect other modules of the software product. Your data is not enough to support your claim about the effects of the fix and you were asked to create an impact analysis document.

Is there a defined process on how to
do this?

What are the key information needed?

Are there any known formats / templates for this
document?

答:
Impact Analysis document is indeed required in large scale project specially where the programmers are working geographically in different locations.

The Impact Analysis document should be approved by the lead to make sure that the change won't affect the other component which is working fine in production.

Impact Analysis is required to make sure that the requirement is completely understood and all the components to be changed are identified to avoid re-work

The Impact Analysis is required for accountability from client stakeholders too.  Otherwise, when an issue occurs post deployment the developer becomes the scapegoat.

The Impact Analysis is the base for estimation.  Without that the estimation does not have any stand. It may be too high or it may be too low.  With Impact Analysis if the actual effort exceeds, it is easy to explain as well.


问:
Programming *into* a language vs. writing C code in Ruby
Code Complete states that you should aways code into a language as opposed to code in it. By that, they mean

Don't limit your programming thinking only to the concepts that are supported automatically by your language. The best programmers think of what they want to do, and then they assess how to accomplish their objectives with the programming tools at their disposal. (chapter 34.4)

Doesn't this lead to using one style of programming in every language out there, regardless of the particular strengths and weaknesses of the language at hand?

Or, to put the question in a more answerable format:

Would you propose that one should try to encode one's problem as neatly as possible with the particulars of one's language, or should you rather search the most elegant solution overall, even if that means that you need to implement possibly awkward constructs that do not exist natively in one's language?

答:
I believe the correct answer, and the one intended by the book is:

one should try to encode one's problem as neatly as possible with the particulars of one's language

By programming into a language, I always assumed it was to use techniques outside of the normal style of the language where it would lead to a benefit. This is a key difference to writing in one style in all languages.

For example, learning Haskell greatly improved my skill at using higher order functions. Now when programming in c#, I use the various IEnumerable methods such as Select more often, as using these methods leads to cleaner code than writing in for loops. I also tend to use pass and use functions (ie Func<int, int>) more often due to my haskell experience. My use of inheritance has dropped due to this, and most of the time the result is simpler code.

However, I don't use concepts like monads, or algebraic data types in c#. This is because neither are clearly representable in c#, and lead to little benefit in exchange for a lot of obscurity.

So I use the tools of the language to use the skills I have to the best effect. I believe that is programming into the language.


问:
As a software architect, am I supposed to focus that much on analysing the logs and fixing other's bugs?
Since my graduation (late 2005) I was working for the same company as a c++ software engineer. A year ago I was promoted as a software architect but I have found myself involved more and more in qualification and fixing bugs, level 2 support.

50% of my time spent in Notepad++ analysing the software logs and trying to figure out what went wrong. 30% fixing other's bugs and the remaining (if any) reviewing developers spaghetti code.

I started hating this product and thinking about an exit strategy out of this company.

What do you think I can do in this situation? do you other software architect still fixing bugs in the code?

答: The role of a Software Architect is much more than what you are doing in your present company.  He is responsible for defining software design standards, making high level design, standards for coding etc., and fixing bugs may be considered only a small part of it thought actually it isn't.  But as you have said, you are working on a product, it means, being a Software architect, the expectation from you for the reliability of the product will be quite high, and in such a case, your involvement in such things will not only help the product but also the company, as you are quite experienced in that.  But you should also be provided with some exposure to new feature development and new tasks, that will inculcate your interest in your present organization.</p>


问:
Integrating feature request functionality directly into the business software you write?
What are relative merits of something like a button on a piece of custom bizware that says, "press me to ask for a feature" or "click here if something didn't work right".

The problem I'm trying to remedy is the general lack of formality surrounding feature requests.  Most specifically, the rate at which I receive walk-ups from end-users.  Taken one at a time, it can be beneficial, but sometimes it can hinder productivity on the larger scale.

Has anyone done something like this and has it been a general success or alternately somewhat a waste of time.  My instincts are not giving me a hint here.

答:
We did this a year or two back, it's probably the close contact we have with our customers but I don't think it's ever been used.

It was a separate (basic) screen under the Help menu of our "thick" client apps, where the user could make a suggestion, feature request or send in a problem (optionally with a screenshot of only our app).

Since we do low-volume, highly-customized line-of-business software we tend to be in direct contact with our customers (mostly by phone) and often visiting them on-site, I think this is the main reason for the lack of use of the feature.

Many of the direct users tend not to be the most computer-savy so they usually call us direct. The UI and friendliness of the feature can play a major part here depending on your client base.

It's probably a lot more successful in high-volume software (particularly web software) were it's the easiest (sometimes only) way of contacting the software company.


答:
The TDD cycle is all about quick feedback - post-commit asynchronous reviews will break your pace.

If you want unit tests to be approved by another developer, pair programming is IMO a much better idea.

Title: Review tests first


问:
Is a functional spec a part of the System requirement spec?
I wonder, sources like wikipedia or templates I found shows that Functional spec is a part of System requirement documents. I always thought that SRD is just overall decsription of the system, with all functional and non functional requirements. Yet I thought that Functional spec is more detailed and it is a separate document, while SRD is high level customer-created description (how is this one called then?)
Could anyone help to make this clear for me?

答:
I agree with your interpretation. Broadly speaking...

Requirements = What should it do?

Specifications = How should it do it?

Despite very rough, I think this rule of thumb describes pretty well the intent and scope of these documents. My 2 cents...


问:
How to test a localized WPF application in visual studio 2012
I am trying to create a localized application in C# / WPF in Visual Studio 2012. For that I created two resource files and changed one string in a (XAML) window to use the resource files (instead of a hardcoded string).

I see the English text from the resource file, which is correct. However, I want to check if the other resource file (fr-FR) also works but I cannot find a setting or procedure how to change my 'project' to run in French.

Thanks in advance.

答: I've never been fond of the basic WPF "support" for localization.  I've been using this for over four years: Advanced WPF Localization (the "advanced" version is relatively new - I used the "simple" version up to about a year ago).  This implements a markup extension and allows you to localize text, images, brushes, etc.  It also supports changing language on the fly, which can be useful in some scenarios.</p>


问:
Should I manage authentication on my own if the alternative is very low in usability and I am already managing roles?
As a small in-house dev department, we only have experience with developing applications for our intranet. We use the existing Active Directory for user account management. It contains the accounts of all company employees and many (but not all) of the business partners we have a cooperation with.

Now, the top management wants a technology exchange application, and I am the lead dev on the new project. Basically, it is a database containing our know-how, with a web frontend. Our employees, our cooperating business partners, and people who wish to become our cooperating business partners should have access to it and see what technologies we have, so they can trade for them with the department which owns them. The technologies are not patented, but very valuable to competitors, so the department bosses are paranoid about somebody unauthorized gaining access to their technology description. This constraint necessitates a nightmarishly complicated multi-dimensional RBAC-hybrid model.

As the Active Directory doesn't even contain all the information needed to infer the roles I use, I will have to manage roles plus per-technology per-user granted access exceptions within my system. The current plan is to use Active Directory for authentication. This will result in a multi-hour registration process for our business partners where the database owner has to manually create logins in our Active Directory and send them credentials.

If I manage the logins in my own system, we could improve the usability a lot, for example by letting people have an active (but unprivileged) account as soon as they register. It seems to me that, after I am having a users table in the DB anyway (and managing ugly details like storing historical user IDs so that recycled user IDs within the Active Directory don't unexpectedly get rights to view someone's technologies), the additional complexity from implementing authentication functionality will be minimal. Therefore, I am starting to lean towards doing my own user login management and forgetting the AD altogether.

On the other hand, I see some reasons to stay with Active Directory. First, the conventional wisdom I have heard from experienced programmers is to not do your own user management if you can avoid it. Second, we have code I can reuse for connection to the active directory, while I would have to code the authentication if done in-system (and my boss has clearly stated that getting the project delivered on time has much higher priority than delivering a system with high usability). Third, I am not a very experienced developer (this is my first lead position) and have never done user management before, so I am afraid that I am overlooking some important reasons to use the AD, or that I am underestimating the amount of work left to do my own authentication.

I would like to know if there are more reasons to go with the AD authentication mechanism. Specifically, if I want to do my own authentication, what would I have to implement besides a secure connection for the login screen (which I would need anyway even if I am only transporting the pw to the AD), lookup of a password hash and a mechanism for password recovery (which will probably include manual identity verification, so no need for complex mTAN-like solutions)? And, if you have experience with such security-critical systems, which one would you use and why?

Update When I wrote the question, I had been told by my boss that I will get read-only access to the Active Directory, and that all users of my system would have follow internal procedures for managing accounts (such as showing a picture ID to our secretary to reset a forgotten password). I wouldn't have had the possibility to create my own groups. But after explaining the situation to my boss and to the AD administrator, I got permission to save my users' accounts in a separate OU and manage them as I see fit. So now I can use Active Directory and still offer an acceptable user experience. Still, if you have an answer which addresses my question under the old constraints, please write it down, I would be interested to hear more about it even if my interest is only academic now.

答:
I would recommend you use an AD based approach, and enhance your existing AD environment to provide the groups / roles that you need to support your application.

One element you haven't discussed in your question is Auditing.  How are you going to verify that you have all the correct roles and rules and blah blah blah that your paranoid process owner is demanding?  (n.b. paranoia isn't always a bad thing)

AD has a large set of tools already built around it in order to simplify the registration process, handling auditing, and quick account deactivation.  Can your development team provide all of that functionality?  Is there any real value in your team building that functionality?  That's why AD is the more attractive option of the two.

User management is a big realm, and it's not core to your business.  Those are excellent reasons to use a 3rd party tool (AD in this case) to simplify your development tasks.  Scheduling and delivery concerns simply add more weight to this argument.


答: One more benefit is that objects can implement interfaces/traits, unlike static methods.

Title: What are the advantages of Scala's companion objects vs static methods?

Body: Scala has no static-keyword, but instead has similar functionality through companion objects. Behind the scenes the companion objects are compiled to classes that have static methods, so all this is syntactic sugar. What are the advantages of this design choice? Disadvantages? Do other languanges have similar constructs?


问:
Do most programmers copy and paste code?
I learned very early on that cutting & pasting somebody else's code takes longer in the long run that writing it yourself.  In my opinion unless you really understand it, cut & paste code will probably have issues which will be a nightmare to resolve.

Don't get me wrong, I mean finding other peoples code and learning from it is essential, but we don't just paste it into our app.  We rewrite the concepts into our app.

But I'm constantly hearing about people who cut & paste, and they talk about it like it's common practice.  I also see comments by others which indicate it's common practice.

So, do most programmers cut & paste code?

答: Given that, in one open source repository, 15 % of all methods are copied from one project to another (pdf), the answer seems to be a clear yes.</p>


问:
Web versus desktop development - is web development worse?
As a longtime desktop developer looking at doing our first large-scale web application, what are the pros and cons of doing web development?

Is developing a web application much worse than developing a desktop app?  E.g., is it more tedious or annoying?  Is the time to market much worse?  Is the web platform excessively limiting?  If the answer to any of these is yes, then why?

(And how does developing a Flash or Silverlight app compare?)

答:
As mentioned by others, it's a matter of trade-offs and of having the right knowledge.

The only pitfall you might want to consider is this: you mention in your question that you see the web as having "cross-platform" as an advantage. But does it really? Think of it this way: if you develop something for the desktop, you need to define the list of platforms and their requirements to support.

Make no mistake, it's the same for the web. And even though it's already tremendously simpler than it used to be, if you design a wide public app, you're going to have to deal with every possible version of every web browser out there. And if it's more of an enterprise app, then brace yourself and prepare to draft your supported browser platforms requirements very precisely.

Don't think you'll avoid to have platform-specific hacks here and there if you build something significant.

And then the fun parts. What is best? Browsers that update themselves almost transparently very regularly like Chrome? Or the ones that roll-out security updates only monthly and major features every stone age (like IE)? The answer is not as obvious as you might think, because some of these frequent "transparent" updates might break your code, and you will need to follow this and react promptly. Or keep an eye on beta and dev pre-releases while developing and testing. For all of the browsers you foolishly said you wanted to support (good luck).

Oh and let's not forget UI considerations. You also face the joy of deciding whether you want a consistent UI ACROSS all your target platforms, or a consistent UI WITH each host's target platform. See all those little buttons you can view on web-pages? Do you want them to be exactly the same everywhere, or to integrate with the environment used by your user? Of course this problem isn't new and existed for other development models, but it seems to be more important here, and depends on the type of users you target and what they expect. Public end-user would tend to want you to integrate with their platform - but will still want you to "wow!" them with fancy stuff - while the enterprise user will want something that looks like a desktop app. And mobile platforms had a new dimension to all this.

For the last 2 paragraphs, a common idea is sometimes to package a pre-configured web-browser with your installer, which then connects to your web-app (locally hosted or on the web). It's great because you control the update frequency and you can "freeze" the state and you know exactly what to support and test on. Plus you can add cool stuff like dedicated user extensions. For instance, packaging a "frozen" Chromium with small Chrome Extensions you've developed to make the use of your web-app easier for different types of users can be extremely nice. On the other hand... you're now responsible if a security breach occurs because you froze the release cycle, and your app won't benefit of speed improvements (if any).

Like many things, it's a double edged ax.

Note: I have a strong bias against the web for being basically a big pile of half-baked technologies (and I am polite here), down to the OSI layers, on which we keep adding layers of crap hiding the problems underneath without really solving or fixing them.

That being said, I am in favor of the web for its ubiquitous nature as a platform. I think your company's move is (probably) the right one. It depends on your target market and the platforms you aim for, obviously. If you want to expose something as a service, then you're probably good to go (though it's not necessary either). If you don't, then maybe there's not so many reasons for it.

Hmm, and expect some fun developments in the future now that more light-weight variants of existing operating systems keep spawning for mobile environments (netbooks, smartphones, PDAs, tablets, eBooks...), with more emphasis on using lightweight embedded browsers... but with all their new share of UI rendering glitches.

Regarding plugin-based technologies... I'd say steer away from them. They will enhance your app's power, but will limit its market penetration. In some cases you will see it as a plus in terms of cross-platform support, until a new platform suddenly refuses to support them. Web Standards are here for a reason (be careful not to get too excited about everything in HTMl5 either, or it might blow up in your face).

EDIT: other things to consider...

Recruitment

It's extremely hard to find knowledgeable web developers. You'd think there's a herd of them, but they're lost in a huge pool of, well, fairly incompetent people who think having managed to write 700 lines of JavaScript/ECMAScript to implement some validation in their forms is the end-all and be-all of what can be achieved in terms of high-level skills.

I'm not kidding, lately my first question for all web-development interviews is how to declare a variable, and then whether there's a different between using var or not (depending on how they answer). It's depressing. I find it a lot more difficult to find an average or advanced web developer than to find an average or advanced desktop developer.

Perception

No one will ever consider you seriously when you say "I'm a web developer". It's for a sub-class of programmers, developers, isn't it? The ones you ignore and mock from afar, and don't join when they go get coffee. :)

This is obviously untrue, but it comes down to the fact that you develop for an environment that is mostly managed for you. Browsers correct your screwed up markup, your screwed up styles, and will even correct your screwed scripting for some of them, and optimize it for you if you please. And if you're a web developer, people won't assume you have a clue about lower-level programming, so you must be a complete idiot, right?

And then they realize how crazily complex ECMAScript can be, but will refuse to review their opinion. Because it's web. We don't like it intrinsically, we just like what it enables us to do.

ContentLicense: CC BY-SA 2.5


问:
Sublinear Extra Space MergeSort
I am reviewing basic algorithms from a book called Algorithms by Robert Sedgewick, and I came across a problem in MergeSort that I am, sad to say, having difficulty solving.  The problem is below:

Sublinear Extra Space.  Develop a merge implementation that reduces that extra space requirement to max(M, N/M), based on the following idea: Divide the array into N/M blocks of size M (for simplicity in this description, assume that N is a multiple of M).  Then, (i) considering the blocks as items with their first key as the sort key, sort them using selection sort; and (ii) run through the array merging the first block with the second, then the second block with the third, and so forth.

The problem I have with the problem is that based on the idea Sedgewick recommends, the following set of arrays will not be sorted: {0, 10, 12}, {3, 9, 11}, {5, 8, 13}.  The algorithm I use is the following:

Divide the full array into subarrays of size M.

Run Selection Sort on each of the subarrays.

Merge each of the subarrays using the method Sedgwick recommends in (ii).  (This is where I encounter the problem of where to store the results after the merge.)

This leads to wanting to increase the size of the auxiliary space needed to handle at least two subarrays at a time (for merging), but based on the specifications of the problem, that is not allowed.

I have also considered using the original array as space for one subarray and using the auxiliary space for the second subarray.  However, I can't envision a solution that does not end up overwriting the entries of the first subarray.

Any ideas on other ways this can be done?

NOTE: If this is suppose to be on StackOverflow.com, please let me know how I can move it.  I posted here because the question was academic.

答:
To merge 2 blocks of size M you only need M extra space:

If you have a block from i to j and a block from j to k you first copy the first block to the additional space so i to j is free to receive the sorted array.

Then the merge is implemented as:

```<code>extra = new array[j-i]
arraycopy(arr,i,extra,0,j-i)//copy from arr to extra
p =0
while i<k
    if(arr[j]<extra[p])
       arr[i++]=arr[j++]
    else
       arr[i++]=extra[p++]
    if(j==k)break;
    if(i==j)break;
end while
arraycopy(extra,p,arr,i,extra.length-p)//copy remaining from extra
</code>```

you can see that i only increments without j up to j-i times so i is never larger than j

Title: Sublinear Extra Space MergeSort

Body:
To merge 2 blocks of size M you only need M extra space:

If you have a block from i to j and a block from j to k you first copy the first block to the additional space so i to j is free to receive the sorted array.

Then the merge is implemented as:

extra = new array[j-i]
arraycopy(arr,i,extra,0,j-i)//copy from arr to extra
p =0
while i<k
    if(arr[j]<extra[p])
       arr[i++]=arr[j++]
    else
       arr[i++]=extra[p++]
    if(j==k)break;
    if(i==j)break;
end while
arraycopy(extra,p,arr,i,extra.length-p)//copy remaining from extra

you can see that i only increments without j up to j-i times so i is never larger than j

ContentLicense: CC BY-SA 4.0


问:
What is thread safety?
What is it? I was reading  Effective STL and came across it. I have also Googled it, but couldn't get any helpful info.</p>

答:
Thread safety is a generic term that relates to avoiding R/W and synchronization problems, in the presence of multiple threads accessing the same data.

In practice, when two (or more) threads access the same data and at least one modifies the data, the other thread may be either reach an inconsistent state, or read corrupted data (the code is not "thread-safe").

To avoid this, there is a whole set of techniques in C++ (various mutex implementations, events, "double lock checking pattern", std::atomic and a lot more).

For a simple example, consider:

```<code>void an_object::member_function()
{
    if (p != nullptr)   // 1
    {
        delete p;       // 2
        p = new int(10);// 3
    }
    int q = *p;         // 4
}
</code>```

Consider two threads executing an_object::member_function for the same object instance, where p and q belong to an_object.

Here are some scenarios:

scenario 1:

thread 1 executes line 1

thread 2 executes line 1

thread 1 executes line 2

thread 2 executes line 2 and you have a double delete (and undefined behavior ensues)

scenario 2:

thread 1 executes line 1, 2 and 3

thread 2 executes line 1 and 2

thread 1 executes line 4, using an address just deleted by thread 2 (and undefined behavior appears again).

There are many more scenarios leading to undefined behavior with these four lines of code.

Title: What is thread safety?

Body:
Thread safety is a generic term that relates to avoiding R/W and synchronization problems, in the presence of multiple threads accessing the same data.

In practice, when two (or more) threads access the same data and at least one modifies the data, the other thread may be either reach an inconsistent state, or read corrupted data (the code is not "thread-safe").

To avoid this, there is a whole set of techniques in C++ (various mutex implementations, events, "double lock checking pattern", std::atomic and a lot more).

For a simple example, consider:

void an_object::member_function()
{
    if (p != nullptr)   // 1
    {
        delete p;       // 2
        p = new int(10);// 3
    }
    int q = *p;         // 4
}

Consider two threads executing an_object::member_function for the same object instance, where p and q belong to an_object.

Here are some scenarios:

scenario 1:

thread 1 executes line 1

thread 2 executes line 1

thread 1 executes line 2

thread 2 executes line 2 and you have a double delete (and undefined behavior ensues)

scenario 2:

thread 1 executes line 1, 2 and 3

thread 2 executes line 1 and 2

thread 1 executes line 4, using an address just deleted by thread 2 (and undefined behavior appears again).

There are many more scenarios leading to undefined behavior with these four lines of code.


答:
Thread safety was best solidified in my mind when I thought about it in terms of an ORM.

When your ORM goes to save all your objects to the database, it's not thread safe.

Why?  Well, part of an ORM's responsibility is to track a lot of internal state (In order to figure out what to do when it comes time to actually do persistence).  If you are half way through all the state management routines for a call to 'Save' and you start running a secondary 'Save' routine, what the heck is going to happen?   You will be disappointed with the results if you were hoping for good things to happen.

This is such a good example because thread safety is all about whether or not the state of objects can "survive" a second entry to a routine.

(Also why anyone who creates a static repository for their web app is shamed relentlessly.)

Title: What is thread safety?

Body: What is it? I was reading  Effective STL and came across it. I have also Googled it, but couldn't get any helpful info.</p>


问:
Why does the Scrum guide say no testers?
I have been reading the Scrum Guide from scrum.org and it says:

Development Teams do not contain sub-teams dedicated to particular domains like testing or business analysis.

In its literal translation this means that there are no testers which is confusing. How can they be suggesting this?

答:
It means that either:

Testers are integrated into the development team - building tools to help developers test as well as testing.

or:

The team practices Test Driven Development - i.e. They write automated tests that exercise the system.

Either of these means that there is no need for a separate testing team.


答: It says there is not sub-team dedicated to testing. That does not mean there are no tests done whatsoever. It only means that team members will do their own testing, and often test other people's code/features. I'm not that familiar with the scrum methodology, but I will go on a limb and say that the client may also be involved in the testing.

Title: Why does the Scrum guide say no testers?

Body:
I have been reading the Scrum Guide from scrum.org and it says:

Development Teams do not contain sub-teams dedicated to particular domains like testing or business analysis.

In its literal translation this means that there are no testers which is confusing. How can they be suggesting this?


答:
In its literal translation this means that there are no testers which is confusing... How can they be suggesting this?

Yes, this is exactly what they suggest. In other words - the developers are the testers and the testers are the developers.

The idea is to foster code ownership and quality.

This does not mean that code is not tested, but that the people involved in writing it are the ones involved in testing it - there is no separation of responsibilities.

The problem this approach is trying to address is the all too common separation between the developers and testers, where developers will write code and "throw it over the wall" to the other team and it then goes back and forth, delaying the project and producing sub-standard software.


答:
I think this partly means you are expected to write tests for your own code so that you know it works (if not, you haven't really finished it) and partly that you may well be expected to be a tester for other people's code sometimes.

Rather than allowing people to offload the software quality job onto someone else and ignore it, this forces everyone to think about the code they are writing from a quality perspective all the time, so it's a good idea.


问:
System requirement specification vs functional one - separate docs?
A lot of sources (e.g. Wikipedia) mentiones System requirement specification and Functional specification as two separate entities.
However, Wiegers in his book writes:

The software requirements specification is sometimes called  a
  functional specification, a product specification...

This is very confusing for me as I thought FS describes just functions while SRS whole system. From this point of view, FS would contain both non functional and functional requirements and everything else.

答: SRS and FS are indeed two separate entities.  Software requirement specification document is the primary document that contains detailed requirement specification, which describes the expected behaviour of the system and gives an overview of various functional units of the system.  Functional specification, on the other hand, is more detailed understanding of the behaviour of the system and may take inputs from software requirements specification document.  Functional specification is more about basic building blocks, how these should be built, what should be their behaviour and how will it meet the required expectation from the system.</p>


问:
Which VCS is more applicable for our workflow?
Currently we have code stored on a shared network drive and do not use any kind of VCS.  The code stored on our shared network drive is always being backed up.  We would like to keep things as close to they are now as possible, while using some kind of VCS software.

I am envisioning a centralized workflow with each developer having a local copy of the code on his/her machine.  We don't do any branching or working offline.  Typically when we spin off a new version we would just copy the current working directory to a new directory.  I believe we would continue doing this and just create a repository for the new version.

I would rather not get into an argument over which VCS is better, just hoping to get some opinions for which is best suited and most applicable for what we are trying to do.

答:
Most, if not all, version control systems will be able to cope with your workflow.

You'll simply check out from a main trunk and check back into it when each development is finished. The developers will just need to get into the habit of doing a "get latest/head" at regular intervals.

It would be better to take a branch of the code for each new version, rather than a copy. Or perhaps create a branch to preserve the last version (it doesn't really matter).

What you'll probably find is that as you become more used to using version control you'll see more possibilities for using branches, so I'd pick one that has good branching and merging tools.


答:
In essence, many things can go wrong in a multi threaded environment (instructions reordering, partially constructed objects, same variable having different values in different threads because of caching at the CPU level etc.).

I like the definition given by Java Concurrency in Practice:

A [portion of code] is thread-safe if it behaves correctly when accessed from multiple threads, regardless of the scheduling or interleaving of the execution of those threads by the runtime environment, and with no additional synchronization or other coordination on the part of the calling code.

By correctly they mean that the program behaves in compliance with its specifications.

Contrived example

Imagine that you implement a counter. You could say that it behaves correctly if:

counter.next() never returns a value that has already been returned before (we assume no overflow etc. for simplicity)

all values from 0 to the current value have been returned at some stage (no value is skipped)

A thread safe counter would behave according to those rules regardless of how many threads access it concurrently (which would typically not be the case of a naive implementation).

Title: What is thread safety?


答:
The fundamental part to this is that the coder's responsibility is to create code that works and fills the requirement.  This requires a particular mindset - "The code that I am writing does what it is supposed to do."

To mix the responsibilities of the coder means that the coder is now required to enter other mindsets for other activities, however, as a coder, it is difficult to impossible for one to completely divorce one's self from that mindset.

The tester's responsibility is to find bugs and places where the functionality diverts from the required functionality.  This required the mindset of "The code is broken and I will find out how."

Likewise, a business analyst is trying to identify the requirements that the customer is actually asking for.  This requires another mindset of "the application doesn't work this way, but it should."

For a coder to work in any of those other capacities, there is a reasonable likelihood that the mindsets will conflict and the coder will perform sub-par:

Coder/QA - "The code works perfectly, and I have already coded to
handle every possible way I can think of that might break it."

Coder/BA - "The code should work the way that I want it to and these
would be neat things to add to it that the customer didn't think of.

This is not to say that every coder is susceptible to these problems (I have meet some very gifted coder/QA types... though not for code that they wrote).

This extends up to the development team as well.  Mixing the responsibilities and associated mindsets of those responsibilities for a development team compromises the final product (the code).


答:
Your workflow (of a centrally accessible folder with copies) would map to VCS like TFS and Subversion.  Each of these relies con common access to a shared history.  A VCS would be an amazing leap forward in terms of keeping track of changes to these folders, but the concept would feel the most "at home" with someone already used to working this way.  I might have suggested Visual Source Safe (if it was 1998, ohh burn) because of the concept of file locking which I think is a side effect of your workflow.  However in terms of training your team to work with a VCS the one big leap will be to understand that you will pull down a working copy when developing and you will need to push (commit) your changes in order to get them back onto the common code base.

Now if your team is used to having large copies of the their code on their computers and they see merging it with the shared codebase as a pain, then I would direct you tot Distributed Version Control.  As mind bending as the concept is (here is an excellent resource, to get a team to understand it: http://hginit.com/), it helps speed up the process of synchronizing your teams efforts.

Title: Which VCS is more applicable for our workflow?

Body:
Currently we have code stored on a shared network drive and do not use any kind of VCS.  The code stored on our shared network drive is always being backed up.  We would like to keep things as close to they are now as possible, while using some kind of VCS software.

I am envisioning a centralized workflow with each developer having a local copy of the code on his/her machine.  We don't do any branching or working offline.  Typically when we spin off a new version we would just copy the current working directory to a new directory.  I believe we would continue doing this and just create a repository for the new version.

I would rather not get into an argument over which VCS is better, just hoping to get some opinions for which is best suited and most applicable for what we are trying to do.


答: Something is thread safe if it can be used from several threads without malfunctioning.</p>

Title: What is thread safety?


答: Well, you tagged eclipse, so I would go with git, since its pretty well integrated with the IDE (with EGit). Also you can push on a network drive without having to set up a server like SVN. Plus if you ever decide to use more feature of your VCS you will have a pretty powerful and modern tool at your disposal.</p>


问:
How can I evaluate a candidate's knowledge of Html/CSS during an interview?
I am trying to determine some good interview questions to assess the ability of people coming in for a Html/CSS job, however that topic is extremely broad, and I'm not sure what sort of questions I can ask to properly evaluate someone's HTML/CSS knowledge.

What sort of questions can I ask to evaluate a candidate's Html/CSS abilities during an interview?

Ideally I would like to ask few questions and then give them a real life scenario to combat.

答:
I sat in on a few web designer interviews, and what we did was print out a very simple looking Blog layout on paper, and then ask the candidate to just jot some HTML and/or CSS on the page over 10min or so, to give us a basic idea of how they'd code it up. This let us know if someone ACTUALLY knew CSS or not. We were just looking for basic stuff like floats vs tables, or whatever, and we explained that it didn't have to be perfect by any means.

Tons of folks claimed years of experience with CSS, but when pressed to write it out, they were writing in wild guesses like "layout: floating; direction: up;" or other such jibberish. More than 1 "CSS Ninja" didn't even get the syntax right, a la "div(margin=5)". That was very eye opening for me, to see how many people just straight up lie in interviews. And its seemingly easier to lie about CSS than about straight up coding. You could not know a thing about CSS, but do some googling and be able to throw the proper terminology around pretty quickly. You can't really do that effectively with higher level concepts like OOP, for example.


问:
Forking a repo on GitHub but allowing new issues on the fork
I have previously forked other people's repos on GitHub, and I have noticed that issues stay with the original repo, and that I can't file issues on the forked repo.

I now have the following task.  I am working for a small business where development was being done by one of the principals on his personal account.  He has amicably left the project, and we would like to migrate that project away from his personal account to a new "role" account on GitHub.

I would naturally fork the repo, in order to preserve the code history, but then I'll end up with a repo where we can't file new issues, which is quite undesirable.

How can I make a copy of this original repo into our new account, ideally still preserving code history, but be able to file new issues within this new account?

答:
After a quick test, it is possible to attach an issue to your own fork of a repo. Here is what I did :

Fork a repo

Go to the Settings page of your fork.

Check the box next to Issues

You can now file issues on your own fork and they will not be placed in the main repo.


问:
Amnesic Environment
My team is looking for a technical term which may or may not exist.

We are trying to describe an environment, such as a database, which has been built up over time with little or documentation about the change process that has gone into it.  Generally these are legacy systems who's original developers have long since moved on and they are in such a tangled and unmanageable state that the only way to recreate the environment, say for testing purposes, is to copy it and do your best guess at re-configuring it for its new purpose.

So far the best term we have come up with is Amnesic, such as "setting up the new test environment is going to be a challenge because it is an amnesic db."  However, we are still not quite happy with the term and were wondering if a better and/or more accepted term for this situation exists.

答:
There are terms which are close to describing what you want, but maybe not exactly right.

The term Legacy Code (mentioned in the comments to the question) is often used as a derogatory term because it's been hacked on and has become brittle and hard to understand and work with.

The term Lava Flow (also mentioned in the comments to the question) is used to denote clumps of code that have been there for eons and nobody dares touch them because they work (or nobody has ever touched them without breaking the world).

But "legacy code" merely implies old, and "lava flow" implies little blobs within a system, not the whole thing.

So... With tongue firmly planted in cheek, howsabouts I invent a term: "Basalt Deposit?" A basalt deposit consists of (often multiple) lava flows that have solidified at or near the base of a long-active volcano. Like the re-solidified wax that ran down the side of a candle and pooled at its base. It's a hard rock, and after the volcano has gone extinct and erosion has run its course, is usually the dominant feature in the landscape.

Usage: "Do you really want to go digging around in there? It's a basalt deposit, and you're gonna break your shovel."

Of course, instead of a pithy term, you could just post warning signs at the borders explaining what the dangers of the code are :)

Title: Amnesic Environment


答:
Setting up the new test environment is going to be a challenge because there is a significant amount of technical debt. Corners have been cut and development was geared towards time constraints over quality control. By leaving off the necessary work required for a project (documentation, refactoring, regression testing, code reviews), they put off that investment into future. They reaped a benefit at the moment in exchange for some technical debt. But this debt grows with interest. As time progresses, the mind-space of the developers was dedicated elsewhere and the reasons for this change here or that addition there was lost. And with that loss, the task of documenting and cleaning the project up became that much harder. There comes a point where the debt is unmanageable and you should simply start anew. This is offset by how tightly coupled the project is to the rest of your business and how much of this cruft is legitimate business knowledge. Even for extremely crufty projects, reverse engineering the details may be a better solution than starting from scratch.

But it's going to be hard because you have to start paying off a massive debt. Most of the payment (that is, the time you spend reverse engineering this thing) is going to interest rather than the principle (we'll be documenting and refactoring more than we're adding new code or tests). At least at the start.

Title: Amnesic Environment

Body:
My team is looking for a technical term which may or may not exist.

We are trying to describe an environment, such as a database, which has been built up over time with little or documentation about the change process that has gone into it.  Generally these are legacy systems who's original developers have long since moved on and they are in such a tangled and unmanageable state that the only way to recreate the environment, say for testing purposes, is to copy it and do your best guess at re-configuring it for its new purpose.

So far the best term we have come up with is Amnesic, such as "setting up the new test environment is going to be a challenge because it is an amnesic db."  However, we are still not quite happy with the term and were wondering if a better and/or more accepted term for this situation exists.


问:
What's a nice explanation for pointers?
In your own studies (on your own, or for a class) did you have an "ah ha" moment when you finally, really understood pointers? Do you have an explanation you use for beginner programmers that seems particularly effective?

For example, when beginners first encounter pointers in C, they might just add &s and *s until it compiles (as I myself once did). Maybe it was a picture, or a really well motivated example, that made pointers "click" for you or your student. What was it, and what did you try before that didn't seem to work? Were any topics prerequisites (e.g. structs, or arrays)?

In other words, what was necessary to understand the meaning of &s and *, when you could use them with confidence? Learning the syntax and terminology or the use cases isn't enough, at some point the idea needs to be internalized.

Update: I really like the answers so far; please keep them coming. There are a lot of great perspectives here, but I think many are good explanations/slogans for ourselves after we've internalized the concept. I'm looking for the detailed contexts and circumstances when it dawned on you.

For example:

I only somewhat understood pointers
  syntactically in C. I heard two of my
  friends explaining pointers to another
  friend, who asked why a struct was
  passed with a pointer. The first
  friend talked about how it needed to
  be referenced and modified, but it was
  just a short comment from the other
  friend where it hit me: "It's also
  more efficient." Passing 4 bytes
  instead of 16 bytes was the final
  conceptual shift I needed.

答:
How I really learned about pointers? By writing a simple compiler freshmen year of college. </p>

<p>How to explain pointers in layman's terms? I like the (dated?) analogy of a library catalog stored on index cards. Each card ("pointer") contains information about where some book ("data") is located, but doesn't actually contain the book itself. If you modify the card ("pointer arithmetic"), all it does is change what book it points to and has no impact on the book itself - just be careful not to screw up the address or you might point to a non-existent book or even the wrong library. However, if you follow the "address" on the card and go to the proper part of the library ("dereference the pointer"), you can see/modify the book itself.  </p>

Title: What's a nice explanation for pointers?

Body:
How I really learned about pointers? By writing a simple compiler freshmen year of college.

How to explain pointers in layman's terms? I like the (dated?) analogy of a library catalog stored on index cards. Each card ("pointer") contains information about where some book ("data") is located, but doesn't actually contain the book itself. If you modify the card ("pointer arithmetic"), all it does is change what book it points to and has no impact on the book itself - just be careful not to screw up the address or you might point to a non-existent book or even the wrong library. However, if you follow the "address" on the card and go to the proper part of the library ("dereference the pointer"), you can see/modify the book itself.


问:
Returning status code where one of many errors could have occured
I'm developing a PHP login component which includes functions to manipulate the User object, such as $User->changePassword(string $old, string $new)
What I need some advice with is how to return a status, as the function can either succeed (no further information needs to be given) or fail (and the calling code needs to know why, for example incorrect password, database problem etc.)

I've come up with the following ideas:

Unix-style: return 0 on success, another code on failure. This doesn't seem particularly common in PHP and the language's type-coercion messes with this (a function returning FALSE on success?) This seems to be the best I can think of.

Throw an exception on error. PHP's exception support is limited, and this will make life harder for anybody trying to use the functions.

Return an array, containing a boolean for "success" or not, and a string or an int for "failure status" if applicable.

None of these seem particularly appealing, does anyone have any advice or better ideas?

答:
I would lean toward using exceptions, because you are least likely to bypass or mishandle an error condition. If you have to define error codes or create custom structures, you have to account for those manually in the caller and callee.

If you forget that a critical error is (for example) the return integer 3, that won't necessarily prevent your code from entering an invalid state, or saving invalid data.

If you want to return multiple error reasons, you can always extend exceptions:

```<code>class MyException extends Exception
{
    // Redefine the exception so message isn't optional
    public function __construct($message, $code = 0, Exception $previous = null) {
        // some code

        // make sure everything is assigned properly
        parent::__construct($message, $code, $previous);
    }

    // custom string representation of object
    public function __toString() {
        return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
    }

    public function customFunction() {
        echo "A custom function for this type of exception\n";
    }
}
</code>```

Body:
I would lean toward using exceptions, because you are least likely to bypass or mishandle an error condition. If you have to define error codes or create custom structures, you have to account for those manually in the caller and callee.

If you forget that a critical error is (for example) the return integer 3, that won't necessarily prevent your code from entering an invalid state, or saving invalid data.

If you want to return multiple error reasons, you can always extend exceptions:

class MyException extends Exception
{
    // Redefine the exception so message isn't optional
    public function __construct($message, $code = 0, Exception $previous = null) {
        // some code

        // make sure everything is assigned properly
        parent::__construct($message, $code, $previous);
    }

    // custom string representation of object
    public function __toString() {
        return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
    }

    public function customFunction() {
        echo "A custom function for this type of exception\n";
    }
}


问:
How do you rate Hosting?
1) Up-time
2) Latency
3) Throughput
4) Server software such as SQL, etc.
5) $$$ -- transfer, overages, etc.

What else?

And is there a web site rating hosts by this criteria that is actually reliable and not simply a dishonest advertising site... or do you guys have any recommendations?

(BTW, someone with 150+ rep should create "hosting" and "web hosting" tags.)

答:
#1. Simplicity

I want a simple interface and a root prompt.

#2. Cost

I don't want an arm and a leg for Plesk, CPanel, phpMyAdmin, and a million other tools I won't use.

Any reputable web host will have great uptime, latency, throughput. Server software is something you add on yourself. #2 (cost) is up to you. Do you need more bandwidth? Do you need things pre-installed or setup? That will cost you. Most overages and rates are standardized and aren't exorbitant.

Title: How do you rate Hosting?


问:
Why is multithreading often preferred for improving performance?
I have a question, it's about why programmers seems to love concurrency and multi-threaded programs in general.

I'm considering 2 main approaches here:

an async approach basically based on signals, or just an async approach as called by many papers and languages like the new C# 5.0 for example, and a "companion thread" that manages the policy of your pipeline

a concurrent approach or multi-threading approach

I will just say that I'm thinking about the hardware here and the worst case scenario, and I have tested this 2 paradigms myself, the async paradigm is a winner at the point that I don't get why people 90% of the time talk about multi-threading when they want to speed up things or make a good use of their resources.

I have tested multi-threaded programs and async program on an old machine with an Intel quad-core that doesn't offer a memory controller inside the CPU, the memory is managed entirely by the motherboard, well in this case performances are horrible with a multi-threaded application, even a relatively low number of threads like 3-4-5 can be a problem, the application is unresponsive and is just slow and unpleasant.

A good async approach is, on the other hand, probably not faster but it's not worst either, my application just waits for the result and doesn't hangs, it's responsive and there is a much better scaling going on.

I have also discovered that a context change in the threading world it's not that cheap in real world scenario, it's in fact quite expensive especially when you have more than 2 threads that need to cycle and swap among each other to be computed.

On modern CPUs the situation it's not really that different, the memory controller it's integrated but my point is that an x86 CPUs is basically a serial machine and the memory controller works the same way as with the old machine with an external memory controller on the motherboard. The context switch is still a relevant cost in my application and the fact that the memory controller it's integrated or that the newer CPU have more than 2 core it's not bargain for me.

For what i have experienced the concurrent approach is good in theory but not that good in practice, with the memory model imposed by the hardware, it's hard to make a good use of this paradigm, also it introduces a lot of issues ranging from the use of my data structures to the join of multiple threads.

Also both paradigms do not offer any security abut when the task or the job will be done in a certain point in time, making them really similar from a functional point of view.

According to the X86 memory model, why the majority of people suggest to use concurrency with C++ and not just an async approach ? Also why not considering the worst case scenario of a computer where the context switch is probably more expensive than the computation itself ?

答:
the application is unresponsive and is just slow and unpleasant.

And there's your problem. A responsive UI does not make a performant application. Often the opposite. A bunch of time is spent checking UI input rather than having the worker threads do their job.

As far as 'just' having an async approach, that's multithreading as well although tweaked for that one particular use case in most environments. In others, that async is done via coroutines that are... not always concurrent.

Frankly, I find async operations to be more difficult to reason about and use in a way that actually provides benefit (performance, robustness, maintainability) even compared to... more manual approaches.


问:
What's the point of the Prototype design pattern?
So I'm learning about design patterns in school. Many of them are silly little ideas, but nevertheless solve some recurring problems(singleton, adapters, asynchronous polling, ect). But today I was told about the so called 'Prototype' design pattern.

I must be missing something, because I don't see any benefits from it. I've seen people online say it's faster than using "new"' but this is doesn't make any sense, since at some point, regardless how the new object is created, memory needs to be allocated for it ect.

Furthermore, doesn't this pattern run in the same circles as the 'chicken or egg' problem? By this I mean, since the prototype pattern essentially is just cloning objects, at some point the original object must be created itself (ie, not cloned). So this would mean, that I would need to have an existing copy of every object that I would ever want to clone already ready to clone? Seems stupid to me.

Can anyone explain what the use of this pattern is?

Original post: https://stackoverflow.com/questions/13887704/whats-the-point-of-the-prototype-design-pattern

答: Allocating memory might not be the slow part of creating your object. If the object is data driven or otherwise the result of a calculation, it is sometimes prudent to cache the result so that that result can be cloned rather than re-done. Thus, the Prototype pattern.</p>


问:
What are some non-MS languages that can write xlsx (Excel 2007+) documents efficiently?
Unfortunately, Excel format is required for the project I am working on. I have no problems getting the data I need in objects and arrays, and currently PHPExcel is doing handling the document generation. It works, but it's slow and loopy. Was wondering if there is a more efficient server language to generate Excel documents (not CSVs).

This is a pure Linux environment so I need to stay away from .NET. I am open to any programming language that does it cleanly and efficiently.

答: .xlsx files are actually XML so you can use most any language out there. Perl's CPAN seems to have a number of options for instance. Most of it is going to boil down to how much money you want to spend vs completeness of the open source modules/ability to write your own compiler.</p>


答:
There are lots of uses for Prototype, small and large...JavaScript and Io are both prototype based languages for instance. In one sense it is object based inheritance (vs class based), which is a pretty cool concept, IMO.

From a nuts and bolts design pattern perspective, Prototype works well if you have some specific case where the "cost" of creating an object is high, does not consist of only memory allocation, and you need more than one instance of that object...the higher the count the more useful the pattern.

Because of its general utility for solving this specific case, Prototype combos well with other design patterns; its frequently listed as complementary to other patterns in the GoF book.

Tangent

You can also do some fun little tricks w/ Prototype. For instance I recall a custom snippets based code generator utility I wrote a number of years ago that had a CodeScripter prototype that had a few instance specific things like target path, filename, some metadata options, and a mechanism to specify which snippets to use in what order...it pulled in a bunch of different templates from files on disk on creation, and then specific output scenarios would clone the CodeScripter thus avoiding the initialization cost, push in the appropriate info for the instance, and configure the appropriate selection of ordered snippets.

Of course, I could have solved that problem a lot of ways, but though it had its downside* the volume of outputs that needed to be generated and the fact that most of the scenarios were very similar and there was a high overlap in the snippets made Prototype a neat option.

 * The downside was that the CodeScripter prototype was unabashedly a god object...but in the case of that utility I found it to be an acceptable tradeoff.

Title: What's the point of the Prototype design pattern?

Body:
So I'm learning about design patterns in school. Many of them are silly little ideas, but nevertheless solve some recurring problems(singleton, adapters, asynchronous polling, ect). But today I was told about the so called 'Prototype' design pattern.

I must be missing something, because I don't see any benefits from it. I've seen people online say it's faster than using "new"' but this is doesn't make any sense, since at some point, regardless how the new object is created, memory needs to be allocated for it ect.

Furthermore, doesn't this pattern run in the same circles as the 'chicken or egg' problem? By this I mean, since the prototype pattern essentially is just cloning objects, at some point the original object must be created itself (ie, not cloned). So this would mean, that I would need to have an existing copy of every object that I would ever want to clone already ready to clone? Seems stupid to me.

Can anyone explain what the use of this pattern is?

Original post: https://stackoverflow.com/questions/13887704/whats-the-point-of-the-prototype-design-pattern


问:
Can publicly accessible code be closed source?
Is it possible, legally, for code to be publicly available online, but have copyright protection?</p>

答:
Disclaimer.IANAL()

You may be conflating open-source with unlicensed. Most open-source code is licensed. As to picking a license, well we have posts for that. Copyright is typically automatic but varies from country to country and is somewhat different from licensing which involves copyright but is not itself a copyright. You're protected by copyright even if your code is publicly available as though it were a book or blog post most of the time. If you want to grant use of your code, you pick a license and go.


答:
Yes. Having access to source code does not give permission to redistribute. Here is an analogy: Think about photos on Flickr, just because you can view them doesn't mean you can redistribute them.

For example: Several hardware companies will make code available to use with their hardware, but the license will say only their hardware. It doesn't meet the OSI definition of open source, and you can use it in a limited fashion.

Why are you asking? Is this something you've seen or what to do.

Title: Can publicly accessible code be closed source?

Body: Is it possible, legally, for code to be publicly available online, but have copyright protection?</p>


答:
You have multiple cores/procesors, use them

Async is best for doing heavy IO bound processing but what about heavy CPU bound processing?

The problem arises when single-threaded code blocks (ie gets stuck) on a long-running process. For instance, remember back when printing a word processor document would make the whole application freeze until the job was sent? Application freezing is a side-effect of a single-threaded application blocking during a CPU-intensive task.

In a multi-threaded application, CPU-intensive tasks (ex a print job) can be sent to a background worker thread thereby freeing up the UI thread.

Likewise, in a multi-process application the job can be sent via messaging (ex IPC, sockets, etc) to a subprocess designed specifically to process jobs.

In practice, async and multi-threaded/process code each have their benefits and drawbacks.

You can see the trend in the major cloud platforms, as they will offer instances specialized for CPU bound processing and instances specialized for IO bound processing.

Examples:

Storage (ex Amazon S3, Google Cloud Drive) is CPU bound

Web Servers are IO bound (Amazon EC2, Google App Engine)

Databases are both, CPU bound for writes/indexing and IO bound for reads

To put it into perspective...

A webserver is a perfect example of a platform that is strongly IO bound. A multi-threaded webserver that assigns one thread per connection doesn't scale well because every thread incurs more overhead due to the increased amount of context switching and thread locking on shared resources. Whereas an async webserver would use a single address space.

Likewise, an application specialized for encoding video would work much better in a multi-threaded environment because the heavy processing involved would lock the main thread until the work was done. There are ways to mitigate this but it's much easier to have a single thread managing a queue, a second thread managing cleanup, and a pool of threads managing the heavy processing. Communication between threads happens only when tasks are assigned/completed so thread-locking overhead is kept to a bare minimum.

The best application often uses a combination of both. A webapp, for instance may use nginx (ie async single-threaded) as a load balancer to manage the torrent of incoming requests, a similar async webserver (ex Node.js) to handle http requests, and a set of multi-threaded servers handle uploading/streaming/encoding content, etc...

There have been a lot of religious wars over the years between multi-threaded, multi-process, and async models. As with the most things the best answer really should be, "it depends."

It follows a the same line of thinking that justifies using GPU and CPU architectures in parallel. Two specialized systems running in concert can have a much greater improvement than a single monolithic approach.

Neither are better because both have their uses. Use the best tool for the job.

Update:

I removed the reference to Apache and made a minor correction. Apache uses a multiprocess model which forks a process for every request increasing the amount of context switching at the kernel level. In addition, since the memory can't be shared across processes, each request incurs an additional memory cost.

Multi-threading gets around requiring additional memory because it relies on a shared memory between threads. Shared memory removes the additional memory overhead but still incurs the penalty of increased context switching. In addition -- to ensure that race conditions don't happen -- thread locks (that ensure exclusive access to only one thread at a time) are required for any resources that are shared across threads.

It's funny that you say, "programmers seems to love concurrency and multi-threaded programs in general." Multi-threaded programming is universally dreaded by anybody who has done any substantial amount of it in their time. Dead locks (a bug that happens when a resource is mistakenly locked by two different sources blocking both from ever finishing) and race conditions (where the program will mistakenly output the wrong result randomly due to incorrect sequencing) are some of the most difficult to track down and fix.

Update2:

Contrary to the blanket statement about IPC being faster than network (ie socket) communications. That's not always the case. Keep in mind that these are generalizations and implementation-specific details may have a huge impact on the result.

Title: Why is multithreading often preferred for improving performance?

Body:
I have a question, it's about why programmers seems to love concurrency and multi-threaded programs in general.

I'm considering 2 main approaches here:

an async approach basically based on signals, or just an async approach as called by many papers and languages like the new C# 5.0 for example, and a "companion thread" that manages the policy of your pipeline

a concurrent approach or multi-threading approach

I will just say that I'm thinking about the hardware here and the worst case scenario, and I have tested this 2 paradigms myself, the async paradigm is a winner at the point that I don't get why people 90% of the time talk about multi-threading when they want to speed up things or make a good use of their resources.

I have tested multi-threaded programs and async program on an old machine with an Intel quad-core that doesn't offer a memory controller inside the CPU, the memory is managed entirely by the motherboard, well in this case performances are horrible with a multi-threaded application, even a relatively low number of threads like 3-4-5 can be a problem, the application is unresponsive and is just slow and unpleasant.

A good async approach is, on the other hand, probably not faster but it's not worst either, my application just waits for the result and doesn't hangs, it's responsive and there is a much better scaling going on.

I have also discovered that a context change in the threading world it's not that cheap in real world scenario, it's in fact quite expensive especially when you have more than 2 threads that need to cycle and swap among each other to be computed.

On modern CPUs the situation it's not really that different, the memory controller it's integrated but my point is that an x86 CPUs is basically a serial machine and the memory controller works the same way as with the old machine with an external memory controller on the motherboard. The context switch is still a relevant cost in my application and the fact that the memory controller it's integrated or that the newer CPU have more than 2 core it's not bargain for me.

For what i have experienced the concurrent approach is good in theory but not that good in practice, with the memory model imposed by the hardware, it's hard to make a good use of this paradigm, also it introduces a lot of issues ranging from the use of my data structures to the join of multiple threads.

Also both paradigms do not offer any security abut when the task or the job will be done in a certain point in time, making them really similar from a functional point of view.

According to the X86 memory model, why the majority of people suggest to use concurrency with C++ and not just an async approach ? Also why not considering the worst case scenario of a computer where the context switch is probably more expensive than the computation itself ?


问:
What mistakes do your users make, and how can you update your application to handle them?
In fact this question is about cautions to be taken to enhance quality user experience and reduce avoidable support calls.</p>

答:
A lack of proper input validation is one of those things which tends to lead quite quickly to users doing "bad" things with your application, when it should really be handled by the programmer.

I've seen legacy apps where users have been trained to:

not enter apostrophes in names

not enter any symbol other than a-z0-9,

ensure there are no spaces before or after the text they've entered

check that a correctly formatted email address is being entered in to the email field, otherwise subsequent mailings to that user will use whatever's in the field and will fail

make sure "http://" is put before web addresses

etc etc

All of the above issues are ones which should be handled by an application developer. When your input validation is essentially "make sure the user knows what format this field should be in and trust what they've entered is right", then unexpected things are bound to find their way in to the app. Aside from the obvious security implications, users make mistakes. As programmers we often produce our best products by bending over backwards to make sure that the user can't get it wrong, no matter how hard they try!


答:
Comparing hosting is like comparing dentists: there are plenty to choose from, everyone has a favorite and everyone recommends his/her own. And unfortunately just like with dentists, you need to find yours via trial and error rather than others' recommendations. You can probably start with various reviews and ratings available on the Internet.

One non-obvious thing that I learned recently though was that these so called "cloud-based" services where you pay per resource usage can turn into a disaster. I saw how one poor guy received a ridiculous bill from his hosting company just because he was running poorly optimized code (actually a third-party Wordpress plugin). I'd say stay away from this kind of hosting unless you absolutely know what you are doing.

Title: How do you rate Hosting?

Body:
1) Up-time
2) Latency
3) Throughput
4) Server software such as SQL, etc.
5) $$$ -- transfer, overages, etc.

What else?

And is there a web site rating hosts by this criteria that is actually reliable and not simply a dishonest advertising site... or do you guys have any recommendations?

(BTW, someone with 150+ rep should create "hosting" and "web hosting" tags.)


答:
Second below up-time would be decent support.

Find someone who has competent 24 hour technical support. If your production box has a hardware failure at 4am - which it will inevitably at some point - or you need to ask advice on an upgrade - you need to know that you're in good hands.

Title: How do you rate Hosting?


答:
all of the above, plus

no additional charges for additional domains - you're already paying for bandwidth and compute-time, the number of web sites is not relevant

24/7 immediate support from people who speak your language

scalable service, in case you get slashdotted

sane, automatic handling of subdomains

Title: How do you rate Hosting?


问:
Which are the fundamental stack manipulation operations?
I'm creating a stack oriented virtual machine, and so I started learning Forth for a general understanding about how it would work. Then I shortlisted the essential stack manipulation operations I would need to implement in my virtual machine:

```<code>drop ( a -- )
dup  ( a -- a a )
swap ( a b -- b a )
rot  ( a b c -- b c a )
</code>```

I believe that the following four stack manipulation operations can be used to simulate any other stack manipulation operation. For example:

```<code>nip  ( a b -- b )       swap drop
-rot ( a b c -- c a b ) rot rot
tuck ( a b -- b a b )   dup -rot
over ( a b -- a b a )   swap tuck
</code>```

That being said however I wanted to know whether I have listed all the fundamental stack manipulation operations necessary to manipulate the stack in any possible way.

Are there any more fundamental stack manipulation operations I would need to implement, without which my virtual machine wouldn't be Turing complete?

答:
Many stack based languages use roll as well, which is a generalized rot on an arbitrary number of elements in the stack. They also implement the reverse operation for rotating the stack the other way.

I would say that roll is more fundamental than rot.

I have no answer though about Turingness of this.


答: There are several libraries available in the Java world, the most popular being Apache POI I believe, which is an open source library that enables you to read and write Excel files (officially supports versions 97 to 2007 but should work fine with 2010 too).</p>

Title: What are some non-MS languages that can write xlsx (Excel 2007+) documents efficiently?

Body:
Unfortunately, Excel format is required for the project I am working on. I have no problems getting the data I need in objects and arrays, and currently PHPExcel is doing handling the document generation. It works, but it's slow and loopy. Was wondering if there is a more efficient server language to generate Excel documents (not CSVs).

This is a pure Linux environment so I need to stay away from .NET. I am open to any programming language that does it cleanly and efficiently.


问:
In developing a soap client proxy, which return structure is easier to use and more sensible?
I'm writing (in PHP) a client/proxy for a SOAP web service. The return types are consistently wrapped in response objects that contain the return values.  In many cases this make a lot of sense - for instance when multiple values are being returned:

```<code>GetDetailsResponse Object
(
    Results Object
    (
        [TotalResults] => 10
        [NextPage]     => 2
    )

    [Details] => Array
    (
        [0] => Detail Object
        (
            [Id] => 1
        )
    )
)
</code>```

But some of the methods return a single scalar value or a single object or array wrapped in a response object:

```<code>GetThingummyIdResponse Object
(
    [ThingummyId] => 42
)
</code>```

In some cases these objects might be pretty deep, so getting at properties within requires drilling down several layers:

```<code>$response->Details->Detail[0]->Contents->Item[5]->Id
</code>```

And if I unwrap them before passing them back I can strip out a layer from consumers' code.

I know I'm probably being a little bit of an Architecture Astronaut here, but the latter style really bug me, so I've been working through my code to have my proxy methods just return the scalar value to the client code where there's no absolute need for a wrapper object.

My question is, am I actually making things more difficult for the consumers of my code? Would I be better off just leaving the return values wrapped in response objects so that everything is consistent, or is removing unneccessary layers of indirection/abstraction worthwhile?

答:
I've found it's better to be as consistent as possible so any consumer services know what to expect, it'll also be faster, easier and less buggy for yourself to simply return a response object around whatever data you're sending.

On the consumer side they can always use local vars to cut down the depth:

```<code>$cont = $response->Details->Detail[0]->Contents;
$cont->Item[5]->Id;
</code>```

In short: always do what will surprise your users the least, make it simple for them.

Body:
I've found it's better to be as consistent as possible so any consumer services know what to expect, it'll also be faster, easier and less buggy for yourself to simply return a response object around whatever data you're sending.

On the consumer side they can always use local vars to cut down the depth:

$cont = $response->Details->Detail[0]->Contents;
$cont->Item[5]->Id;

In short: always do what will surprise your users the least, make it simple for them.


问:
Web versus desktop development - is web development worse?
As a longtime desktop developer looking at doing our first large-scale web application, what are the pros and cons of doing web development?

Is developing a web application much worse than developing a desktop app?  E.g., is it more tedious or annoying?  Is the time to market much worse?  Is the web platform excessively limiting?  If the answer to any of these is yes, then why?

(And how does developing a Flash or Silverlight app compare?)

答:
the biggest re-think going from desktop to web is: the web app is inherently stateless

figure that part out, and you're good.


答: As others already said, xlsx is nothing but bunch of zipped XMLs, and there is (some) documentation online, so it's not big deal making it by hand. Anyways, there are lots of libraries around for different languages. We are using Ruby and there is a nice library called axlsx. We also brewed our own, called spreadshoot (more DSL-ish), but it's far from finished and not documented yet.</p>


问:
Should I write HTML or CSS first?
There are a lot of analogies for HTML/CSS development; which can be a bit confusing for a beginner.

HTML = foundations/house

CSS = walls/blueprint/wallpaper

Is there any best practice here? Which one should we write first?

答:
You should build a house first, then paint it.

An HTML document can stand on its own, even though it may look dull. A CSS style sheet cannot; it is nothing displayable (except as code) but instructions for display.

It’s a different issue that during painting, you may wish to do changes to the house. With real houses that’s usually not feasible, but in HTML+CSS development, it’s commonplace to notice that you need extra markup in your HTML document to make styling easier. (It’s less common than it used to be, thanks to powerful CSS3 selectors.)

Title: Should I write HTML or CSS first?


答: This depends on your actual role and primary goal of development. If the goal is to determine what should be shown to which extend at a web page, one should start with HTML. If the goal is to create a pleasant and uniform design, one may start with CSS. In both cases one might better first start with paper and pencil, and if the current goal is to develop a web application, one should not start with HTML or CSS at all. The best practice is to first think about what you want to develop and then divide the task into goals and sub-goals instead of just hacking everything together.</p>

Title: Should I write HTML or CSS first?

Body:
There are a lot of analogies for HTML/CSS development; which can be a bit confusing for a beginner.

HTML = foundations/house

CSS = walls/blueprint/wallpaper

Is there any best practice here? Which one should we write first?


答:
under the berne convention all source code has copyright protection in signatory countries. The protections this actually give vary from country to country, but the wholesale copying of the work is forbidden. There is not even a requirement to mark the work with a (c) symbol to obtain this protection.

However, the owner of the copyright can offer a license to people viewing the code granting entitlement to perform actions that otherwise would be reserved to the copyright holder.

This is how the GPL works. copyright is retained by the creator and everyone else is offered a licensed to use and make derived works.

In your specific case, I would question what you are wanting to achieve. Having copyright protection, and enforcing your rights are two very different things. For example, to enforce your rights, you would need to know that copying had occured, and have a way to prove it. Copyright protection does not prevent someone else coming up with the same idea independently. This is particularly problematic in software development, with the common software methodologies, common shared libraries etc, it is highly likely that two software developers when faced with the same problem would create simular code.


答:
It depends what I need it for...

If I'm building an application, I want to have easy access to the hosted database and I look for the appropriate DBMS to be available.  As an example, I want to be able to connect using Management Studio for an MSSQL database.

If I'm looking for domain name hosting, I want to be able to change the DNS info myself, or create an A record.

At the end of the day, I ask: Does it give me the tools to do what I need?

Title: How do you rate Hosting?


答:
A lot depends on the type of website / web application you make, and the kind of context in which it is going to be used.

In most cases, the best way to go is to build semantically sound HTML, then add CSS for standards-compliant browsers, and then applying non-intrusive hacks and rules (e.g., IE's conditional comments, -vendor-something CSS rules, javascript compliance layers, etc.) to support nonstandard browsers and enable vendor-specific features.

However, sometimes you have a bunch of independent web applications that share stylesheets (e.g. as part of a house style), and you may even be in the luxury position to control the HTML output of each one. In that case, writing the CSS first, and then tweaking the HTML to work with it, may be a better way to go. If you do this, the way to go is to first analyze what kind of page elements you are going to need, define classes for these, then write a some static test document that use them, write the stylesheets, and only then start writing the applications that use them.

In all honesty, though, I suspect that such a luxury position is extremely rare, and few companies actually recognize the value of a unified house style at the CSS level; more often, practicality dictates that a designer makes the house style, and then independent sets of stylesheets are written for each application that needs to follow it. The reason for this is, mainly, that most companies use off-the-shelf software with limited modification possibilities for at least some of their stack, and often, changing their HTML output to fit a given stylesheet is much harder (or even impossible for some proprietary packages) than rewriting the CSS. Additionally, the effort of maintaining a dozen sets of stylesheets is often underestimated, and some minor differences and quirks are deemed acceptable.

Title: Should I write HTML or CSS first?


问:
What is the difference between technical specifications and design documents?
What are technical specifications? Are they the same as design documents. If not, what is the difference and some examples?</p>

答:
Technical specifications, at least in the form of a technical design, are part of the design documents, along with, for example, requirements lists, functional designs, user stories, graphics design mockups, usability studies, UML diagrams, business process diagrams, data model specifications, etc.

Technical specifications of the type that you write after the fact, to document the finished product, are not generally part of the design documents, but they can be included in the set of design documents of a later version (for reference) or another product that relies on them.


问:
Formalizing a requirements spec written in narrative English
I have a fairly technical functionality requirements spec, expressed in English prose, produced by my project manager. It is structured as a collection of UI tabs, where the requirements for each tab are expressed as a lit of UI fields and a list of business rules for the tab.

Most business rules are for UI fields on a tab, e.g:

Must be alphanumeric, max length 20.

Must be a dropdown, with values from table x.

Is mandatory.

Is mandatory under certain conditions, e.g. another field is just populated, or has a specific value.

Then other business rules get a little more complex. The spec is for a job application, so the central business object (table) is the Applicant, and we have several other tables with one-to-many relationships with applicant, such as Degree, HighSchool, PreviousEmployer, Diploma, etc.

One such complex rule says a status field can only be assigned a certain value if a many-side record exists in at least one of the many-side tables. E.g. the Applicant has at least one HighSchool or at least one Diploma record.

I am looking for advice on how to codify these requirements into a more structured specification defined in terms of tables, fields, and relationships, especially for the conditional rules for fields and for the presence of related records. Any suggestions and advice will be most welcome, but I would be overjoyed if i could find an already defined system or structure for expressing things like this.

答: Try modeling it with MVC (model, view, control) objects. Separate data from presentation. For example, you have an education object with fields/properties for high school and diploma. The validator for this object has logic to ensure that education is not valid unless one of these is specified.</p>


答:
Design the house (grid layout) along with an idea of how it will be decorated; Build the house (HTML) with the grid; then decorate it (CSS style sheet).

After you have built the first house (HTML page), you can just apply the same decoration (CSS style sheet) as you go along.  You may tweak the decoration as you go along.

Eventually, you may want to redecorate (redo the CSS style sheet).

Title: Should I write HTML or CSS first?


问:
What problems will I face if I remove the concept of interfaces from my code?
I have been programming for many years but I am still not comfortable with the concept of "Interfaces". I try to use interfaces but many times I don't see a mandatory use for it. I think this is probably because the projects weren't so big, or because interfaces are more useful when teamwork is involved.

So, making another attempt to understand the importance of interfaces, here is my question:

What problems will I face if I remove the concept of interfaces from my code?

答:
An interface is very useful to hide implementation details. E.g. there might be a logging-class. It is not necessary to know how the logging is managed, the log messages may saved in a text file or in a database.
All logging-implementations might implement this interace:

```<code>public interface Logging {
void log(String message, int level)
}
</code>```

If you use the interface (and get the implementation via a fabric or dependency injection) you don't depend on a certain implementation, which might change over time. And you are available to change the implementation without any changes in the code.

Body:
An interface is very useful to hide implementation details. E.g. there might be a logging-class. It is not necessary to know how the logging is managed, the log messages may saved in a text file or in a database.
All logging-implementations might implement this interace:

public interface Logging {
void log(String message, int level)
}

If you use the interface (and get the implementation via a fabric or dependency injection) you don't depend on a certain implementation, which might change over time. And you are available to change the implementation without any changes in the code.


答:
I always use pen and paper first, full size paper, to-scale drawings.

That is if you don't have your design ironed out. If you are confident in your design, I have a balanced approach; html is the structure, css the glue. Keep building up in (HTML,CSS) concept 'tuples'.

```<code>(HTML,CSS) + (HTML,CSS) -> (bigHTML,bigCSS)

(bigHTML,bigHTML) + (bigHTML,bigCSS) -> (biggerHTML, biggerCSS)
</code>```

and so on.

That's how I do it, anyway.

Title: Should I write HTML or CSS first?

Body:
I always use pen and paper first, full size paper, to-scale drawings.

That is if you don't have your design ironed out. If you are confident in your design, I have a balanced approach; html is the structure, css the glue. Keep building up in (HTML,CSS) concept 'tuples'.

(HTML,CSS) + (HTML,CSS) -> (bigHTML,bigCSS)

(bigHTML,bigHTML) + (bigHTML,bigCSS) -> (biggerHTML, biggerCSS)

and so on.

That's how I do it, anyway.