答:
I've known a three person team that managed a 1.5 million line codebase and wasn't drowning in it. The important measurement is not how much code you're responsible for, but rather how much code you need to change in a certain increment of time.

There's also the risk assessment angle. If you are the only person that knows a piece of code, what is the opportunity cost that would be lost if you walk under a bus? Small companies usually don't do risk assessment like that, but this means that the continued success of the business is left to chance.


问:
What is MVC, really?
As a serious programmer, how do you answer the question What is MVC?

In my mind, MVC is sort of a nebulous topic — and because of that, if your audience is a learner, then you're free to describe it in general terms that are unlikely to be controversial.

However, if you are speaking to a knowledgeable audience, especially an interviewer, I have a hard time thinking of a direction to take that doesn't risk a reaction of "well that's not right!...".  We all have different real-world experience, and I haven't truly met the same MVC implementation pattern twice.

Specifically, there seem to be disagreements regarding strictness, component definition, separation of parts (what piece fits where), etc.

So, how should I explain MVC in a way that is correct, concise, and uncontroversial?

答:
MVC is a software design that separates the following components of a system or subsystem:

Model - Data about the state of the application or its components. May include routines for modification or access.

View - An interpretation of the data (model). This is only limited
to a visual representation, but could be audio, derived information
(e.g. statistics piped into another model object), etc. Furthermore, a single model may have
multiple views.

Control - Handles external input to the system invoking modifications on the model. The control/view may be closely related (in the case
of a UI). However, other external input (such as network commands),
may be processed which are completely independent of the view.

ContentLicense: CC BY-SA 3.0

Title: What is MVC, really?


问:
Knowledge and skills required for Sharepoint
I was just wondering what skills and technologies I need to know to in order to start a career path in Sharepoint. I know that it primarily depends on the job I am applying for but there must be a number of baseline skills that are common among most Sharepoint jobs.

Btw, I'm currently a CS student who has only learnt Java.

答: Assuming you want to develop for Sharepoint then .net and C# are a must</p>


答:
to begin with you won't need a development language nor development experience to learn how to use the out-of-the-box features and the basic CMS stuff, but when you start custom development you'll need: -

C#\VB & ASP.NET is a must, for custom development.

Common web development stuff like (HTML, CSS & JavaScript).

books i recommend: -

beginner

Beginning SharePoint 2010 Administration

Beginner SharePoint 2010 development

advanced

Professional SharePoint 2010 Administration

Professional SharePoint 2010 development

Title: Knowledge and skills required for Sharepoint

Body:
I was just wondering what skills and technologies I need to know to in order to start a career path in Sharepoint. I know that it primarily depends on the job I am applying for but there must be a number of baseline skills that are common among most Sharepoint jobs.

Btw, I'm currently a CS student who has only learnt Java.


问:
Does it hurt to learn bits of many programming languages?
I started my programming career with BASIC, during 9th grade. I learned a bit of BASIC by writing simple programs to add, subtract and to print. Then I went to the university and took Computer Information and Systems Engineering. In the first year I was taught C, and I have good command over it.

Next I learned C++ in the second year. It just taught me some knowledge of OOP. Now I am doing PHP (along with HTML). I have not mastered C++, BASIC or PHP. I am now planning to move to mobile development. But I feel that I have not covered everything in the languages I learned.

Does it really matter?

答:
I believe that the most important in programming is to understand the different  paradigms.

In your question, you mentioned Object-Oriented Programming (OOP). If you mastered this topic, you should be able to explain it using only pseudo-code and essentially some graphical modelling representation (such as UML class diagrams).

Whether you decide to use Java, C++ or C# (...) is up to you or to the company you work for, but what is really important is to understand/recognize the different problems and decide the best model to solve them. A very important way to solve problems in programming is to use the design patterns which you can discover in this reference book.

As for embedded languages, I believe the important thing is to understand the different problems associated with such technologies.

In a metaphoric way, I'd compare this to writing a good scientific book; what is important is the theory you expose, the problems you manage to solve, and so on. Whether you write the book in English, in French or in Japanese is not that important in the end.

That said, it is also important to know the specifics of a particular language if you want to specialize in that technology in order to exploit it very efficiently.


问:
Comma as a separator vs. comma as a delimiter
In this video, the speaker says:

"Some people get confused about how commas work. They think they
  should be delimiters rather than separators. Now you can think about
  them either way."

I don't understand the difference between a delimiter and a separator (if there is one). The implication in the video is that now (that trailing commas are valid), one can think of them as delimiters, rather than separators...

Btw the language in question is JavaScript. From my understanding, the comma token has two meanings:

as an operator (rarely used)

as a separator (in argument and parameter lists, array and object literals, etc.)

I'm not sure how a comma delimiter fits into this...

答:
A separator would be put between two values, separating them.

```<code>one,two,three
</code>```

A delimiter would delimit a field - it would be on both sides.

```<code>,one,two,three,
</code>```

When taken this way, it makes little difference, so long as one can extract the separate fields out.

This is a completely different issue to that of usage of a comma in a programming language such as javascript. It is about delimiting/separating values within a string.

Body:
A separator would be put between two values, separating them.

one,two,three

A delimiter would delimit a field - it would be on both sides.

,one,two,three,

When taken this way, it makes little difference, so long as one can extract the separate fields out.

This is a completely different issue to that of usage of a comma in a programming language such as javascript. It is about delimiting/separating values within a string.


答:
If you consider the comma as a separator, you use a comma between two items of a sequence to separate them, if you consider it as a delimiter, you put it after each item to indicate where an item ends. See the examples below:

Comma as a separator

```<code>var myCars = ["Saab", "Volvo", "BMW" ];
</code>```

Comma as a delimiter

```<code>var myCars = ["Saab", "Volvo", "BMW", ];
</code>```

I think the video says that you can think of commas both as separators and delimiters because both array examples above are valid. On the other hand in Javascript you can only use the comma as a separator in the parameter list of a function, e.g.

```<code>foo(a, b, c) // separator, OK
</code>```

is valid whereas

```<code>foo(a, b, c,) // delimiter, NOT OK!
</code>```

is not valid.

EDIT

As far as I understand, according to the wikipedia page a separator is a special case of a delimiter, namely one that is put between the different text regions whose boundaries need to be marked. In fact, the wikipedia page names comma-separated values as an example use of delimiters.
So, in general you can use delimiters in different ways: before, after, on both sides of the portion of text to be marked.

The reason why I interpreted delimiter as "marker that is put after an item" in the Javascript context was motivated by the array literal example, which is valid also for C, C++, and Java (I think I have seen at least one question on stack overflow regarding this topic).

Another example of similar but different use of a character is that of semicolon as a statement delimiter (C, C++, Java, Ada, ...) and as a statement separator (Pascal). Therefore

```<code>if (a > 0)
    printf("Positive\n");
else
    printf("Non positive\n");
</code>```

is correct C code whereas

```<code>IF a > 0 THEN
    WriteLn('Positive'); (* Syntax error here! *)
ELSE
    WriteLn('Non positive');
</code>```

is no correct Pascal code.

Maybe terminator would be a better / less ambiguous term than delimiter?
E.g. one could formulate the quote as follows: "Some people get confused about how commas work. They think they should be item terminators rather than item separators. Now (in many cases) you can think about them either way."

Title: Comma as a separator vs. comma as a delimiter

Body:
In this video, the speaker says:

"Some people get confused about how commas work. They think they
  should be delimiters rather than separators. Now you can think about
  them either way."

I don't understand the difference between a delimiter and a separator (if there is one). The implication in the video is that now (that trailing commas are valid), one can think of them as delimiters, rather than separators...

Btw the language in question is JavaScript. From my understanding, the comma token has two meanings:

as an operator (rarely used)

as a separator (in argument and parameter lists, array and object literals, etc.)

I'm not sure how a comma delimiter fits into this...

Body:
If you consider the comma as a separator, you use a comma between two items of a sequence to separate them, if you consider it as a delimiter, you put it after each item to indicate where an item ends. See the examples below:

Comma as a separator

var myCars = ["Saab", "Volvo", "BMW" ];

Comma as a delimiter

var myCars = ["Saab", "Volvo", "BMW", ];

I think the video says that you can think of commas both as separators and delimiters because both array examples above are valid. On the other hand in Javascript you can only use the comma as a separator in the parameter list of a function, e.g.

foo(a, b, c) // separator, OK

is valid whereas

foo(a, b, c,) // delimiter, NOT OK!

is not valid.

EDIT

As far as I understand, according to the wikipedia page a separator is a special case of a delimiter, namely one that is put between the different text regions whose boundaries need to be marked. In fact, the wikipedia page names comma-separated values as an example use of delimiters.
So, in general you can use delimiters in different ways: before, after, on both sides of the portion of text to be marked.

The reason why I interpreted delimiter as "marker that is put after an item" in the Javascript context was motivated by the array literal example, which is valid also for C, C++, and Java (I think I have seen at least one question on stack overflow regarding this topic).

