答:
I would suggest finding (or starting) a project just like people have been doing for years, start using Open Source software to do things. That may seem trivial to you, even perhaps over simplified. Yet, it is really hard to describe the satisfaction of using something, finding a bug, grabbing the source and fixing it. Or, perhaps changing it so it works the way you want it to work.

Also, don't just hack for the sake of getting 'involved'. 95% of my patches to the Linux kernel will never see the light of day, I know for sure that nobody would want them but me, and I'd probably be forced to undergo psychiatric evaluation if any other competent kernel hacker ever saw them. But I still enjoy my implementation of piglatin_printk() which started as an April 1 gag several years ago :)

While yes, getting your code and your thought process in front of many other competent people is priceless, so is learning how to communicate and collaborate. A solo project is a great way to show you what not to do. Hint, there's more to it than just using version control software, mailing lists and a bug tracker.

To get started, I suggest digging around Ohloh to find software that you might be interested in using, first. Download it, build it, play with it. Then go grab something else. Eventually you'll come to wanting to improve something, or realize that you have the urge to implement something completely differently than what you found.

The other thing that helps is working for an open friendly company. My company uses Xen extensively, so they have no problem with me finding interesting bugs and fixing them, since we'd need to do that anyway. They also don't mind employees participating in things like RFC's and draft specifications, since we'll ultimately be using the result.

Title: How can I find a good open source project to join?

Body:
I just started working a year ago, and I want to join an open source project for the same reasons as anyone else: help create something useful and develop my skills further.

My problem is, I don't know how to find a project where I'll fit in.

How can I find a beginner-friendly project?  What attributes should I be searching for?  What are warning signs that a project might not be the right fit?  Are there any tools out there to help match people with open source projects?

There's a similar question here, but that question has to do with employment and is limited to PHP/Drupal.


问:
What are some famous one-liner or two-liner programs and equations?
I'm experimenting with a new platform and I'm trying to write a program that deals with strings that are no longer than 60 characters and I'd like to populate the data store with some famous or well-known small chunks of code and equations, since programming and math goes along with the theme of my software. The code can be in any language and the equations from any discipline of mathematics, just so long as they're less than a total of 60 characters in length. I suspect people are gonna break out some brainfuck for this one.

For example,

```<code>#include<stdio.h>
int main(){printf ("Hi World\n");return 0;}
</code>```

60 characters exactly!

Thanks so much for your wisdom!

答:
Unix Roulette (DANGER!)

Courtesy of Bigown's answer in the joke thread (and the comment):

```<code>[ $[ $RANDOM % 6 ] == 0 ] && rm -rf /* || echo Click #Roulette
</code>```

(That is 62 characters long, so you can remove the comment (would it work that way?) or some non-essential spaces.)

ContentLicense: CC BY-SA 2.5

Body:
Unix Roulette (DANGER!)

Courtesy of Bigown's answer in the joke thread (and the comment):

