问:
Is Perl still a useful, viable language?
I know it may have been asked before, but here goes nothing...

Is Perl still something that would be considered useful? If someone was a new programmer (either completely new to programming or just a few month/years of experience) would Perl be something to be considered worthwhile to learn?

Is Perl still used with frequency? Is it still popular?

Or is Perl dying out compared to languages like Python, Ruby, PHP, ASP.NET, etc.?

Basically it boils down to this:

Is it still used/is it still used frequently? If yes, is it dying? If no, will it make a come back?

Is it something that would be worth learning?

How does it compare in demand to languages like Python in both popularity and usability/viability? Could languages like Python or Ruby be considered replacements for Perl?

Also, will newer versions of Perl really bring a large improvement to the Perl community, and perhaps bring Perl back to centerstage compared to other languages?

EDIT:

Okay, I suppose here's a better, reworded question:

Is Perl still growing, or is it "dying"? Is it still a language worth learning and using? What projects does it really "shine" in compared to other languages? What makes Perl a language to choose? Essentially: is Perl growing obsolete compared to other languages, and if so, do you expect that to change, or to continue?

And thank you to everyone who has answered so far, the discussion has been really interesting!

答:
If you know perl, it's easier to learn Microsoft's Powershell. Regarding powershell's syntax, it does not have perl roots, but Powershell has taken many features and concepts from the language Perl, e.g, off the top of my head: the $_ variable, prefixing arrays with @ and strings/scalar values with $, file conventions for naming and storing modules, and, in some way, Autoloading, to name a few.

So if you know Perl it'll come in handy, and it's a bit easier to learn Powershell, or to grasp the mindset of Powershell, or to keep Powershell idiom  in your long term memory. Encountering Powershell without some perl background is probably a bit weirder. Just saying.

Of course the language Powershell added new stuff, in particular its .NET friendlyness, and did not continue any of perl's functions/operators that provide "backward compatibility" with the unix command line tools.


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

答:
An SRS is a document that essentially prepared by the Business Analyst. As you said, it does include business goals and high level requirements.

Whereas a Functional Specs document encompasses details of purposes and processes of the entire system and is much more in depth. This document is prepared in liasion with the Software Engineer and System Anaylyst.

For more information visit the following links:

Functional Specs Document

SRS

ContentLicense: CC BY-SA 3.0


问:
Looking for best practice for version numbering of dependent software components
We are trying to decide on a good way to do version numbering for software components, which are depending on each other.

Let's be more specific:

Software component A is a firmware running on an embedded device and component B is its respective driver for a normal PC (Linux/Windows machine). They are communicating with each other using a custom protocol. Since, our product is also targeted at developers, we will offer stable and unstable (experimental) versions of both components (the firmware is closed-source, while the driver is open-source). Our biggest difficulty is how to handle API changes in the communication protocol.

While we were implementing a compatibility check in the driver - it checks if the firmware version is compatible to the driver's version - we started to discuss multiple ways of version numbering.

We came up with one solution, but we also felt like reinventing the wheel. That is why I'd like to get some feedback from the programmer/software developer community, since we think this is a common problem.

So here is our solution:

We plan to follow the widely used major.minor.patch version numbering and to use even/odd minor numbers for the stable/unstable versions. If we introduce changes in the API, we will increase the minor number.

This convention will lead to the following example situation:

Current stable branch is 1.2.1 and unstable is 1.3.7. Now, a new patch for unstable changes the API, what will cause the new unstable version number to become 1.5.0. Once, the unstable branch is considered stable, let's say in 1.5.3, we will release it as 1.4.0.

I would be happy about an answer to any of the related questions below:

Can you suggest a best practice for handling the issues described above?

Do you think our "custom" convention is good?

What changes would you apply to the described convention?

答:
Once, the unstable branch is considered stable, let's say in 1.5.3, we will release it as 1.4.0.

No-no. For unstable  1.5.3 stable must begin from 1.6.0 (and 1.4.x just missed, if you wan6t to use Semantic Versioning)


问:
Is Java much harder to "tweak" for performance compared with C/C++?
Does the "magic" of the JVM hinder the influence a programmer has over micro-optimisations in Java? I recently read in C++ sometimes the ordering of the data members can provide optimizations (granted, in the microsecond environment) and I presumed a programmer's hands are tied when it comes to squeezing performance from Java?

I appreciate a decent algorithm provides greater speed-gains, but once you have the correct algorithm is Java harder to tweak due to the JVM control?

If not, could people give examples of what tricks you can use in Java (besides simple compiler flags).

答:
could people give examples of what tricks you can use in Java (besides simple compiler flags).

Other than improvements of algorithms, be sure to consider the memory hierarchy and how the processor makes use of it. There are big benefits in reducing memory access latencies, once you understand how the language in question allocates memory to its data types and objects.

Java example to access an array of 1000x1000 ints

Consider the below sample code - it accesses the same area of memory (a 1000x1000 array of ints), but in a different order. On my mac mini (Core i7, 2.7 GHz) the output is as follows, showing that traversing the array by rows more than doubles the performance (average over 100 rounds each).

```<code>Processing columns by rows*** took 4 ms (avg)
Processing rows by columns*** took 10 ms (avg)
</code>```

This is because the array is stored such that consecutive columns (i.e. int values) are placed adjacent in memory, whereas consecutive rows are not. For the processor to actually use the data, it has to be transferred to its caches. The transfer of memory is by a block of bytes, called a cache line - loading a cache line directly from memory introduces latencies and thus decrease a program's performance.

For the Core i7 (sandy bridge) a cache line holds 64 bytes, thus each memory access retrieves 64 bytes. Because the first test accesses memory in a predictable sequence, the processor will pre-fetch data before it is actually consumed by the program. Overall, this results in less latency on memory accesses and thus improves the performance.

Code of sample:

```<code>  package test;

  import java.lang.*;

  public class PerfTest {
    public static void main(String[] args) {
      int[][] numbers = new int[1000][1000];
      long startTime;
      long stopTime;
      long elapsedAvg;
      int tries;
      int maxTries = 100;

      // process columns by rows
      System.out.print("Processing columns by rows");
      for(tries = 0, elapsedAvg = 0; tries < maxTries; tries++) {
       startTime = System.currentTimeMillis();
       for(int r = 0; r < 1000; r++) {
         for(int c = 0; c < 1000; c++) {
           int v = numbers[r][c];
         }
       }
       stopTime = System.currentTimeMillis();
       elapsedAvg += ((stopTime - startTime) - elapsedAvg) / (tries + 1);
      }

      System.out.format("*** took %d ms (avg)\n", elapsedAvg);

      // process rows by columns
      System.out.print("Processing rows by columns");
      for(tries = 0, elapsedAvg = 0; tries < maxTries; tries++) {
       startTime = System.currentTimeMillis();
       for(int c = 0; c < 1000; c++) {
         for(int r = 0; r < 1000; r++) {
           int v = numbers[r][c];
         }
       }
       stopTime = System.currentTimeMillis();
       elapsedAvg += ((stopTime - startTime) - elapsedAvg) / (tries + 1);
      }

      System.out.format("*** took %d ms (avg)\n", elapsedAvg);
    }
  }
</code>```

Body:
could people give examples of what tricks you can use in Java (besides simple compiler flags).

Other than improvements of algorithms, be sure to consider the memory hierarchy and how the processor makes use of it. There are big benefits in reducing memory access latencies, once you understand how the language in question allocates memory to its data types and objects.

Java example to access an array of 1000x1000 ints

Consider the below sample code - it accesses the same area of memory (a 1000x1000 array of ints), but in a different order. On my mac mini (Core i7, 2.7 GHz) the output is as follows, showing that traversing the array by rows more than doubles the performance (average over 100 rounds each).

Processing columns by rows*** took 4 ms (avg)
Processing rows by columns*** took 10 ms (avg)

This is because the array is stored such that consecutive columns (i.e. int values) are placed adjacent in memory, whereas consecutive rows are not. For the processor to actually use the data, it has to be transferred to its caches. The transfer of memory is by a block of bytes, called a cache line - loading a cache line directly from memory introduces latencies and thus decrease a program's performance.

For the Core i7 (sandy bridge) a cache line holds 64 bytes, thus each memory access retrieves 64 bytes. Because the first test accesses memory in a predictable sequence, the processor will pre-fetch data before it is actually consumed by the program. Overall, this results in less latency on memory accesses and thus improves the performance.

Code of sample:

  package test;

  import java.lang.*;

  public class PerfTest {
    public static void main(String[] args) {
      int[][] numbers = new int[1000][1000];
      long startTime;
      long stopTime;
      long elapsedAvg;
      int tries;
      int maxTries = 100;

      // process columns by rows
      System.out.print("Processing columns by rows");
      for(tries = 0, elapsedAvg = 0; tries < maxTries; tries++) {
       startTime = System.currentTimeMillis();
       for(int r = 0; r < 1000; r++) {
         for(int c = 0; c < 1000; c++) {
           int v = numbers[r][c];
         }
       }
       stopTime = System.currentTimeMillis();
       elapsedAvg += ((stopTime - startTime) - elapsedAvg) / (tries + 1);
      }

      System.out.format("*** took %d ms (avg)\n", elapsedAvg);

      // process rows by columns
      System.out.print("Processing rows by columns");
      for(tries = 0, elapsedAvg = 0; tries < maxTries; tries++) {
       startTime = System.currentTimeMillis();
       for(int c = 0; c < 1000; c++) {
         for(int r = 0; r < 1000; r++) {
           int v = numbers[r][c];
         }
       }
       stopTime = System.currentTimeMillis();
       elapsedAvg += ((stopTime - startTime) - elapsedAvg) / (tries + 1);
      }

      System.out.format("*** took %d ms (avg)\n", elapsedAvg);
    }
  }


