问:
Is LISP still useful in today's world? Which version is most used?
I try to teach myself a new programming language in regular intervals of time. Recently, I've read how Lisp and its dialects are at the complete opposite end of the spectrum from languages like C/C++, which made me curious enough to know more about it. However, two things are unclear to me, and I'm looking for guidance on them :

Is LISP still practiced/used in todays world, or is it a legacy language like FORTRAN/COBOL ? I mean, apart from maintaining existing code, is it used on new projects at all ?

What is the most widely used dialect ? I came across Scheme and Common Lisp as the 2 most prevalent dialects, and wanted your opinion as to which is the most favored/useful one to learn - and would be immensely gratified if you can suggest any resources for a rank beginner to start from.

While eager to learn a language which is fundamentally different from the procedural languages I'm used to, I don't want to invest undue effort in something if its totally obsolete - I'd still learn it if it was professionally "dead", but only with an academic perspective...

答:
Is LISP still practiced/used in todays world, or is it a legacy language

Yes, it is, but you have to know where to look. People who use LISP don't tend to shout too loudly about it but there's a handful of examples of a few high-profile startups having used it to great effect over the last 20 years.
It is also very popular with small companies in Europe.

What is the most widely used dialect ?

This is a valid question, but it's not an easy one to answer. It may also not be a particularly useful one to answer: many implementations have a specific focus so are best chosen if they fit your particular problem rather than based on how widely it is otherwise used. Instead, I'll tell you a little bit about your options and you can decide for yourself.

LISP is a family of languages and each of those languages has a family of dialects and implementations. Broadly dialects fall into two camps "LISPs" and "Schemes".

LISPs:
Until relatively recently, Common LISP was king. It was an attempt to unify all the disparate LISPs and, without being unkind, was the "C++" of LISP. That is to say, it was a HUGE language. It had everything. Over the last few years, Clojure has appeared. Clojure is a LISP that runs on the Java Virtual Machine and tries to root itself in a functional programming philosophy. Traditionally, other LISPs have been strictly multi-paradigm. Clojure is interesting because it gets both the very best and very worst of both LISP and the JVM. There's still a lot of the verbosity of Java-based languages and they've been fairly free and easy with the syntax so that has lots of knobs and buttons for different things, but they've got some really interesting ideas around datatypes, especially some of the practical ways they have come up with to apply ideas from functional programming.

Schemes:
Schemes are a strict subset of LISPs. Scheme was invented by Steele and Sussman and in early life was notable for being used in the MIT Computing 101 Lecture Course. Scheme is defined in the "Revised^n Report on the Algorithmic Language Scheme (RnRS)". Yes: they have a maths joke in there. Scheme is a standardised language in a way that other LISPs are not. This helps greatly with portability between implementations, but it's not a silver bullet. The standardisation efforts have tended to be conservative and innovations in the implementations, especially around things like modules, have tended to be disparate. There is also a series of SRFIs (Scheme Requests For Implementation) which is similar to the IETF's RFC process. People use it to standardise small things as needed.

Schemes are different from LISPs that they have a set of hard requirements that they must satisfy, one of which is "tail call optimisation" which helps make recursion efficient. Therefore, recursive styles of programming are much more popular in Scheme than in LISP. Scheme is, also without being unkind, like the "C" of LISP. That is to say, it's a small languages and you're supposed to be able to keep all of it in your head at once.

There are currently two Scheme families: Those based on the 5th version (R5RS) and those based on the 6th version (R6RS). The complexity of R6RS was wildly greater than that of any of its predecessors and so many R5RS implementations have opted to skip it, hoping that R7RS will be more similar to R5RS than R6RS. The R7RS standardisation process is currently ongoing and has tried to include both the R5RS implementers' desires as well as those of the R6RS folk by standardising a small base language in their first working group and then commissioning a second working group to standardise the larger features. This will allow the language to have efficient and useful implementations on both tiny embedded hardware as well as more capable machines.

Now I'll be more specific:

PicoLisp is a really, really cool LISP. It's tiny! It's author wrote it for himself and, as I understand it, he's been making a living off of it since the 1980s. If you ever get the opportunity to attend a talk by him then you should do it: he's really interesting and really knows his stuff and you won't get even the smallest sniff of anything mainstream or boring.

I'm not familiar with Common Lisp implementations so I won't comment further on them.

Guile is the official GNU Scheme.

Racket is an R6RS scheme but lately it seems to have widened the net and is trying "to serve as a platform for language creation, design, and implementation.".

Chicken aims to be a practical Scheme. It's based on R5RS and compiles down to C. This turns out to be a really, really, important advantage as it makes it absolutely trivial to use existing C libraries. Therefore Chicken is probably the most useful scheme for replacing Perl, Python, Ruby, etc, as your day-to-day scripting language. There are several people who have used it exclusively for all their needs for several years. It has an interactive REPL as well as a compiler. The community (both on the mailing list and IRC) are knowledgeable, friendly and helpful.

Look for an implementation with lots of modules: this shows that it's widely usable and means that it's likely to have something that helps with the task at hand.

Look for an implementation with a compiler or, at the very least, something that isn't strictly IDE or REPL based. A lot of the implementations designed for teaching are very difficult to use for general purpose scripting.

I'd recommend Chicken as that's what I use. I've used it in my personal projects and I've used it (and am currently using it) professionally.

I don't want to invest undue effort in something if its totally obsolete -
  I'd still learn it if it was professionally "dead", but only with an academic
  perspective...

Scheme isn't professionally dead, but you might have to go to some lengths to use it in that context. Something like Chicken is far more than an academic pursuit and it can easily cover almost all the bases of whatever high-level languages you currently use.


问:
How to use Dependency Injection in conjunction with the Factory pattern
Consider a module that is responsible for parsing files of any given type. I am thinking of using the strategy pattern to tackle this problem as I have already explained over here. Please refer to the linked post before proceeding with this question.

Consider class B that needs the contents of the product.xml file. This class will need to instantiate the appropriate concrete implementer of the Parser interface to parse the XML file. I can delegate the instantiation of the appropriate concrete implementer to a Factory such that class B "has-a" Factory. However, class B will then "depend" on a Factory for instantiating the concrete implementer. This means that the constructor or a setter method in class B will need to be passed the Factory.

Therefore, the Factory and class B that needs to parse a file will be tightly coupled with each other. I understand that I may be completely wrong about whatever I have explained so far. I would like to know whether I can use dependency injection in a scenario where the dependency to be injected is a Factory and what would be the right way to implement this so I can take advantage of areas such as mocking the Factory in my unit tests.

答:
The right way to do this is to depend on an interface, and then inject an implementation of that interface into Class B.

An interface is just about the thinnest thing that you can depend on -- I liken it to trying to grab a wisp of smoke.  Code has to couple to something or else it won't do anything, but coupling to an interface is about as decoupled as you can get, yet interfaces can provide all the functionality that you could want.

So have Class B's constructor take an interface to the class it needs, and have the factory produce that class as an implementer of the interface.  Don't depend on the factory, depend on the interface, and have the factory provide an implementation of that factory.

So yes, you will be using dependency injection, but there's nothing wrong with that.  Dependency injection -- particularly simple constructor injection -- should be the "normal" way of doing things.  Simply put off new-ing things as far back in your app (and as close to the first line of main) as possible, and hide the new call in a class designed specifically for creating things.

Bottom line: Don't be hesitant to inject dependencies. That should be the normal way of doing things.

ContentLicense: CC BY-SA 3.0


问:
When would using a scripting language within a larger program be useful?
I have heard of several situations of people using say, JavaScript or Python (or something), inside a program written in C#. When would using a language like JavaScript to do something in a C# program be better then just doing it in C#? </p>

答:
From my experience, we once developed a big application that does rewrite sourcecode of an "ancient" langue to be unicode compatible. The was done in C#. I ended up writing only the engine (that creates a data model and provides means to do the steps necessary for the rewrite process) in C# - the "glue code" for actually executing things is done in IronPython.

The biggest point for the integrated IronPython: Let's assume you loaded a big data model (about one hour load time). Then you want to -manually- collect information and look up things. Doing this with a Python script from an interactive console is far far better than clicking through the data model with the debugger (plus, it's replayable).


问:
How to count condition coverage
I am wondering, What would be the correct condition coverage test cases for the following condition:

```<code>if(A && E && (B || C || D))
</code>```

Considering short circuiting, what cases would I need?

EDIT: Sorry I put only a half of the expression

答:
Short answer is yes.

There are many more cases but since you are taking into account short circuiting, then only need to consider one case where A is False and only one case in which A is True and B is True and you don't need to bother checking C. The only time you need to check all three values is if A is True and B is False.

EDIT** With the new expression (A && E && (B || C || D))
With this new expression and still taking into account short cuircuiting, you will only be concerned with the instances where both A is true and E is true. From there, you only need to test B || C || D in that order until you find a true value. So these instances:

```<code>T--
FT-
FFT
</code>```

So D will only be checked if B and C are False. C will only be checked in B is false. If B is true, no need to check any further.

Title: How to count condition coverage

Body:
Short answer is yes.

There are many more cases but since you are taking into account short circuiting, then only need to consider one case where A is False and only one case in which A is True and B is True and you don't need to bother checking C. The only time you need to check all three values is if A is True and B is False.