Another example of similar but different use of a character is that of semicolon as a statement delimiter (C, C++, Java, Ada, ...) and as a statement separator (Pascal). Therefore

if (a > 0)
    printf("Positive\n");
else
    printf("Non positive\n");

is correct C code whereas

IF a > 0 THEN
    WriteLn('Positive'); (* Syntax error here! *)
ELSE
    WriteLn('Non positive');

is no correct Pascal code.

Maybe terminator would be a better / less ambiguous term than delimiter?
E.g. one could formulate the quote as follows: "Some people get confused about how commas work. They think they should be item terminators rather than item separators. Now (in many cases) you can think about them either way."


问:
Is the GoF book still the one to read?

Possible Duplicate:

  Is there a canonical book on design patterns?

I'd like to read a design patterns book. GoF for sure is the one to read. But after 15 years is it still valid, I mean isn't there an updated one?

Something like "Charles Darwin On the origin of species" is a very important book, and some main concepts are still valid, anyway today (2010) one would read another book to study the subject.

In this question the main suggestions are the Head First and GoF books. But Head first is not a replacement for GoF.

So any suggestion or should I stick with GoF?

答: I fear the day the patterns in that book will not exist anymore. That day is likely never to come. Get the book.</p>

ContentLicense: CC BY-SA 2.5

Title: Is the GoF book still the one to read?


问:
What's the best place for a high school programmer to get his work noticed?
I'm a 16 year old high school student, with a passion for computer programming.
I'm in grade 11, and I've been learning it as part of the school syllabus for about 8 months.
I've gone beyond what's being taught at school, and witten a few (reasonably good) applications. The language that I program in is C++, on the windows platform.
Eventually I'd like to major in CS at a good college and then work as a programmer.

The specific questions that I have are:

What is a good place for me to get my work noticed ?

Are there any journals, or publications specifically for young programmers ?

If not publications, then are there any good blogs, or is it just better to start your own ?

Is there anything else, that would help me get noticed as a programmer ?

I've tried to be as objective as possible.

If all this was tl;dr:
What's the best way to get noticed as a young programmer ?

Edit:
I am not looking to get hired straight out of high school
The aim is not to impress the community as a professional programmer.
This is with intent towards college applications where having your work seen and critiqued by other people will improve your application. I am not looking to earn money from what I've written (so far).

答: If you are into games, try participating in Ludum Dare. A good game there will get some renown.</p>


答:
Learning multiple programming languages is good practice and is necessary nowadays; as many times you can't always use your language of choice for everything.