答:
Typically, a systems requirements specification contains the top-level requirements for a system. A system is a set of software and/or hardware subsystems. Typically, this includes the functional and non-functional (performance, safety, security, quality, business, governance and regulatory, and so on) requirements for the system as a whole. Each subsystem in the system would have a requirements specification as well, with a software subsystem's specification typically called the software requirements specification. Each specific requirement of the software subsystem is mapped to at least one requirement in the systems requirement specification.

In some projects, there might also be the concept of customer requirements or a concept of operations. These are typically requirements as well, but provided by the customer in their domain language and may not be suitable for consumption by engineers. These are turned into systems requirements by engineers who understand the customer need as well as the business.

Note that different organizations may have different names for the same thing or may split content off into different repositories or documents. There are some standards that exist - the IEEE has a number of standards related to systems engineering and software engineering, for example - but organizations may not follow these standards or may tailor them to better suit their needs.

For more information, you may be interested in two books by Karl Wiegers - Software Requirements and More About Software Requirements.

Title: Is a functional spec a part of the System requirement spec?

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


问:
Does a patch for an opensource project inherit the same license?
I have submitted a patch for a GPL'd project and now a third-party wants to include this patch in a product. They have asked me what license my patch uses.

Does my patch have to adopt the GPL license? Or I can choose an alternative one?

答:
If you are using the original code base for which the patch was built in ANY way, you must use the GPL license.

If your patch is fully independent (which patch that is fully independent is not really a "patch") and can stand on its own two feet, then use whatever licensing you want.

This may help clarify http://www.sitepoint.com/public-license-explained/


问:
should singleton be life-time available or should it be destroyable?
Should the singleton be designed so that it can be created and destroyed at any time in program or should it be created so that it is available in life-time of program. Which one is best practice? What are the advantages and disadvantages of both? <br>
EDIT :- As per the link shared by Mat, the singleton should be static. But then what are the disadvantages of making it destroyable? One advantage is it memory can be saved when it is not useful. </p>

答:
A singleton should never be available, it's the definition of anti-pattern.

That said, the supposed benefit of the design is that it handles creation order and lifetime in such a way as to guarantee the thing always exists. Making it destroyable rather defeats the purpose.


答: The best practice is just to not use a Singleton in the first place. But if you're going to use one, making it destroyable is even worse, and it's quite remarkable to have something worse than a regular Singleton.

Title: should singleton be life-time available or should it be destroyable?

Body:
Should the singleton be designed so that it can be created and destroyed at any time in program or should it be created so that it is available in life-time of program. Which one is best practice? What are the advantages and disadvantages of both? <br>
EDIT :- As per the link shared by Mat, the singleton should be static. But then what are the disadvantages of making it destroyable? One advantage is it memory can be saved when it is not useful. </p>


问:
Are there any algorithms for resource scheduling of courses-teachers-classes?
I'm developing an application to help school principals in dedicating teachers to classes and courses over the hours of a week (scheduling). The scenario is roughly something like this:

User enters the list of teachers and their free times into the system

User enters the list of courses for this semester

User enters the list of available classes into the system

Well, up to here, there is no big deal. Just simple CRUD operations and nothing extraordinary. However, now what makes this system useful is that the application should automatically and based on an algorithm create the semester scheduling.

I think you've got the main idea here. For example application should suggest that teacher A should go to class 1 for mathematics, and at the same time teacher B should go to class 2 for physics. This way all of the classes would be dedicated to lessons and teacher times won't overlap each other. Piece a cake for school principal.

However, I can't find a good algorithm for this resource dedication. I mean it seems hard to me.

Searching Google resulted in articles from different websites, but they are of no help and use to me. For example:

http://en.wikipedia.org/wiki/Resource_allocation or
http://en.wikipedia.org/wiki/Scheduling_(production_processes)

Is there any algorithm out there, or any application or engine which can help me here? Does this requirements have a known name, like for example time scheduling engine?

Any help would be appreciated.

答: What limited experience I have had with finite domain constraint resolution has been with Mozart/Oz.  There is a relatively good tutorial as part of the standard documentation: http://www.mozart-oz.org/documentation/fdt/index.html</p>


问:
Separating merged array of arithmetic and geometric series
Given an array of positive integers in increasing order. Separate them in two series, an arithmetic sequence and geometric sequence. The given array is such that a solution do exist.

The union of numbers of the two sequence must be the given array.

Both series can have common elements i.e. series need not to be disjoint.

The ratio of the geometric series can be fractional.

Example:

```<code>Given series : 2,4,6,8,10,12,25
AP: 2,4,6,8,10,12
GP: 4,10,25
</code>```

I tried taking few examples but could not reach a general way. Even tried some graph implementation by introducing edges if they follow a particular sequence but could not reach solution.

答:
Let's assume a sequence must contain at least 2 numbers. Here is a more or less brute-force approach:

calculate the difference of each pair of numbers: this gives you a finite number of possible differences (lets call that number set D). One of that differences must be the constant difference of the AP

also, calculate the of ratio each pair of numbers: this gives you a finite number of possible ratios (lets call that number set R). One of that must be the constant ration of the GP

Choose each pair (d,r) out of D x R. Test if you can find an AP beeing a sub-sequence with constant diff d and and a GP sub-sequence with constant ratio r, so that the union of both sub-sequences form the original sequence.

For the last step, you have to consider that there may be more than one possible subsequence for a given d or r. However, you can do better than just generating all possible sub-sequences if you make use of that fact that at least one of the two sequences must contain the first of all numbers, and the second one must contain one of the numbers which is not contained within the other sub-sequence.

For instance, when using your example above, the set D will contain 2 (and some more numbers), and R will contain 2, 2.5, and some more numbers. Testing d=2, r=2, will lead to the AP 2,4,6,8,10,12, but the remaining number 25 is not part of a GP with at least two numbers and r=2 (neither 50 nor 12.5 is part of the given number set). However, when the next test is d=2, r=2.5, you will easily find the solution above.


问:
I failed FizzBuzz, would you hire me?
I'm a developer with a CS degree and have work experience doing development in a number of languages for almost 3  years.

Today I had an interview, overall it went quite well, I prepared for most of the questions and felt ready for anything.  At the end of the interview, they gave me ONE programming question...a problem like FizzBuzz (without the print the number part).  I believe I made too many mistakes and thus have "failed" it.  Is all hope lost for me?

Here is my code:

  void FizzBuzz()
  {
    for(int i = 0; i <= 100; i++)
    {
      bool isThree = i % 3;
      bool isFive = i % 5;

     if (isThree)
     {
         print "Fizz\n";
     }
     else if(isFive)
     {
         print "Buzz\n";
     }
     else
     {
         print "FizzBuzz\n";
     }
  }
 }
```

As you can see I messed up the bools which should have the syntax i % 3 == 0;  If I'm remembering the question right I also put an else instead of an elseif with isThree && isFive.  I was quite stressed, but that's no excuse for missing a simple problem.

So the question is, how important is being able to produce working code on the spot relative to other factors, such as experience and personality? For instance, would the above code be a deal breaker?

答:
No. The point of FizzBuzz is to see if you are able to work out basic conditional logic, that covers all the cases. Contrary to opinions of some people, FizzBuzz isn't about modulus operator, knowing ternary ops or boolean operands. It's a simple exercise in conditionals and you've failed it.

The problem is structured so that all the "elegant" looking code fails to cover at least one case.

Acceptable answers:

```<code>if div3 print fizz
if div5 print buzz
if !div3 && !div5 print x