EDIT** With the new expression (A && E && (B || C || D))
With this new expression and still taking into account short cuircuiting, you will only be concerned with the instances where both A is true and E is true. From there, you only need to test B || C || D in that order until you find a true value. So these instances:

T--
FT-
FFT

So D will only be checked if B and C are False. C will only be checked in B is false. If B is true, no need to check any further.


问:
Why do large websites use different languages for the backend and frontend?
My understanding from small MVC applications is that you have the front end, which deals with HTML, JS, jQuery, etc, and you have the back end, which consists of your controllers and models.

However, when I talk to developers from large companies, they often mention having a frontend tier and a backend tier. So sometimes, I might hear that they have a frontend with C# and a backend with Java. Why would any company want a backend and frontend in different languages? Does this help the large website scale better?

When people say that their frontend is built in C#, does this mean that they are using a framework for the frontend (like .NET) and an additional framework on the backend (such as Spring)? Or does it mean something entirely different?

答:
It's helpful to think of your front end and back end as separate applications that both use the same data source.

Even for smaller sites, you can think of the front end as being what the client interfaces with, and the back end as something like a CMS. These can easily be separate MVC applications. The front end still needs models and controllers to run - after all, the controller is the point of entry for your site visitors and the models are going to be the way you get data from your database to the user.

I tend to like using Django/Python as a CMS on the back end, and using Rails, CodeIgniter or Spring MVC on the front end. Often there's no choice; the client already has some legacy site set up in some language on the front end and they just want a CMS solution. Most clients wouldn't even know the CMS was running a different language or framework if they weren't told.

It's really about finding what works best for the site you want to build. The front and back ends really only need to share the database, so as long as they can both work with that, feel free to choose the best options for the task at hand.


问:
Why do web sites require certain characters in their credentials?
It seems like when web site lists requirements as to what characters MUST be in the password they're only providing a password map for someone who wants to hack their system.

For instance, fsd.gov requires:

```<code>The password must be 10-14 characters in length.

The password must contain two each of the following:

Upper/lower case letters, numbers, and special characters.

An example of an acceptable password is:  AAbb1234!@
</code>```

Congrats!  If I wanted to hack your password, now I know that trying to guess "aaaaaaaaa" will be wrong, you've given me clues as to what I can guess and helped narrow it down.

It seems to me like it's more open and more possible combinations if they didn't require special characters.  Then if you included one your account is now more secure.

Note - As you've probably guessed, I'm not a pro at security, which is why I posted here.

答:
It's encouraging people to use a wider range of characters than what people would use without thinking. Considering that the top password is "password", followed by 123456 etc., it at least encourages people to think about using a broader range of characters. Special characters and numbers do improve the complexity of the password since they can be placed anywhere in the string to be legal, and mean a larger pool of passwords among the weakest.

Personally though I think it's clearly not effective, and that it would be superior to analyze the password through Javascript and warn the user of insecure passwords based on what we now know following the hacking of various major websites. Sadly forcing numbers and special characters doesn't improve things that much due to very common pattern of [word][number][special-character]. A link to this site might suffice as a warning: http://howsecureismypassword.net/


答:
The goal (and normal effect) of these policies is to make it harder for an attacker to guess most people's passwords by increasing the number of characters that an attacker needs to try in order to compromise most passwords.  Theoretically, of course, you are correct that restricting the type of characters you use in a password does reduce the number of theoretically valid passwords.  But the vast majority of users are lazy and, without password restrictions, attackers can leverage that laziness to greatly reduce the number of passwords that they have to check to compromise an average account.

The average user creating an account on a random web page, assuming there are no restrictions on what the password is, will choose a password that is a word from the dictionary in all lower case.  Knowing this, an attacker can try the most common, say, 10,000 words from the dictionary in lower case and compromise most passwords.  When you force users to use mixed-case, numbers, and/or special characters, you substantially increase the number of passwords that have to be checked for the average user.

There are, realistically, better ways of enforcing password complexity by looking at the amount of entropy in the password (such as the password meter).  There are, however, reasons in practice that it is often easier to provide a rule about required characters rather than using a more sophisticated complexity checker.  First, most auditors are more comfortable with a relatively simple password complexity policy that is relatively common rather than a more sophisticated policy that is harder for a human to understand.  Second, providing users with a simple set of rules to follow tends to make it easier for non-technical users than a more sophisticated password entropy checker.

Title: Why do web sites require certain characters in their credentials?

Body:
It seems like when web site lists requirements as to what characters MUST be in the password they're only providing a password map for someone who wants to hack their system.

For instance, fsd.gov requires:

```<code>The password must be 10-14 characters in length.

The password must contain two each of the following:

Upper/lower case letters, numbers, and special characters.

An example of an acceptable password is:  AAbb1234!@
</code>```

Congrats!  If I wanted to hack your password, now I know that trying to guess "aaaaaaaaa" will be wrong, you've given me clues as to what I can guess and helped narrow it down.

It seems to me like it's more open and more possible combinations if they didn't require special characters.  Then if you included one your account is now more secure.

Note - As you've probably guessed, I'm not a pro at security, which is why I posted here.


问:
Patching open source software when upgrading is not an option?
I recently ran into a rather annoying (confirmed) bug in an open source software package that I have integrated into my application.  According to the public issue tracker this bug has been resolved in the latest release of the software.

Occasionally you NEED that bug fix to avoid an expensive refactor of a particular module, however for technical and/or political reasons, you will not be able to upgrade to the latest release.

On inspecting the code changes made, the fix seems simple enough that I feel a viable option would be to patch the code myself and recompile my current approved version of the software, however detractors want to argue the case that this is nearly always a bad idea in that it is risky and introducing a troublesome complexity.

In their eyes because this code change was done by us solely for our use, it must be part of our code base, meaning that rather than introducing the open source software as a third party dependency, we must introduce it as a new project and incorporate its automated build into our build process.

To me I think this is wrong headed, as we would be pulling their code from their source control repository into ours, and we lose the history behind any code changes that came before that.  Also it just seems like something that is far too complicated for such a small code change that needs to be made.

Would it be a bad idea to do the above in this case?  If so, then what is the ideal situation when open source needs to change, but only for your sole benefit in house?

答:
What you want to do seems reasonable enough, but it sounds like there are (sound?) process reasons for opposing it. I won't compare the proposed solutions, but perhaps there's a way you could have your cake and eat it too:

If the open source project in question allows it, contribute your back-ported bugfix to their repository. That is, if you're using version 1.5.2 and the current stable version is 1.6.1, contribute a patch to 1.5.2. If it gets adopted, you can fetch the fixed source directly from the repository (perhaps as version 1.5.3) and make everyone happy.

In other words: Patch it for everyone else who's in your situation, too. Of course this is only possible if the project supports (or at least allows) updates to released versions. But that's certainly pretty standard practice these days.


问:
I want to adopt an agile methodology - in a company that has NO process at all?
I'm in a team of two developers and currently we have no formal processes for software development and testing - I'd like to adopt one solo initially.

Where I need some opinions is really on the matter of where to begin? Having read various books it isn't terribly clear what the best starting point would be.

Recently I put in place a simple sharepoint/access database for recording issues and resolutions, and a changelog. Beyond that, testing is a manual process.

In my control is the process by which I design and develop any of my own tools or content and would very much like to adopt a lightweight agile methology that works well for a single developer but is intended to be a "follow my example" for the company to pull all the software development into it.

I do like picking out items from various projects I have on the go and refactoring them or adding functionality; one of the notions I was considering was the notion of user stories whereby I could cherry pick out various stories when I was in the general project to which it applies.

Anyone else in a similar single developer position who has adopted agile/other 'ology?

答:
If you only added one thing, I'd suggest regular retrospectives. From there you'll be able to find out where your current (non) process makes you hurt, and you can start there.

My uninformed guess is that you pretty soon will realize that you need a good interface between you and whoever is responsible for the requirements of the systems you're developing.
Delivering in short fixed-time iterations is generally considered a good idea in order to reduce amount of work in progress, managing expectations and establish a short feed back loop.

This is a rather defensive way of introducing some agile methodology. If you prefer a more agressive way, just read up on, for instance, scrum and try using that methodology although your team is smaller than a typical scrum team.


答:
I did this in my current position not in case we hire another developer, but to manage the current situation. I do: support, training & materials, documentation, requirements gathering, and make a presentation to C-level execs each quarter

A Sprint lasts a week. I built a small database to track any project that has multiple pieces. Most projects are just a one page document that is probably a consolidation of a few email messages. There's no way I could plan my schedule any further into the future.

Project Owners I work with different people in different departments on many small apps, reports, changes, etc. The goal is to work as closely as possible with these people to work out the details. If I feel a higher-up manager won't have the time to do this, I'll suggest working with someone else who is a little closer to using the project. Very few people can conceptualize what the "really" want until they see something (prototype) and they come up with a better idea of what they want. No detailed specs or contracts here.

Adding one more developer could change this depending on the reason for the new hire. If it was the result of a large project, we would lengthen sprints, try to review each other's code, share more information, and coordinate the project together. If it was because there is a backlog of these little projects, most of this wouldn't change. The goal would be to get the new person up to speed and each one would work independently on the small projects. Of course, we'd like to have more exchange of knowledge and prepare for the "hit by a bus" scenario, but the reality is, management isn't going to be happy if we add another developer and not get a lot more done.