The benefits of seeing how other languages do things will help you as a programmer; even if occassionally when you are jumping around you make syntactical mistakes (e.g., is checking for inequality !=, ~= or <>).  You should be careful though to learn more than just the syntax of a language, but best practices within a language as well as just general good software engineering skills.  Stuff if you learned C and then learned C++ you should make sure when you are writing C++ code that it is in the style of C++ code (rather than just C with a few new keywords.  That is you have multiple classes/objects, prefer references/smart pointers over raw pointers, etc.

Title: Does it hurt to learn bits of many programming languages?

Body:
I started my programming career with BASIC, during 9th grade. I learned a bit of BASIC by writing simple programs to add, subtract and to print. Then I went to the university and took Computer Information and Systems Engineering. In the first year I was taught C, and I have good command over it.

Next I learned C++ in the second year. It just taught me some knowledge of OOP. Now I am doing PHP (along with HTML). I have not mastered C++, BASIC or PHP. I am now planning to move to mobile development. But I feel that I have not covered everything in the languages I learned.

Does it really matter?


问:
Suggesting albums based on friends' top ten lists
Just wondering if someone could suggest a good algorithm in the collaborative filtering vein that I could use to suggest music choices based on top ten lists.

This is a personal project, I am a member of a private music blog where most of the users recently submitted "best of 2011" lists.  The lists range in size (say 10-50 albums) and are not ranked.  Have around 100 lists.

Basically hoping to give each user some recommendations based on the correlation of their list with everyone else's.

答:
There are a number of collaborative filtering methods you can research.  As an alternative, I'm going to suggest something very pedestrian instead that should be easy to code and should give you reasonable results.  Caveat: This is just off the top of my head, and may be very inferior to some of the more established methods out there, but it seems like a fun topic so I'll take a shot.

Since the lists are not ranked, you can compare each list to each other list.  The number of common albums should be easily determined (assuming album names are not misspeled).  Use that as a weight for each other album on everyone else's lists.  So each album you don't have that appears on the list of someone with whom you share at least one album in common will appear in your recommendation list, weighted by the albums you have in common with that user.  You will then aggregate the scores for each album across all other users.

So if you have 5 albums in common with User B, you would assign a weight of 5 to each album on that user's list that isn't on yours.  Moving to User C, you would do the same.  If User C has 3 common albums with you, then any albums on both User B and User C's list that aren't on yours now have a weight of 8.

You may want to increase the weight for lists where you share a lot of albums so those recommendations are even more valuable.  In other words, a list with 10 common albums might get a weight of higher than 10, so it would count for more than 10 lists where you share a single album.  This should be easy enough to tweak and test.

Once you have run through every other list, you can truncate your recommendation list to top 10 or something reasonable.

OwnerDisplayName: nycdan


答:
I am answering this because you said "Start with SharePoint" and not "Start with SharePoint Development" and this is not an indictment or an endorsement of SharePoint but ...

If you are economically hard up and are looking for a minimum set of skills, I can say with some authority, because our company does a lot of SharePoint work, that many many companies actually are not interested in any kind of customization or development work of any type. Most of the 'development' work, actually ends up being a lot of infrastructure work, setting of lists, configuring configuring configuring, maybe some skinning, maybe deploying some off of the shelf components, maybe a workflow here and there if they are fancy.

So it is conceivable that at a minimum all you might need is a SharePoint admin certification and some mad interviewing skills and you might be able to land a job somewhere doing SharePoint. However, the HUGE caveat here is that will only take you so far. If you do not have knowledge of the ASP.NET framework that it is built on top of, much less web programming in general, or any kind of C#/VB if you are doing a workflow, then you will run into a road block pretty fast. I'd direct you at @OmarQa answer for more info.

One of the most brilliant developers I ever met worked primarily in custom SharePoint development and was deep in code most days. Another I knew came from a non-technical background and tired to do a little coding as possible but that what the people wanted so he did well. So keep in mind there is a huge spectrum to work within.


问:
I want to write a 2-player web-based board game. Which framework should I use?
I am a C# software developer.  I was recently approached by a client to develop a multiplayer board game (max 4 players).  I fiddled around with WCF, WPF and EF 4.1 to get something going but I keep running into small stumbling blocks.  It certainly does appear that integrating all these technologies into one solution is problematic.

I do not have extensive experience in WPF/WCF but I find the concepts easy to grasp.  It's just that I keep running into little problems which are huge stumbling blocks.

My thoughts were to first create a WCF service to manage the boards and rules.  I would then turn to the UI (possibly Silverlight/WPF).

I am actually at the point where I think I should try a framework or even venture to PHP/Ruby/Python.

The requirements are simple:

Web based

Turn based

Board game

Database backend

As a C# developer (possibly a poor one), what would you suggest?

答:
IMO, use whatever technologies you want, but remember to start small.  Game development gets complicated quick.  Think about something like checkers that has very few rules - you still need to be able to do a number of things before you can even play a game.

Can you draw a basic board on the screen?  Ok, now color alternating squares red and black.  Can you draw a piece on the board?  How about all of the pieces?  Approach the problem like this and strive to make small improvements, not huge jumps in functionality - you'll stay saner longer. :)

There's a number of blogs / articles on the web that deal with game development and C# game development in particular.  I've always found the Coding4Fun blog to be very enlightening.  That might function as a good starting point.


问:
How to reply to incomplete requests from potential customers?
Working as a freelancer, I receive many weird, invalid or incomplete requests from the actual or potential customers. The most frequent case is this one:

Hi,

I need a website where people can register and there are also postings and ratings. How much will it cost to me?

Thank you.

The request sucks, but it doesn't mean that a customer like this is not worth it. This person doesn't know how to make a request correctly, but with a bit of effort and a bit of learning and advice, this person may become a valuable customer who will not waste my time.

For a while, I just replied by asking to provide details. They never do.

Recently, I decided to reply in a more detailed way, explaining why is it impossible to give a price (except telling that it would be somewhere between $500 and $50 000). First I just made a simple explanation, telling that their description of the project is too sparse. Then I added further info, metaphors, etc., or by making comparisons with other domains which are better known by people with no technical background. For example:

“Imagine you want to build a two-storey house. Do you believe it's possible to determine the cost of building a house just by knowing the number of storeys? You probably need to provide much more details: is it built with rock or wood? Are there solar panels on the roof? Is there a swimming pool in the backyard?

A large Victorian-style house using the newest technologies, with two garages, a large terrace, etc. will cost much more than an tiny modest two-storey house for a family who really don't have too much money to spend.”

It's still not working: those potential customers never respond.

I also tried the "let me gather the project requirements for you from scratch and do the specification and architecture, but don't forget to pay me for this" technique, but it looks like scam¹. In all cases, in my country (France), this never works with new customers for several reasons.

Some hints show me that some of those people actually succeed finding a developer and succeed with their project. It means that my approach with those potential customers fails, while there is one approach used by someone else which works well.

How to reply to such price requests, considering that those people don't know me, don't trust me yet, don't want to spend days writing a detailed document describing every functionality of the project, and sometimes don't even know precisely what they want, but are not ready to pay you thousands of dollars just for requirements, specification and architecture steps?

¹ Most projects are small enough and have tiny funding; most customers don't bother to know that the source code is clean and maintainable, that it was regularly refactored, and that you have unit and integration tests. They want to pay less, now, no matter how expensive it would be later to maintain the codebase. In this context, talking about functional and non functional requirements, architecture etc., is perceived like the attempt either to waste half of the customer's money doing marketing jibber-jabber instead of writing code, or to scam them by making them pay for something they don't need nor understand, and then disappearing with their money when it will come to actually writing source code. They don't know that you are a professional, and they even don't care.

答:
Are you sure, you really want such customers? I have managed many projects that were started by someone else who underestimated the effort by the factor of five to ten. The result was a huge mess in the project, my customer having serious trouble with his customers and much more serious trouble between my customer and his previous supplier including ugly lawsuits. My job was to turn the software ruins left by others into functional systems. I was always payed well for this. Nobody asked about a price. That was suddenly unimportant. As long as the customer beliefs in you, as long as he has the sound believe, that you finally get the thing going, they pay you almost every price - per hour of course, not a fixed price.

Certainly, you can fool around as other answers suggest and try to hook them up with low prices and inappropriate results. But consider the price - for you. Do you really need trouble? And that's for sure, if you fool around or just make a wild guess what they might need. There are a lot of freelancers / students / hobbyists / newbies / unemployed / ... out there, that do the job for peanuts. Are you really in need of that? I belief, Sting is right: Be yourself, no matter what they say. For me that means in this case: Stick to your professionalism. And forget such customers, if they are unwilling to make a fair deal. Or offer them your help later - for twice the price.

You gave the solution already:

They want to pay less, now, no matter how expensive it would be later to maintain the codebase.

Right. So, try to be later - be the one that maintains the mess "no matter how expensive it would be". That's common business: The liquidators earn most of all and they work for advance payment only.

Good luck!


问:
Best practices for moving large MS Access application towards .Net?
We have a really huge MS Access application developed in-house initially for our personal needs which then was turned into a commercial software and successfully sold. The software is a sort of "all-round-software-for-your-business" and contains several modules including Document Management System, Enterprise Resource Planning, Inventory Management, Customer Relationship Management, Data Analysis etc. We are quite satisfied with the current functionality of the application, but in order to meet the requests from our clients we realize that we have to move to something new.

We decided to gradually move our application towards .Net because we can stick to Visual Basic .Net: even though it is a new language for most of the developers here, we have deep knowledge of VBA and several dozen small projects implemented in VB6.

We already started moving the data layer functionality of our application to MS SQL Server, so that every data manipulation and search is performed directly on the server.

What we are looking for are best practices for gradually moving our extensive GUI (about 500-600 different forms including subforms, about 200 reports with multi-language support etc). Following the recent request from our potential customer to implement asynchronous data encryption on documents in DMS we would be also happy to completely decouple this part from MS Access and implement it in .Net.

The question is how to seamlessly integrate the .Net application with the existing MS Access system, so that we can invoke it with certain parameters (user rights etc.) and enable data exchange between this application and running MS Access application.

EDIT:

We tried to apply some practices from Martin Fowler's book "Enterprise intergration patterns" to achieve some integration between the MS Access application and some small utilities we implemented in .Net for various needs. But we only managed to use the "shared database" pattern and weren't really satisfied with our solution.

For instance, we implemented a small utility running as a Windows service which automatically downloads all messages from the mail server using POP3 connection and stores them into one table, whereas all attachments are stored in file system.

What we mainly did is we used ADO.NET to directly access MS Access databases in MDB format and populate table with some processed data (like the data about mail messages from the example above: we have fields for FROM, TO, CC, BCC, Subject and Body).

There is absolutely no problem to work with MDB data format from .Net, moreover we don't want to stay with MDB and upsized almost everything to MS SQL Server 2008 -- this gives us much more freedom concerning the data management and scalability.

The main problem here is that we don't know how to implement a sort of "callback" in Access so that we can trigger the execution of certain VBA code on data update.

We had great hopes with MS Access 2010 supporting update and insert triggers for data tables, but it turned out that we can only use MS Access Macros for these triggers and there is no way to execute any custom VBA code within the trigger.

We also tried some solutions with sending keystrokes directly to MS Access window to mimick some user-invoked data requery. This works, but we don't think this is a realiable solution that can be used in production.

We also looked into DDE for MS Access, but we couldn't find any good sample solution implementing DDE commands and using them for in-memory data and command exchange.

So, the main problem is to have MS Access and .Net application co-exist and interact with each other.

EDIT2:

I forgot to mention what we also implemented MSMQ library in VBA for message passing between .Net and MS Access, the problem was again the lack of callback here: we really had to poll the queue for new messages and given that VBA does not really support multi-threading it wasn't really a nice solution.

答: I am amazed you did all that with Access.  There is a very important question you not asking .NET Windows Forms or .NET WPF.   WPF has a steeper learning curve but in my opinion it is more powerful with a better UI.   We recently converted our commercial application from Forms to WPF and we are already getting more sales.  We also added new features but the WPF UI is just sexier.  Review your table design and clean it up - now is the time.  Make sure you are declaring all you FKs.  In Access you can add stuff on the fly pretty easy some times that stuff slips.  If this is your first WPF UI build some prototypes.  We could pack more into WPF that the new app has more features, less screens, and less a lot less code.  You will go from hating XAML to how loving it.  Consider a structure like MVVM. You may decide not to use MVVM (we did not) but at make that decision.</p>


问:
Is it worth listing testing or self-learning repositories on my résumé?
I have a GitHub repository with toy programs that I write when I learn something. For example, when I read an about an algorithms or data structures, I write up a quick implementation of of it to make sure that it works and I understand it.

I sometimes solve algorithm and data structure puzzles and that gets pushed into the repository.

Would this repository be worth linking on my résumé, or would it actually be a detriment to my chances of getting hired?

答:
A resume has exactly one purpose: to advance you to the next stage of the hiring process.  Anything that impedes that purpose is a bad idea.  As a former hiring manager, I can tell you that the amount of time I had available for any single candidate during the initial screening process did not allow for more than reading the resume and deciding whether to shred it or not.  Folks who sent me 7-page resumes (really!) didn't get the attention they desired.  Folks who sent me resumes that were primarily URLs didn't either.  Later, after I was more-invested in the remaining candidates, perhaps.

A portfolio is a Good Thing.  That's especially true in certain aspects of our business, like web design.  But except if you're a Graphic Artist, your portfolio shouldn't be your introduction.


答: I think it won't hurt to learn a bit of many different languages, but at the same time you should learn at least one or two in depth.</p>


问:
Python: What is the point of using "import"?
I am not very clear on this aspect. Let's say you have a bunch of .py files that are their own separate modules.

Why does each .py file need to import the others when they use that class? Or do they? Because I was pretty sure that other languages (Java, for instance), did not require import when referring to classes/files in the same directory. I might be wrong.

答:
Imagine you had this code in python:

```<code>foo = MyObject()
fo.bar()
</code>```

Obviously, we've got a typo and fo should have been foo. Right now python says:

```<code>Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'fo' is not defined
</code>```

But with implicit class loading it might say:

```<code>Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named fo
</code>```

which would be confusing. Worse yet, if you misspelled a variable name that just happened to be the name of a module, you would get an even more confusing error as you tried to treat that module as if it were your variable. Python can't tell whether something is a class name, object or whatever.

Java, on the other hand, I believe can tell from the syntax whether a certain identifier refers to a class or something else. Thus it has no problem with producing an appropriate error message.

Overall, it fits into the Python philosophy of being explicit rather then implicit. They figure its better to explicitly import a module rather than have it imported automatically. The error message issue is factor that plays into the decision.

Some have suggested that there would be a large runtime cost to implicit imports. I don't think so. What happens is something like this:

LOAD_GLOBAL opcode invoked with name "foo"

globals dictionary checked for "foo"

builtins dictionary checked for "foo"

If foo found, store in globals and continue on

If foo not found, raise NameError

To support implicit module loading we could do:

LOAD_GLOBAL opcode invoked with name "foo"

globals dictionary checked for "foo"

builtins dictionary checked for "foo"

if the above fail, try import foo

If foo found, store in globals and continue on

If foo not found, raise NameError

The first time the module is used, it would take a bit longer because it has to search through other dictionaries first. But that's only the first time, and shouldn't be significant in terms of whole program runtime.

There would be a significant cost, in the case of misspelled variable names. When they occour, python would waste time reading the disk trying to find the module. But if that happens your program is about to die with a traceback anyways and the performance isn't a big concern.

Body:
Imagine you had this code in python:

foo = MyObject()
fo.bar()

Obviously, we've got a typo and fo should have been foo. Right now python says:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'fo' is not defined

But with implicit class loading it might say:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named fo

which would be confusing. Worse yet, if you misspelled a variable name that just happened to be the name of a module, you would get an even more confusing error as you tried to treat that module as if it were your variable. Python can't tell whether something is a class name, object or whatever.

Java, on the other hand, I believe can tell from the syntax whether a certain identifier refers to a class or something else. Thus it has no problem with producing an appropriate error message.

Overall, it fits into the Python philosophy of being explicit rather then implicit. They figure its better to explicitly import a module rather than have it imported automatically. The error message issue is factor that plays into the decision.

Some have suggested that there would be a large runtime cost to implicit imports. I don't think so. What happens is something like this:

LOAD_GLOBAL opcode invoked with name "foo"

globals dictionary checked for "foo"

builtins dictionary checked for "foo"

If foo found, store in globals and continue on

If foo not found, raise NameError

To support implicit module loading we could do:

LOAD_GLOBAL opcode invoked with name "foo"

globals dictionary checked for "foo"

builtins dictionary checked for "foo"

if the above fail, try import foo

If foo found, store in globals and continue on

If foo not found, raise NameError

The first time the module is used, it would take a bit longer because it has to search through other dictionaries first. But that's only the first time, and shouldn't be significant in terms of whole program runtime.

There would be a significant cost, in the case of misspelled variable names. When they occour, python would waste time reading the disk trying to find the module. But if that happens your program is about to die with a traceback anyways and the performance isn't a big concern.


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

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

Can anybody explain that to me?

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

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

答:
If your code is open source, the restrictions are very light-weight: you cannot export your code to countries or entities that have been restricted and you must notify the government of the location where they can download source and object files. You must make some effort to prevent the code from being downloaded by Cuba, Iran, Libya, North Korea, Syria, and Sudan. You must ask all your users to not export to these nations.

You will be expected to prepare lists of all "packages" and "files" that contain the encryption primitives. (I recall that we were allowed to skip hashing primitives that were used only for authentication or integrity controls.)

If your code is not open source, you must file for exceptions on your own code. I expect you'll need to prepare similar lists of source / object files and which algorithms are implemented for what mechanisms. I further expect it'll require review before the license is granted.

While I believe all my information is correct as of 30 December 2011, I am not a lawyer and cannot provide you with legal advice. These are simply pointers to currently-available US government resources.

OwnerDisplayName: Marco W.

OwnerDisplayName: sarnold


答:
Are you writing your own cryptographic routines or merely calling a 3rd party routine?

The reason I ask is because if for example on Windows you are using one of the Microsoft provided routines then you are not the one publishing or distributing the controlled software, in which case your software would not be under any restriction.

Title: Programmers' concerns about export restrictions from the United States

Body:
Which aspects do I need to consider when designing and publishing software that must meet the US export restrictions for cryptographic software?

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

Can anybody explain that to me?

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

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


问:
Can we use Java for commercial use?
The Java is GPL license (reference from wikipedia). I am not sure I can use it in in commercial projects. I already have a website written in Java and I plan to use this for commercial use. Is that illegal?</p>

答:
After movement to Java BLC the entire licensing of Java usage is subject to interpretation which means "contact Oracle if you want to really sure".

That means pay if they want you to pay. As per BLC, Java can be freely used for "General Purpose Desktop Computers and Servers" (as in http://www.oracle.com/technetwork/java/javase/terms/license/index.html) , whose definition includes words "general purpose computing".

I don't know if my computing is a general purpose computing - are you sure that yours is? Oracle have also added clauses like "used for general computing functions under end user control".

Check with your legal department.

OwnerDisplayName: Shisoft

Title: Can we use Java for commercial use?


问:
User friendly scheduling feature
I'm trying to add a scheduling feature to my web scraping application that will let the user schedule scraping jobs so he can, for instance, perform a job every Monday, or every 2 hours or stuff like that.

On one end, I could make a very simple scheduler that let you pick a specific date and time and pick a time interval that would indicate how often to execute the job starting at the specified date and time. So if, for instance, I pick Dec 31 at 2:00 pm and choose 1 day as my interval, the job would run every day at 2:00 pm starting Dec 31. But what if he wants to run the job every Saturday and Sunday, or three times a day on Sundays?

On the other end, I could embed some kind of scripting language that will let the user use any logic he wants, but this would be overkill for me and for the user. He doesn't need to run a job every day of the month that is prime number or anything like that.

So this is a common sense question, not a programming one. How would you implement this, or, do you know any similar kind of scheduling job in any other kind of application? I looked at the scheduler in my antivirus but this one is extremely plain and simple.

答: I would think that something like the Windows Task Scheduler model would provide enough versatility for what your users are probably going to want.  This is a task where I would take a YAGNI approach.  Implement something basic and straightforward that covers most scenarios and then only work to include the exceptional cases on demand.</p>

Title: User friendly scheduling feature


答:
I would develop a UI for the most common scenarios.  Once a day at a given time may be common.  Or maybe continuously on a specific interval will be more common (for example, every half an hour).

If you want to offer more flexibility, I suggest allowing CRON expressions.  No need for a custom scripting, CRON is it when it comes to scheduling.  To allow ultimate flexibility, simply allow multiple CRON expressions.

One major advantage of CRON expressions, is that you will almost certainly have an scheduler implementation available to you that can accept them.  There is Quartz for Java, Quartz.Net, and of course the cron daemon on any unix based system.  I have used Quartz.Net with great success in the manner I described (simple config for daily and interval timing, with CRON used for more expressive timing)

Title: User friendly scheduling feature

Body:
I'm trying to add a scheduling feature to my web scraping application that will let the user schedule scraping jobs so he can, for instance, perform a job every Monday, or every 2 hours or stuff like that.

On one end, I could make a very simple scheduler that let you pick a specific date and time and pick a time interval that would indicate how often to execute the job starting at the specified date and time. So if, for instance, I pick Dec 31 at 2:00 pm and choose 1 day as my interval, the job would run every day at 2:00 pm starting Dec 31. But what if he wants to run the job every Saturday and Sunday, or three times a day on Sundays?

On the other end, I could embed some kind of scripting language that will let the user use any logic he wants, but this would be overkill for me and for the user. He doesn't need to run a job every day of the month that is prime number or anything like that.

So this is a common sense question, not a programming one. How would you implement this, or, do you know any similar kind of scheduling job in any other kind of application? I looked at the scheduler in my antivirus but this one is extremely plain and simple.


答:
Why even do this at all? The operating system already has a scheduling service built-in (e.g. cron on *nix, Task Scheduler on Windows, etc). Just provide the ability to launch your process from the command-line launch and let the operating system take care of it.

If you like, you could build a UI in your application that interfaces with the operating system's built-in mechanism to provide the most common configurations, but for anything more complicated, scheduling is basically a solved problem.

Title: User friendly scheduling feature


答:
Give them quotes for specific features:

Sir, you wish your users to be able to register a new account, and be able to log back into that account at some point in the future? That will cost $199.99.

You wish to have the ability to post articles onto your website? The cost for that feature is an additional $125.

And then you can offer a discount for the number of features that they request, say, 1.5% for each feature. You want a site that includes registration, blogging, a forum, and a search box? That's 4 separate features, so you'll get a 6% discount, bringing the total cost to $672 (a savings of $28!) This will encourage your new customer to request more features.

You should define what each feature includes, and the effort involved. This will help your customer to know what to expect from their website when it is finished.

Having a list of prices is always a good idea as well, along with the cost of maintenance into the future...

Title: How to reply to incomplete requests from potential customers?

Body:
Working as a freelancer, I receive many weird, invalid or incomplete requests from the actual or potential customers. The most frequent case is this one:

Hi,

I need a website where people can register and there are also postings and ratings. How much will it cost to me?

Thank you.

The request sucks, but it doesn't mean that a customer like this is not worth it. This person doesn't know how to make a request correctly, but with a bit of effort and a bit of learning and advice, this person may become a valuable customer who will not waste my time.

For a while, I just replied by asking to provide details. They never do.

Recently, I decided to reply in a more detailed way, explaining why is it impossible to give a price (except telling that it would be somewhere between $500 and $50 000). First I just made a simple explanation, telling that their description of the project is too sparse. Then I added further info, metaphors, etc., or by making comparisons with other domains which are better known by people with no technical background. For example:

“Imagine you want to build a two-storey house. Do you believe it's possible to determine the cost of building a house just by knowing the number of storeys? You probably need to provide much more details: is it built with rock or wood? Are there solar panels on the roof? Is there a swimming pool in the backyard?

A large Victorian-style house using the newest technologies, with two garages, a large terrace, etc. will cost much more than an tiny modest two-storey house for a family who really don't have too much money to spend.”

It's still not working: those potential customers never respond.

I also tried the "let me gather the project requirements for you from scratch and do the specification and architecture, but don't forget to pay me for this" technique, but it looks like scam¹. In all cases, in my country (France), this never works with new customers for several reasons.

Some hints show me that some of those people actually succeed finding a developer and succeed with their project. It means that my approach with those potential customers fails, while there is one approach used by someone else which works well.

How to reply to such price requests, considering that those people don't know me, don't trust me yet, don't want to spend days writing a detailed document describing every functionality of the project, and sometimes don't even know precisely what they want, but are not ready to pay you thousands of dollars just for requirements, specification and architecture steps?

¹ Most projects are small enough and have tiny funding; most customers don't bother to know that the source code is clean and maintainable, that it was regularly refactored, and that you have unit and integration tests. They want to pay less, now, no matter how expensive it would be later to maintain the codebase. In this context, talking about functional and non functional requirements, architecture etc., is perceived like the attempt either to waste half of the customer's money doing marketing jibber-jabber instead of writing code, or to scam them by making them pay for something they don't need nor understand, and then disappearing with their money when it will come to actually writing source code. They don't know that you are a professional, and they even don't care.


问:
What does the 'R' in x64 register names stand for?
I know the 32 bit registers were named like the 16 bit registers with an 'E' prefix to mean extended. I've always assumed that meant extended from 16 to 32 bits although I've never seen that explicitly stated.

I was trying to find out what the 'R' stands for but my google skills have failed me. Anyone know?

答:
In the earlier processors, not all registers were equal:

There was not enough space on the chips to have an adder unit for each register.

With 8 bits, there weren't enough opcodes available for all possible combinations of source and destination.

So assuming that one specific register was always implicated when the adder was involved, made the chip less complex and opcodes shorter.

E.g. the 6510 (used in Commodore 64) could only add using register A, and indexing used either X or Y. There are INC X and INC Y instructions, but no INC A.

As registers had different usages, mnemonics were chosen reflecting their usage. E.g. the A, X, and Y in the 6510 (instead of A, B, and C).

The names in the 8086 are chosen to reflect their usage as well. With 4 general purpose registers, it was logical to name them AX, BX, CX, and DX. Additional indexing registers were called BP and SP (mnemonic: Base Pointer, Stack Pointer).

As many opcodes were extended to 16 bits, there was some space to indicate which one out of four register was used. However, some of the historical reasons still applied, as CX was a bit special: REP and the likes, which are 8 bit opcodes, always use CX as the counter. A simple mnemonic, CX = Counter, helps to remember which one is used.

The opcodes for successors to the 8086 had to be backwards compatible, and are a mess as a result of the variable length opcodes. When 32 bit busses became more common, processors with fixed opcode length were tried. This simplifies the decoding part of the CPU, which freed up space that could be used for e.g. more registers.

Processors that followed this line of thought are called RISC processors (Reduced Instruction Set CPU), to contrast with the CISC (Complex Instruction Set CPU).

More registers results in less spill-over to memory. Basically, registers are the fastest cache available, so increasing the number of registers is a good idea, even  nowadays. The lack of specialized instructions was (hopefully more than) compensated by the faster through-put of simple instructions.

Fixed length 32 bit opcodes have enough space to include a source, a second source, an operation, and a destination. SPARC managed to wringle 5 bits for each of the source, second source, and destination, and therefor had 32 registers visible at the same time.

32 registers are too many to use letters, and they were mostly equal anyway, so numbering them was the obvious choice. The 'R' was used to distinguish them from the constants 0..31, and 'R' was an easy mnemonic for Register. Therefore: R0..R31.

Over the years, the Pentium and its successors have maintained backwards compatiblity. However, many of the more succesfull RISC ideas were incorperated as well. Frequently, those new, RISC-like instructions will run faster than the backwards compatible versions.

The number of registers was also increased by Intel, to reduce the number of memory accesses.

And apparently, Intel finally has started to use the R-notation. Backwards compatibility will ensure that AX, BX, ... will stay, but I would bet that AX is just a synonym for e.g. R0.

Disclaimer: The above is my view on history. It will be incomplete as I wasn't around to witness the earlier parts of history first hand. Nevertheless, I hope it is useful to some.


答:
The problem is that most people who want a website don't know what is involved in building one.  It's magic to them.  They just see it as a big Word document that someone wrote up and put on the web.  How hard can that be?

Because they don't know what is involved, they see your attempts at clarification as trying to jack up the price, and feed them BS to baffle and confuse them into accepting your inflated pricing.

The jobs that people get, probably started by someone just saying "Sure, it'll cost foo Euros, and take bar weeks".  Then, as the system was sketeched out, the price point changed (or someone worked themselves to death trying to meet their original ballpark estimate).

You don't want to work in either of those situations if you don't have to.  But finding knowledgeable customers is a tough job, and requires pretty much full-time sales staff to go looking for them.

Here's another issue, they may have submitted their request to 30 different freelancers, and you never got a response back because 5 of them responded with a bid, or maybe someone responded before you did and they ran with that person.

The most likely answer, however, is that they were not expecting what they heard from people.  They thought it would be a simple job costing a few hundred, and had sticker shock... so never called you back.

In the end, as a freelancer, you are going to have to build relationships with clients.. so they trust you and your estimates.  That's the only thing that counts.


答:
First, you have to determine who the asker of the question is, and what sort of answer he's looking for.  You respond to this question with another question, such as "In what sense?"

You can ask if they are referring to MVC in general, a particular implementation of MVC (ie asp.net MVC, spring MVC, smalltalk MVC, etc..), what it is technically, what it is philisophically (yes, it has a philosophy as well), etc..

If this is a question on a test, and you can't ask the asker to clarify, then you will have to guess based on the context.

A good, simple answer is:

MVC is a software user interface architecture used to seperate structural and behavioral concerns in order to facilitate more maintainable sofware.

You can also say:

By seperating the View from the Controller from the Model, it encourages isolation of components based on their responsibilities.  In theory, and usually in practice, this helps to improve maintainability by preventing the different parts of the system from co-mingling and creating more complex systems.

But, in the end, you will be judged on whether you give the answr they are expecting.  The only solution to the problem is find out what kind of answer they are expecting.

Title: What is MVC, really?

Body:
As a serious programmer, how do you answer the question What is MVC?

In my mind, MVC is sort of a nebulous topic — and because of that, if your audience is a learner, then you're free to describe it in general terms that are unlikely to be controversial.

However, if you are speaking to a knowledgeable audience, especially an interviewer, I have a hard time thinking of a direction to take that doesn't risk a reaction of "well that's not right!...".  We all have different real-world experience, and I haven't truly met the same MVC implementation pattern twice.

Specifically, there seem to be disagreements regarding strictness, component definition, separation of parts (what piece fits where), etc.

So, how should I explain MVC in a way that is correct, concise, and uncontroversial?


答: it's good to study languages from different programming paradigms at least! Procedural, declarative, functional, object-oriented, prototypical, and dynamic language - each class of programming offers its own bit of insight as to how to organize and solve a problem. Eventually you discover one or more paradigms that you're most productive and happy with, and use it.</p>


问:
Benchmarking databases
I see lots of discussions flying around about performance of db 'x' or that moving from 'x' to 'y' improved our site performance.

I'm yet to see proper benchmarking that works across different types of databases.

Is it possible to write a meaningful benchmark that could be used across multiple db types, such as Relational, Document-oriented, etc.

How would you go about designing such a benchmark?

答:
Short answer

Yes, you can write a meaningful benchmark of a studied case, if you do it with care, and understand that if it's relevant for the particular case, it may not be for other cases. This is equally true when comparing the databases of the same type (relational database vs. another relational database) or the databases of different types.

No, you cannot write a benchmark which will magically prove that a specific database is ways better than another in every case, for every application.

Long answer

It's definitely possible to say that "moving from a database to another improved our site performance".

You measure the performance of the previous database through profiling or runtime statistics by gathering enough information about the queries and how fast they are.

You move the application to the new database.

You do the same measures.

You compare.

For example, if the full list of 3 182 432 products loaded in 2.834 s. on an old database and loads in 0.920 s. on a new database, given that in both cases, the application has an empty cache, it's a win: the new database improved your site performance concerning this query.

Now, as any performance metric, it's biased:

Agreed, the new query is faster. But wait, your DBA didn't know how to use the database you had before, so the query which loads all the products is not optimized. If you rewrite it like that, you would be able to load those products in 0.855 s. instead of 2.834.

Ok, you have a better result. But don't you think that it's unfair to compare a database with fresh data just flushed to a 10 years old database for which the last maintenance plan was run three years ago? By the way, don't you think you should have updated the database product at least once during the last four years?

Some queries are faster. Some are slower. How do you compute the average result to know that you gained performance overall when moving to the new database? Ok, the time you load all 3 182 432 products is faster. But does it matter, while the query is executed on the website only in a rare case when an administrator is performing some specific task he performed only two times in the last ten years? On the other hand, executing all queries on the home page for a fresh user wastes 0.281 s. with the new database, when it was 0.207 s. with the old database. This result matters much more, especially since those queries cannot be cached for a long time, and are executed tens of thousands of times per day.

Both databases must be tested on the same servers, same hardware, same structure. For example, you can't test one database on a single hard drive, and the other one on a RAID1 of two SSDs. When you migrate a large project to a new database, there are chances that you'll just host the new database on hundred other newly deployed rack servers, when the previous database will still remain on the previous machines.

To summarize, you can benchmark the database queries of an application, and obtain precise metrics. But then, you have to give a meaning to numbers. At this state, it's tempting to say that you gained site performance: otherwise, management would be angry to learn that you've spent thousands of dollars and months of work just to make things slower.

The most terrible mistake is to take those conclusions from the benchmarks and to conclude some stupidity like "Microsoft SQL Server is three times faster than Oracle": saying this is like saying that "Java is better than PHP". Define better. Better in what cases? For what sort of applications? For what team of developers?

More you interpret and generalize, more the thing becomes irrelevant and meaningless.

The query select [...] you can find in the revision #832 in file ProductFactory.cs, line 117 executes under 0.5 s. with the new database when tested under the conditions specified in the non-functional requirements annex M, case 3. This allows passing the non-functional requirement 527 (see page 80, revision 9). The same requirement was not satisfied with the previous database, when the test results was in the range 0.9..1.3 s. in the same conditions.

is meaningful for a developer, and precise enough to know what was tested, how, and what was the results. This answers your question number 2.

Sadly, it doesn't make any sense for the management. Instead:

Migrating our product from MySQL to the newest version of Microsoft SQL Server improved the overall performance of our product by five, reducing at the same time the costs by two and the environmental footprint by three. We believe that migrating all our applications to Microsoft SQL Server the next year will give even better results and increase our market competitiveness.

is a pure marketing jibber-jabber, and, technically, doesn't mean anything, but surprisingly has a value for the management and marketing departments.

Finally, can we compare different types of databases? I would say it's totally possible. Let's say I have a website hosting large photos. Those photos are stored in varbinary(max) in Microsoft SQL Server 2005 (so I can't use filestream). I am concerned about the performance when loading those photos, so I decide to store the photos as files instead, using the file system as my new database. First, those files are stored on the same machine than the database. I profile the new solution, and obtain the result that shows that in my case, files are loaded 4% faster from file system than from Microsoft SQL Server. The benchmark is very clear. Now I can think about deploying a dedicated server optimized for direct file storage, rather than using the server optimized for Microsoft SQL Server.

Title: Benchmarking databases


答:
No, the differences between them are such that any one benchmark would be biased.

That said, developing a site like Computer Language Benchmarks Game, which includes a broad range of tests and makes it easy to compare tests (either specific tests language-to-language, or composites of many languages), would be of some benefit (at least in my eyes), especially if it was set up so the community could submit solutions and improve any short-comings in schemas or queries.

In the case of the DB benchmark site, instead of implementing algorithms (as in the case of the language shootout), tests could consist of raw data that has to be stored and then retrieved according specific constraints. For instance, maybe there's a set of raw data that contains information representing a simple schema representative of what a community library may use to track patrons and books. Each DB must store all 1 million records and then retrieve some sub-sets of the data that meet the constraints. Then, there could also be a data set that represents some very simple structure/relationship (maybe a comment system typically used for sites like ESPN, etc.) that contains 100 million records, and it has its own set of queries that must be performed. Etc.

Testing DBs on a broad range data sets (ranging from complex to simple relationships, small sets to humongous) could prove very helpful, as you'd at least be able to see general tendencies for data that bears similar qualities to the project you're currently assessing.

Title: Benchmarking databases

Body:
I see lots of discussions flying around about performance of db 'x' or that moving from 'x' to 'y' improved our site performance.

I'm yet to see proper benchmarking that works across different types of databases.

Is it possible to write a meaningful benchmark that could be used across multiple db types, such as Relational, Document-oriented, etc.

How would you go about designing such a benchmark?


问:
Is there a name for a testing method where you compare a set of very different designs?
"A/B testing" is defined as "a method of marketing testing by which a baseline control sample is compared to a variety of single-variable test samples in order to improve response rates".

The point here, of course, is to know which small single-variable changes are more optimal, with the goal of finding the local optimum.

However, one can also envision a somewhat related but different scenario for testing the response rate of major re-designs: take a baseline control design, take one or more completely different designs, and run test samples on those redesigns to compare response rates.

As a practical but contrived example, imagine testing a set of designs for the same website, one being minimalist "googly" design, one being cluttered "Amazony" design, and one being an artsy "designy" design (e.g. maximum use of design elements unlike Google but minimal simultaneously presented information, like Google but unlike Amazon)

Is there an official name for such testing?

It's definitely not A/B testing, since the main component of it (finding local optimum by testing single-variable small changes that can be attributed to response shift) is not present. This is more about trying to compare a set of local optimums, and compare to see which one works better as a global optimum. It's not a multivriable, A/B/N or any other such testing since you don't really have specific variables that can be attributed, just different designs.

答:
I would consider this to be A/B testing as your variables are design A and design B.

You are comparing two or more variables of the same type albeit two complex one.

As long as your goal is to decide whether A is better (you need to define better) than B it doesn't really matter how complex the components of the two variables are.


答:
I've used many languages during my career, like AMOS Basic, Java, C++, PHP, VB6, Delphi etc. Today I use C#, JavaScript, Ruby and some Clojure at work, and I've also played with Pyhton, Erlang, Common Lisp and Scheme.

But this fall I wanted to make a special x-mas calendar for my blog, and decided to familiarize myself with and solve a particular problem in 24 additional languages. This was a great experience, I learned a lot, and I highly recommend doing this once you have some programming experience.

My answer to you is this: Learn a couple of languages really well (they should be quite different), but make sure you sample and familiarize yourself with many.

Today it's important to know both OOP and FP (functional programming) well, and you should also be comfortable in both a very static and a very dynamic language.

PS: My blog is in Norwegian, but if you'd like to see the list of languages I covered you can have a look here.


问:
Modified Strategy Design Pattern
I've started looking into Design Patterns recently, and one thing I'm coding would suit the Strategy pattern perfectly, except for one small difference.

Essentially, some (but not all) of my algorithms, need an extra parameter or two passed to them.

So I'll either need to

pass them an extra parameter when I invoke their calculate method

or

store them as variables inside the ConcreteAlgorithm class, and be able to update them before I call the algorithm.

Is there a design pattern for this need / How could I implement this while sticking to the Strategy Pattern?

I've considered passing the client object to all the algorithms, and storing the variables in there, then using that only when the particular algorithm needs it. However, I think this is both unwieldy, and defeats the point of the strategy pattern.

Just to be clear I'm implementing in Java, and so don't have the luxury of optional parameters (which would solve this nicely).

答: If you look into the Design patterns book, it isn't wrong per se that some SimpleStrategy exists that uses less or none of the passed parameters, or that the parameters are a one-size-fits-all/least-common-multiplier. The design choice here is whether this hurts you in terms of extra processing that ends up not being used.</p>

Title: Modified Strategy Design Pattern


问:
Question about a "Benchmark" regarding Java and .NET
To get that out of the way - i am not asking about which platform is faster or try to start a flame war.

Question: Why is the .NET version slower 5x in the first test ?
The results i got were:

.NET Test1: 48992696 Test2: 1210070

Java Test1: 9651995  Test2: 1029374

Is this strictly behind list implementations ? If yes, is there something to make list insertion faster on .NET side ?

EDIT:

Used preallocated lists and removed int appends, got this down to

.NET Test1: 11 838 363

Java Test1: 712 481

.NET

```<code>namespace TestApp
{
    class Program
    {
        static void Main(string[] args) {
            long samples = 100;
            long test1Average = 0;
            for (int i = 0; i < samples; i++) {
                test1Average += runTest1();
            }
            test1Average = test1Average / samples;
            System.Diagnostics.Debug.WriteLine("TEST 1 AVERAGE: " + test1Average);

            List<String> list = new List<String>();
            for (int i = 0; i < 100000; i++)
            {
                list.Add("String: " + i);
            }

            long test2Average = 0;
            for (int i = 0; i < samples; i++)
            {
                test2Average += runTest2(list);
            }
            test2Average = test2Average / samples;
            System.Diagnostics.Debug.WriteLine("TEST 2 AVERAGE: " + test2Average);
        }

        private static long runTest1()
        {
            List<String> list = new List<String>();
            long time = System.DateTime.Now.Ticks;
            for (int i = 0; i < 100000; i++)
            {
                list.Add("String: " + i);
            }
            return (System.DateTime.Now.Ticks - time) * 100;
        }

        private static long runTest2(List<String> list)
        {
            long time = System.DateTime.Now.Ticks;
            foreach (String s in list) {
                s.ToString();
            }
            return (System.DateTime.Now.Ticks - time) * 100;
        }

    }
}
</code>```

Java

```<code>public class Main {

public static void main(String[] args) {
    long samples =  100;
    long test1Average = 0;
    for (int i = 0; i < samples; i++) {
        test1Average += runTest1();
    }
    test1Average = test1Average / samples;
    System.out.println("TEST 1 AVERAGE: "+test1Average);

    List<String> list = new ArrayList<String>();
    for (int i = 0; i < 100000; i++) {
        list.add("String: " + i);
    }
    long test2Average = 0;
    for (int i = 0; i < samples; i++) {
        test2Average += runTest2(list);
    }
    test2Average = test2Average / samples;
    System.out.println("TEST 2 AVERAGE: "+test2Average);
}

private static long runTest1() {
    long time = System.nanoTime();
    List<String> list = new ArrayList<String>();
    for (int i = 0; i < 100000; i++) {
        list.add("String: " + i);
    }
    return System.nanoTime()-time;
}

private static long runTest2(List<String> list) {
    long time = System.nanoTime();
    for (String s : list) {
        s.toString();
    }
    return System.nanoTime()-time;
}
</code>```

}

答:
In short I can't give you the answer as I certainly don't know enough about .NET, but as you can see it's usually not just a simple matter of comparing high-level Java vs C# code...

Disclaimer: There's a whole bunch of stuff I know I'm missing in my ramling below. I'm not a performance / benchmarking expert, but a few of my colleagues play one in real life :-).

It's very hard to compare Apples with Apples between the two platforms. It you really wanted to do it the hard core scientific way, you'd have to do things like:

Look at the underlying implementations of the data structures involved

See what bytecode both sets of code generated

Look at how the respective VMs then in-lined and ran that bytecode

I'll assume you ran both tests on the same hardware and took into account things like:

Allowing the VMs to 'warm up'.

Having similar VM settings such as GC, memory allocation and other tuning

Oh and what versions of Java and .NET and what parameters are you running the VMs under?


问:
How does unit testing work?
I am trying to make my code more robust and I have been reading about unit testing, but I find it very hard to find an actual useful use.
For instance, the Wikipedia example:

```<code>public class TestAdder {
    public void testSum() {
        Adder adder = new AdderImpl();
        assert(adder.add(1, 1) == 2);
        assert(adder.add(1, 2) == 3);
        assert(adder.add(2, 2) == 4);
        assert(adder.add(0, 0) == 0);
        assert(adder.add(-1, -2) == -3);
        assert(adder.add(-1, 1) == 0);
        assert(adder.add(1234, 988) == 2222);
    }
}
</code>```

I feel that this test is totally useless, because you are required to manually compute the wanted result and test it, I feel like a better unit test here would be

```<code>assert(adder.add(a, b) == (a+b));
</code>```

but then this is just coding the function itself in the test.
Can someone provide me with an example where unit testing is actually useful? FYI I am currently coding mostly "procedural" functions that take ~10 booleans and a few ints and give me an int result based on this, I feel like the only unit testing I could do would be to simply re-code the algorithm in the test. edit:
I should also have precised this is while porting (possibly badly designed) ruby code (that I didn't make)

答: One of the benefits of writing unit tests is that it helps you to write more robust code by forcing you to think about edge cases.  How about testing for some edge cases, like integer overflow, decimal truncation, or handling of nulls for the parameters?  </p>

Title: How does unit testing work?


答:
Is this strictly behind list implementations?

There are several things which are affecting the performance of those tests.

One is the fact that you are using DateTime. It's not intended to measure performance, and I suppose it's really slow when it comes to profiling. Since you are using it inside the loop, it makes the whole loop slower.

The second one is that you are adding elements through a loop to an empty list. When you are adding an element and there is no enough place, the list must expand in size. It costs resources.

If yes, is there something to make list insertion faster on .NET side?

Here is the same code with some refactoring. The most important change is that instead of creating an empty list, then adding the elements one by one, the list is created directly with all the elements inside.

Sadly, I see only 10 to 15% improvement in performance, which is still way beyond the same code running in Java. I continue to search why there is such a huge difference, but don't have a solution yet.

```<code>namespace Delme__benchmark_
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Linq;

    public class Program
    {
        public static void Main()
        {
            Trace.Listeners.Add(new TextWriterTraceListener(Console.Out));

            int countSamples = 100;

            var samples = Enumerable.Range(0, countSamples).ToList();
            var list = Enumerable
                .Range(0, 100000)
                .Select(c => string.Concat("String: ", c)).ToList();

            Trace.WriteLine("Running the benchmark...");
            Trace.WriteLine(string.Format(
                "Test 1 average: {0}.",
                samples.Average(c => RunTest1())));
            Trace.WriteLine(string.Format(
                "Test 2 average: {0}.",
                samples.Average(c => RunTest2(list))));
        }

        private static long RunTest1()
        {
            Stopwatch time = Stopwatch.StartNew();

            var list = Enumerable
                .Range(0, 100000)
                .Select(c => string.Concat("String: ", c)).ToList();

            time.Stop();
            return time.ElapsedTicks;
        }

        private static long RunTest2(IEnumerable<string> list)
        {
            Stopwatch time = Stopwatch.StartNew();

            foreach (var s in list)
            {
                s.ToString();
            }

            time.Stop();
            return time.ElapsedTicks;
        }
    }
}
</code>```

Title: Question about a "Benchmark" regarding Java and .NET

Body:
To get that out of the way - i am not asking about which platform is faster or try to start a flame war.

Question: Why is the .NET version slower 5x in the first test ?
The results i got were:

.NET Test1: 48992696 Test2: 1210070

Java Test1: 9651995  Test2: 1029374

Is this strictly behind list implementations ? If yes, is there something to make list insertion faster on .NET side ?

EDIT:

Used preallocated lists and removed int appends, got this down to

.NET Test1: 11 838 363

Java Test1: 712 481

.NET

```<code>namespace TestApp
{
    class Program
    {
        static void Main(string[] args) {
            long samples = 100;
            long test1Average = 0;
            for (int i = 0; i < samples; i++) {
                test1Average += runTest1();
            }
            test1Average = test1Average / samples;
            System.Diagnostics.Debug.WriteLine("TEST 1 AVERAGE: " + test1Average);

            List<String> list = new List<String>();
            for (int i = 0; i < 100000; i++)
            {
                list.Add("String: " + i);
            }

            long test2Average = 0;
            for (int i = 0; i < samples; i++)
            {
                test2Average += runTest2(list);
            }
            test2Average = test2Average / samples;
            System.Diagnostics.Debug.WriteLine("TEST 2 AVERAGE: " + test2Average);
        }

        private static long runTest1()
        {
            List<String> list = new List<String>();
            long time = System.DateTime.Now.Ticks;
            for (int i = 0; i < 100000; i++)
            {
                list.Add("String: " + i);
            }
            return (System.DateTime.Now.Ticks - time) * 100;
        }

        private static long runTest2(List<String> list)
        {
            long time = System.DateTime.Now.Ticks;
            foreach (String s in list) {
                s.ToString();
            }
            return (System.DateTime.Now.Ticks - time) * 100;
        }

    }
}
</code>```

Java

```<code>public class Main {

public static void main(String[] args) {
    long samples =  100;
    long test1Average = 0;
    for (int i = 0; i < samples; i++) {
        test1Average += runTest1();
    }
    test1Average = test1Average / samples;
    System.out.println("TEST 1 AVERAGE: "+test1Average);

    List<String> list = new ArrayList<String>();
    for (int i = 0; i < 100000; i++) {
        list.add("String: " + i);
    }
    long test2Average = 0;
    for (int i = 0; i < samples; i++) {
        test2Average += runTest2(list);
    }
    test2Average = test2Average / samples;
    System.out.println("TEST 2 AVERAGE: "+test2Average);
}

private static long runTest1() {
    long time = System.nanoTime();
    List<String> list = new ArrayList<String>();
    for (int i = 0; i < 100000; i++) {
        list.add("String: " + i);
    }
    return System.nanoTime()-time;
}

private static long runTest2(List<String> list) {
    long time = System.nanoTime();
    for (String s : list) {
        s.toString();
    }
    return System.nanoTime()-time;
}
</code>```

}

Body:
Is this strictly behind list implementations?

There are several things which are affecting the performance of those tests.

One is the fact that you are using DateTime. It's not intended to measure performance, and I suppose it's really slow when it comes to profiling. Since you are using it inside the loop, it makes the whole loop slower.

The second one is that you are adding elements through a loop to an empty list. When you are adding an element and there is no enough place, the list must expand in size. It costs resources.

If yes, is there something to make list insertion faster on .NET side?

Here is the same code with some refactoring. The most important change is that instead of creating an empty list, then adding the elements one by one, the list is created directly with all the elements inside.

Sadly, I see only 10 to 15% improvement in performance, which is still way beyond the same code running in Java. I continue to search why there is such a huge difference, but don't have a solution yet.

namespace Delme__benchmark_
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Linq;

    public class Program
    {
        public static void Main()
        {
            Trace.Listeners.Add(new TextWriterTraceListener(Console.Out));

            int countSamples = 100;

            var samples = Enumerable.Range(0, countSamples).ToList();
            var list = Enumerable
                .Range(0, 100000)
                .Select(c => string.Concat("String: ", c)).ToList();

            Trace.WriteLine("Running the benchmark...");
            Trace.WriteLine(string.Format(
                "Test 1 average: {0}.",
                samples.Average(c => RunTest1())));
            Trace.WriteLine(string.Format(
                "Test 2 average: {0}.",
                samples.Average(c => RunTest2(list))));
        }

        private static long RunTest1()
        {
            Stopwatch time = Stopwatch.StartNew();

            var list = Enumerable
                .Range(0, 100000)
                .Select(c => string.Concat("String: ", c)).ToList();

            time.Stop();
            return time.ElapsedTicks;
        }

        private static long RunTest2(IEnumerable<string> list)
        {
            Stopwatch time = Stopwatch.StartNew();

            foreach (var s in list)
            {
                s.ToString();
            }

            time.Stop();
            return time.ElapsedTicks;
        }
    }
}


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

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

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

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

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

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

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

答:
The problem is that because in theory any object can be a null and toss an exception when you attempt to use it, your object-oriented code is basically a collection of unexploded bombs.

You're right that graceful error handling can be functionally identical to null-checking if statements.  But what happens when something you convinced yourself couldn't possibly be a null is, in fact, a null?  Kerboom.  Whatever happens next, I'm willing to bet that 1) it won't be graceful and 2) you won't like it.