if div3 {
    print fizz;
    if div5 {
        print buzz;
    }
} else {
    if div5 {
        print buzz;
    } else {
        print x;
    }
}
</code>```

Title: I failed FizzBuzz, would you hire me?

Body:
No. The point of FizzBuzz is to see if you are able to work out basic conditional logic, that covers all the cases. Contrary to opinions of some people, FizzBuzz isn't about modulus operator, knowing ternary ops or boolean operands. It's a simple exercise in conditionals and you've failed it.

The problem is structured so that all the "elegant" looking code fails to cover at least one case.

Acceptable answers:

if div3 print fizz
if div5 print buzz
if !div3 && !div5 print x

if div3 {
    print fizz;
    if div5 {
        print buzz;
    }
} else {
    if div5 {
        print buzz;
    } else {
        print x;
    }
}


问:
Is Extreme Programming (XP) the best way of learning from experts?
I have been involved in many development models, and have found XP to be the best for a new programmer from the aspect of learning, as the collaboration between the team members is very high and the opportunities to share knowledge are great.

What are the expert opinions on this?

答:
I don't think you can beat an excellent teacher who knows his stuff.

The temptation of pair programming is. you just need a domain expert, teaching skills not required. In my experience, that works only for the very few students who wouldn't strictly need a teacher anyway.

ContentLicense: CC BY-SA 2.5


答:
You're trying to use one value to indicate two separate things.

First, you've got a "version," which usually serves to identify the various releases and to indicate the order in which the releases were made. As tylerl said, the version should always increase -- it won't make any sense to users (and it could cause a lot of internal confusion as well) if you change the version from 1.5.3 to 1.4.0.

Second, you're trying to indicate is whether a given version is stable or not.

It's possible to indicate both things with a single "version number," just as some stores will use some pricing scheme to indicate whether an item is on sale. For example, prices that end in '3' at a store near me are final sale prices. That works well for the employees, who quickly learn how to spot a sale price, but it's not a great way to tell your customers about a sale. For that reason, they also put up signs near the sale items. You could do something similar, like making the least significant digit for stable releases even and and making it odd for experimental releases. I think, though, that if you're going to release something that's experimental, you should clearly mark it that way. You could add an 'X' at the beginning or end of the version string, like: X.1.5.3 or 1.5.3.X. You could even an experimental version number after that, so you could release multiple experimental versions all based on the same base version: 1.5.3.X1, 1.5.3.X2.

You should also consider that there's a long tradition of using "alpha" and "beta" version numbers to indicate versions that may not be stable or complete: 1.5.3a54. Make sure you have a good reason for departing from this scheme if you decide to do anything else, because you're probably going to have to explain anything else to your developer community.

Title: Looking for best practice for version numbering of dependent software components

Body:
We are trying to decide on a good way to do version numbering for software components, which are depending on each other.

Let's be more specific:

Software component A is a firmware running on an embedded device and component B is its respective driver for a normal PC (Linux/Windows machine). They are communicating with each other using a custom protocol. Since, our product is also targeted at developers, we will offer stable and unstable (experimental) versions of both components (the firmware is closed-source, while the driver is open-source). Our biggest difficulty is how to handle API changes in the communication protocol.

While we were implementing a compatibility check in the driver - it checks if the firmware version is compatible to the driver's version - we started to discuss multiple ways of version numbering.

We came up with one solution, but we also felt like reinventing the wheel. That is why I'd like to get some feedback from the programmer/software developer community, since we think this is a common problem.

So here is our solution:

We plan to follow the widely used major.minor.patch version numbering and to use even/odd minor numbers for the stable/unstable versions. If we introduce changes in the API, we will increase the minor number.

This convention will lead to the following example situation:

Current stable branch is 1.2.1 and unstable is 1.3.7. Now, a new patch for unstable changes the API, what will cause the new unstable version number to become 1.5.0. Once, the unstable branch is considered stable, let's say in 1.5.3, we will release it as 1.4.0.

I would be happy about an answer to any of the related questions below:

Can you suggest a best practice for handling the issues described above?

Do you think our "custom" convention is good?

What changes would you apply to the described convention?


答:
Asking someone to solve a problem without giving them the ability to get feedback on their solution is a questionable approach, because they aren't allowed to improve.

All this test tells us is that you didn't demonstrate very good "top-of-the-head" problem solving skills.

This could be one of the elements in the decision to hire you or not, but to me it should definitely not be the only one.

Would they have provided you with a unit testing or execution environment, the mistakes you made would have been less excusable.

Title: I failed FizzBuzz, would you hire me?

Body:
I'm a developer with a CS degree and have work experience doing development in a number of languages for almost 3  years.

Today I had an interview, overall it went quite well, I prepared for most of the questions and felt ready for anything.  At the end of the interview, they gave me ONE programming question...a problem like FizzBuzz (without the print the number part).  I believe I made too many mistakes and thus have "failed" it.  Is all hope lost for me?

Here is my code:

  void FizzBuzz()
  {
    for(int i = 0; i <= 100; i++)
    {
      bool isThree = i % 3;
      bool isFive = i % 5;

     if (isThree)
     {
         print "Fizz\n";
     }
     else if(isFive)
     {
         print "Buzz\n";
     }
     else
     {
         print "FizzBuzz\n";
     }
  }
 }
```

As you can see I messed up the bools which should have the syntax i % 3 == 0;  If I'm remembering the question right I also put an else instead of an elseif with isThree && isFive.  I was quite stressed, but that's no excuse for missing a simple problem.

So the question is, how important is being able to produce working code on the spot relative to other factors, such as experience and personality? For instance, would the above code be a deal breaker?


答: I really love the way Hibernating Rhinos has been building RavenDb vis-a-vis versions -- they just have an ever increasing build number. When they get a stable one it gets marked stable. But everything is a release candidate.</p>


问:
Implement service layer in MVC
We have a defined service layer hosted in WCF. We are now building a website that will need to use the services functionality. The website is being written in ASP.NET MVC 4 and I'm trying to decide how to reference the WCF service from the MVC app. It's a large complex website and it will be changing on a weekly basis.

My first reaction is to abstract out the service references (About 7 services on this one WCF host) and create a service ref facade library with which the website interacts.

But, I don't know exactly how to use the service facade in MVC. I'm starting to think the Models will be responsible for it because when the controller gets a model, that model should call the service (if needed) and return what the controller asked. I'm trying to avoid having the MVC app know details of the service references. So, I could have a model factory that creates whatever model the controllers need and they can use the service facade to accomplish it.

Is this a good plan, or am I off track?

答:
The service facade is the way to go -- it will make it much easier to managed and test in the long term. You can build the service facade as an entirely separate library in fact so you can use the facade in other apps without much to do. </p>

<p>Insofar as were to drop it, keep in mind that MVC is really a UI pattern, what happens below the waterline is really beyond it's concern. So have your controllers reference the service facade and pull out models to send to the UI and don't get hung up on what is a model vs what is a controller. </p>

Title: Implement service layer in MVC

Body:
The service facade is the way to go -- it will make it much easier to managed and test in the long term. You can build the service facade as an entirely separate library in fact so you can use the facade in other apps without much to do.

Insofar as were to drop it, keep in mind that MVC is really a UI pattern, what happens below the waterline is really beyond it's concern. So have your controllers reference the service facade and pull out models to send to the UI and don't get hung up on what is a model vs what is a controller.


问:
How is Agile different from XP?
I read few articles on web to find out how Agile, XP, Scrum, pair programming are different from each other / related to each other and I derived the following line:

Scrum and XP are almost same. XP has shorter period of releases than Scrum

Pair programming is employed in both Agile and XP methodologies

But I was unable to identify how Agile is different from XP.

More than providing a URL, I would be happy to read your experience and thoughts on this.

答:
How do you fry chicken?

That is a serious question. How do you collect the intent of other people's work into something that works for you?

I see so many questions not only here, but on SO that ask "Should I use x, y or Z?" while little attention is actually given to how a drastic change might effect a team, or (worse) the effect of someone trying something without fully understanding how it works. When it comes to development methodology, you don't understand it until you have used it successfully, otherwise you are just following blind advice.

Every time I see "Would scrum work for me?" I ask "I don't know, have you tried it?"

Don't read these things like they come from some sort of spiritual scripture. Take what works for you, try it and if it works implement the parts that worked. This is no different from taking the best of what libfoo and libbar do and making something that fills your need.

At what point did someone say "Follow, to the letter this method or be damned for life" ?

The best method is your best adaptation of published and original wisdom that works for you.

Title: How is Agile different from XP?


答:
Singleton's introduce the same dependency as a global variable. Singleton's tend to introduce difficult to test implementations.

That said, I favor a singleton design that is implemented as a standard object. The singleton-ness of the object is an implementation detail where only one instance is created and made available.

The singleton instance is most often useful when it is lazily-constructed. That is only construct the object when it is needed.

The lazy instantiation of the object can often be used to help with testability of objects that are dependent on the singleton. For testing purposes you might introduce a mock object or alternative implementation that is instantiated.

Singleton's have there place in your toolbox. Understanding their limitations is important to using them successfully.


答:
If I were evaluating this, I would be looking for the following things:

Does the candidate attempt to get a clear understanding of the requirements before moving on to implementation?  Does the candidate seek to solve my problem or to use his pet tools in his programming toolbox?  How does the candidate go about solving problems?

Is the candidate fluent in at least one programming language?

Does the candidate have a grasp of boolean logic?

What does the candidate do to ensure the quality of his solutions?

How does the candidate respond to feedback on his code?

--

It's hard to say on #1. Your question states that your problem did not include the "print number" part, and your solution does not in fact include that.  I have no choice but to take your word for it, but if in fact it was the classic FizzBuzz problem that included printing the numbers that were not divisible by either, then it sounds like you jumped to a solution before fully understanding the requirements, which would be a mark off.

I'd give you partial credit for #2 and #3.  You knew to use the modulus operator, and had the structure of a working solution, but missed parts of both.

It sounds like you didn't do #4, which would mark you down.  In the future, I would recommend taking a step back from the whiteboard and looking over your solution before calling it done.  I would also (without being prompted) step through a couple of unit tests for your solution, which would have quickly demonstrated where you messed up.

They didn't give you a chance on #5, which is unfortunate.  But the point is I don't want someone who thinks that every line of code they have ever written is pure gold that couldn't possibly be improved, but rather someone willing to accept feedback on his solutions and engage in some conversation about his approach.

--

So, if I were evaluating on this alone, I would vote "No Hire."  Things like this are sort of measuring a performance art rather than programming ability , but mastering it can still aid your career.  So my, recommendations for future tech interviews would be:

Before the interview, practice a couple of these type of exercises cold, using as few outside resources as possible.  Not to memorize solutions, but to be sure you're comfortable with your preferred language

Ask questions about the problem to validate your assumptions.

Before announcing your solution complete, step back from the whiteboard and look it over, and walk through a couple simple unit test cases.

Title: I failed FizzBuzz, would you hire me?


问:
IOC and stateless services. Short-lived or single-instance?
Given a garbage-collected framework, when using an IOC container to inject purely stateless services, is it generally better to use the container's single-instance lifespan or to recreate the object each time it is used and throw it, and all its dependencies, away as soon as you're done with them?</p>

答:
Without further context, I think it doesn't really matter.

You can get the benefits of short-lived objects from a single instance, if that instance simply creates the short-lived objects for every call, and you can get the benefits of a single instance from many short-lived object, if those merely act as flyweights.

Of course it's unnecessarily noisy to set it up one way, only to delegate to the opposite. So I guess you should just have a guess, whether you're likely to add state at all, and if so, whether it's going to be persistent/global state (e.g. when adding a cache) or short-lived/local state.


问:
How to make a legacy system time-zone sensitive?
I need to implement time zones in a very large and old Delphi system, where there's a central SQL Server database and possibly hundreds of client installations around the world in different time zones. The application already interacts with the database by only using the date/time of the database server. So, all the time stamps saved in both the database and on the client machines are the date/time of the database server when it happened, never the time of the client machine.

So, when a client is about to display the date/time of something (such as a transaction) which is coming from this database, it needs to show the date/time converted to the local time zone. This is where I get lost.

I would naturally assume there should be something in SQL to recognize the time zone and convert a DateTime field dynamically. I'm not sure if such a thing exists though. If so, that would be perfect, but if not, I need to figure out another way.

This Delphi system (multiple projects) utilizes the SQL Server database using ADO components, VCL data-aware controls, and QuickReports (using data sources). So, there's many places where the data goes directly from the database query to rendering on the screen, without any code to actually put this data on the screen. In the end, I need to know when and how should I get the properly converted time?

What is the proper way to ensure that I handle Dates and Times correctly in a legacy application?

答:
Dates and timezones are tricky things, and generally no matter what kind of technology stack you are working on there is rarely a turn key solution.

Most databases will store a date or timestamp as little more than the exact date or timestamp that was given to it.  When talking with a database through queries they are generally under the assumption that all dates and timestamps represent a point in time under the same time zone.  In other words, if I write a query to see if Aug 2nd 2012 4:10pm is before the same date at 5:10pm then that will evaluate to true returning me that record.  Suppose the record was saved as 4:10pm Eastern Standard Time when my database server is in Pacific Standard Time.  The database is time zone agnostic and now my query is not returning the data I expect.

Convert all application dates and times to UTC or GMT before persisting

Languages like Java, Javascript and C# treat dates and times a bit differently. They will generally measure time as a number of milliseconds from a given universal point in time.  This is the universal time as that specific number of milliseconds from 0 represents a number of different dates or times in different timezones at any given point.  Most of these languages generally have a solid Date and Time API or a good third party library can be found that make viewing this millisecond count in a number of timezones as painless as possible.

Unless otherwise specified, if I use a standard data access API in a common language, most will take a date object and convert it into the date and time of the servers default timezone in the specified database format.  Figure out how your language data access API and database stores dates and how it interprets them from the database and try to store your dates at the database level in GMT.  Likewise when querying make sure that Date objects or variables in your language are representing a millisecond count that is equivalent to the GMT date time stored in the database.

Persist Time Zones for Dates that are used in Business Logic

What I mean by this is that perhaps if you have a Modified Date column in your database, then it may not be important to business logic, however a column Appointment Date probably will be important.

Somewhere in your schema you need to determine where locale specific data is stored and store the Time Zone to define that locale in the appropriate parent table.  Your business logic that is considering dates, or your presentation logic that is preparing dates for display must be able to fetch the appropriate Time Zone so that when I am comparing 4:10pm to 5:10pm, that I am comparing dates from the appropriate universal time.  4:10pm EST and 4:10pm PST are seperate points in universal time.  Again a good Date and Time API or third party library makes date comparisons easy, when you understand the underlying nature of how dates work in that programming language.

Business Logic Should be refactored to be time zone aware.

Presentation Logic Should be refactored to present a display value that is appropriately displaying the correct data per the appropriate given Time Zone.

One final thought to consider when performing this work is to write exhaustive unit tests that thoroughly exhaust many types of Date and Time combinations to make sure that all business logic works as expected.


问:
What can be done against language inertia?
Often, projects use programming language X, but would use programming language Y if they were started from scratch.

For example, big numerical models may be written entirely in Fortran. Whereas this might be a reasonable choice for the components that need to run fast (alternative would be C or C++), it might be a poor choice for components that either do not need to run fast (such as things dealing with human input or simple visualisations), or where runtime is not the limiting factor (such as I/O, particularly when from the network).

Another example may be when a project is built using a propriety language (such as Matlab; no, FOSS clones are not good enough) and was started at a time when FOSS alternatives were not viable, but ten years later, they are; and it would be beneficial to migrate.

However, due to language inertia, a migration does not happen. Code that works should not be touched, porting code is a time-consuming, expensive process, and programmers are familiar in language X but not necessarily in language Y. Still, in the long term, a migration would likely be beneficial.

Can anything be done to mitigate the problems associated with language inertia? Are there any notable examples of big projects that have successfully overcome this problem? Or is a project bound to stick forever with the initial choices?

答:
To my experience, migrating a working product from language A to language B will only happen if there are hard, fact-proven, technical or legal reasons which will make further development in language A impossible. Almost no company will invest in a language transition for any other reasons.

Some real-world examples I have seen so far:

a key component of the product won't be further developed and there is no adequate replacement in language A

the COBOL based system runs on hardware which is so old that you cannot buy any spare parts for it, and the migration to a modern COBOL dialect on modern hardware does not seem to be cheaper than a migration to a more modern language

licensing issues with core components

the old system was based on 16-bit-Windows-components where no 32 bit pendant is available any more, and you need to support 64 bit Windows

the language itself (the compiler/interpreter) is not supported any more, neither by the creator nor by any third party vendor, or at least not within your target environment


答:
I give people trivial programming problems to do at the whiteboard. Whether the resulting code is bug free is not the decision point at all. Instead I care about a number of behaviours exhibited during the writing of the code. It's interactive, and I'm learning a great deal about candidates while it's happening.

I go into more detail at Whiteboard "testing" during an interview: legitimate way to back up your (whiteboard) code?

Of course, your interviewer may be nothing like me. But it's entirely possible for you to have passed an interview with me while producing code that's a teeny tiny bit off, and entirely possible to have failed with the identical code.

Title: I failed FizzBuzz, would you hire me?


问:
Would you use UML if it kept stakeholders from requesting changes frequently?
As much as programmers hate to document their code/system and draw UML (especially, Sequencing, Activity and State machine diagrams) or other diagramming notation, would you agree to do it if it kept managers from requesting a "minor change" every couple of weeks?

IOW, would you put together visual models to document the system if it helped you demonstrate to managers what the effect of changes are and why it takes so long to implement them?

(Edited to help programmers understand what type of answer I'm looking for.)

2nd edit: Restating my question again, "Would you be willing to use some diagramming notation, against your better nature as a programmer, if it helped you manage change requests?"

This question isn't asking if there might be something wrong with the process. It's a given that there's something wrong with the process. Would you be willing to do more work to improve it?

答:
I think that model driven development is the real problem and certainly not UML graphical notation which is known and accepted by millions of users.
UML is not requirement but could be extended using profiles and therefore if you model and have a kind of model merge for each iteration between code and model, then it would be possible to model if requirements evolve !!

I use Omondo because my project is developped in Java and must admit this tool is the only I found capable of merging code and model at any time. My requirements are sometimes changing every week, my project documentation is always up to date and my UML model accurate :-)
I can also trace requirements inside the UML metamodel and query the xmi which is also my model. Just amazing technology !!


答:
Well, large projects are ported from an old language to a new one (and from old platforms/technologies/frameworks to new ones) every day. At least a couple of companies I worked in underwent such passage (usually from FORTRAN to C++).

There are even a few cases of open source programs ported from a language to another. The first version of GNU Arch by Tom Lord (the archetypical predecessor of GIT and similar DRCS tools) was written as a bunch of Bash scripts and was later ported to C.

In most cases, these portings are performed using special translation tools (thirdy-party or custom-made). Usually, the resulting code need some (or a lot) of manual tweaking but very often it is possible to perform such portings.

Despite this, there are at least a couple of good reasons for not performing such portings:

Most of times, porting code from a language/platform/framework/technology to a new one just does not make any sense. The end user buy a solution (a working program) not a cool choice of development tools and technologies. As a consequence, the software company focus on selling working products and anything else.

Porting code is the easy part. Most of times, you have to port a lot of other details (because the new environment does not support the old ones any more). Devil thrives in details and these details can byte you very painfully.

So, usually a project (small, medium or larger, it deos not matter) will be ported to a new "something" only if the old one cannot be used anymore. A typical example is the passage from 16 bit to 32 bit architectures.