Title: I want to adopt an agile methodology - in a company that has NO process at all?

Body:
I'm in a team of two developers and currently we have no formal processes for software development and testing - I'd like to adopt one solo initially.

Where I need some opinions is really on the matter of where to begin? Having read various books it isn't terribly clear what the best starting point would be.

Recently I put in place a simple sharepoint/access database for recording issues and resolutions, and a changelog. Beyond that, testing is a manual process.

In my control is the process by which I design and develop any of my own tools or content and would very much like to adopt a lightweight agile methology that works well for a single developer but is intended to be a "follow my example" for the company to pull all the software development into it.

I do like picking out items from various projects I have on the go and refactoring them or adding functionality; one of the notions I was considering was the notion of user stories whereby I could cherry pick out various stories when I was in the general project to which it applies.

Anyone else in a similar single developer position who has adopted agile/other 'ology?


答:
I think it is more the result of cargo cult programming, especially where there is maximum size to a password enforced. Whenever there is a maximum size, you just know that it's because they are storing the passwords in clear-text, and the maximum size is the number of characters in their database's password column.

Monkey-see, monkey do.


答:
I think your premise is a little confused here, you speak of injecting a factory, but the factory pattern is a creational pattern whose purpose was to do a subset of what a dependency injection framework does, when DI frameworks weren't prevalent this pattern was useful for that reason. However if you have a DI framework, you no longer really need a factory as the DI framework can fulfill the purpose the factory would have fulfilled.

That said, let me explain a bit about dependency injection and how you would generally use it.

There's a variety of ways to do dependency injection, but the most common are constructor injection, property injection, and direct DIContainer. I'll speak regarding constructor injection as property injection is the wrong approach most of the time (the right approach some of the time), and DIContainer access is not preferable except when you absolutely cannot do either of the other approaches.

Constructor injection is where you have the interface for a dependency and a DIContainer (or factory) that knows the concrete implementation for that dependency, and wheresoever you need an object that depends on that interface, at construction time you hand the implementation from the factory to it.

i.e.

```<code>IDbConnectionProvider connProvider = DIContainer.Get<IDbConnectionProvider>();
IUserRepository userRepo = new UserRepository(connProvider);
User currentUser = userRepo.GetCurrentUser();
</code>```

Many DI frameworks can simplify this significantly to where your DIContainer will inspect the constructor of UserRepository for interfaces it knows concrete implementations for, and will automatically hand those to it for you; this technique is frequently called Inversion of Control, though DI and IoC are both terms which get interchanged a lot and have vague(if any) differences.

Now if you're wondering how the overarching code accesses the DIContainer, well you can either have a static class for accessing it or what is more appropriate is that most DI frameworks allow you to new up a DIContainer, wherein it will actually just behave as a wrapper to an internal singleton dictionary for the types which it knows to be concrete for given interfaces.

That means, you can new up the DIContainer anywhere you want in the code and effectively get the same DIContainer that you had already configured to know your interface-to-concrete relationships. Usual means of hiding the DIContainer from parts of the code which shouldn't interact with it directly is to simply ensure only the necessary project(s) have a reference to the DI framework.

Title: How to use Dependency Injection in conjunction with the Factory pattern

Body:
Consider a module that is responsible for parsing files of any given type. I am thinking of using the strategy pattern to tackle this problem as I have already explained over here. Please refer to the linked post before proceeding with this question.

Consider class B that needs the contents of the product.xml file. This class will need to instantiate the appropriate concrete implementer of the Parser interface to parse the XML file. I can delegate the instantiation of the appropriate concrete implementer to a Factory such that class B "has-a" Factory. However, class B will then "depend" on a Factory for instantiating the concrete implementer. This means that the constructor or a setter method in class B will need to be passed the Factory.

Therefore, the Factory and class B that needs to parse a file will be tightly coupled with each other. I understand that I may be completely wrong about whatever I have explained so far. I would like to know whether I can use dependency injection in a scenario where the dependency to be injected is a Factory and what would be the right way to implement this so I can take advantage of areas such as mocking the Factory in my unit tests.

Body:
I think your premise is a little confused here, you speak of injecting a factory, but the factory pattern is a creational pattern whose purpose was to do a subset of what a dependency injection framework does, when DI frameworks weren't prevalent this pattern was useful for that reason. However if you have a DI framework, you no longer really need a factory as the DI framework can fulfill the purpose the factory would have fulfilled.

That said, let me explain a bit about dependency injection and how you would generally use it.

There's a variety of ways to do dependency injection, but the most common are constructor injection, property injection, and direct DIContainer. I'll speak regarding constructor injection as property injection is the wrong approach most of the time (the right approach some of the time), and DIContainer access is not preferable except when you absolutely cannot do either of the other approaches.

Constructor injection is where you have the interface for a dependency and a DIContainer (or factory) that knows the concrete implementation for that dependency, and wheresoever you need an object that depends on that interface, at construction time you hand the implementation from the factory to it.

i.e.

IDbConnectionProvider connProvider = DIContainer.Get<IDbConnectionProvider>();
IUserRepository userRepo = new UserRepository(connProvider);
User currentUser = userRepo.GetCurrentUser();

Many DI frameworks can simplify this significantly to where your DIContainer will inspect the constructor of UserRepository for interfaces it knows concrete implementations for, and will automatically hand those to it for you; this technique is frequently called Inversion of Control, though DI and IoC are both terms which get interchanged a lot and have vague(if any) differences.

Now if you're wondering how the overarching code accesses the DIContainer, well you can either have a static class for accessing it or what is more appropriate is that most DI frameworks allow you to new up a DIContainer, wherein it will actually just behave as a wrapper to an internal singleton dictionary for the types which it knows to be concrete for given interfaces.

That means, you can new up the DIContainer anywhere you want in the code and effectively get the same DIContainer that you had already configured to know your interface-to-concrete relationships. Usual means of hiding the DIContainer from parts of the code which shouldn't interact with it directly is to simply ensure only the necessary project(s) have a reference to the DI framework.


答:
If you just required a password without constraints, a single letter would do, so 1 letter is 26 possible combinations.

If you require a minimum length, you have 26^N possible combinations.

If you require at least 1 case change, you have almost 52^N possible combinations.

If you add digits, you have almost 62^N possible combinations.