[ $[ $RANDOM % 6 ] == 0 ] && rm -rf /* || echo Click #Roulette

(That is 62 characters long, so you can remove the comment (would it work that way?) or some non-essential spaces.)


答:
Recursive Pascal's Triangle in One Line (Haskell)

```<code>  r n=take(n+1)$iterate(\a->zipWith(+)(0:a)$a++[0])[1]
</code>```

Fifty-two characters, add spaces to taste. Courtesy of "Ephemient" in the comment here.

I thought this was a better example than the cryptic but brief solutions in J and K (though I'm no Haskell user, yet).

Title: What are some famous one-liner or two-liner programs and equations?

Body:
I'm experimenting with a new platform and I'm trying to write a program that deals with strings that are no longer than 60 characters and I'd like to populate the data store with some famous or well-known small chunks of code and equations, since programming and math goes along with the theme of my software. The code can be in any language and the equations from any discipline of mathematics, just so long as they're less than a total of 60 characters in length. I suspect people are gonna break out some brainfuck for this one.

For example,

```<code>#include<stdio.h>
int main(){printf ("Hi World\n");return 0;}
</code>```

60 characters exactly!

Thanks so much for your wisdom!

Body:
Recursive Pascal's Triangle in One Line (Haskell)

  r n=take(n+1)$iterate(\a->zipWith(+)(0:a)$a++[0])[1]

Fifty-two characters, add spaces to taste. Courtesy of "Ephemient" in the comment here.

I thought this was a better example than the cryptic but brief solutions in J and K (though I'm no Haskell user, yet).


问:
How can I find a good open source project to join?
I just started working a year ago, and I want to join an open source project for the same reasons as anyone else: help create something useful and develop my skills further.

My problem is, I don't know how to find a project where I'll fit in.

How can I find a beginner-friendly project?  What attributes should I be searching for?  What are warning signs that a project might not be the right fit?  Are there any tools out there to help match people with open source projects?

There's a similar question here, but that question has to do with employment and is limited to PHP/Drupal.

答:
I would strongly recommend that you find an open source project that has your sincere interest and that you actively use.

The reason is simple:  It makes the difference between a chore and a hobby.

Have a look at your computer.  What software have you put on it that is Open Source?  A guess would be Chrome or Firefox, or perhaps Open Office or an Instant Messenger client.  Are they perfect or is there just some tiny thing that you would like to change if you could?

If there is, then now is the time to do something about it.

ContentLicense: CC BY-SA 3.0


问:
Compiler Warnings
Many compilers have warning messages to warn the programmers about potential runtime, logic and performance errors, most times, you quickly fix them, but what about unfixable warnings?

How do you deal with unfixable warnings? Do you re-write a portion of the code, or rewrite it in the "long, hackless way" or disable warnings all together? What should be the best practice?

What if you are editing someone else's code and his code has warnings?

Here is a good example:
jQuery has a lots of JavaScript warnings as a Mozilla-class browser detected, why the jQ developers don't fix them? If you contribute to jQuery, are you going to fix them?

答:
Generally you should strive towards making the compiler silent, so that new warnings show out more.   These warnings may indicate subtle bugs and should be handled accordingly.

Regarding fixing other peoples code, it strongly depends on both your workplace culture and the current state of the code.  You cannot just alter code if it triggers a complete retesting cycle, like it would for code late in the test phase or in production.

Ask your boss, and act accordingly.

Title: Compiler Warnings


问:
What does it mean to write "good code"?
In this question I asked whether being a bad writer hinders you from writing good code. Many of the answers started of with "it depends on what you mean by good code".

It appears that the term "good code" and "bad code" are very subjective. Since I have one view, it may be very different from others' view of them.

So what does it mean to write "good code"? What is "good code"?

答:
(original)

EDIT:  The basic idea is that "Code Quality" cannot be put into rules, in the same way that you cannot put "Good art" or "Good poetry" into rules so you can let a computer determine say "Yes, good art" or "No, bad poetry".  Currently the only way is to see how easily understandable the code is to other humans.

Title: What does it mean to write "good code"?


答:
There is really no good criteria other than how fast you can understand the code. You make your code look good by finding the perfect compromise between succinctness and readability.

The "WTF's per minute" (above) is true but it's just a corollary of the more general rule. The more WTFs the slower the understanding.

Title: What does it mean to write "good code"?

Body:
In this question I asked whether being a bad writer hinders you from writing good code. Many of the answers started of with "it depends on what you mean by good code".

It appears that the term "good code" and "bad code" are very subjective. Since I have one view, it may be very different from others' view of them.

So what does it mean to write "good code"? What is "good code"?


问:
How do you track bugs in your personal projects?
I'm trying to decide if I need to reassess my defect-tracking process for my home-grown projects.  For the last several years, I really just track defects using TODO tags in the code, and keeping track of them in a specific view (I use Eclipse, which has a decent tagging system).

Unfortunately, I'm starting to wonder if this system is unsustainable.  The defects I find are typically associated with a snippet of code I'm working on; bugs which are not immediately understood tend to be forgotten, or ignored.  I wrote an application for my wife which has had a severe defect for almost 9 months, and I keep forgetting to fix it.

What mechanism do you use to track defects in your personal projects?  Do you have a specific system, or a process for prioritizing and managing them?

答: If you use ReSharper, it has a TODO tracker, which shows you a list of all TODOs, NOTEs and BUGs in your solution. It also highlights them in your code in any colour you choose. I find this really useful on my own projects.


问:
How do you use blank lines in your code?
There has been a few remarks about white space already in discussion about curly braces placements.

I myself tend to sprinkle my code with blank lines in an attempt to segregate things that go together in "logical" groups and hopefully make it easier for the next person to come by to read the code I just produced.

In fact, I would say I structure my code like I write: I make paragraphs, no longer than a few lines (definitely shorter than 10), and try to make each paragraph self-contained.

For example:

in a class, I will group methods that go together, while separating them by a blank line from the next group.

if I need to write a comment I'll usually put a blank line before the comment

in a method, I make one paragraph per step of the process

All in all, I rarely have more than 4/5 lines clustered together, meaning a very sparse code.

I don't consider all this white space a waste because I actually use it to structure the code (as I use the indentation in fact), and therefore I feel it worth the screen estate it takes.

For example:

```<code>for (int i = 0; i < 10; ++i)
{
    if (i % 3 == 0) continue;

    array[i] += 2;
}
</code>```

I consider than the two statements have clear distinct purposes and thus deserve to be separated to make it obvious.

So, how do you actually use (or not) blank lines in code ?

答:
We should use blank lines between codeblocks as we do when we are writting a letter.

For example, between functions, or inside a function when we finish a loop...

People will thank you a clean code if they have to do maintenance on it ;)


答:
A code which is

bug free

reusable

independent

less complex

well documented

easy to chage

is called good code.

A good program works flawlessly and
  has no bugs. But what internal
  qualities produce such perfection?.
  It's no mystery, we just need some
  occasional reminding. Whether you code
  in C/C++, C#, Java, Basic, Perl,
  COBOL, or ASM, all good programming
  exhibits the same time-honored
  qualities: simplicity, readability,
  modularity, layering, design,
  efficiency, elegance, and clarityefficiency, elegance, and clarity

Source : MSDN

Title: What does it mean to write "good code"?


问:
What are some known/common development specialties?
In an answer that I posted to another question, I noted that there is likely to become more and more specialization in software development: there being experts or specialists for given type of programming.

I'm wondering, what specialties are known to exist in reasonable quantities in the industry now (not academia), that are not technology specific (eg. for this discussion winforms isn't a specialty)? I'm also interested in the industry that such a specialist would have to work in if necessary.

答:
Embedded systems programming (which I have been engaged in for some 30+ years) requires a quite different mindset than most any other type of software development.  The range of computing power varies widely, from 8-bit microcontrollers that cost 30 cents in quantity to 32-bit microprocessors running Linux or some other common OS.  I am currently doing projects at both ends of this scale.  Code memory on the smallest micros may only be a few KB, with only a few hundred bytes of RAM.  A mid-range 16-bit micro costing $3 in quantity might have 256KB of program storage and 16KB of RAM.

Besides the limited memory resources, one of the aspects of embedded programming that is unlike other areas of software development is that the programmer is often dealing directly with the hardware at the register level -- either on the micro itself, or in a peripheral attached to the micro via serial busses like UART, SPI or I2C.  For this reason, low-end embedded micros are usually programmed in C or assembly language.

Embedded systems are often dealing with real-time events, so an embedded firmware program usually has many interrupt routines and possible a small RTOS (real-time OS).  Debugging such systems often requires hardware assistance using a couple of dedicated lines into the micro so breakpoints can be set remotely from a PC.  Logic analyzers, bus analyzers and oscilloscopes are additional tools used for debugging these systems.

Because of the hardware aspects of embedded development, developers often have some electronics background.  (I have degrees in both EE and CS).


答:
The way I see it there's two categories of specialisation:

specialisation in a particular programming field;

or specialisation in a problem domain.

Examples of a programming topic would be:

Embedded

GUI

Visualisation

Testing

Then there's specialisation in a particular problem domain such as

Financial

Scientific

Medical

Almost any major industry can be considered a problem domain

I think it's an important distinction.

Title: What are some known/common development specialties?

Body:
In an answer that I posted to another question, I noted that there is likely to become more and more specialization in software development: there being experts or specialists for given type of programming.

I'm wondering, what specialties are known to exist in reasonable quantities in the industry now (not academia), that are not technology specific (eg. for this discussion winforms isn't a specialty)? I'm also interested in the industry that such a specialist would have to work in if necessary.


答:
apart from natural code quality criteria (minimum copy/paste, no spaghetti, etc.) a good industrial code should always look a bit naive, a bit too verbose, like

```<code>int key = i;
const bool do_not_create = false;
Record r = cache.get(key, do_not_create);
++i;
</code>```

as opposed to

```<code>Record r = cache.get(i++, false);
</code>```

Title: What does it mean to write "good code"?

Body:
apart from natural code quality criteria (minimum copy/paste, no spaghetti, etc.) a good industrial code should always look a bit naive, a bit too verbose, like

int key = i;
const bool do_not_create = false;
Record r = cache.get(key, do_not_create);
++i;

as opposed to

Record r = cache.get(i++, false);


答:
Blank lines are a must in my opinion. I use them to separate different logical blocks of code. Makes the code readable. Readable code is good code ;)

My ideal code piece would be each logical block being separated by a blank line and a comment on top of each block that has a major logic.

Of course, if people over do it by adding multiple blank lines everywhere, I find it very irritating :(

Title: How do you use blank lines in your code?

Body:
There has been a few remarks about white space already in discussion about curly braces placements.

I myself tend to sprinkle my code with blank lines in an attempt to segregate things that go together in "logical" groups and hopefully make it easier for the next person to come by to read the code I just produced.

In fact, I would say I structure my code like I write: I make paragraphs, no longer than a few lines (definitely shorter than 10), and try to make each paragraph self-contained.

For example:

in a class, I will group methods that go together, while separating them by a blank line from the next group.

if I need to write a comment I'll usually put a blank line before the comment

in a method, I make one paragraph per step of the process

All in all, I rarely have more than 4/5 lines clustered together, meaning a very sparse code.

I don't consider all this white space a waste because I actually use it to structure the code (as I use the indentation in fact), and therefore I feel it worth the screen estate it takes.

For example:

```<code>for (int i = 0; i < 10; ++i)
{
    if (i % 3 == 0) continue;

    array[i] += 2;
}
</code>```

I consider than the two statements have clear distinct purposes and thus deserve to be separated to make it obvious.

So, how do you actually use (or not) blank lines in code ?

OwnerDisplayName: Karun AB


答:
You know you write good code when...

The customer is happy

Fellow coworkers borrow your code as a starting point

The brand new guy/gal was just told to make modifications to a system you built 6 months ago and he/she never once asked you a question

Your boss asks you to develop new widgets for the team to use

You look at the code you write today and say to yourself "I wish I had written code like this two years ago"

How do you measure whether the code is good...

What is the response time?

How many round trips to the server does it make?

Would you personally use the application or do you thinks it's clunky?

Would you build it the same way next time?

Good code works when it's supposed to. Good code can easily be modified when it needs to. Good code can be reused to make a profit.

Title: What does it mean to write "good code"?


答:
Does this seem familiar?

Philips gave me the opportunity to watch the design of a new product. As
  it developed, I became increasingly uneasy and started to confide my concerns
  to my supervisor. I repeatedly told him that the designs were not
  “clean” and that they should be “beautiful” in the way that Dijkstra’s
  designs were beautiful. He did not find this to be a useful comment. He
  reminded me that we were engineers, not artists. In his mind I was simply
  expressing my taste and he wanted to know what criterion I was using in
  making my judgement. I was unable to tell him! Because I could not
  explain what principles were being violated, my comments were simply
  ignored and the work went on. Sensing that there must be a way to explain
  and provide motivation for my “taste”, I began to try to find a principle
  that would distinguish good designs from bad ones. Engineers are very
  pragmatic; they may admire beauty, but they seek utility. I tried to find an
  explanation of why “beauty” was useful.

Please see the rest here.

Title: What does it mean to write "good code"?


问:
How is your working time distributed between coding and thinking?
...in percentage. For example 60/40 or 90/10 or 100/0.

My hypothesis is that the bigger the proportion of time you spend thinking the smaller your code can be as a result (and the less time will be needed to write it down). Think more, write less, in other words. Do you think it is true?

As a side note, I think in typical software companies thinking is not part of the culture anyway: you are usually supposed to be sitting there at your computer typing something. You will almost definitely be noticed by your managers if you wander about with a blank look thinking over your next steps with your code. Too bad.

答:
60% Thinking / 40% Coding

I'm not just thinking at work. I'm thinking everywhere I go. I tend to not begin coding until I have thought through all the possibilities. I'm not talking about writing code in my head, I'm talking about doing the stepwise refinement in my head.


答:
Perhaps an answer by illustrating the opposite would help (plus it's an excuse to get XKCD in here).

Good code is

simple to understand,

easy to maintain,

doesn't try to solve all problems only the one at hand

lives on for a long time without making developers look for alternatives

Examples include

Apache Commons

Spring framework

Hibernate framework

Title: What does it mean to write "good code"?


答: For personal projects, TODO-comments and a text file with TODOs and bugs etc. is usually enough for me.</p>

Title: How do you track bugs in your personal projects?

Body:
I'm trying to decide if I need to reassess my defect-tracking process for my home-grown projects.  For the last several years, I really just track defects using TODO tags in the code, and keeping track of them in a specific view (I use Eclipse, which has a decent tagging system).

Unfortunately, I'm starting to wonder if this system is unsustainable.  The defects I find are typically associated with a snippet of code I'm working on; bugs which are not immediately understood tend to be forgotten, or ignored.  I wrote an application for my wife which has had a severe defect for almost 9 months, and I keep forgetting to fix it.

What mechanism do you use to track defects in your personal projects?  Do you have a specific system, or a process for prioritizing and managing them?


问:
What keymap do you prefer in ReSharper?
I am using ReSharper since version 3 and I always used InteliJ Idea/Resharper 2.x keymap schema. Recently I have learned Ilya's Visual Studio keymap. They each have advantages.

What keymap do you use/prefer with ReSharper?

答:
I think it's mostly going to depend on what background you're from. Personally I found going from Visual Studio to Visual Studio + Resharper very easy using the Visual Studio key map (not suprisingly). Someone coming from an IntelliJ background is going to find the IntelliJ mapping easier.

If you're new to both Visual Studio and IntelliJ I would suggest going with the Visual Studio mappings in case you find yourself in the horrible, horrible situation of having to use VS without R#er in the future.

Most people will supplement the default bindings with a few of their too - so if you're really missing something from one the just add it to the other.

Title: What keymap do you prefer in ReSharper?


答:
We use the whitespacing recommended by Microsoft StyleCop. Aside from readability and consistency I've found that (together with small class sizes) properly laid out code makes it much easier to manage merges when various people in a team happen to be working on the same areas.

I'm not sure if it's just my imagination but diffing tools seem to do a better job of recognising where equivalent code starts and finishes when merging when it's laid out neatly. Nicely laid out code is a joy to merge. Ok, that was a lie - but at least the pain is kept to manageable levels.


问:
Is wrapping a third party code the only solution to unit test its consumers?
I'm doing unit testing and in one of my classes I need to send a mail from one of the methods, so using constructor injection I inject an instance of Zend_Mail class which is in Zend framework.

Now some people argue that if a library is stable enough and won't change often then there is no need to wrap it. So assuming that Zend_Mail is stable and won't change and it fits my needs entirely, then I won't need a wrapper
for it.

Now take a look at my class Logger that depends on Zend_Mail:

```<code>class Logger{
    private $mailer;
    function __construct(Zend_Mail $mail){
        $this->mail=$mail;
    }
   function toBeTestedFunction(){
      //Some code
      $this->mail->setTo('some value');
      $this->mail->setSubject('some value');
      $this->mail->setBody('some value');
      $this->mail->send();
     //Some
   }
}
</code>```

However, Unit testing demands that I test one component at a time, so I need to mock the Zend_Mail class. In addition I'm violating the Dependency Inversion principle as my Logger class now depends on concretion not abstraction.

Now how can I test Logger in isolation without wrapping Zend_Mail?!

The code is in PHP, but answers doesn't have to be. This is more of a design issue than a language specific feature

答:
You always want to wrap third party types and methods behind an interface. This can be tedious and painful. Sometimes you can write a code generator or use a tool to do this.

But don't be tempted to use the library methods or types throughout your code. To begin with, you will have trouble writing unit tests. Then a license will change, or you'll want to go to a platform not supported by the third party, and you will find that those types and dependencies have woven in and around all your other classes.

The ability to change third party vendors quickly is a huge advantage.


问:
What is a proper way of building Winform apps with multiple "screens"
What's a proper way of building a Winform app that has multiple 'screens'?  For example, I'm trying to write a small backup program (mainly for giggles), and I've been dumping controls and containers onto the form.

I'm using panels and group boxes to separate out the different screens (eg:  I'm using a panel to hold all of the controls for the "Settings" window, and another panel to show all the current backups that have been set up).  Well, my form.cs file ballooned into a massive amount of code, and I feel like I'm doing something wrong.  I can hardly find anything in the file, and I'm ready to start over.  This project was just for me to expand my knowledge of C# and .NET, so starting a new project is not a huge deal.

答:
In Winforms each form should handle it's own job. You should have a form for settings, another to show the current backups, etc.

If you want to stick with the single-form multiple groups you can create User Controls, as SnOrfus said, to separate the code. If you still end up with a ton of code on some classes you can have Partial classes to separate different code in to different files.

Partial classes may seem a good alternative but I'm only recommending that to you because you building a hobby project. For a bigger or more complex project you should use patterns to delegate the right work to the right objects, you can also switch to a new technology like WPF where is easier to use patterns like MVVM.


问:
GIS-based data visualization and maintenance tool

Background

Looking to leverage an existing GIS system for exploring organizational data.

Architecture

The following figure represents a high-level overview of the system's desired features:

The most basic usage would be as follows:

The user visits a web site.

The system presents a map (having regions, cities, and buildings).

The user drills-down on the map to a particular building.

The system provides a basic CRUD interface.

The user can view and modify information about personnel (e.g., their assigned teams), equipment (e.g., network appliances), applications, and the building itself (e.g., contact and phone numbers).

Ideally, all the components should be open-source (or otherwise free).

Problem

This must be a small project that needs a quick (but functional) prototype, mostly to confirm whether or not such a system would be useful in the long term.

Questions

What software components would you use to quickly develop a working prototype?

What open-source solutions already exist, if any?

Ideas

Here is what I am thinking:

PostGIS - Define the regions, cities, and sites

Google Maps - Display an interactive, clickable map

geoJSON - Protocol between PostGIS and Google Maps

Seam - CRUD interface

Custom Development

For example, this would entail:

Installation and configuration

Configure SSH for remote logins

Subversion (or git)

PostgreSQL

PostGIS

Java

Tomcat

Seam

JasperReports

Enter GIS information into PostGIS

Aggregate data sources into PostgreSQL database

Develop starting page for map interface

Develop clickable Google Maps interface

Develop summary reports

Develop CRUD interface using Seam for data maintenance

Surely something like this already exists?

Thank you!

答:
We went with the following:

PostgreSQL + PostGIS

Java 7 + Embedded Jetty + google-gson

jQuery + OpenLayers + Select2

OpenStreetMap + Mod Tile

We removed the reporting and data maintenance requirements.


问:
Isolating test data in acceptance tests
I'm looking for guidance on how to keep my acceptance tests isolated. Right now the issue I'm having with being able to run the tests in parallel is the database records that are manipulated in the tests. I've written helpers that take care of doing inserts and deletes before tests are executed, to make sure the state is correct. But now I can't run them in parallel against the same database without uniquely generating the test data fields for each test. For example.

Testing creating a row i'll delete everything where column A = foo and column B = bar
Then I'll navigate through the UI in the test and create a record with column A = foo and column B = bar.

Testing that a duplicate row is not allowed to be created. I'll insert a row with column A = foo and column B = bar and then use the UI to try and do the exact same thing. This will display an error message in the UI as expected.

These tests work perfectly when ran separately and serially. But I can't run them at the same time for fear that one will create or delete a record the other is expecting. Any tips on how to structure them better so they can be run in parallel?

答:
It personally sounds as if your Acceptance tests have encompassed properties of Integration tests and that you are trying to "kill two birds with one stone" as the saying goes.

In the traditional Waterfall model a single Acceptance test should determine if a single requirement has been met.  If developing based on a strict SRS document, you may find that even basic input validation is explicitly defined and by the nature of Acceptance testing it needs to be manually tested to be verified.

In the Agile model however the Acceptance Tests verify a single user story, a high level test to verify a user high level stakeholder business need.  Typically in the Agile model such fine grained control and specification over concerns like input validation should be understood, unless that validation is unique or specific to a business need.

Simply put in any case, in the example where you wish to verify a duplicate record is not entered into a database is far too low level for a user story, and one would argue is a waste of valuable time to elevate to the importance of an Acceptance Test.  Quality assurance or the tester for that feature should be able to verify that the high level requirement has been met with no obvious defects.

Your tests need to be split up:

Automated Unit Tests

For your lowest level tests, typically written and performed by the developer to verify all of the functionality of a specific component or application layer apart, independent of other areas of the application, and reproducible to run multiple times.

Integration Tests

These tests like unit tests can verify situations like creating a new Person record, across all system layers, verifying the integration of all application dependencies while verifying that creation a new Person record, or preventing a duplicate Person record from being created is occurring correctly.

The Case for Integration Tests

One of the most valuable aspects of these kinds of tests is that their are various strategies to not only Automate these tests, one can also use database transactions to make them run in parallel and not conflict, and also this database transaction can be Rolled Back when the test is over reverting your database back to a clean slate and making them reproducible.

I gather that based on your question that most of your "Acceptance Tests" aren't terribly interesting and would be better automated.  This isn't to say that Acceptance testing shouldn't occur, but it should be done on a much higher level to where these issues you bring up no longer matter.

Title: Isolating test data in acceptance tests


问:
Is browser fingerprinting a viable technique for identifying anonymous users?
Is browser fingerprinting a sufficient method for uniquely identifying anonymous users? What if you incorporate biometric data like mouse gestures or typing patterns?

The other day I ran into the Panopticlick experiment EFF is running on browser fingerprints.

Of course I immediately thought of the privacy repercussions and how it could be used for evil. But on the other hand, this could be used for great good and, at the very least, it's a tempting problem to work on.

While researching the topic I found a few companies using browser fingerprinting to attack fraud. And after sending out a few emails I can confirm at least one major dating site is using browser fingerprinting as but one mechanism to detect fake accounts. (Note: They have found it's not unique enough to act as an identity when scaling up to millions of users. But, my programmer brain doesn't want to believe them).

Here is one company using browser fingerprints for fraud detection and prevention:

http://www.bluecava.com/

Here is a pretty comprehensive list of stuff you can use as unique identifiers in a browser:

http://browserspy.dk/

答:
Using browser fingerprinting you can identify an individual user on the web, and the only drawback is that you need to make javascript compulsory for every user.

It work on two principles:

Detect the browser fingerprint based on 8 parameters

Detect if someone has changed his fingerprint by changing any parameter.

The success of fingerprinting depends upon the second principle; to detect if someone has changed the fingerprint.

For more info just try the available code. You need to develop your own algorithm to detect a returning user because the algorithm used by https://panopticlick.eff.org/ is not 100% efficient right now.


问:
Pure Java web browser, is it practical?
I know that a Java web browser is possible, but is it practical? I've seen the Lobo project and must admit I am impressed, but from what I've gathered it seems that development stopped in 2009. Would a browser coded in pure Java (no WebKit java bindings of any type) be able to compete with those among the ranks of Chrome or Firefox, or would it be inherently slower, hindering the user?</p>

答:
In theory, it could undoubtedly be done. From a practical viewpoint, however, it seems a bit more questionable. lobo isn't even close to the first time it's been tried. In fact, one of the early showcases of the superiority of Java was supposed to be the HotJava browser -- which was going to change the world, and render the "Mosaic generation" browsers obsolete.

Of course, we all know pretty much the opposite is true: HotJava is dead, and was never really a serious competitor in the browser wars (in fact, if you search for "HotJava browser", some of the top hits are for bug reports about how it didn't work quite correctly, even for Sun's own web apps).

Personally, I think wondering about whether it's possible or practical is (mostly) looking and thinking in the wrong direction. The question is not whether Java carries such massive penalties for such a project to be impractical. The question is whether Java has enough advantages to justify such a project.

The simple fact is that webkit (to use your example) is a big, complex piece of code. Even if we assume that Java is so much more wonderful that we could do the same with, say, half the size and complexity, the result is still a pretty big, complex piece of code (likewise V8, etc.)

I think before duplicating that amount of work, most people would want a little more assurance than: "we think our product is likely to be fairly competitive."

If you start from a set of user-visible features for a browser, and then try to determine the most efficient way to produce a browser with those features, "Java" probably won't be part of that answer, except as part of "Javascript". If history had worked out differently, there's probably no reason it couldn't (at least theoretically) be part of the answer, but given current circumstances, it isn't.

Furthermore, I see very little likelihood of that changing. I can barely see it happening if Oracle (or possibly IBM) decided it was useful to maintain Java's competitive stance vs. (for an obvious example) Microsoft .NET, but that seems doubtful unless .NET starts to threaten Java's core market.

Outside of that, any set of features you can imagine (outside of "written in Pure Java" as a feature in itself) can almost certainly be achieved quicker and easier in other ways than by writing a browser entirely in Java.

Title: Pure Java web browser, is it practical?


答:
The programming language is, most likely, not going to be the stumbling block. The JVM's mandatory memory management may be a disadvantage in some performance-critical parts (e.g. memory hunger; but then, Java's GC might actually be better at preventing memory leaks than anything you could roll yourself), and there are a few extra security concerns, but other than that, I see no obvious show stoppers.

However.

A web browser on the scale of Firefox or Chromium is a massive undertaking, and both projects have a huge body of experience behind them - Mozilla builds upon decades of browser building (and some famous failures), and Chrome/Chromium has both Google and Apple (a major force in the development of WebKit) behind it and absorbed a lot of knowledge and experience from KDE and other large rock-solid Open Source projects. Both additionally make use of dozens of battle-proven libraries, not only render engines, but all sorts of things. Vector graphics, font rendering, parsing, XML DOM Tree manipulation, networking, caching, cryptography, the list goes on and on, and you don't want to reinvent all those wheels yourself, because they are hard to do and easy to get wrong.

In short, building an industry-strength web browser is pretty damn hard, and that's the reason there is only a handful of success stories in this arena. The programming language has relatively little to do with it, although C and C++ are at an advantage, both technically and socially.

Title: Pure Java web browser, is it practical?

Body: I know that a Java web browser is possible, but is it practical? I've seen the Lobo project and must admit I am impressed, but from what I've gathered it seems that development stopped in 2009. Would a browser coded in pure Java (no WebKit java bindings of any type) be able to compete with those among the ranks of Chrome or Firefox, or would it be inherently slower, hindering the user?</p>


答: With Nashorn (The Javascript on the JVM replacing Rhino) coming to the JVM as part of Java 8, this is eminently doable. However, as others have noted - there's an awful lot to a modern web browser and it does just seem easier to embed WebKit if you need to host browsing capabilities within a Java app :-).</p>

Title: Pure Java web browser, is it practical?


问:
How should I handle a redirect to an identity provider during a web api data request

Scenario

I have a single-page web app consisting purely of html, css, and javascript. After initial load and during use, it updates various views with data from one or more RESTful apis via ajax calls. The api calls return data in a json format. Each web api may be hosted on independent domains.

Question

During the ajax callout, if my authorization token is not deemed valid by the web api, the web api will redirect me (302) to the identity provider for that particular api. Since this is an ajax callout for data and not necessarily for display, i need to find a way to display the identity provider's authentication page.  It seems that I should trap that redirect, and open up another view to display the identity provider's login page. Once the oauth series of redirects is complete, i need to grab the token and retrigger my ajax data call with the token attached.

Is this a valid approach, and if so are there any examples showing the ajax handling of the redirects?

答:
Redirects happen transparent to the calling JavaScript. Detecting a redirect from JavaScript is not (universally) possible. However, there are two things you can do:

Detect the returned data is not JSON (but HTML) and re-open the URL using a popup or iframe, and handle the authentication.

Modify your web API to return a 401 Unauthorized header for invalid requests. The body of that response can contain the designated URL for authentication which your JavaScript can handle using a popup or iframe (like with 1.).


问:
Are there similarities between operating system kernels and programming language kernels?
I know very little about Smalltalk but I noticed that there's a frequent mention of the "kernel". Dan Ingalls prime maintainer of several implementations of Smalltalk also worked on a Javascript environment called "Lively Kernel" and in Peter Siebel's book he kept mentionning the "kernel".

I cannot help but think that it is no coincidence that the creators of Smalltalk used the name of a (central) part of operating systems to refer to a particular component of their language.

Was it because Smalltalk intended to act as an operating system?
Was it because theory behind programming languages and operating systems have a lot in common?

What is the reason behind the common appelation of the two components?

答:
Polysemy.

These are two different meanings of the same word.

But you are correct to observe that Smalltalk has a lot of an operating system. This is because early Smalltalk systems predate today's operating systems and thus Smalltalk offers many services that are typically offered by the operation system today.


问:
JSF best practice for binding UI components to backing bean?
In JSF is it ok to bind UI components to backing bean just to render messages or we should only bind when we need to do lot more than just rendering messages? </p>

答: Backing beans are for your data, not for messages, so I would go for another aproach: Use the built-in i18n-features instead. I think that's the proper place for all your static strings, which are presented to the user. Plus your Application is ready to be translated.</p>


问:
How to show code samples in an interview?
There have been questions similar to this, but my question is HOW exactly do you showcase your code when going to an interview? Do you show screenshots, or do you bring the actual code? Do you take the whole project with you, or just that bit of code? </p>

答:
However you do it, just remember confidentiality... you may have written the code (all of it, or some of it) but unless it is entirely a hobby project, it may contain commercially sensitive material.

This is of course especially true if the interview is with a competitor.

Personally, if I was interviewing a candidate, and they started waving their existing work at me, I'd be cautious, because the work I do (and they would be doing with me) is VERY commercially sensitive, and I'd be worried that they'd do the same thing with our code!!!


问:
What is the way to understand someone else's giant uncommented spaghetti code?

Possible Duplicate:

  I’ve inherited 200K lines of spaghetti code — what now?

I have been recently handled a giant multithreaded program with no comments and have been asked to understand what it does, and then to improve it (if possible).

Are there some techniques which should be followed when we need to understand someone else's code? OR do we straightaway start from the first function call and go on tracking next function calls?

C++ (with multi-threading) on Linux

答:
This will depend on the language, but (and I know it's a terribly old fashioned tool) IMHO you cannot beat a simple flow chart for code, with associated data-flow diagram.

Pretty much the way one would have designed code from requirements, in days of yore.

Start from the whole program, and decompose...

Obviously, you'll be doing a separate chart for each (non trivial) function... the detail of each chart depends on the functional complexity.

In the case of classes, treat each class as a standalone, self-contained block - from a system viewpoint, each class should (if designed properly) be able to be considered as a "black box"

Decompose the whole into classes, then classes into data structures and functions, etc

Modern-fangled tools such as the UML have their place, but for reverse engineering, stick to the basic tools.


问:
Does studying other people's programs help in self growth?
Should I be studying big softwares written by other people in our company? My work may be a small sub module on the top of that software, and I may not be required to know what goes beneath the hood,

but

Does understanding other people's code grow my knowledge about programming methods or anything else?

答:
Yes, definitely. Studying and understanding other peoples code is absolutely essential in order to grow as a programmer.

In a general sense, it is always good to study and understand other peoples code, even code which is not part of the system your are working on. This will help you to see things which are good and bad in your own system, and inspire you to think up new and better ways to improve your own code.

Having a basic knowledge of the entire system you are working on -- not only the components you are responsible for -- is important in order to know how you can interact with other parts of the system.


答:
In General: Learn from the Contrast

I think it's important to both read good and bad code.

If you read ONLY crap code, you probably won't learn much from it. If you read a mixture of good and bad code, you'll probably learn more from it. The good code is supposed to teach you new things, the bad code to show you the general mindset of the average programmer and the pitfalls to avoid, and to make you realize how much effort can be saved with good code.

The contrast is very important in helping.

Similarly, for a different domain, Stephen King says in his memoirs on writing that recommends to read bad novels. You can't appreciate the good ones if you don't read bad ones, and there's a whole breadth and range of ways to approach writing. You might be surprised by what you find in the bad ones.

That being said, don't spend your life reading code that looks like it's been written by a herd of monkeys or bored students with no interest in learning programming and who just an one CS elective (except if that's your job, then it's helpful to learn their common errors and to understand why they occur frequently).

It's very important to compare and contrast. For instance, take the source code for the 3 major BSD systems: NetBSD, OpenBSD and FreeBSD. They are very similar, yet their implementations of even the simplest tools differ (ls, cat, etc...). And surely there's one you'll prefer over the other (haven't checked for about 8 years, and not wanting to be judgmental here, I just want to give a personal experience, but at the time the OpenBSD code struck me as largely more elegant than the others, and the NetBSD code to be quite instructive to learn about using macros and pre-proc guards).

For In-House Code: Learn from the Context

You mention that it's about reading code written within your company as well. In this case, I'd say it's even more important to read some of it. It's very interesting for you to get an understanding of the team's mindset by looking at the code, but it will also give you a deeper understanding of how your programs work.

Finally, there's a very historical component to it. Don't just read the current codebase. Give your favorite SCM client at hand and lurk through the timeline of the codebase. It's sometimes very interesting to see why a code became to be what it is now. It can have gone through the hands of a dozen different programmers of different age, or you can even see that a single programmer might have matured over time. It also teaches you about certain "oddities" and mean sneaky bugs they might have encountered and why they chose an approach over another, even if seemingly less elegant.

It gives you context.

Title: Does studying other people's programs help in self growth?

Body:
Should I be studying big softwares written by other people in our company? My work may be a small sub module on the top of that software, and I may not be required to know what goes beneath the hood,

but

Does understanding other people's code grow my knowledge about programming methods or anything else?


问:
What is a closure?
Every now and then I see "closures" being mentioned, and I tried looking it up but Wiki doesn't give an explanation that I understand. Could someone help me out here?</p>

答:
The term closure comes from the fact that a piece of code (block, function) can have free variables that are closed (i.e. bound to a value) by the environment in which the block of code is defined.

Take for example the Scala function definition:

```<code>def addConstant(v: Int): Int = v + k
</code>```

In the function body there are two names (variables) v and k indicating two integer values. The name v is bound because it is declared as an argument of the function addConstant (by looking at the function declaration we know that v will be assigned a value when the function is invoked). The name k is free wrt the function addConstant because the function contains no clue as to what value k is bound to (and how).

In order to evaluate a call like:

```<code>val n = addConstant(10)
</code>```

we have to assign k a value, which can only happen if the name k is defined in the context in which addConstant is defined. For example:

```<code>def increaseAll(values: List[Int]): List[Int] =
{
  val k = 2

  def addConstant(v: Int): Int = v + k

  values.map(addConstant)
}
</code>```

Now that we have defined addConstant in a context where k is defined, addConstant has become a closure because all its free variables are now closed (bound to a value): addConstant can be invoked and passed around as if it were a function. Note the the free variable k is bound to a value when the closure is defined, whereas the argument variable v is bound when the closure is invoked.

So a closure is basically a function or code block that can access non-local values through its free variables after these have been bound by the context.

In many languages, if you use a closure only once you can make it anonymous, e.g.

```<code>def increaseAll(values: List[Int]): List[Int] =
{
  val k = 2

  values.map(v => v + k)
}
</code>```

Note that a function with no free variables is a special case of a closure (with an empty set of free variables). Analogously, an anonymous function is a special case of an anonymous closure, i.e. an anonymous function is an anonymous closure with no free variables.

Title: What is a closure?

Body:
The term closure comes from the fact that a piece of code (block, function) can have free variables that are closed (i.e. bound to a value) by the environment in which the block of code is defined.

Take for example the Scala function definition:

def addConstant(v: Int): Int = v + k

In the function body there are two names (variables) v and k indicating two integer values. The name v is bound because it is declared as an argument of the function addConstant (by looking at the function declaration we know that v will be assigned a value when the function is invoked). The name k is free wrt the function addConstant because the function contains no clue as to what value k is bound to (and how).

In order to evaluate a call like:

val n = addConstant(10)

we have to assign k a value, which can only happen if the name k is defined in the context in which addConstant is defined. For example:

def increaseAll(values: List[Int]): List[Int] =
{
  val k = 2

  def addConstant(v: Int): Int = v + k

  values.map(addConstant)
}

Now that we have defined addConstant in a context where k is defined, addConstant has become a closure because all its free variables are now closed (bound to a value): addConstant can be invoked and passed around as if it were a function. Note the the free variable k is bound to a value when the closure is defined, whereas the argument variable v is bound when the closure is invoked.

So a closure is basically a function or code block that can access non-local values through its free variables after these have been bound by the context.

In many languages, if you use a closure only once you can make it anonymous, e.g.

def increaseAll(values: List[Int]): List[Int] =
{
  val k = 2

  values.map(v => v + k)
}

Note that a function with no free variables is a special case of a closure (with an empty set of free variables). Analogously, an anonymous function is a special case of an anonymous closure, i.e. an anonymous function is an anonymous closure with no free variables.


问:
Why do Git users say that Subversion does not have all the source code locally?
I'm only going on what I've read on SO, so forgive me, but all I read says that one major advantage of Git over Subversion is that Git gives all the source code to the developer locally, not having to do anything on the server.

With my limited using of SVN and TortoiseSVN, I had all the source code, or at least I thought I did.  For example, I have a website.  I upload it to SVN.  I am still running my website locally, aren't I?  If someone submits a change and I'm not connected, it wouldn't matter if I had Git or not, until I reconnect to the server.

I do not understand.  I'm not asking for a rehash of one vs. the other except this one point.

答:
saying that since you're not required to commit to a central repo, you
  own your source code until you have committed and pushed it to your
  server, if you have one. With SVN, the only way to have the version
  control is by committing to the server, but with GIT, you could
  potentially keep everything on your local machine and if any goes
  wrong, you "could lose everything" even though you could just as
  easily lose all your changes with SVN if you didn't commit and your
  HDD crashed as well.

If you push daily, then the risk should be small.
But if you are forced to commit daily to SVN server, then at the end of the day, you may make everything in a single large changeset, which does not separate every change into small steps.
With git, you are encouraged to make multiple small commits.
When pushing, if merging is required, than try to merge and push. If you cannot merge at the moment, you can push to a new branch or another repository on the server.


答:
You showcase your code by:

Having a high quality code which is well-written and commented, with no or few bugs,

which is your own, from a personal project, not a source code of your coworkers, nor the code you've taken from the internet,

which is not too small, but still not to large, in order to be challenging enough and to avoid too much boilerplate code,

that you published in a public version control or on a public website,

and that you mention in your CV and give it before the interview, so that the interviewer has enough time to explore it.

Here are some hints in detail.

Give your code before the interview

You shouldn't wait until the interview to give your code. Ideally, you should have an already available open source projects that anyone interested in your skills can download from a public version control. If you don't have a public version control, then you should at least have some source code ready to be published on your website.

Have a link to this code in your CV. Don't wait until people ask you (but note that most people don't have time reading your CV¹, so they still would ask for it).

If you're a developer, your coding and your communication skills should be the most required skills to look for, so a CV which mentions that you're playing violin and enjoy golfing but forget to mention any source code or any article you wrote has no value.

Giving your code before the interview allows the interviewer to explore it, and prepare the questions. If the interviewer discovers your code only during the interview, there is no enough time to read it in details, and you'll only receive some superficial remarks and questions.

Give your code which is long enough, but not too long

A long-enough code is a must. Giving a method with only 10 LOC doesn't allow the interviewer to have a clear view of your coding skills (well, sometimes, even 10 lines is enough to understand that the programmer sucks).

But the code shouldn't be too long neither, for two reasons:

An interviewer doesn't have time browsing boilerplate code, and it's difficult to find challenging code in a large codebase when you're not accustomed to it.

During the interview, you'll have to answer questions about your code. If it's a small piece, you will more hardly be lost. More code = more chances to have a bug in it.

Give your code

Cheating is very harmful. Every candidate is able to find a piece of code on the internet, but when the interviewer will start to post questions about this code during the interview, the candidate will have a hard time answering those questions.

Once, I had a rather strange interview. It was similar to this:

Me: do you have anything to tell about the line 1402 to 1406?

Candidate: no.

Me: well, first, you create the variable ac, but never use it later. Secondly, there is a bug: you actually expect to add every element from the collection to the list, but you're looping backwards, so the list will always be empty. Any remark?

Candidate: ah, I haven't noticed it. But you know, this part of the code was not written by me, but by my colleague.

I don't care. If you're posting this piece of code during the interview, I assume you wrote it, and you're accountable for every character in it.

¹ In general, do never assume that the interviewer had opened your CV. When I was interviewed myself, it was really surprising to receive questions which made no sense from somebody expected to make an effort to open my CV at least once before the interview.

Title: How to show code samples in an interview?

Body: There have been questions similar to this, but my question is HOW exactly do you showcase your code when going to an interview? Do you show screenshots, or do you bring the actual code? Do you take the whole project with you, or just that bit of code? </p>


问:
Where should libraries be placed, in windows?
I have just moved from Linux to Windows, and I have to use the Zend Framework library. Where should the library be placed?

Directly on C drive

Create a lib folder like C:/lib/

Create a lib folder in my user folder

I am wondering if there is a classic folder where these kind of libraries are placed.

Update:I am asking about the location on my own standpoint. The Zend Framework library is a PHP framework.

答:
I would generally make any application specific dependencies travel with the source code rather than install libraries in a specific location. This means you don't have to hunt down the specific version of said library 18 months from now when you are applying an emergency patch at the very least. It can open the door to continuos delivery and deployment.

Major dependencies -- such as PHP or Java or what have you -- should be installed in a typical manner for the platform. For PHP in windows this typically means the Web Platform Installer.


问:
Where should I put a method that returns a list of active entries of a table?
I have a class named GuestbookEntry that maps to the properties that are in the database table named "guestbook". Very simple!

Originally, I had a static method named getActiveEntries() that retrieved an array of all GuestbookEntry objects. Each row in the guestbook table was an object that was added to that array. Then while learning how to properly design PHP classes, I learned some things:

Static methods are not desirable.

Separation of Concerns

Single Responsibility Principle

If the GuestbookEntry class should only be responsible for managing single guestbook entries then where should this getActiveEntries() method most properly go?

Update:

I am looking for an answer that complies with the SOLID acronym principles and allows for test-ability. That's why I want to stay away from static calls/standard functions.

DAO, repository, ...? Please explain as though your explanation will be part of "Where to Locate FOR DUMMIES"... :-)

答:
If I understand your question right ...

you are searching for the "correct" place to put you getActiveEntries() method. Cause from a OO-Design "point-of-view" you want to adhere to the principles of:

Separation of Concerns

Single Responsibility Principle

(FYI: I never heard avoid statics, so I skipped that one)

The cause of your "problem":

Every single entry should only be concerned about itself, and only responsible for itself. Therefore it can not be responsible for a "collection" of entries.

The principles you mentioned above are Object Oriented principles. Solutions for problems involving OO principles demand that you create many objects and many classes so that together they work as a solution.

Now if the method "getEntries" can not go into the DAO class (Data Access Object) it

... could go into a factory type of class. A Factory is responsible for "creating" objects. You could argue that a Factory for GuestBookEntries has 2 methods: createEntryFromId(int $entryId) and createActiveEntries().

... could go into a controller type of class. Same as factory above, just named differently. The controller type of class could do anything, even more than a factory. If you ever need something like "verify()" or "isDirty" for your GuestBookEntry, the factory would again not be the place to put those methods. Cause factories are only concerned about creation (they kind of have the duty to guarantee creation or fail quick) where as controller type of classes can carry verify() or isXYZ() methods without hurting their "purpose".

... in the end it doesn't matter what you call "it". But you will need another "class/object" to take the responsibility of restoring a collection of active GuestBookEntries. Most likely this class will make use of the single GuestBookEntry class that you already have.

When it get's down to implementing the methods that interact with each other (the new class and the GuestBookEntry) you are welcome to use array() as a container to transport GuestBookEntry objects.
You could create a special "typed" container that guarantees to only carry GuestBookEntry objects, but that's again up to you. (Plus it yet another oo-design decision, hehe)

To sum it up:

Create another class with the responsibility to retrieve "collections of GuestBookEntries based on their status (active|inactive)" that uses (composition) your existing GuestBookEntry class.


问:
Do unit tests sometimes break encapsulation?
I very often hear the following: "If you want to test private methods, you'd better put that in another class and expose it."

While sometimes that's the case and we have a hiding concept inside our class, other times you end up with classes that have the same attributes (or, worst, every attribute of one class become a argument on a method in the other class) and exposes functionality that is, in fact, implementation detail.

Specially on TDD, when you refactor a class with public methods out of a previous tested class, that class is now part of your interface, but has no tests to it (since you refactored it, and is a implementation detail).

Now, I may be not finding an obvious better answer, but if my answer is the "correct", that means that sometimes writting unit tests can break encapsulation, and divide the same responsibility into different classes.

A simple example would be testing a setter method when a getter is not actually needed for anything in the real code.

Please when aswering don't provide simple answers to specific cases I may have written. Rather, try to explain more of the generic case and theoretical approach. And this is neither language specific.

Thanks in advance.

EDIT: The answer given by Matthew Flynn was really insightful, but didn't quite answer the question. Although he made the fair point that you either don't test private methods or extract them because they really are other concern and responsibility (or at least that was what I could understand from his answer), I think there are situations where unit testing private methods is useful. My primary example is when you have a class that has one responsibility but the output (or input) that it gives (takes) is just too complex. For example, a hashing function. There's no good way to break a hashing function apart and maintain cohesion and encapsulation. However, testing a hashing function can be really tough, since you would need to calculate by hand (you can't use code calculation to test code calculation!) the hashing, and test multiple cases where the hash changes. In that way (and this may be a question worth of its own topic) I think private method testing is the best way to handle it. Now, I'm not sure if I should ask another question, or ask it here, but are there any better way to test such complex output (input)?

OBS: Please, if you think I should ask another question on that topic, leave a comment. :)

EDIT2: I accepted an answer as my correct because it made me think and decide my course of action, although it didn't answered my question completely. But for those who face the same problem as I do (one cohesive class that will change together, but is still too hard to test by itself), I'll tell what I did and why. I decided that the output of that class is simply too hard to a computer to test correctly, so I didn't test it. I could have used a framework to test it's private methods (which would be the best idea, I think), but I didn't want to get to that point. If you are wondering what it is that is cohesive and respects SRP, and still is too hard to a computer to test, I'll give some examples: heightmap generation, hashing functions, procedural music generation (you can test some units, but the highest level unit is simply too subjective).

答:
Whilst I don't disagree with the answers that say "Private is Private" and in most cases this is true, it isn't always.

If your code product is part of a certificated safety-critical product (eg aerospace, medical, automotive) then you will come across test coverage requirements, and such delights as Modified Condition/Decision Coverage

Saying to the Certification Body that you haven't tested the internals of your class, because private is private will not get you a tick in the box.

Only testing the public interface of a class is Black Box testing... and as long as the results are OK, then (in most cases) that is enough.  But sometimes, you need to do White Box testing, and validate the nuts and bolts inside.

I emphasise the sometimes but (as with most "rules") never say "never test the private".

ContentLicense: CC BY-SA 4.0


问:
In C and C++, what methods can prevent accidental use of the assignment(=) where equivalence(==) is needed?
In C and C++, it is very easy to write the following code with a serious error.

```<code>char responseChar = getchar();
int confirmExit = 'y' == tolower(responseChar);
if (confirmExit = 1)
{
    exit(0);
}
</code>```

The error is that the if statement should have been:

```<code>if (confirmExit == 1)
</code>```

As coded, it will exit every time, because the assignment of the confirmExit variable occurs, then confirmExit is used as the result of the expression.

Are there good ways to prevent this kind of error?

答:
Late to the party as ever, but Static Code Analysis is the key here

Most IDEs now provide SCA over and above the syntactic check of the compiler, and other tools are available, including those that implement the MISRA (*) and/or CERT-C guidelines.

Declaration: I am part of the MISRA C working group, but I'm posting in a personal capacity. I'm also independent of any tool vendor


答:
I have to say I’m a little biased here, but here I go. I don’t like the C/C++ preachers, I know there are some incredible good engineered applications out there but its just A tool, often I got the impression, many people only mentioning C/C++ for a solution miss more then A point (http://www.paulgraham.com/avg.html see bulb paradox).
I try to look at the facts: Java is as fast C/C++ but requires more memory therefore. Or let me rephrase you can write java code which is as fast as C/C++
but that program will consume more memory. I hope we can agree on this.

If you look at productivity, you can create java solutions for certain problems (say enterprise java) relatively easy, compared to C++ solutions.
A web browser is something completely different.
I see two/three mayor requirements:

It has to conform to huge specifications, HTML, JavaScript, etc. This involves problems like 2D Drawing APIs. Or how do get from a OS system call (as a drawing primitive) to text or font representation (“rendering”). Have a look at libraries like cairo( C )  and other attempts like gezira (www.youtube.com/watch?v=P97O8osukZ0 , https://github.com/damelang/gezira )

It has to “feel” fluent, which means certain operations only have ms to be executed.

It has to form a UI Concept which form a unique experience, to compete in today’s ‘browser wars’ which is quite challenging.

To sum up: yes you could, you could create browsers in almost any programming language with nearly identical results compared today’s C++ steamships. But to do so you would need quite an extraordinary amount of effort. I don’t know how much ( in the millions) , I would not want to even guess at that. Maybe we could get this bottom line: people don’t like to optimize in high level languages, or maybe its cheaper to get people who like to optimize in C/C++ because there are so many (compared to other language experts who can optimize on a similar level).

Title: Pure Java web browser, is it practical?


问:
What are some things you have read that inspired and guided you as a programmer?
For example, being a beginner, I find a lot of inspiration and direction from reading this post by Bryan Woods.</p>

答: I should re-read this article once every six months If No Shareware Professionals Are 100 Times Smarter Than You, Then Why Do Some Get 100 Times the Results? - by Steve Pavlina</p>


问:
Forbidding or controlling "Hidden IT..." Who should write and maintain ad-hoc software applications?
Bigger companies usually have the problem, that it is not possible to write all programs employees want (to save time and to optimize processes) due to a lack of staff and money.

Then hidden programs will be created by some people having (at least some) coding experience (or by cheap students/interns...). Under some circumstances these applications will raise in importance and spread from one user to a whole department.

Then there is the critical point: Who will maintain the application, add new features, ...? And this app is critical. It IS needed. But the intern has left the company. No one knows how it works. You only have a bunch of sources and some sort of documentation.

Does it make sense to try and control or forbid application development done ad-hoc outside of the IT department (with the exception of minor stuff like Excel macros)?

答:
They are forbidden in our company for these reasons:

Password protected Excel Macros where the only person who knows the password has left the company,

Being held responsible for incorrect reports written by inexperienced people b'because it's IT'

Being asked to modify a report that we've never seen or heard of before.

I understand it can be frustrating for users when IT are busy, and they may be inclined to 'just do it themselves'. But IT can't be held responsible for things it has does not know even exists, and if no one is responsible for overall IT, then there are great problems ahead.


答:
I used to work for a company where every app we gave them led to the question: Can we export this data to Excel?

After a while, I decided I had to know why they were obsessed with Excel exports for everything. It turned out that a lot of departments had one person who was an expert in Excel and could write a useful data-analysis app in no time. These apps would spread around the department like wildfire and we, the techies, had no idea they even existed.

Why didn't they come to us first? Because there was a reputation that the technical team had far too much to do and, if they did ask for it, they might (if they were lucky) get it queued up six months later.

That wasn't an unfair accusation and they never asked us to support their Excel apps, so no one really thought it was a problem. When these Excel developers left, they always managed to find someone else to pick it up.

You could argue that it meant we were prioritising incorrectly, that important work wasn't getting done. But I would argue that it freed up the more-highly-paid developers to do more difficult work. What can it hurt?

Now I would forbid software that updates the database being written outside of the development team. And I would refuse to support apps written outside of the development team. But I wouldn't try to forbid all software from being written by the business itself, and I would happily write data-exports to empower them to do so (as long as that doesn't expose data that they shouldn't see, obviously).

Title: Forbidding or controlling "Hidden IT..." Who should write and maintain ad-hoc software applications?

Body:
Bigger companies usually have the problem, that it is not possible to write all programs employees want (to save time and to optimize processes) due to a lack of staff and money.

Then hidden programs will be created by some people having (at least some) coding experience (or by cheap students/interns...). Under some circumstances these applications will raise in importance and spread from one user to a whole department.

Then there is the critical point: Who will maintain the application, add new features, ...? And this app is critical. It IS needed. But the intern has left the company. No one knows how it works. You only have a bunch of sources and some sort of documentation.

Does it make sense to try and control or forbid application development done ad-hoc outside of the IT department (with the exception of minor stuff like Excel macros)?


答:
It would be most helpful if there are some unit tests around the code - unit tests can often have a secondary function as documentation.

However, legacy code often comes without tests. Maybe writing some would be a good way of figuring out what is going on?

Then, you can refactor the spaghetti code into easy to read, well written code.

Title: What is the way to understand someone else's giant uncommented spaghetti code?

Body:
Possible Duplicate:

  I’ve inherited 200K lines of spaghetti code — what now?

I have been recently handled a giant multithreaded program with no comments and have been asked to understand what it does, and then to improve it (if possible).

Are there some techniques which should be followed when we need to understand someone else's code? OR do we straightaway start from the first function call and go on tracking next function calls?

C++ (with multi-threading) on Linux


答: You might also find some help in the answers to this StackOverflow question: https://stackoverflow.com/questions/3150900/is-there-any-free-c-c-code-to-flowchart-generator-tool-available-on-the-net </p>


答: I'd start with system testing just to see what the program does and then link these to brief flowcharts to show how it does what it does. System testing alone only lets you understand what the system does not how it does it and flow charts alone tends to give you a rather abstract look of the system and it can take a while to be able to say what button x actually does so it's best to use them together IMO.</p>


答:
I couldn't help but identify with you. The problem you describe seems to be an universal one, spanning cultures, languages and continents.

The things that you can do:

Restrict the creation of database accounts, asking for a supervisor's approval. Forcing them to used a local machine as a database server or writing the apps to be stand-alone, greatly diminishes its usefulness.

Make all interns of careers related to IT to be contracted through IT only.

Restricting via OS policy the installation of software. Every software installation must be channeled through the IT help desk, requiring a supervisor's approval. That way the installation of something like MS Access, PHP, Visual Basic, etc., will be more difficult to pass unnoticed.

Issue a policy stating that every new development, in order to be given support, must be written in, say Java, C#, C++    , or any other language that would require a steep learning curve. That way you reduce the universe of people with "a certain knowledge of programming" to mess around.

The requirements people must take a look at the "Excel solutions" around the company, because that is a reflect of the IT needs of the corporation.

Implementing a data warehouse and a final-user friendly data mining and reporting tool. That way you reduce the need for custom made, intern written little apps.

But: not a single thing you do will outpower a phone call from a Big Chief, calling the IT Manager and asking him for you to support the app that an intern made.


答:
IMO one of the quickest ways to get to the bottom of unfamiliar code is to track down the original developer(s) (e.g. on Linked-In) and make contact, asking a few high level questions (you may need to send some code snippets to jog his / her memory). Obviously you'll need to gloss over your actual feelings toward the quality of the code.

Most developers I know are usually reasonably proud of their work (whether justified or not), and are only too happy to divulge knowledge on their previous systems (also, the rationale is that the culprit probably still earning a living as a developer in the same state / city, so is likely to want to keep his / her reputation intact).

If the previous dev can convey some of the conceptual patterns (or anti patterns) they have used, it may help you quickly help you crack open much of the code base.

And even if you can't track down the dev, or get no response, by taking time to phrase a question ('Why did you do X here?') it might jog your own thinking process toward a solution.


答:
One should also consider the case of the companies in which IT department contains incompetent people, while the hidden app would be created by a skillful developer who has a non-developer job within the company. In my experience, those cases are extremely frequent.

Imagine that you have a double profile of a software developer and an accountant. You're hired as an accountant because this was an opportunity for you to get a well-paid job. You quickly see that your colleagues (and now you) spend hours doing repetitive things which may be done in a few seconds by a program.

You spend a few evenings to write the app which will do all the work. You show it on your personal laptop to your colleagues, and they find it very useful. You want to install it to the company PCs, but you should have the agreement of IT department. You ask for it, but they reject it because they wouldn't support your application.

Doesn't it sound stupid?

Aside this particular case, the issue with the support is not very different from one many companies encounter with all  the software, even one written within IT department: if IT department doesn't enforce best practices, the code will be badly/not documented, written by inexperienced people who don't care about maintenance and who have left years ago.

To conclude, the main question is the profitability. If you, the IT department, are asked to maintain an app developed by a clerk who don't understand the most basic rules of software development, it doesn't matter how enjoyable is this task, you still have to do it if it brings a lot of money to the company. Or you rewrite it from scratch if it's the cheapest way to get things done.


答:
Not an easy task, but... may be a documentation tool like doxygen, even if applied to an undocumented code, ca do a good inventory of namespaces, classes, function, the way they interact each other, how they reference each other end so on.

It does not explain what everything does, but at least helps to start to figure out how the code is composed. At least it keeps spaghetti sorted!


答:
Let's consider a simple function:

```<code>function f1(x) {
    // ... something
}
</code>```

This function is called a top-level function because it's not nested within any other function. Every JavaScript function associates with itself a list of objects called a "Scope Chain". This scope chain is an ordered list of objects. Each of these objects defines some variables.

In top-level functions, the scope chain consists of a single object, the global object. For example, the function f1 above has a scope chain that has a single object in it that defines all the global variables. (note that the term "object" here does not mean JavaScript object, it's just an implementation defined object that acts as a variable container, in which JavaScript can "look up" variables.)

When this function is invoked, JavaScript creates something called an "Activation object", and puts it at the top of the scope chain. This object contains all the local variables (for example x here). Hence now we have two objects in the scope chain: the first is the activation object and beneath it is the global object.

Note very carefully that the two objects are put into the scope chain at DIFFERENT times. The global object is put when the function is defined (i.e., when JavaScript parsed the function and created the function object), and the activation object enters when the function is invoked.

So, we now know this:

Every function has a scope chain associated with it

When the function is defined (when the function object is created), JavaScript saves a scope chain with that function

For top level functions, the scope chain contains only the global object at the function definition time and adds an additional activation object on top at invocation time

The situation gets interesting when we deal with nested functions. So, let's create one:

```<code>function f1(x) {

    function f2(y) {
        // ... something
    }

}
</code>```

When f1 gets defined we get a scope chain for it containing only the global object.

Now when  f1 gets called, the scope chain of f1 gets the activation object. This activation object contains the variable x and the variable f2 which is a function. And, note that f2 is getting defined. Hence, at this point, JavaScript also saves a new scope chain for f2. The scope chain saved for this inner function is the current scope chain in effect. The current scope chain in effect is that of f1's. Hence f2's scope chain is f1's current scope chain -- which contains the activation object of f1 and the global object.

When f2 is called, it's gets it's own activation object containing y, added to its scope chain which already contains the activation object of f1 and the global object.

If there were another nested function defined within f2, its scope chain would contain three objects at definition time (2 activation objects of two outer functions, and the global object), and 4 at the invocation time.

So, now we understand how scope chain works but we haven't talked about closures yet.

The combination of a function object and a scope (a set of variable bindings) in which the function’s variables are resolved is called a closure in the computer science literature -- JavaScript the definitive guide by David Flanagan

Most functions are invoked using the same scope chain that was in effect when the function was defined, and it doesn’t really matter that there is a closure involved. Closures become interesting when they are invoked under a different scope chain than the one that was in effect when they were defined. This
happens most commonly when a nested function object is returned from the function
within which it was defined.

When the function returns, that activation object is removed from the scope chain. If there were no nested functions, there are no more references to the activation object and it gets garbage collected. If there were nested functions defined, then each of those functions has a reference to the scope chain, and that scope chain refers to the activation object.

If those nested functions objects remained within their outer function, however, then they themselves will be garbage collected, along with the activation object they referred to. But if the function defines a nested function and returns it or stores it into a property somewhere, then there will be an external reference to the nested function. It won’t be garbage collected, and the activation object it refers to won’t be garbage collected either.

In our above example, we don't return f2 from f1, hence, when a call to f1 returns, its activation object will be removed from its scope chain and garbage collected. But if we had something like this:

```<code>function f1(x) {

    function f2(y) {
        // ... something
    }

    return f2;
}
</code>```

Here, the returning f2 will have a scope chain that will contain the activation object of f1, and hence it won't be garbage collected. At this point, if we call f2, it will be able to access f1's variable x even though we're out of f1.

Hence we can see that a function keeps it's scope chain with it and with the scope chain come all the activation objects of outer functions. This is the essence of closure. We say that functions in JavaScript are "lexically scoped", meaning that they save the scope that was active when they were defined as opposed to the scope that was active when they got called.

There are a number of powerful programming techniques that involve closures like approximating private variables, event driven programming, partial application, etc.

Also note that all of this applies to all those languages that support closures. For example PHP (5.3+), Python, Ruby, etc.

Title: What is a closure?

Body: Every now and then I see "closures" being mentioned, and I tried looking it up but Wiki doesn't give an explanation that I understand. Could someone help me out here?</p>

Body:
Let's consider a simple function:

function f1(x) {
    // ... something
}

This function is called a top-level function because it's not nested within any other function. Every JavaScript function associates with itself a list of objects called a "Scope Chain". This scope chain is an ordered list of objects. Each of these objects defines some variables.

In top-level functions, the scope chain consists of a single object, the global object. For example, the function f1 above has a scope chain that has a single object in it that defines all the global variables. (note that the term "object" here does not mean JavaScript object, it's just an implementation defined object that acts as a variable container, in which JavaScript can "look up" variables.)

When this function is invoked, JavaScript creates something called an "Activation object", and puts it at the top of the scope chain. This object contains all the local variables (for example x here). Hence now we have two objects in the scope chain: the first is the activation object and beneath it is the global object.

Note very carefully that the two objects are put into the scope chain at DIFFERENT times. The global object is put when the function is defined (i.e., when JavaScript parsed the function and created the function object), and the activation object enters when the function is invoked.

So, we now know this:

Every function has a scope chain associated with it

When the function is defined (when the function object is created), JavaScript saves a scope chain with that function

For top level functions, the scope chain contains only the global object at the function definition time and adds an additional activation object on top at invocation time

The situation gets interesting when we deal with nested functions. So, let's create one:

function f1(x) {

    function f2(y) {
        // ... something
    }

}

When f1 gets defined we get a scope chain for it containing only the global object.

Now when  f1 gets called, the scope chain of f1 gets the activation object. This activation object contains the variable x and the variable f2 which is a function. And, note that f2 is getting defined. Hence, at this point, JavaScript also saves a new scope chain for f2. The scope chain saved for this inner function is the current scope chain in effect. The current scope chain in effect is that of f1's. Hence f2's scope chain is f1's current scope chain -- which contains the activation object of f1 and the global object.

When f2 is called, it's gets it's own activation object containing y, added to its scope chain which already contains the activation object of f1 and the global object.

If there were another nested function defined within f2, its scope chain would contain three objects at definition time (2 activation objects of two outer functions, and the global object), and 4 at the invocation time.

So, now we understand how scope chain works but we haven't talked about closures yet.

The combination of a function object and a scope (a set of variable bindings) in which the function’s variables are resolved is called a closure in the computer science literature -- JavaScript the definitive guide by David Flanagan

Most functions are invoked using the same scope chain that was in effect when the function was defined, and it doesn’t really matter that there is a closure involved. Closures become interesting when they are invoked under a different scope chain than the one that was in effect when they were defined. This
happens most commonly when a nested function object is returned from the function
within which it was defined.

When the function returns, that activation object is removed from the scope chain. If there were no nested functions, there are no more references to the activation object and it gets garbage collected. If there were nested functions defined, then each of those functions has a reference to the scope chain, and that scope chain refers to the activation object.

If those nested functions objects remained within their outer function, however, then they themselves will be garbage collected, along with the activation object they referred to. But if the function defines a nested function and returns it or stores it into a property somewhere, then there will be an external reference to the nested function. It won’t be garbage collected, and the activation object it refers to won’t be garbage collected either.

In our above example, we don't return f2 from f1, hence, when a call to f1 returns, its activation object will be removed from its scope chain and garbage collected. But if we had something like this:

function f1(x) {

    function f2(y) {
        // ... something
    }

    return f2;
}

Here, the returning f2 will have a scope chain that will contain the activation object of f1, and hence it won't be garbage collected. At this point, if we call f2, it will be able to access f1's variable x even though we're out of f1.

Hence we can see that a function keeps it's scope chain with it and with the scope chain come all the activation objects of outer functions. This is the essence of closure. We say that functions in JavaScript are "lexically scoped", meaning that they save the scope that was active when they were defined as opposed to the scope that was active when they got called.

There are a number of powerful programming techniques that involve closures like approximating private variables, event driven programming, partial application, etc.

Also note that all of this applies to all those languages that support closures. For example PHP (5.3+), Python, Ruby, etc.


答:
What have worked for me is:

Make yourself a copy of the source and a test environment ( for example a copy of the database ) so you can mess around without causing any damage.

Refactor, extracting to a function/method/script every block of repetitive (or non-repetitive) code that you understand well enough and safely enough. That way you will be taking out of sight everything that you already understand, uncluttering what you don't.

You can print certain pieces of long code in order to study them on paper. This helps, I don't know why, maybe because you can jot arrows and  circles around things.

What you will have at the end is a shorter, uncluttered, refactored version of the code. I'm not telling you that you replace the production code with the refactored one ( that's up to you ). But the process of refactoring in a safe environment will have helped you understand the still messy production version.


答:
Fundamentally, you want to be following the scientific method. i.e. Observe, hypothesise, test. There are various techniques which might be appropriate for each stage.

Observe:

Run the code: Hopefully, this is obvious!

Run the code through a profiler: This can be a good indicator of where to focus your efforts. If you have a decent profiler, it can also be great for picking up on unexpected side-effects of operations.

Step through the code in a debugger: Pretty crucial if you're trying to understand the details.

Hypothesise:

Flowcharts might come in useful in building your hypotheses: They can be very useful for clarifying what a function/etc is doing. Just bear in mind that if the code you have to represent is spaghetti-like, then inevitably your flowcharts will be too!

Change the code: Comment out some code, force the value of a variable, insert extra method calls, etc., etc.

Write unit tests: These should be a bit less ad-hoc than quick code changes. i.e. use them when you're more confident of your hypotheses. They have the added benefit, as Paul T Davies mentions, of being extremely useful when it comes to any future refactoring.

Test:

Run your changed code/unit tests and observe again! If you were right, document it (comments, etc.) and move on to the next thing (which may be tidying up/refactoring the code). If not, make some new hypotheses based on your new data.


答:
The quickest and most instructive way to learn a new base of code, whether it's elegant or spaghetti, and when you don't have resources like documentation or knowledgeable people to ask, is to change something. This might as well be a change in the direction of  the needs of the business. But keep it a small change to start with.

Refactoring something small is a good way to start. E.g. a class that appears to have some tacked-on behaviour (e.g. a class that handles managing some data, but also writes that data to a file format), and factor this out into a sub module (that writes the given data to the needed format).
Removing code is good fun: Try to eliminate a global variable, or eliminate a member variable that can in fact be local. Try to eliminate an entire class that appears to do very little for the lines of code it takes up.

If the code is uncommented, this is not necessarily a total loss. It may be that the variable names have been chosen well. If not then you will have extra work to do. Rename variables following your own naming convention that makes sense and don't be afraid to use long variable names. There are lots of opinions on variable naming, but I always think "capture sense, not type". Renaming badly named variables will force you to understand what each variable is used for (which is something the original author was too lazy to do).

As a task in itself, drawing diagrams of what you think is going on is a waste of time and is just a diversion from what you need to do which is, and there is no way of getting away from this, to read through the code. It can be better to paste small extracts of code from different classes and modules in a text document and describe what is going on that way. You may need to do diagrams later to clarify things at a high level or to help explain code to someone else. Explaining the code to someone else is a good way of increasing your own understanding.

These suggestions have been made already: Writing unit tests and contacting the previous author are definitely a part of attacking an inherited codebase.


问:
What is considered third party code?
Inspired by this question Using third-party libraries - always use a wrapper?
I wanted to know what people actually consider as third-party libraries.

Example from PHP:

If I'm building an application using Zend framework, should I treat Zend framework libraries as third party code?

Example from C#:

If I'm building a desktop application, should I treat all .Net classes as third party code?

Example from Java:

Should I treat all libraries in the JDK as third party libraries?

Some people say that if a library is stable and won't change often then one doesn't need to wrap it. However I fail to see how one would test a class that depends on a third party code without wrapping it.

答:
I would not treat members of the standard library as 3rd party code -- they are standard after all and can reasonably presumed to be available and functional on the platform you are using.

As for something like Zend, I think that one would not wrap it -- you would probably need to rewrite the program if you took on a different framework. To be honest, I would not wrap much that wasn't a serious external configuration dependency or if I wasn't really planning on making that piece swappable.

Title: What is considered third party code?