And do not dismiss the value of "easy to debug."  Mature production code is a mad, sprawling creature; anything that gives you more insight into what went wrong and where may save you hours of digging.

Title: Are null references really a bad thing?


答:
That's an excellent question. I ran the C# test on my computer and got very similar results:

TEST 1 AVERAGE: 47,812,500

TEST 2 AVERAGE:  1,562,500

This is what I get if I replace list.Add("String: " + i); in runTest1()...

...with String s = "String: " + i;:

TEST 1 AVERAGE: 19,843,750

TEST 2 AVERAGE:  1,406,250

...with list.Add( "moo" );:

TEST 1 AVERAGE:  2,343,750

TEST 2 AVERAGE:  1,406,250

EDIT:

...with list.Add( i.ToString() );

TEST 1 AVERAGE: 20,312,500

TEST 2 AVERAGE:  1,093,750 (<-- BTW, this shows that these benchmarks are not very accurate)

...with String s = i.ToString();

TEST 1 AVERAGE: 14,531,250

TEST 2 AVERAGE:  1,406,250

...with String s = i.ToString( System.Globalization.CultureInfo.InvariantCulture );

TEST 1 AVERAGE: 13,906,250

TEST 2 AVERAGE:  1,406,250


问:
What limitation will we face if each user-perceived character is assigned to one codepoint?
What limitations will we have if Unicode standards had decided to assign one and only one codepoint to every user-perceived character?