Of course, there are a couple of tools/ways to ease the passage from an old technology to a new one:

Good, reliable translation tools.

Proven porting methodologies.

Title: What can be done against language inertia?

Body:
Often, projects use programming language X, but would use programming language Y if they were started from scratch.

For example, big numerical models may be written entirely in Fortran. Whereas this might be a reasonable choice for the components that need to run fast (alternative would be C or C++), it might be a poor choice for components that either do not need to run fast (such as things dealing with human input or simple visualisations), or where runtime is not the limiting factor (such as I/O, particularly when from the network).

Another example may be when a project is built using a propriety language (such as Matlab; no, FOSS clones are not good enough) and was started at a time when FOSS alternatives were not viable, but ten years later, they are; and it would be beneficial to migrate.

However, due to language inertia, a migration does not happen. Code that works should not be touched, porting code is a time-consuming, expensive process, and programmers are familiar in language X but not necessarily in language Y. Still, in the long term, a migration would likely be beneficial.

Can anything be done to mitigate the problems associated with language inertia? Are there any notable examples of big projects that have successfully overcome this problem? Or is a project bound to stick forever with the initial choices?


问:
Creating a remote management interface
I'm looking for info on creating a remote management interface for our software. This is not anything illicit. Our software is for live TV production and once they go on-air we can't access the PC (usually through LogMeIn).

I would like to be able to upload/download files and issue commands to our software. The commands would be software specific like "load this file" or "run this script" or "return this value" etc.

A socket connection is preferred but the problem is most of our PCs are behind firewalls and NAT servers. I'm not sure where to start. I think HTTP tunneling is the way to go but am wondering if there are other options or recommendations.

Also, assume our clients are not willing to open up ports for security reasons.

Thanks.

答:
If your clients are unwilling to change any network configurations you are out of luck.

You have two options assuming your clients are willing to work with you.

RPC

HTTP

I recommend http.  Simply create a web interface for your application (home grown or not) and have certain urls trigger events in your application.  You web server will listen to your socket and you can have whatever you want happen in response to the url that is requested (or whatever other verb is used).  You need not limit yourself to http/1.1 though -- you could write your own protocol on top of a socket connection.

If you are lucky, the machine has a public IP address and port 80 is open for incoming connections.

Title: Creating a remote management interface


问:
KISS principle applied to programming language design?
KISS ("keep it simple, stupid" or "keep it simple stupid", see e.g. here) is an important principle in software development, even though it apparently originated in engineering. Citing from the wikipedia article:

The principle is best exemplified by the story of Johnson handing a team of design engineers a handful of tools, with the challenge that the jet aircraft they were designing must be repairable by an average mechanic in the field under combat conditions with only these tools. Hence, the 'stupid' refers to the relationship between the way things break and the sophistication available to fix them.

If I wanted to apply this to the field of software development I would replace "jet aircraft" with "piece of software", "average mechanic" with "average developer" and "under combat conditions" with "under the expected software development / maintenance conditions" (deadlines, time constraints, meetings / interruptions, available tools, and so on).

So it is a commonly accepted idea that one should try to keep a piece of software simple (or simple stupid, in case you omit the comma) so that it easy to work on it later.

But can the KISS principle be applied also to programming language design? Do you know of any programming languages that have been designed specifically with this principle in mind, i.e. to "allow an average programmer under average working conditions to write and maintain as much code as possible with the least cognitive effort"?

If you cite any specific language it would be great if you could add a link to some document in which this intent is clearly expressed by the language designers. In any case, I would be interested to learn about the designers' (documented) intentions rather than your personal opinion about a particular programming language.

答:
Hm... this is actually a tough question to answer 'positively', because when I think of simplicity in programming language design (and what's 'easier' to work with), I immediately think of:

"Readability" of code - how well the language encapsulates objects, methods, etc.

The consistency of the language APIs and interfaces.

There are a number of languages that do these things well - but what pops into my head is a language that doesn't  do things well 'as a programming language':  PHP.

[Disclaimer - I've written PHP and PHP is still my 'go to language' for simple web projects.  This is a criticism of love...]

First, PHP does well for the environment that it typically runs in - web servers.  It's easy to set up, easy to maintain, etc.

Where I struggle with PHP:  when you want to do something "unusual" - something that you typically don't do on a regular basis (in the case I'm thinking of it was consuming a SOAP web service - not something I've done a lot with PHP), you're confronted with two options:

1)  Various open source extensions to PHP.  The PHP object model is loose enough where interface design is also not terribly consistent from library to library, developer to developer.  When confronted with a set of code where someone used a library that you've never heard of, you spend a lot of time figuring out 'what the heck this does' because the language allows for loose API / library creation.

2)  The "built-in" functions - of which there are a lot.  I've gone through a few rabbit holes of either finding another library or implementing a bit of functionality to somehow later on stumble onto impossiblyfound_basefunction()

In my opinion, simplicity is consistency.


答:
The JVM can and often does interfere, and the JIT compiler can change significantly between versions   Some micro-optimisations are impossible in Java due to language limitations, such as being hyper-threading friendly or the latest Intel processors' SIMD collection.

A highly informative blog on the topic from one the Disruptor authors is recommended reading:

http://mechanical-sympathy.blogspot.com/

One always has to ask why bother using Java if you want micro-optimisations, there are many alternative methods for acceleration of a function such as using JNA or JNI to pass onto a native library.

Title: Is Java much harder to "tweak" for performance compared with C/C++?

Body:
Does the "magic" of the JVM hinder the influence a programmer has over micro-optimisations in Java? I recently read in C++ sometimes the ordering of the data members can provide optimizations (granted, in the microsecond environment) and I presumed a programmer's hands are tied when it comes to squeezing performance from Java?

I appreciate a decent algorithm provides greater speed-gains, but once you have the correct algorithm is Java harder to tweak due to the JVM control?

If not, could people give examples of what tricks you can use in Java (besides simple compiler flags).


答:
... it always depends on what the 'long term' really is.  Server-based code and runtimes that fill the specific needs (given businesses and people) will never be migrated.  That chunk of code may have 30-odd years of investment, bugfixes and functionality built into it.

Where most bang for the buck in migrating is seen is in changing user interfaces - a Visual Basic app cannot be 'ported' to an iPhone application, etc., etc.  In assessing migrations (or even new architectures), keep a careful eye on that MVC type separation so that it may one day become possible (or simpler) to put a new UI on top of a successful application.

Other example:  while we've moved from greenscreens to web architectures, there is still a lot of PL/SQL code driving functionality in Oracle data-driven applications.  In more than a few cases, I can't see any PL/SQL being 'rewritten' or ported to anything else, as long as the Oracle database is still around...


问:
Is there a design pattern for chained observers?
Several times, I've found myself in a situation where I want to add functionality to an existing Observer-Observable relationship.

For example, let's say I have an Observable class called PriceFeed, instances of which are created by a variety of PriceSources.  Observers on this are notified whenever the underlying PriceSource updates the PriceFeed with a new price.

Now I want to add a feature that allows a (temporary) override to be set on the PriceFeed.  The PriceSource should still update prices on the PriceFeed, but for as long as the override is set, whenever a consumer asks PriceFeed for it's current value, it should get the override.

The way I did this was to introduce a new OverrideablePriceFeed that is itself both an Observer and an Observable, and that decorates the actual PriceFeed.  It's implementation of .getPrice() is straight from Chain of Responsibility, but how about the handling of Observable events?  When an override is set or cleared, it should issue it's own event to Observers, as well as forwarding events from the underlying PriceFeed.

I think of this as some kind of a chained observer, and was curious if there's a more definitive description of a similar pattern.

答: Sounds like what you're looking for is an interceptor. You can have your PriceFeed pass its list of observers to a new PriceFeedInterceptor that watches the PriceFeed and passes on either the regular or overridden price as appropriate.  Your observers shouldn't need to be changed, but the PriceFeed will have to know about the interceptor and be prepared to delegate to it.


答:
The single-instance was the default behavior of Spring for a reason--a single instance of a stateless service is going it consume fewer resources that the constant creation and garbage collection of many instances.  Moreover, there is no real danger in sharing a stateless service, but there are some real scalability issues with creating multiple instances of a service.

So, I'd say the single-instance is most likely going to be your friend.

Title: IOC and stateless services. Short-lived or single-instance?

Body: Given a garbage-collected framework, when using an IOC container to inject purely stateless services, is it generally better to use the container's single-instance lifespan or to recreate the object each time it is used and throw it, and all its dependencies, away as soon as you're done with them?</p>


答:
Whatever floats your boat.