If you add special chars (~!@#$%^&*_-?), you have almost 74^N possible combinations.

So with the constraints you specified, you'd have a possible combination of almost 74^10 combinations, which is a big freak'n number.

Not to mention you've eliminated real words which is what most people will usually use.

As far as maximum length goes, I'm not sure why they restrict the possible number of characters to 14 in that case.  As far as I know there's no reason to keep it so low.  I suspect is for a legacy 'space saving' reason which doesn't really apply for hashing passwords ... let's hope they're hashing their passwords.

*'almost' takes into account the fact that you can't have something like 'aaaaaaaaaa'.


问:
Interview puzzle on traveling on a line segment
On a number line of length M, where 0 < M <= 1,000,000,000, you given N (1 < N <= 100,000) integer pairs of points. In each pair, the first point represents where an object is currently located, and the second point represents where an object should be moved. (Keep in mind the second point may be smaller than the first).

Now, assume you start at the point 0 and have a cart that can hold 1 object. You want to move all objects from their initial positions to their respective final positions while traveling the least distance along the number line (not displacement). You have to end up on point M.

Now, I've been trying to reduce this problem to a simpler problem. To be honest I can't even think of a brute force (possibly greedy) solution. However, my first thought was to degenerate a backwards movement to two forward movements, but that doesn't seem to work in all cases.

I drew out these 3 sample test cases in here:

The answer to the first testcase is 12. First, you pick up the red item at point 0. Then you move to point 6 (distance = 6), drop the red item temporarily, then pick up the green item. Then you move to point 5 (distance = 1) and drop the green item. Then you move back to point 6 (distance = 1) and pick up the red item you dropped, move to point 9 (distance = 3), then move to point 10 (distance = 1) to finish off the sequence.

The total distance traveled was 6 + 1 + 1 + 3 + 1 = 12, which is the minimum possible distance.

The other two cases have answers of 12, I believe. However, I can't find a general rule to solve it.

Anyone got any ideas?

答:
If you're empty, start moving to the right.

Whenever you reach an object and you're empty, pick it up (duh) and move toward its destination.

Whenever you reach an object a and you're already carrying b, always choose whichever of the objects has the numerically smallest destination (furthest to the left).

If you're not yet at M, go back to step 1.

This is optimal: The only place where you have a real choice is in step 3. Handling the leftmost destination first ensures that by the time you've dispatched both objects, you'll be as far to the right as possible.

Why is this question on programmers.sx? Yes, "interview question", but it's just a nice riddle.

PS. In terms of implementation, all you need is the list of tasks (the integer pairs of points) sorted by original position.


问:
Shelving code in Team Foundation Server (TFS)
I'm pretty new at using TFS and I'd like to know how you or your team use the "shelve" function of tfs.

We have the following guidelines in using TFS:
- perform a "Get Latest" before you check in and try to build/compile
- do not check in code that does not compile
- at the end of the day, if your work is not complete/partially done, you should "shelve" your pending changes

The first two make sense but I don't really get the last one. I asked my mgr and he said that its so he knows that you actually did some work for that day, which does kind of makes sense but still, I'm wondering what other teams use the "shelve" function for?

答:
I think it's a bit more complex and nuanced than the other answers given here, but also that there's a good discussion of it on StackOverflow: https://stackoverflow.com/questions/556981/what-is-shelving-in-tfs-just-a-soft-checkin-so-others-can-see-code

Yes, it's about being able to check things in and go home, but it's also so that you can set down new work at a point where that work isn't ready to be committed, so that you can work on other things in the same solution.  The example for this is having to set down new development in order to address a bug.  You can shelve the new development, pick up the released version, address the bug, and then return to your new development.


问:
Policy and practice on code maintenance
I just came out of University and have been working at this company for roughly 8 months, while I was given the title of developer, most of the time I have spent on is fixing and debugging other people's codes.

I always wonder why isn't the original developer's responsibility for fixing his/her code. I understand that if the original developer is no longer present, then the other developers have to take over the work, but what if the developer is still working as an employee in the company?

One may argue that it is beneficial to the new developers as they see it as an opportunity to learn, and I agree with that, but what if the complexity of the problem/issue of the code is very steep? In my case, most of the codes they assigned me to fix are non trivial problems, and it always ends up myself asking the original developer questions regarding the code. Why can't the developers who created it fix the existing problem if they understand it so much better since they coded it? And the problem I am referring to is not some trivial problem where you can fix it in a day or two,but problem that requires a deep understanding of the code in order to come up with a solution.

What is the reasoning behind this and is it common in the software industry?

答:
I think the main reason you'll see justifying this sort of thing in the broadest sense is the "bus factor".  If the same person writes and maintains a piece of code in perpetuity, nobody besides that person will have any clue how it works, which is trouble when that person leaves.  So having new developers fix bugs to get started is often justified with that rationale.

Personally, I think the justification is unlikely to match the reasoning.  I think the actual reason that this happens with newer developers is that departments honestly don't really know what to do with them, don't really have a comprehensive training program and are nervous about tasking them with major features.  So whatever you might be told, it's probably a sort of default way to have you prove that you're capable of handling stuff and hopefully learn a thing or two along the way.

I personally think there are much better ways of accomplishing this, but it's a way, and I suppose it does sometimes work, after a fashion (notwithstanding the risk of boring newbies into quitting for greener pastures).

Title: Policy and practice on code maintenance


答:
The reason is business risk-balancing.

Let's say you're a giant employer in one city. You have to hire a lot of developers to build a lot of different services. Let's say your initial evaluation is that Lanuage A suits your interests best, and you want to start with it.

If you commit to one technology you might dry out the talent pool. Are you sure you want to hire a decent Langauge A guy when there is a Language B star just around the corner? What if tomorrow Langauge A's frameworks seize to be supported by the main developer? What if tomorrow there is an amazing Language C, should you ignore it because you committed to language A five years ago?

Ideally what you want is a hetrogenous system with different languages that reflects the current talent pool and technology trends. You want this balance to shift slowly as the talent pool and trends are changing so that at any point all of your systems are workable and you can hire the people to maintain them.

...and that's sort of what companies do.

Title: Why do large websites use different languages for the backend and frontend?

Body:
My understanding from small MVC applications is that you have the front end, which deals with HTML, JS, jQuery, etc, and you have the back end, which consists of your controllers and models.

However, when I talk to developers from large companies, they often mention having a frontend tier and a backend tier. So sometimes, I might hear that they have a frontend with C# and a backend with Java. Why would any company want a backend and frontend in different languages? Does this help the large website scale better?

When people say that their frontend is built in C#, does this mean that they are using a framework for the frontend (like .NET) and an additional framework on the backend (such as Spring)? Or does it mean something entirely different?


问:
Is BDD scalable for medium to large projects?
In every Website you read about BDD (Behaviour Driven Development) you find a very simple nice example showing you how obvious and easy is it to define your requirements. But trying to implement this process in a big product (not a calculator example) showed me that things can get (or will get) pretty complex and unreadable; especially changing requests at a later point means a lot of work to correct the Integration tests for this.

So I'm wondering, is BDD really worth it? Does it solve a problem that other techniques don't!

答:
We built a fairly complex (domain complexity) project last fall and I can honestly say putting the up front work into BDD saved the project. I've seen a strong correlation between the domain complexity and the benefits of BDD.

Let me get one thing out of the way: testing complex business rules is hard. The question is, do you want to try and remember all the crazy scenarios whenever you make a change, or do you want that safety net to let you know when you've broken the spec. Spend the up-front time and work out all the scenarios, write them down, and eventually write all the tests for them.

And when you come back later trying to make sense of things, having that testable spec is a life saver.


问:
creating simple states for a stateless input
Given an input device (basically a keyboard) that reports keyup and keydown, how may I most efficiently store and retrieve information about which keys are currently depressed? My first thought was a dynamic array, but maintaining and searching a dynamic array seems like a serious drain on resources.

Many thanks in advance for any help

Joe

答:
A fixed-length array will work just fine, since the number of keys can't change.
So, make an array, call it depressed, of length N, where N is the number of keys on your input device.
When key X is depressed, set depressed[X] to True.
When key X is released, set depressed[X] to False.
To report the True/False state of any given key, you'll need a mapping from user-/API-level names, to indices into your array.
e.g. MOTOR_REVERSE_TOGGLE -> position 6 in your array.

As for efficiency, an array should be adequate for space, unless you've got very tight memory restrictions on whatever device you're programming. In that case, you'd use a bitfield to store the data. Basically, it's the same as your array, except instead of words being set to True or False (which would end up a some magic numbers, say for example 11111111 and 00000000), you set individual bits in a word to 1 or 0.


答:
We have to admit that software developers spend much more time reading/understanding code than creating it. And from my personal experience, the better is company you work for the more code you read. So the fact that you have to deal with others' code so much shouldn't surprise or confuse you at all.

And this seems quite natural. In order to learn something you have to see how its done. There aren't many companies where pair programming is practiced and novices are taught this way. Most of the time you learn new techniques, patterns, company's coding style etc. by reading others' code.

And the most efficient way of understanding code is actually working with it: debugging, refactoring, fixing bugs. This is a common practice if you are to take the ownership of the code.

The possible reasons why the original developer doesn't fix his/her bugs might be that

the bug has little priority, and the developer's current task is more important or urgent.

the developer hasn't worked with that code for a long while and it would anyway take them some time to recall their old code.

the developer is very busy with something complicated and needn't be interrupted.

P.S. I think you're lucky that the original developer is there to answer your questions.

Title: Policy and practice on code maintenance

Body:
I just came out of University and have been working at this company for roughly 8 months, while I was given the title of developer, most of the time I have spent on is fixing and debugging other people's codes.

I always wonder why isn't the original developer's responsibility for fixing his/her code. I understand that if the original developer is no longer present, then the other developers have to take over the work, but what if the developer is still working as an employee in the company?

One may argue that it is beneficial to the new developers as they see it as an opportunity to learn, and I agree with that, but what if the complexity of the problem/issue of the code is very steep? In my case, most of the codes they assigned me to fix are non trivial problems, and it always ends up myself asking the original developer questions regarding the code. Why can't the developers who created it fix the existing problem if they understand it so much better since they coded it? And the problem I am referring to is not some trivial problem where you can fix it in a day or two,but problem that requires a deep understanding of the code in order to come up with a solution.

What is the reasoning behind this and is it common in the software industry?


问:
How do ORM'S manage CRUD operations in multi thread environment
Suppose I have code which retrieves an object and modifies it and submits it via any ORM from a web application. Below is the pseudo code:

First request

```<code>var objCust = _dbContext.Customers.Where(c=>c.CustomerId == "ALFKI").SingleOrDefault();
objCust.Address ="test address 1";
//and add some orders
_dbContext.SubmitChanges();
</code>```

Second simultaneous request

```<code>var objCategory = _dbContext.Categories.Where(c=>c.CategoryId == 1).SingleOrDefault();
objCategoryName = "test name";
_dbContext.SubmitChanges();
</code>```

How does the first request only grasp the changes done to customers and submit the changes. Is there any mechanism inbuilt in ORM's to track changes to entities per thread or request.

答:
The ORM does not (always) manage the transactionality. At the end of the day, the transactionality is going to be handled by the ACID guarantees of your database while the ORM simply acts as a communication layer with your database.

That said, some ORMs have built-in caching and other more complex techniques in attempts to avoid the database except when necessary to lower the load on the database. In these forms of ORMs there is surely transactionality management required to some extent, and the technique will be the same techniques any multi-threaded app uses for transaction handling: shared state with locks/semaphores/signals/mutexes where necessary inside of the ORM. Alternatively they could be lacking those locks and be simply not thread safe for certain scenarios, but I have to think an ORM developer is going to be knowledgeable enough to be keen on these scenarios and focus on ensuring thread safety.

Note I say this referring to the Java/C# style OO languages where locking is the required technique for multi-threaded safety assurances, I do recognize other types of languages use lockless techniques.


答:
You can pass a factory via dependency injection just like you pass anything else, don't let the recursiveness of the situation confuse you.  I don't know what else to say about implementing it - you already know how to do dependency injection.

I use DI to inject factories pretty regularly.


答:
Other commenters have already covered some important points - I'm talking from the position of someone who worked for a while in a development team specifically tasked with maintenance of shipped code. Pretty much all of your questions came up time and time again.

There are many things that could be going on. You pointed one out - the original developer may have left the company. Another possibility is that, while the original developer is still in the company, he/she has long since moved on to other things, and no longer has that stuff in working memory (especially if the code has changed quite a bit since they were working on it).

What we had to deal with, for instance, is that the product team had very aggressive schedules for delivering next versions of the product. If they also had to work on bugs in the existing versions, at least so the reasoning went, they wouldn't have been able to meet their schedules. I guess this point could be argued, but the reality of the corporate software world is that getting stuff out the door trumps everything else, including observing all the best practices of software engineering at all times. "Tradeoffs" is the vague term under which fall all the unpleasant compromises us developers sooner or later have to do in those environments.

On the other hand, however, fixing non-trivial bugs requires you to really learn a lot about the codebase. It is painful, sometimes demoralizing, and oftentimes overwhelming. But how exactly do you think you're going to become a subject-matter expert on a software project? You can spend days reading the code for your edification, but that kind of code perusal doesn't really stick as well as having had to "battle" with the code in order to fix a problem. Researches continually trump the motto that we learn by doing. Sadly, unless you're in a startup or a new team, this means that you're usually joining a software project which has been around for several releases, and has real customers with real complains that need to be addressed. This implies that you will be fixing bugs first before you're given functionality to add/redesign.

What's really important is to communicate regularly with your manager and express what you want to get out of the job, and see if the business can actually accommodate for your goals at the moment. Hopefully, the answer will be yes. Stick around for a while and gather all the experience you can from your current team. If the answer turns out to be no, and you're a good developer, you will have many options. But do not discount the experience you gain by fixing bugs - I'm now into my third software job and I have to write tons of code. Fortunately, a lot of it works from the start because I've spent so much time identifying, fixing, and trying to prevent bugs.

Title: Policy and practice on code maintenance


答:
There's nothing wrong in injecting factories.
It is standard way if you can't decide during build of 'parent' object what kind of dependency you will need. I think example will explain it best. I will use c# because I don't know java.</p>

```<code>
class Parent
{
    private IParserFactory parserFactory;
    public Parent(IParserFactory factory)
    {
        parserFactory = factory
    }

    public ParsedObject ParseFrom(string filename, FileType fileType)
    {
        var parser = parserFactory.CreateFor(fileType);
        return parser.Parse(filename);
    }
}
</code>```

Body:
There's nothing wrong in injecting factories.
It is standard way if you can't decide during build of 'parent' object what kind of dependency you will need. I think example will explain it best. I will use c# because I don't know java.

class Parent
{
    private IParserFactory parserFactory;
    public Parent(IParserFactory factory)
    {
        parserFactory = factory
    }

    public ParsedObject ParseFrom(string filename, FileType fileType)
    {
        var parser = parserFactory.CreateFor(fileType);
        return parser.Parse(filename);
    }
}


问:
Real performance of node.js
I've got a question concerning node.js performance.

There is quite lot of "benchmarks" and a lot of fuss about great performance of node.js. But how does it stand in real world? Not just process empty request at high speed.

If someone could try to compare this scenario:

Java (or equivalent) server running an application with complex business logic between receiving request and sending response.

How would node.js deal with it? If there was need for a lot of JavaScript processing on server side, is node.js really so fast that it can execute JavaScript, and stand a chance against more heavyveight competitors?

答:
Node's kind of hard to compare directly because it's a bit of an odd bird. The critical thing to understand is that yes, while JS does block, which is intended desirable behavior in the case of Node, the other half of the system is the C++ operations under the hood that can in fact run in parallel with one another. That's the reason you do almost everything asynchronously with the JS in Node. The key thing to understand is that there are two layers. You direct traffic and handle simple data structures with the JS and its blocking nature acts as a kind of auto-queuing system. As a bonus, you get to reap all the benefits of JS being an obscenely easy language to implement messaging/event-driven paradigms with. For anything that's likely to take a while, no matter what you write it in, you're best off doing that with the C++.

The point of the JS as-blocking-interface on top of that is to bury all that nasty/messy thread-handling stuff WITHOUT actually reducing you to the use of one processor only.

People are no doubt going to write some absolutely hideously performing stuff with Node out of ignorance but I don't see any reason it couldn't scale for an enterprise(ew @ terminology)-level framework and I'm personally getting more and more excited about it the more I use it (which has so far mostly been to reduce config/build complexity of a web app triple-stack of Rails, .NET and Java).

Furthermore, modern JS JIT compilers have improved performance of JS by an order of magnitude in recent years and Node is built on Chrome's V8. I'd be surprised if JS didn't at least compare favorably to Python for single-threaded speed and like Python, you can handle the architectural glue of an app with a lot less code which tends to result in things being less messy and easier to manage in terms of basic work avoidance and writing a legible, modifiable, maintainable app, where you never have to think through what should (IMO) be obvious in higher level.

How do you really measure that semi-objectively for comparison? Barring some sort of competition with massive participation to write the same app with different stacks, you can't really. I think the best you can do is look at how apps tend to behave, what the team knows best, what tools are available, and not worry about performance comparisons unless the tool in question has a rep for crummy perf across the board. In my experience, Java wins the micro-benchmark wars, but is typically a notoriously poor performer on the server-side web compared to Rails, PHP, Python and ASP.net post-MVC for basic and not-so-basic web apps that I've worked on.

That's not to say Java couldn't outperform any app in another language or that it never does. Nor am I saying I've never seen shoddily written JS, Python, or PHP. However, given the quality of your average large Java team vs. a typically MUCH smaller team of JS or Python ninjas doing a web-app of average complexity for probably less total pay (and yes I'm absolutely offering a purely subjective opinion based on personal experience because that's all that's left) I'd put my money on an app produced by a few seasoned devs with a language that can get a lot more done in a lot fewer verbs and nouns without limiting your ability to structure things.