Currently, Unicode has code-points that correspond to combining characters.  Such characters combine with a previous code-point (or sequence thereof) to present to the user what appears to be a single character.

From what I can see, the current standard is full of complexities. (We're not talking about   encoding issue here.  Even if we try to avoid any kind of complexities by using an encoding like UTF-32, the problem still persists.)

For example, in Unicode when a grapheme cluster is represented internally by a character sequence consisting of base character + accent, then when the user clicks the > button to skip to the next user-perceived character, we had to skip from the start of the base character to the end of the last character of the cluster.

Why does it need to be so hard? Why can't Unicode assign a single code point to every user perceived character such going to the user-perceived character is simply a matter of reading the next code point?

The unicode website seems to acknowledge this complexity:

In those relatively rare [not rare at all!] circumstances where programmers need to
  supply end users with user-perceived character counts, the counts
  should correspond to the number of segments delimited by grapheme
  clusters. Grapheme clusters may also be used in searching and matching

Diacritics are also the reason why things don't work as expected. For example, if I throw 2 ピ characters (japanese katakana PI using the unicode representation U+30d2 U+309a) into a String builder and reverse it, I would naturally expect the output to be 2 ピ characters (i.e. ピピ), but it gives an invalid output of ゚ピヒ !

If Unicode had assigned individual code points for each user-perceived character and scrapped the idea of grapheme clusters, this wouldn't have happened at all.

What I would like to know is, what exactly is wrong with representing every user-perceived character as one unicode codepoint? Is it likely that doing so would would exceed U+10FFFF possible code points (if it does exceed U+10FFFF code points I see no reason why they couldn't have set the limit to 2^32 in the first place), Even when there is so much spare space to include the whole family of Elf Languages ?

Unicode states:

If you wanted, for example, to give each “instance of a character on paper throughout history” its own code, you might need trillions or quadrillions of such codes;

But seriously that doesn't make sense at all. Where is the source for making such a claim? A trillion codes is quite an over-statement.

答:
The origins of Unicode date back to 1987–1988, when Joseph D. Becker published the first Unicode draft proposal. A 16-bit fixed width encoding (UCS-2) was an indispensable part of his design. He was very proud of the distinction he made between characters and glyphs, just to squeeze everything to this small range. Unfortunately his naïve assumptions were proven wrong, or at least unrealistic, when in 1996 Unicode code-space was increased beyond the 16-bit limit and UCS-2 was extended to UTF-16. Currently Unicode has almost twice as much allocated codepoints than the code-space of Becker's original design.

[...] if it does exceed U+10FFFF code points I see no reason why they couldn't have set the limit to 2^32 in the first place [...]

It is currently limited by U+10FFFF because it's the maximum range possible to be encoded with UTF-16. UTF-16 is an ugly hack applied late in the day to extend the code-space. It's not extensible. UTF-8 on the other hand is. UTF-8 was originally allowed to encode 231 codepoints and was later limited to just match the same range as UTF-16. In fact you can extend the scheme used by UTF-8 indefinitely, even to encode 2128 codepoints and preserve all the nice properties of UTF-8 at the same time (lexicographically comparable, unambiguous substring matching with UTF-8 unaware code, etc...) except that you won't be able to determine the length of the codepoint from the first byte.

From what I can see, the current standard is full of complexities. Even if I try to avoid any kind of complexities by using an encoding like UTF-32, this problem still persists. It's not an encoding issue at all.

Exactly! I want to point out that variable length encodings are not the problem. Indeed, finding the next code-point in a UTF-8 string is simple, just scan for the next byte of the form 0xxxxxxx or 11xxxxxx. So we could easily increase the available codespace without increasing the average memory consumption. The real problem is that to find the next grapheme you must have a Unicode database available (in some form), which is definitely complex and costly for many simple applications.


问:
What's the point of adding Unicode identifier support to various language implementations?
I personally find reading code full of Unicode identifiers confusing. In my opinion, it also prevents the code from being easily maintained. Not to mention all the effort required for authors of various translators to implement such support. I also constantly notice the lack (or the presence) of Unicode identifiers support in the lists of (dis)advantages of various language implementations (like it really matters). I don't get it: why so much attention?</p>

答:
I would say:

to ease non-professionals and novices that learn programming (e.g. at school) and don't know English. They don't write production code anyway. I've seen many times code like:

```<code>double upsos, baros;
cin >> upsos >> baros;
</code>```

Just let the poor guy to write it in his language:

```<code>double ύψος, βάρος;
cin >> ύψος >> βάρος;
</code>```

Don't you like it?

```<code>class ☎ {
public:
    ☎(const char*);
    void ();
    void ();
};

☎ ☏("031415926");
☏.(("Bob"));
ofstream f;
f.();
</code>```

Body:
I would say:

to ease non-professionals and novices that learn programming (e.g. at school) and don't know English. They don't write production code anyway. I've seen many times code like:

double upsos, baros;
cin >> upsos >> baros;

Just let the poor guy to write it in his language:

double ύψος, βάρος;
cin >> ύψος >> βάρος;

Don't you like it?

class ☎ {
public:
    ☎(const char*);
    void ();
    void ();
};

☎ ☏("031415926");
☏.(("Bob"));
ofstream f;
f.();