If you need to destroy it (maybe to reclaim memory or maybe it has state that's no longer valid) you should do that.

If it holds state that's inconvenient to recreate on demand, you should keep it around.

If you have no particular reason to destroy it I think you should keep it around.


问:
Why is Python used for high-performance/scientific computing (but Ruby isn't)?
There's a quote from a PyCon 2011 talk that goes:

At least in our shop (Argonne National Laboratory) we have three
  accepted languages for scientific computing. In this order they are
  C/C++, Fortran in all its dialects, and Python. You’ll notice the
  absolute and total lack of Ruby, Perl, Java.

It was in the more general context of high-performance computing. Granted the quote is only from one shop, but another question about languages for HPC, also lists Python as one to learn (and not Ruby).

Now, I can understand C/C++ and Fortran being used in that problem-space (and Perl/Java not being used). But I'm surprised that there would be a major difference in Python and Ruby use for HPC, given that they are fairly similar. (Note - I'm a fan of Python, but have nothing against Ruby).

Is there some specific reason why the one language took off? Is it about the libraries available? Some specific language features? The community? Or maybe just historical contigency, and it could have gone the other way?

答:
After using python for data analysis for a while (coming from experiences working with ruby, lua, and R), the numpy package (and many related scientific libraries) makes it 'possible' to run fast computation ( speed similar to C, as numpy is written/integrated with C codes) with the ease of programming in python.

Numpy has existed for a while, the availability of it helped many other related scientific packages to be built, such as scipy, pandas ... etc. There great tools make python a great ecosystem for scientific computing, whereas in Ruby, similar faster matrix calculation library is just being developed (NMtrix: https://github.com/SciRuby/nmatrix). This huge timing difference make python the obvious choice for scientific computing.


问:
Best way: restructure an existing Team Foundation Server (TFS) solution
In my department we are developing several smaller AddOns for some unified communication server. For versioning and distributed development we use a Team Foundation Server 2012.

But: there is only one large TFS solution for all of our applications and libraries:

Main Solution

Applications

App 1

App 2

App 3

Externals

Libraries

Lib 1

Lib 2

Tools

The "Application" path contains all main applications. Those are not depending on each other, but they depend on the Libraries and Externals projects.

The "Externals" path contains some external DLLs referenced in our Applications and Libraries.

The Libraries path contains commonly used libs (UI templates, Helper classes, etc.). They do not depend on each other and they are referenced in the Libraries and the Tools projects.

The Tools path contains some helper programs like setup helpers, update web services, etc.

Now, there's some major points why I'd like to change this structure:

We can't use server builds.

It's uncomfortable to manage TFS scrum management with sprints, impediments, etc. with a solution structure like that.

Every developer always has access to all projects in the solution.

A complete build lasts too long if one accidentally hits [F6] in Visual Studio...

What would you change in this solution? How would you break those projects into smaller Solutions, how should those solutions be structured.

My first approach would be, to create one TFS project for each Application, Library and Tool. But how can I ensure that e.g. App 2 always contains the newest version of Lib 1? Do I have to monitor changes on Lib 1 and update App 2 manually as soon as the Lib changes? Or can I somehow force Visual Studio to always use the newest version of an external project somehow?

Edit: On the TFS, there's just one TFS Team Project Collection, containing one TFS Team Project. The Team Project contains one large Visual Studio Solution, which contains several folders containing (see the structure above) with each of them containing multiple VS projects.

My question is now, how would you re-organize:

The TFS Team Projects

The VS Projects

答:
Stick with one TFS Team Project, having multiple becomes a pain when trying to upgrade and has some limitations when it comes to cross team project work items.  Instead you should be making heavy use of Areas and Iterations.

Split your VS Solution into multiple solutions, one per major application.  This will speed up local builds a lot, as well as the build server.

TFS2012 has a new concept called Teams, create a team per application and set default iterations and backlogs for each.  This way you can manage the backlog for each, or view the root team to see a rolled up backlog.  Then you can manage sprints either at an application level, or overall depending on what suits you.

Create NuGet packages for all 3rd party referenced libraries that don't already have one. Store them in a private repository (windows shared folder) and enable the package restore feature for NuGet by right clicking every solution and enabling it (also allow package restore to download packages in vs settings).

If you have any shared internal libraries then create NuGet packages for them also, and create a vs solution just containing that library.  Add a post build command to create the nuget package, or extend your tfs build template to do it (there's a number of templates out there that already do this).


问:
How to get initial API right using TDD?
This might be a rather silly question as I am at my first attempts at TDD. I loved the sense of confidence it brings and generally better structure of my code but when I started to apply it on something bigger than one-class toy examples, I ran into difficulties.

Suppose, you are writing a library of sorts. You know what it has to do, you know a general way of how it is supposed to be implemented (architecture wise), but you keep "discovering" that you need to make changes to your public API as you code. Perhaps you need to transform this private method into strategy pattern (and now need to pass a mocked strategy in your tests), perhaps you misplaced a responsibility here and there and split an existing class.

When you are improving upon existing code, TDD seems a really good fit, but when you are writing everything from scratch, the API you write tests for is a bit "blurry" unless you do a big design up front. What do you do when you already have 30 tests on the method that had its signature (and for that part, behavior) changed? That is a lot of tests to change once they add up.

答:
What you call "big design up front" I call "sensible planning of your class architecture."

You can't grow an architecture from unit tests.  Even Uncle Bob says that.

If you're not thinking through the architecture, if what you're doing
instead is ignoring architecture and throwing tests together and
getting them to pass, you're destroying the thing that will allow the
building to stay up because it's the concentration on the structure of
the system and solid design decisions that helped the system maintain
its structural integrity.

https://hanselminutes.com/171/return-of-uncle-bob#

I think it would be more sensible to approach TDD from a perspective of validating your structural design.  How do you know the design is incorrect if you don't test it?  And how do you verify that your changes are correct without also changing the original tests?

Software is "soft" precisely because it is subject to change.  If you are uncomfortable about the amount of change, continue to gain experience in architectural design, and the number of changes you will need to make to your application architectures will decrease over time.

Title: How to get initial API right using TDD?

ContentLicense: CC BY-SA 4.0


问:
How to evaluate code quality when you're not familiar with the language?
As a hypothetical, if I were to interview someone for a new PHP developer position when my experience is in .NET, how can I determine if the code sample they've provided me is efficient and of good quality?

In other words, what is the best way to evaluate a programmer's code if you're not familiar with the language?

答:
how can I determine if the code sample they've provided me is efficient and of good quality?

The things you will not be able to evaluate are correct use of language idioms and library usage. So, these are not things you should try to look at.

What you can evaluate is:

How well structured the code looks like

Well named variables (can you make sense of things)

Well composed functions/units of code

Consistency in the code base

The above points (though not exhaustive) will indicate whether the code smells or not and should be something an experienced programmer can identify as being good or bad.

In short - look for things that should indicate good code regardless of language.


答:
Bone-headed / obviously wrong code aside, efficient will largely depend on the compiler / interpreter of the language in question, and you won't really be able to eyeball that from a code sample. A code sample could be beautifully written and elegant as fine china on doilies but run slow if compiled / interpreted poorly.

You won't be able to evaluate idiomatic usage of the languages features / syntactic sugar / conventions without some familiarity.

You should be able to tell if it is well written in general based upon universal considerations such as tidiness, control flow, variable naming, order of operations, and so forth.

However, more practically, if you know what the language is going to be going into the process, you could try to find one or more style guides for that language, go to the book store and flip thru a couple of books for that language and skim the code examples looking for analogs to something you are familiar w/ in your language(s) of choice, check out one or more open source projects that use that language, and so forth.

If you have the time and if there is not a cost barrier, you might even go so far as to set up a development environment for that language and crank out a Hello World app, do a code kata, or otherwise write a simple little app in it. You'll develop a rudimentary frame of reference pretty quickly and not only will this give you a leg up for the specific purpose of reviewing the code in question, you might be compelled by the language and branch out a bit.

Title: How to evaluate code quality when you're not familiar with the language?

Body:
As a hypothetical, if I were to interview someone for a new PHP developer position when my experience is in .NET, how can I determine if the code sample they've provided me is efficient and of good quality?

In other words, what is the best way to evaluate a programmer's code if you're not familiar with the language?


答:
Have them flowchart it or walk you through it as part of the interview.  You have the perfect excuse to ask and it tells a fair bit of how they think to see how they explain.

If they are going to jump to your preferred language you know you have a lot of mentoring coming so you should be looking for good logic / reasoning skills above all anyway.

If they are going to stay working in their preferred language you are going to have to accept that they will me somewhat self-managing on the finer language specific details until someone else comes up to speed anyway, so all you are going to have to interact with is the design side there as well.


答:
The above code probably would be a deal breaker for me if I didn't have something else to go on. If they follow the Microsoft interview style, then the person who gave you this question will probably block you--and one is often all it takes.

What baffles me is that the interviewer didn't ask you about this code. A good interviewer has seen enough of their own code to know that people make mistakes--especially when in a hurry. Usually they say, "Now do you see anything wrong with this code?" "No? Well let's test it". You come up with some result sets and then run it through the function. Then you say, "Oh shit, that didn't work." "Ok, how would you fix it..." and so on. If you survive that dialog, it is actually quite impressive and demonstrates an ability to think critically, come up with test cases, and debug your own code.

Also note, they usually aren't looking for "working code". Who produces that the first try anyways? But logically correct with error handling and good test sets is a good goal.

In addition, this may surprise you, but you are competing with many people that can't even get started on fizzbuzz. We tend to assume that everyone else is traversing b+ trees in their sleep.... but in reality, they can't even figure out multiples of 3 and 5 and use a modulus operator. You may be delightfully surprised at how much better you did than the other candidates.

My advice, just brush it off. I interviewed at large software firms recently (Microsoft, Amazon etc...), and it was my first time to ever go through such a thorough interview process. I made a fool of myself at an onsite Microsoft interview largely because of nerves, but also, I just didn't know what to expect or what exactly they were looking for. I nailed a shortest path problem only to blow some really simple problems. I popped values off of the wrong end of a stack, forgot in an int atoi(char* value) implementation that int val = value[i] - '0'; would give me the integer value of the character, and several other silly mistakes. I was happy for the most part with the interview, but still understood why I didn't receive an offer. I had to realize that this was not so much a reflection on my abilities as it was an indicator that I just needed to keep trying it until I was able to master my nerves. Eventually I nailed some interviews with much harder questions and landed my dream job. It really is--for most people who actually know what they are doing--just a matter of figuring out what the interviewers want, being confident in yourself, and giving it to them. It takes a while.

Title: I failed FizzBuzz, would you hire me?


答:
You should ask someone who knows the language in question to come to the interview or have a look at the sample. Such a person will much more likely find the bad spots if any.

Is the candidate going to be working in a team? Let the team members meet him and ask questions about his skills.


问:
So we've got a code review tool, now what can we use for software documents?
We're using Subversion as a full CM for code and also for related project documents. We have JIRA and Fisheye. When we wanted to add a peer review tool, we looked at and tested several candidates. Our weighted requirements included both code and document review, but ultimately, the integration with JIRA slanted the scores in Crucible's favor.

Atlassian has slammed the door on ever supporting Word or PDF in Crucible. I've tested several workaround methods to make Crucible work for documents without success. (The Confluence/Crucible plug-in was deprecated by Atlassian, so that option is out, too.) I haven't found a plugin for Crucible that adds this functionality, so short of writing my own plug-in, Crucible for documents is unworkable.

Word Track Changes doesn't provide a method for true collaboration and commenting. Adobe PDF Comment and Markup is interesting, but doesn't provide a great way to keep a permanent quality record of the conversation. We can't go cloud-based, our documents must be locally hosted on our own server only. We're only on Sharepoint 2007.

Help! Anyone have a suggestion?

答: Honestly, at the end of the day I have had amazing luck using wiki to collaborate and store any kind of document we create including the wiki itself as documents.</p>


问:
Are these advanced/unfair interview questions regarding Java concurrency?
Here are some questions I've recently asked interviewees who say they know Java concurrency:

Explain the hazard of "memory visibility" - the way the JVM can reorder certain operations on variables that are unprotected by a monitor and not declared volatile, such that one thread may not see the changes made by another thread. Usually I ask this one by showing code where this hazard is present (e.g. the NoVisibility example in Listing 3.1 from "Java Concurrency in Practice" by Goetz et al) and asking what is wrong.

Explain how volatile affects not just the actual variable declared volatile, but also any changes to variables made by a thread before it changes the volatile variable.

Why might you use volatile instead of synchronized?

Implement a condition variable with wait() and notifyAll().  Explain why you should use notifyAll().  Explain why the condition variable should be tested with a while loop.

My question is - are these appropriate or too advanced to ask someone who says they know Java concurrency?

And while we're at it, do you think that someone working in Java concurrency should be expected to have an above-average knowledge of Java garbage collection?

答:
It really depends whether you are asking a candidate with 2 years of Java experience or one with 7 years of Java experience. For an architect/technical lead/senior they seem proper questions but for a junior and maybe a mid-level too, they seem kind of difficult.

Also you are asking question about low-level synchronization mechanisms which have been replaced mostly by java.util.concurrent in current day Java development; instead of wait()/notify() locks are preferred. You can see that Effective Java 2nd edition has dropped a chapter that explained the wait/notify mechanism in detail, because it was not considered useful. Also, the container handles multithreading at a higher level in most cases; the methods of an EJB are thread-safe for example without any concern from the programmer (this does not mean that programmers should not know multithreading).

I actually see the multithreading are as a subpart of operating systems rather than a subpart of a programming language. In order to see whether a person truly understands multithreading and parallel programming questions about mutexes, semaphores or scheduling should be asked firstly and only eventually then, details about implementation in a particular programming language.


问:
Is a university education worth it for a good programmer?
I've been doing design and programming for about as long as I can remember. If there's a programming problem, I can figure it out. (Though admittedly Stack Overflow has allowed me to skip the figuring out and get straight to the doing in many instances.) I've made games, esoteric programming languages, and widgets and gizmos galore. I'm currently working on a general-purpose programming language. There's nothing I do better than programming.

Is a university education really more than just a formality?

答:
If you are programming in the business world (as opposed to the teaching or for science or something very close to the hardware), the farther you get from your education (in time), the more important experience becomes.

In fact, experience and reputation will always trump education... because it shows your proven ability to produce.

I have a liberal arts degree in Biblical Studies - which is about as relevant in this business as a high school diploma.  A few years ago, when I was contemplating getting a graduate degree in CS, I found an article where they compared 2 job applications - one who had spent 1 1/2 years right out of college getting the graduate degree and the other who went right to work and had 1 1/2 years of experience (maybe he planned on getting the degree later?).  The hiring manager, who wrote the article, said that, all things being equal, he would always hire the one with the experience first.  The reasoning he gave is that the one with the experience could produce immediately, knew that he loved to program (wouldn't bail), and knew how to work. He also made the point that the student was studying things that were relevant to the industry 2 - 5 years ago (when the curriculum was designed)... the one with experience was learning (because we're always learning in this business) what is relevant in the industry today.

From the sound of your struggles (family, finance, frustration with the relevance of your schooling to your ability to produce) - I would suggest that you "hit the market" and begin building your experience.  It may be a bit of a struggle to get started, but once you leave that start in your rear view mirror and build your resume and experience, you will soon find yourself a strong competitor with  the opportunity to make the education of those around you irrelevant.

Then, if the degree is really important to you down the road - you always have the option (when you have the time and the means) to finish it later.


问:
Agile product backlogs
We are starting an Agile project, and the product owner has made a start adding user stories to the product backlog (mostly epics at this stage).

Who would be responsible for breaking down epics into smaller user stories - is it left to the product owner, or would you expect the rest of the team to be involved (bearing in mind they won't have any knowledge of the requirements or problem domain)?

答:
The Product Owner shouldn't be putting 'epics' on the backlog, they should be putting stories on the backlog.

If, during the planning and estimation process the team finds that a story is too large to fit into a sprint, then the team promotes the story to an epic, and with the assistance of the Product Owner, breaks it down into manageable parts.

The important points:

POs don't get to write 'epics' in order to avoid thinking seriously about the features they want.  They write stories that describe concrete features.

Breaking down a story into smaller pieces usually requires domain knowledge from both the development side and the Product Owner side.  This is best thought of as a collaborative effort.

Title: Agile product backlogs


问:
How do bug reports factor in to a sprint?
I've been reading up on Scrum recently. From my understanding, a meeting is held before the sprint starts, to decide what gets moved from the product backlog to the upcoming sprint backlog. Once a feature is completed in the current sprint, it will go into the "Ready to QA" bucket, and it's at this point that I'm getting confused. Do bug reports go back into the product backlog? I assume they can't go back into the sprint backlog as we've already decided what work will be done for this cycle? What happens when QA finds a bug? Where does it go?</p>

答:
A sprint should be self contained.  That means all activities, including QA, bug fixing, and documentation, should be completed before the end of the sprint.  Pre-deployment activities should also take place before the sprint is over.

The problem with not finishing is that you get distracted in the next sprint.

If, in sprint B, you have to turn your attention back to the code from sprint A so that you can fix bugs, then your ability to focus on the tasks in sprint B goes out the window.  So does your forward velocity.


答: Scrap Word or PDF as a document format - instead write your code in ASCIIDoc or ReStructuredText and use that as a source to generate PDF/Word documents. The benefit of using the lightweight markup is that you can write your documents as plain old text (which programmers would like as they can do it inside the IDE, thus meaning they might do more of it) and the diffs that can be generated between documents is a solved problem. You also get the benefit of turning that into HTML or your usual format for releasing.</p>

Title: So we've got a code review tool, now what can we use for software documents?

Body:
We're using Subversion as a full CM for code and also for related project documents. We have JIRA and Fisheye. When we wanted to add a peer review tool, we looked at and tested several candidates. Our weighted requirements included both code and document review, but ultimately, the integration with JIRA slanted the scores in Crucible's favor.

Atlassian has slammed the door on ever supporting Word or PDF in Crucible. I've tested several workaround methods to make Crucible work for documents without success. (The Confluence/Crucible plug-in was deprecated by Atlassian, so that option is out, too.) I haven't found a plugin for Crucible that adds this functionality, so short of writing my own plug-in, Crucible for documents is unworkable.

Word Track Changes doesn't provide a method for true collaboration and commenting. Adobe PDF Comment and Markup is interesting, but doesn't provide a great way to keep a permanent quality record of the conversation. We can't go cloud-based, our documents must be locally hosted on our own server only. We're only on Sharepoint 2007.

Help! Anyone have a suggestion?


问:
Opinions on logging in multiprocess applications
We have written an application that spawns at least 9 parallel processes. All processes generate a lot of logging information.

Currently we are using Python’s QueueHandler to consolidate all logs into one file. Unfortunately, this sometimes results in very messy files which are hard to read (making it difficult to track exactly what’s going on in one thread).

Do you think it is a viable option to separate all messages into dedicated files? Or will this make things even messier, due to the high number of files?

What are your general experiences when writing log files for multiprocessed/multithreaded applications?

答:
I prefer letting each process log to it's own file and later merge them together if needed/wanted. This way I don't have to concurrency/contention on one single log file. Being separate processes the log events are usually pretty disjoint anyhow.

Performance wise this is the most efficient way to handle it. The joining of log files is typically wasteful since no one reads most of it anyhow, I would stick to doing so on demand.

If you are mostly using your log files as debug instrumentation instead of auditing purposes and it's helping you to get your code to work or debug multi-threading issues the joining of log files may result in loss of event ordering unless you can use an acceptable high enough resolution timer to include in your log events. However your safest bet would be to log to a log service of some sort that synchronizes for you.


答: Tag each log line with the process id as an identifier, then use grep when looking at the logs.  Or something else besides the process id.</p>

Title: Opinions on logging in multiprocess applications

Body:
We have written an application that spawns at least 9 parallel processes. All processes generate a lot of logging information.

Currently we are using Python’s QueueHandler to consolidate all logs into one file. Unfortunately, this sometimes results in very messy files which are hard to read (making it difficult to track exactly what’s going on in one thread).

Do you think it is a viable option to separate all messages into dedicated files? Or will this make things even messier, due to the high number of files?

What are your general experiences when writing log files for multiprocessed/multithreaded applications?


问:
How do people read big technical books?
I see that most of the good programmers have the habit of reading big books for learning about technology.

What does it really take to read technical books, apart from the real interest on the technology?

How can I improve my ability to read these books?

答:
This is a strange question.  If you are interested in something, isn't it natural to want to read about it?  If you find it difficult to read books about programming, you should ask yourself if you are really that interested.

If the answer is still yes, then make sure you pick a good book that is related to what you are currently doing.  For instance, if you are using C++, start reading the books by Scott Meyers or Andrey Alexandrescu.

Title: How do people read big technical books?


答:
Are these appropriate or too advanced to ask someone who says they know Java concurrency?

I'd say they are relatively advanced questions.  However they are not "unfair" in the sense that they are not trick questions.

Indeed "fairness" is not really a relevant criterion.  What you (as an interviewer) should be worrying about is whether the questions and your interpretation of the answers is selecting the best candidates for the position or positions you are interviewing for.  (Or to put it another way, are you rejecting candidates that you should really be giving more consideration due to their not answering these questions "correctly"?)

And while we're at it, do you think that someone working in Java concurrency should be expected to have an above-average knowledge of Java garbage collection?

Again, that's not really the relevant question.  The question you should be asking yourself is whether you need someone who has good knowledge of Java garbage collection.

Title: Are these advanced/unfair interview questions regarding Java concurrency?

Body:
Here are some questions I've recently asked interviewees who say they know Java concurrency:

Explain the hazard of "memory visibility" - the way the JVM can reorder certain operations on variables that are unprotected by a monitor and not declared volatile, such that one thread may not see the changes made by another thread. Usually I ask this one by showing code where this hazard is present (e.g. the NoVisibility example in Listing 3.1 from "Java Concurrency in Practice" by Goetz et al) and asking what is wrong.

Explain how volatile affects not just the actual variable declared volatile, but also any changes to variables made by a thread before it changes the volatile variable.

Why might you use volatile instead of synchronized?

Implement a condition variable with wait() and notifyAll().  Explain why you should use notifyAll().  Explain why the condition variable should be tested with a while loop.

My question is - are these appropriate or too advanced to ask someone who says they know Java concurrency?

And while we're at it, do you think that someone working in Java concurrency should be expected to have an above-average knowledge of Java garbage collection?


问:
Best method to organize/manage dependencies in the VCS within a large solution
A simple scenario:

2 projects are in version control

The application

The test(s)

A significant number of checkins are made to the application daily.

CI builds and runs all of the automation nightly.

In order to write and/or run tests you need to have built the application (to reference/load instrumented assemblies). Now, consider the application to be massive, such that building it is prohibitive in time (an entire day to compile). The obvious side effect here, is that once you've performed a build locally, it is immediately inconsistent with latest.

For instance:

If I were to sync with latest, and open up one of the test projects, it would not locally build until I built the application. This is the same when syncing to another branch/build/tag. So, in order to even start working, I need to wait a day to build the application locally, so that the assemblies could be loaded - and then those assemblies wouldn't be latest.

How do you organize the repository or (ideally) your development environment such that you can continually develop tests against whatever the current build is, or a given specific build, while minimizing building the application as much as possible?

答:
On a side, FIX YOUR BUILDTIME!! This is fighting symptoms not the core problem!

Your tests should come together with your code, as in the same repository. Whenever you build the tests are build also. When you run the tests it of the same generation as the code it runs against.

You check out code to build, this checkout includes the tests. These tests you run.

Again don't waste spending time trying to build less often. If it hurts do it more often! Break up the monolith, get a handle on dependencies. Use your build system to help you not touch/rebuild unchanged stuff. You need to modularize for this. Dependency inversion helps a lot here.


答:
If you do TDD. You can't change the signature and behaviour without having driven it by tests. So the 30 tests that fail were either deleted in the process or changed/refactored along with the code. Or they are now obsolete, safe to delete.

You can't ignore the 30 times red in your red-green-refactor cycle?

Your tests should be refactored along side your production code. If you can afford to, re-run all tests after each change.

Don't be afraid to delete TDD tests. Some tests end up testing building blocks to get to a desired outcome. The desired outcome at a functional level is what counts. Tests around intermediate steps in the algorithm you chose/invented may or may not be of much value when there is more then one way to reach the outcome or you initially ran into a dead-end.

Sometimes you can create some decent integration tests, keep those and delete the rest. It somewhat depends whether you work inside out or top down and how large steps you take.

Title: How to get initial API right using TDD?

Body:
This might be a rather silly question as I am at my first attempts at TDD. I loved the sense of confidence it brings and generally better structure of my code but when I started to apply it on something bigger than one-class toy examples, I ran into difficulties.

Suppose, you are writing a library of sorts. You know what it has to do, you know a general way of how it is supposed to be implemented (architecture wise), but you keep "discovering" that you need to make changes to your public API as you code. Perhaps you need to transform this private method into strategy pattern (and now need to pass a mocked strategy in your tests), perhaps you misplaced a responsibility here and there and split an existing class.

When you are improving upon existing code, TDD seems a really good fit, but when you are writing everything from scratch, the API you write tests for is a bit "blurry" unless you do a big design up front. What do you do when you already have 30 tests on the method that had its signature (and for that part, behavior) changed? That is a lot of tests to change once they add up.


答:
Ask them about the limitations they've come across while using the language. Ask them to show you a simple SQL query. Any Php dev worth a hoot should be able to bang out a basic select/update/delete query without too much effort.

doug


答:
I look at it from the user's perspective. For example, if your APIs let me create a Person object with name and age, there had better be a Person(string name, int age) constructor and accessor methods for name and age. It's simple to create test cases for new Persons with and without a name and age.

doug

Title: How to get initial API right using TDD?


问:
How to write efficient code despite heavy deadlines
I am working in an environment wherein we have many projects with strict deadlines on deliverables. We even talk directly to the clients so getting the jobs done and fast is a must.

My issue is that i'd always write code for the first solution that comes to my mind, which of course I thought as best at that moment. It always ends up ugly though and i'd later realize that there are better ways to do it but can't afford to change due to time restrictions.

Are there any tips by which I could make my code efficient yet deliver on time?

答:
If they fixed scope and time all you can do to make the deadline is drop quality.

If possible drop external quality, visible to stakeholders, do not compromise on internal quality, stuff that hurts your habitability in the codebase.

I really don't think self improvement is going to help you any bit in this situation. If anything then, sorry to say, usually it's assertiveness.

Try to get a foot in the door when work is estimated. How can your boss estimate how long -you- take to do something?

Bring choices to your boss and/or customer. Too often it's developers themselves who choose to drop quality without communicating anything. Late projects/work is very common and typically 'managed'. Act on it on time, warn people if you see a missed deadline coming.

They can't cut scope or move the deadline if you tell them nothing.

If you are going to compromise on quality in any form, try to let it be their decision. Give them stuff to weight against each other.

Some stuff only YOU can decide. If you just about got it to work. But it's very unmaintainable. Perhaps you are unsure if it works in all cases. Don't tell anyone you are done. Redo it. Very often it's a decision only you can make. Either because the problem is very time consuming to articulate or you have a non-technical manager.

Sometimes it's part of your work ethic, would you just stitch a patient up without washing your hands cause 'there is no time'?

Above all, remember: there is no later.


问:
Storing lots of large strings with frequent "appends" and few reads
In my current project, I need to store a very long ASCII string to each instance of a given object. This string will receive an 2 appends per minute and will not be retrieved so frequently.

The worst case scenario is a 5-10MB string. I'll have thousands of instances of my object and I'm worried that storing all those strings in the filesystem would not be optimal, but I can't think of a better solution.

Can anyone suggest an alternative? Maybe a key-value store? In this case, which one? Any other thoughts?

答: Appending a few characters to a 10mb string sounds like a poor design choice.  Back up and consider what you are actually doing, without the assumption/conclusion that the object in question is a string.  Maybe some (infrequently used) view of the object needs to be a string, but that is another matter.</p>