But ultimately, what I assume you're wanting to know is whether it's okay to use it and that involves subjective concerns.

So do you like the idea of writing apps with a given language/stack design, do you like what the community's doing with it, and barring more highly specific concerns does it not suck generally at performance in 80% of obvious use-cases? In Node's case, I'd personally say yes, yes, and yes.

But if you're not really interested in how it works and don't really care for JS, necessarily, I'd stay away from it because those are the two key things that give Node value and are requirements for keeping it performant.

So far for me, it's behaving exactly as I would expect a good JS tool to. It's reducing complexity like a champ by allowing me to wrap an inherently brittle/messy process in something that's robust and legible. That right there is why JS won the undisputed place it's had in browser UI and will continue to expand as a general-use language.

Title: Real performance of node.js


答:
In the general case you'll need to check every combination. The code under the if may depend on any number of variables, whose state is reflected in tests A-E. What if variable x is set whenever condition C is true, but the execution path through condition D doesn't set it? What if calling D has side-effects itself that affect the conditional block?

In practice, this kind of code may encapsulate small commonalities between diverse execution paths, and it's hard to get all paths to set up the state correctly. So mistakes of this sort are likely to happen.

Title: How to count condition coverage

Body:
I am wondering, What would be the correct condition coverage test cases for the following condition:

```<code>if(A && E && (B || C || D))
</code>```

Considering short circuiting, what cases would I need?

EDIT: Sorry I put only a half of the expression


答: Most O/RMs are not thread-safe. When using an O/RM in a web app, the common practice is to create a UnitOfWork per request that is tied to that request's thread. Another option is to expose the UnitOfWork as a [ThreadStatic] variable. And finally, there are some Dependency Injection containers that will allow you to tie the lifetime of an object (e.g. a UnitOfWork) to a thread.</p>

Title: How do ORM'S manage CRUD operations in multi thread environment

Body:
Suppose I have code which retrieves an object and modifies it and submits it via any ORM from a web application. Below is the pseudo code:

First request

```<code>var objCust = _dbContext.Customers.Where(c=>c.CustomerId == "ALFKI").SingleOrDefault();
objCust.Address ="test address 1";
//and add some orders
_dbContext.SubmitChanges();
</code>```

Second simultaneous request

```<code>var objCategory = _dbContext.Categories.Where(c=>c.CategoryId == 1).SingleOrDefault();
objCategoryName = "test name";
_dbContext.SubmitChanges();
</code>```

How does the first request only grasp the changes done to customers and submit the changes. Is there any mechanism inbuilt in ORM's to track changes to entities per thread or request.


答:
ORM is tracking changes per session object not per request/thread.
When I say session I mean _dbContext in your example.
In web applications it is common practice to create one session object per web request.

So if both requests are separate then none of _dbContexts knows about any other.
In your example there will be two updates sent to database.


答:
There are pedagogical reasons and risk factor reasons, but mostly it's just math.  Most programming work is maintenance, and those who have been at a company the longest have generated the most code that needs maintaining.

Consider a one man software company.  After 10 years he hires someone to help him out.  If 90% of the work available is maintenance work, what is the new guy going to work on if he can't touch the old guy's code?  On a larger team the effect is harder to quantify, but that doesn't mean it's not there.

So try not to get hung up on who's responsible for what code.  People get attached to "their" code and don't give it up lightly.  In a few years there will be code you want to preserve your responsibility for, but you just plain won't have time.

Title: Policy and practice on code maintenance


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

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

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

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

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

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

答:
Brent Kirby establishes a number of computationally complete bases of stack operations in his Theory of Concatenative Combinators. You need some notion of “quotation” of stack terms. Using his nomenclature, the following sets of combinators are all Turing-complete:

```<code>            [B] [A] cons == [[B] A]
            [B] [A] sip  == [B] A [B]
            [B] [A] k    == A

    [D] [C] [B] [A] s'   == [[D] C] A [D] B
            [B] [A] k    == A

            [B] [A] cake == [[B] A] [A [B]]
            [B] [A] k    == A

[E] [D] [C] [B] [A] j'   == [[D] A [E] B] [C] B
                [A] i    == A

            [B] [A] take == [A [B]]
            [B] [A] cat  == [B A]
                [A] i    == A

            [B] [A] cons == [[B] A]
            [B] [A] sap  == A B
</code>```

Using my preferred nomenclature, a convenient complete set to implement is:

```<code>          A dup == A A
       A B swap == B A
         A drop ==
        A quote == [A]
[A] [B] compose == [A B]
      [A] apply == A
</code>```

Body:
Brent Kirby establishes a number of computationally complete bases of stack operations in his Theory of Concatenative Combinators. You need some notion of “quotation” of stack terms. Using his nomenclature, the following sets of combinators are all Turing-complete:

            [B] [A] cons == [[B] A]
            [B] [A] sip  == [B] A [B]
            [B] [A] k    == A

    [D] [C] [B] [A] s'   == [[D] C] A [D] B
            [B] [A] k    == A

            [B] [A] cake == [[B] A] [A [B]]
            [B] [A] k    == A

[E] [D] [C] [B] [A] j'   == [[D] A [E] B] [C] B
                [A] i    == A

            [B] [A] take == [A [B]]
            [B] [A] cat  == [B A]
                [A] i    == A

            [B] [A] cons == [[B] A]
            [B] [A] sap  == A B

Using my preferred nomenclature, a convenient complete set to implement is:

          A dup == A A
       A B swap == B A
         A drop ==
        A quote == [A]
[A] [B] compose == [A B]
      [A] apply == A


问:
Why do some websites include the "page name" in the URL?
I'm not a web programmer at all so I really have no idea:

You'll notice that websites like Stack Exchange have links like this:

```<code>http://programmers.stackexchange.com/questions/188078/policy-and-practice-on-code-maintenance
</code>```

As you can see, the link includes the "page name" (Policy and practice on code maintenance).

We know this is unnecessary, since I could just use

```<code>http://programmers.stackexchange.com/questions/188078
</code>```

instead. Curiously, upon using this link, the site will replace it for the one with the page name.

My question is: why do some websites put the page name in their links? What advantages or disadvantages come from that?

The only advantage that comes to my mind is the fact that the link becomes more user friendly since it is easier to identify what the URL is about. But I wonder if there are more technical aspects behind this behavior.

答:
Here are a couple of SO questions that cover this topic as this is an SEO feature generally so that the keywords are part of the URL that can be indexed:

Why do some websites add “Slugs” to the end of URLs? [closed]

Why use page title in URL? [duplicate]


答:
Erik is spot on.

Also management want to hedge their bets by getting all developers familiar with certain aspects of the code. Just because one person wrote some code does not automatically make them responsible for it whilst they are working there. Quite the opposite, the more developers that maintain it, the more chance of bugs being spotted and improvemnets being made. Everyone likes to leave their mark ;) if you know what i mean. Another view is that the code is owned by the company and not the developer. It makes a project managers life slightly easier if their have more developers to choose from for a certain task. They are probably just easing you into to their code libraries and at the same time testing your ability. They would be crazy letting a new employee near anything that could cost the company money, certainly for the first 6 months or so.

Title: Policy and practice on code maintenance


答:
Confusing Semantics

It's a semantics issue. When somebody says a .NET front end or Java front end developer, they're usually talking about the person who knows a lot bout the templating languages and maybe frameworks that should never be used ever again like webforms that were used to try and hide the chucking of things over an http wall (i.e. "web development") from app developers who didn't want to or at least were assumed to not want to learn about all that crap. In the case of mixed .NET and Java, I'm not sure but I could only guess that in the MVC sense of things they've got Java acting for all the business model stuff and .NET handling everything else which would be better described as "middle-tier" but it's still all server-side.

The real separation is what happens on the server and what happens on the client or browser. You could easily conflate building the HTML to be sent to or representing the front end with "front end development" so I prefer avoiding confusion by using the terms client and server-side instead of front and back-end when discussing what I typically do, (usually client-side work).

Client Side Languages

The reason we use the same set of languages on the browser is because the browser is on the receiving end and for the most part (there's been now-mostly-dead resistance from Microsoft and Adobe on this) nobody wants to have to send out three different versions of the same client-side to satisfy every potential customer or require a proprietary plug-in be installed for the web to work. Also, the three languages actually encapsulate client-side concerns quite nicely, allowing us to rapidly build and modify web app front-ends by maintaining loose coupling between document structure, how everything looks and how it all behaves. You can change one without changing the other two quite easily.

Server Side Languages

The reason you have bazillions of options on the server side web of course is because you can. It's your server. All it has to do is communicate via http/ssl and the rest is up to you. JavaScript is now an option by the way, but that brings up an interesting question. Should you still treat a web app like it's really two apps on either side of that HTTP wall. I'm of the informed-through-pain opinion that yes, yes you should and I love Node.js.


答:
Assuming that each of the values is independent of the other (that the value of B does not depend on the value A), then the minimum number of test cases is (true values are cap, false are lower case):

a

Ae

AEB

AEbC

AEbcD

AEbcd

The difficulty with implementing just the minimum number is that if the code changes (extract method refactoring on the conditional) but the business logic does not, it may miss an incorrect result.

Title: How to count condition coverage


问:
Is LISP still useful in today's world? Which version is most used?
I try to teach myself a new programming language in regular intervals of time. Recently, I've read how Lisp and its dialects are at the complete opposite end of the spectrum from languages like C/C++, which made me curious enough to know more about it. However, two things are unclear to me, and I'm looking for guidance on them :

Is LISP still practiced/used in todays world, or is it a legacy language like FORTRAN/COBOL ? I mean, apart from maintaining existing code, is it used on new projects at all ?

What is the most widely used dialect ? I came across Scheme and Common Lisp as the 2 most prevalent dialects, and wanted your opinion as to which is the most favored/useful one to learn - and would be immensely gratified if you can suggest any resources for a rank beginner to start from.

While eager to learn a language which is fundamentally different from the procedural languages I'm used to, I don't want to invest undue effort in something if its totally obsolete - I'd still learn it if it was professionally "dead", but only with an academic perspective...

答:
I learned a lot from the answers.  Thank you to all who contributed to this enlightening conversation.

I should mention newLISP.  Although it differs a bit from both CL and Scheme, it implements a lot of very useful functions.  I find the http server,  multi-processing functionality (Cilk) and remote evaluation functions very clean and easy to use.

The single executable is small, fast and includes a lot of cool batteries.


答:
There are couple reasons.

Learning curve. Virtually everyone can learn and write in javascript.

Security. It's hard to control security context of script code in C# or Java. Javascript is perfect for that. Script author never able access to disk or anywhere if do not allow them. Core javascript engine is just a advanced calculator.

Quality. You put a very thick limit to scripting code.  "Spaghetti code" levels are very different for Javascript or C#/Java. (Which is prevents you from opening the gates of hell)

Type safety. C#/Java are type-safe environment, you mostly don't prefer it in a scripting environment. Expression like "12" + 3 gives "123" in javascript but C#/Java will not even compile. Script writers mostly does not even what is "type"

Dynamic. Any object can contain any property/method and may change it's type in time. For example I could provide a proxy C# object to scripting environment that exposes XML nodes as properties.

Productivity. Usually writing script is much more easy than C#/Java. No compilation or "plugin registration" required. You could directly edit the script content within application with immediate results.

Managing. Using C#/Java requires a SDK to be link on plugins that exposes internal classes to world. This plugin architecture requires the "backward-compatibility" for old SDK versions. This architecture forces you to create "virtual" domain objects that provides internal mechanism of application in domain context. It's more manageable/flexible than exposing an API.

Title: When would using a scripting language within a larger program be useful?

Body: I have heard of several situations of people using say, JavaScript or Python (or something), inside a program written in C#. When would using a language like JavaScript to do something in a C# program be better then just doing it in C#? </p>


答:
Very broadly there are two situations where you would apply this pattern:

This is used internally to leverage some quality of the embedded language.

This is used to provide external programmability.

Internally

Typically the embedded language is interpreted which allows changes
to be made and tested quickly without a re-compile.

The embedded language may be more expressive than the language your core application is written in, again allowing for faster development.

The language may be a better fit for some particular domain compared to a general purpose language.

The language is used by internal users who need a "simpler" programming language/environment.  Short programs are written by people who are not software developers using a relatively simple syntax/API.

An example here would be Lua used in Adobe Lightroom.

So what we do with Lua is essentially all of the application logic
  from running the UI to managing what we actually do in the database.
  Pretty much every piece of code in the app that could be described as
  making decisions or implementing features is in Lua until you get down
  to the raw processing, which is in C++.
  (Mark Hamburg Interview: Adobe Photoshop Lightroom)

Externally

Allow users to extend the behavior of your application without requiring special tooling and/or libraries and/or access to your source code.

Provide those users with a well defined API and a sandboxed enviornment.  This could also be done in the application's language but embedding an interpreter can make this easier.

IBM used scripting languages very successfully in their mainframe operating system VM-CMS.  EXEC, EXEC/2 and later Rexx were used throughout the system both internally and externally.  Different applications (e.g. XEDIT) were scriptable using those same languages and internal applications/utilities (e.g. E-mail) were written in the scripting language and leveraged the tight integration with the OS and other tools.  Customers created and shared many scripted tools and applications. DEC also provided DCL.  Later on Microsoft supported VBscript as a scripting language in most of their applications and more recently PowerShell (also MS/DOS batch files).  Unix shells have scripting as well.

The trend today appears to be exposing APIs in some way and leave the choice of scripting language up to users who can utilize different bindings or other means of accessing the API.


答:
good answers, all; here's another angle -

it may be simple economics

it may take you 5 times longer to find and fix a problem than it would the original developer, but the work the original developer is doing in the meantime provides far more revenue to the company

Title: Policy and practice on code maintenance


问:
Database connection - should they be passed as parameter?
We have a system whereby the database connection is get once using a common method, and being pass throughout the relevant class to be used. There are doubts that passing the database connection as a parameter to different classes would cause problem, so i'm checking here to see whether this is actually viable, and are there any better patterns to do it?

I know there are some ORM tools to do the persistence but we can't go into that, yet..

Any feedback is welcomed, thanks.

答:
there's a tradeoff to doing things this way rather than using a singleton which you can get as needed.  I have done things both ways in the past.

In general, you need to think about the consequences of database connection management, and this may or may not be orthogonal to database query usage.  For example, if you have one db connection for a given application instance and it gets closed when not in use, that would be orthogonal.  Put the management in a singleton class and don't pass it around.  This allows you to manage the db connection as you need.  For example, if you want to close a connection on every commit (and re-open on the next call) this is easier to do on a singleton because the API for this can be centralized.

On the other hand, suppose you need to manage a pool of connections where a given call may need to use any arbitrary connection.  This might happen when doing distributed transactions across multiple servers, for example.  In this case you are usually far better off passing the db connection object than you are working with singletons.  I think this is usually the rarer case, but there isn't anything wrong with doing it when you need to.


问:
Licensing approach for .NET library that might be used desktop / web-service / cloud environment
I am looking for advice how to architect licensing for a .NET library. I am not asking for tool/service recommendations or something like that.

My library can be used in a regular desktop application, in an ASP.NET solution. And now Azure services come into play.

Currently, for desktop applications the library checks if the application and company names from the version history are the same as the names the key was generated for. In other cases the library compares hardware IDs.

Now there are problems:

an Azure-enabled web-application can be run on different hardware each time (AFAIK)

sometimes the hardware ID for the same hardware changes unexpectedly

checking the hardware ID or version info might not be allowed in some circumstances (shared hosting for example)

So, I am thinking about what approach I can take to architect a licensing scheme that:

is friendly to customers (I do not try to fight piracy, but I do want to warn the customer if he uses the library on more servers than he paid for)

can be used when there is no internet connection

can be used on shared hosting

What would you recommend?

答:
It's not perfect, but here's what I would do. I would send a message somewhere to one of your servers each time a new hardware ID pops up. You'd keep track of how many hardware IDs each user has. If they're registered for 5 servers, but there appears to have been 20 hardware IDs used in the past hour, that's a bit suspicious. Email them and warn them that they might be using this outside of the terms of the license.

Note: this in NO way to fight piracy. This is to provide a system so you can ensure your client know if they are possibly going outside of their license (it sounds like you're marketing to businesses, which typically really care about this and lawsuits)


问:
"Public APIs are forever: Only one chance to get it right"?
In an OS book I just read that, "Public APIs are forever: Only one chance to get it right". Is it true? Is it applicable only in APIs of Operating Systems or other APIs too? For example, will this be true for the APIs of Android Applications such as Tasker, Locale and Pushover?</p>

答:
It is generally true for any public API, yes.  Once you expose an API to the public and people start to build applications that depend on that API, it becomes extremely difficult to change the API because doing so will break all those applications.  That tends to be both a difficult technical problem and a difficult political problem.

Of course, it is possible to change a public API.  It does happen, for example, that projects will depricate an API in one release, introduce a new API, and then remove the old API in some future release.  But that assumes that every (important) application that uses the old API will be rewritten to use the new API before the old API is removed.  That often takes multiple years.  And that means that the owner of the public API is imposing a cost on every other project that consumes the API.  Since there are generally far more consumers of an API, those consumers tend to be a relatively powerful political lobby.


答:
Quote author is Joshua Bloch, the statement is from his Bumper-Sticker API Design article:

Public APIs, like diamonds, are forever. You have one chance to get it right so give it your best.

For more details on that, author refers readers to his conference session presentation, "How to Design a Good API and Why it Matters". Slide Why is API Design Important to You states it pretty clearly that this is relevant to any programming activity (operating systems or not, doesn't matter to author):

If you program, you are an API designer

Good code is modular - each module has an API

Useful modules tend to get reused

Once module has users, can’t change API at will

Good reusable modules are corporate assets

Thinking in terms of APIs improves code quality

Slide Conclusion also stresses this as a general approach:

API design is a noble and rewarding craft

Improves the lot of programmers, end-users, companies...

Title: "Public APIs are forever: Only one chance to get it right"?

Body: In an OS book I just read that, "Public APIs are forever: Only one chance to get it right". Is it true? Is it applicable only in APIs of Operating Systems or other APIs too? For example, will this be true for the APIs of Android Applications such as Tasker, Locale and Pushover?</p>


问:
Noda Time vs Joda Time?
In the Noda Time User's Guide, the rationale section states:

the public API has been largely rewritten, both to provide an API which is more idiomatic for .NET, and also to rectify some of the Joda Time decisions which the Noda Time team view as "unfortunate". (Some of these are simply due to having different goals; others I'd argue are really mistakes.)

What are these decisions that are different/better? This would not count differences just for language syntax, but would include anything done to make the users less likely to make a programming error (library usability).

答:
The best place to start is probably the "design philosophy" section of the user guide. But to lay out specific differences between Noda Time and Joda Time:

Noda Time keeps much more of its code internal. This makes it less flexible, in that you actually can't create your own calendar system - but also means the API is simpler both to learn and use.

Nullity is almost always an error in Noda Time. No more "if you pass in null for a time zone, we'll just use the system default." You need to be explicit.

Speaking of defaults... we don't use the system clock as a default. We've got a separate IClock interface with a SystemClock implementation, but nothing defaults to "the current time."

Aside from specific builder classes, everything is immutable. I think MutableDateTime (et al) in Joda Time were a mistake.

We've separated calendar system and time zone from each other, as they're really very different concerns. So a LocalDate knows about the calendar system it uses, but not the time zone, for example.

The manner of resolving local date/time values to zoned date/time values is closer to JSR-310 than Joda Time. We don't just handle ambiguity/skipped times in some particular manner: we make the user say what they want.

Joda Time has various places where it tries to guess what you want from a weakly-typed API (e.g. new Instant(Object)). Noda Time avoids this as far as it possibly can - it's much more explicit.

Noda Time is stricter in what kind of arithmetic you can perform on which types. So for example, you can't add a Period to a ZonedDateTime, because there are oddities around daylight saving transitions which could mess things up. Instead, we encourage users to convert to LocalDateTime, do however much arithmetic they want to in a non-zoned context, and then convert back.

Noda Time uses inheritance rather less - the hierarchies in Joda Time are hugely deep and complicated. The fact that a lot of Noda Time is based on value types actually enforces this anyway, but there are some places where we're still using class inheritance, but I've managed to collapse the inheritance hierarchy significantly... often at the expense of flexibility which I didn't consider to be worthwhile :)

Title: Noda Time vs Joda Time?


问:
Handling error message for a Spring MVC login form
This can apply to many error handling scenarios, but I'm curious about how to do it in a login scenario.

Given this Spring controller method:

```<code>@RequestMapping(value = "/account/login", method = RequestMethod.POST)
public String login(@RequestParam("username") String aUsername,
        @RequestParam("password") String aPassword,
        Model model)
{
        try {
            accountService.login(aUsername, aPassword);
        } catch (LoginException e) {
            // log e
            // add an error to request scope
            model.addAttribute("error", e.getMessage);
            return "login"; // return to login page
        }
        // success, show profile
        return "redirect:profile";
    }
</code>```

And a login.html form (I'm using thymeleaf, but just follow logic, similar to jsp):

```<code><!-- This is saying, if ${error} is set, use it instead of the content of p, `No error` -->
<p th:if="${error}" th:text="${error}">No error</p>
<form method="post" action="#" th:action="@{/account/login}">
    Username: <input name="username" type="text" />
    Password: <input name="password" type="text" />
    <input name="login" type="submit" value="Login" />
</form>
</code>```

Is this how error handling is usually done in java web applications? Anywhere an error can happen, you branch out with different ifs? Is there a cleaner, or more generic, way to do this?

答:
Error Handling and Displaying to users can be unique depending on your UI design and on how you want to view it by the user. Displaying it on mobile can be different from displaying on a desktop.

What I know is it is important as well to categorize these errors. There are validation errors, security access errors, critical error(i.e database exceptions, any unexpected exceptions). And for each categories, you could design different approach such as for critical error, you could use a dedicated page that will catch all critical errors. For validation errors, you must display it on the same page where the user enters invalid data and make sure that your message is very obvious that they will recognize immediately which fields/inputs to correct, etc.

Displaying of errors must always be user friendly, direct and appropriate.


问:
Avoiding "Smart Guy" Syndrome on Team Projects
A lot of bad practices were being committed at the beginning of a project, and I recognized them and fought against all of them. Since I didn't pick and choose my battles, my boss now assumes anything out of my mouth is an over complicated response, and spends a lot of time defending himself personally, instead of looking out for the best interest of the project.

How do I push the team in the right direction, without waiting four months for everyone to come to the consensus I was trying to get in place all along, or scarring my reputation on the team as a difficult know-it-all?

答: be sure not to confuse being recognized as being right and getting result according to what you think is right. Those two goals are both valid and legitimate but they are not the same and it's very hard to get them together especially if you dont have a clear view on which one you are working for.</p>


问:
Strategy for website with international strings
What things need to be considered for a Website that contains International strings, for instance Simplified Chinese and English mixed.

UTF8 seems to me a natural choice, including a meta tag.  Still, some users may only see white boxes.  What is the best solution do deal with this?

Currently I am thinking to provide an alternative image-based rendering, or even make it default.  But IMHO this seems a weak solution.  Or I could tell the user which OS/Browser combinations are known to work but such a list would probably be endless.

Update: it's a Chinese learning site, most users will not have visited Chinese websites before

答:
The white boxes are not dependent on the OS/browser combination, but rather on the fonts that the end-user has installed on his/her system.

With that in mind, there are several options:

If the normal visitors to the site are expected to be able to read the non-English-alphabet texts, then I would not worry too much. You can expect them to have the appropriate fonts installed. For the few who don't, you could add a hint to which languages are used and which additional fonts might be needed.

If the non-English text comes from contributions by other users (such as comments or forum messages), there isn't much you can do anyway as it is impractical to support all alphabets supported by Unicode.

You could offer a fully translated version of the site.

update: Given the update in the question: For a Chinese-teaching website, I would have a page that allows students to test if they have the correct fonts and directions how to obtain and install any missing fonts.


问:
Is there an accepted name for a fake object injected via a preprocessor seam?
I am dealing with some old, sloppy C++ code in which there is a structure with a lot of data members and functions. I want to test a class that I have implemented which uses the struct, but this dependency is going to make the unit tests extremely ugly. Inspired by Michael Feather's discussion of preprocessing seams in Working Effectively with Legacy Code, I am getting ready to solve this problem by faking the ugly structure with the preprocessor (not with inheritance) polymorphism as demonstrated in the following notional code.

test.cpp

```<code>#include <iostream>
#include "NotAsUgly.hpp"
#include "DependsOnUgly.hpp"
int main() {
    std::cout << DependsOnUgly().getDescription() << std::endl;
}
</code>```

DependsOnUgly.hpp

```<code>#ifndef _DEPENDS_ON_UGLY_HPP_
#define _DEPENDS_ON_UGLY_HPP_
#include <string>
#include "Ugly.hpp"
class DependsOnUgly {
public:
    std::string getDescription() {
        return "Depends on " + Ugly().getName();
    }
};
#endif
</code>```

Ugly.hpp

```<code>#ifndef _UGLY_HPP_
#define _UGLY_HPP_
struct Ugly {
    double a, b, ..., z;
    void extraneousFunction { ... }
    std::string getName() { return "Ugly"; }
};
#endif
</code>```

NotAsUgly.hpp

```<code>#ifndef _UGLY_HPP_ // Same name as in Ugly.hpp---deliberately!
#define _UGLY_HPP_
struct Ugly { // Once again, duplicate name is deliberate
    std::string getName() { return "not as ugly"; } // All that DependsOnUgly depends on
};
#endif
</code>```

Is there a special name for the type of fake object I'm using here? I'm inclined to call it a stub, but it is rather different than what I would normally think of as a stub. I would expect something called a stub to implement the interface of the class which is to be faked through inheritance. Here the implementation is only partial, and happens through the preprocessor.

Is there already a known name for this kind of fake/testing object? I want to name the header file that contains it (NotAsUgly.hpp in my example) to properly signify to other developers what it is for.

答:
You could use the generic term "Fake" here.

On the other hand, "Stub" is also a good name. Your description of the fake class fits nicely with the definition of stub on wikipedia.


问:
How is the build for a msdeployment project different than a regular web application project?
In our CI environment we build all the cs projects and then build the deployment projects. The deployment projects do an extra step of compiling the aspx & ascx files and often catch errors that would normally be caught at run time.

1) Is there a name for this step or process?

2) Can I get it in the regular project builds?

3) Where can I learn about the various steps of building specifically to msbuild?

Reading the logs in verbose I'd like to have a better understanding of what is actually happening.

Thank you.

答:
Is there a name for this step or process?

This additional step is the ASP.NET Compilation Tool, which compiles your aspx/ascx pages, to speed up first load times.

Can I get it in the regular project builds?

Yes - the AspNetCompiler Task will do this for you.

Or you can invoke aspnet_compiler.exe directly.


答:
I recommend reading http://www.jamesshore.com/Change-Diary/ It has a lot of incredible remarks about managing change in a company. Also this book might be helpful: http://www.amazon.com/Agile-Coaching-Rachel-Davies/dp/1934356433 . Not because you should go Agile but because it has lot of remarks about providing change to a team and dealing with feedback and response. From my own experience: You will not be able to change anything if people are not with you on it. If they do not already want such change. If that is the case, you can just leave it. You probably expect something different from your work or you outgrow your coworkers.

The best approach IMHO is to be the change. Doing things the right way yourself as you see them. Others will follow you if they found value in your approach. And they will be grateful for you for introducing this change. However first people need to see the good side of the change. Then they want it. It is very hard to do it the other way (introduce change, wait for good results of it).

Wish you best luck.

Title: Avoiding "Smart Guy" Syndrome on Team Projects

Body:
A lot of bad practices were being committed at the beginning of a project, and I recognized them and fought against all of them. Since I didn't pick and choose my battles, my boss now assumes anything out of my mouth is an over complicated response, and spends a lot of time defending himself personally, instead of looking out for the best interest of the project.

How do I push the team in the right direction, without waiting four months for everyone to come to the consensus I was trying to get in place all along, or scarring my reputation on the team as a difficult know-it-all?


问:
Condition coverage for If(A && B) - measuring the input or code exercised?
I have been studying condition coverage for last few days. In a book "The Art of Software Testing" they highlight that it does not assure decision coverage, because for example

IF(A && B)

A=True, B=false and A=False,B=True satisfies the condition coverage but the decision is always False.

I wonder, how can this satisfy the coverage? The True value of B will actually never be tested because of short circuiting so how it can satisfy the coverage?

答:
Condition coverage is about testing that any operands which are part of the if expression can be evaluated to both true and false without issues. In this type of coverage, you don't care about what would be executed inside the braces, nor about the result of the operand used in a condition.

Take the following code:

```<code>bool a = ...;
bool b = ...;
if (a && b)
{
    ...
}
</code>```

Condition coverage of this code would require to test:

a for both true and false, and:

b for both true and false.

In languages which require both operands to evaluate in a logical operation, condition coverage of the code above is satisfied with:

```<code>a = true; b = false
a = false; b = true
</code>```

This is what is illustrated in your question.

Some languages evaluate the second operand of a logical AND only if the first operand is true (or evaluate the second operand of OR only if the first operand evaluates to false). In this case, three tests are required instead of two:

```<code>a = true; b = true
a = true; b = false
a = false
</code>```

As you can note, we don't care about the value of b in the third test, since the program will never compute it when a is false.

Body:
Condition coverage is about testing that any operands which are part of the if expression can be evaluated to both true and false without issues. In this type of coverage, you don't care about what would be executed inside the braces, nor about the result of the operand used in a condition.

Take the following code:

bool a = ...;
bool b = ...;
if (a && b)
{
    ...
}

Condition coverage of this code would require to test:

a for both true and false, and:

b for both true and false.

In languages which require both operands to evaluate in a logical operation, condition coverage of the code above is satisfied with:

a = true; b = false
a = false; b = true

This is what is illustrated in your question.

Some languages evaluate the second operand of a logical AND only if the first operand is true (or evaluate the second operand of OR only if the first operand evaluates to false). In this case, three tests are required instead of two:

a = true; b = true
a = true; b = false
a = false

As you can note, we don't care about the value of b in the third test, since the program will never compute it when a is false.