答:
This is where I go back to being a dinosaur...

Switch statements are not bad in an of themselves, its the use that's made of them that's at issue.

The most obvious one is the "same" switch statement repeated over and over again through your code that is bad (been there, done that, would make every effort not to again) - and its this latter case that you may be able to deal with using polymorphism. There's usually something fairly horrid about nested cases too (I used to have an absolute monster - not entirely sure how I deal with it now other than "better").

Dictionary as switch I find more challenging - fundamentally yes if your switch covers 100% of the cases, but where you want to have default or no action cases it starts to get a bit more interesting.

I think its a question of avoiding repetition and of making sure we're composing our object graphs in the right places.

But there's also the comprehension (maintainability) argument and this cuts both ways - once you understand how it all works (the pattern and the app in which its implemented) its easy... but if you come to a single line of code where you have to add something new you then have to jump all over the place to work out what you need to add/change.

For all that our development environments are massively capable I still feel that it is desirable to be able to understand code (as if it were) printed out on paper - can you follow the code with your finger? I accept that actually no, with a lot of good practice today you can't and for good reasons but that means that getting up to speed with code is harder to start (or maybe I'm just old...)


问:
If you were the manager of a team of 25 developers, how would you motivate them?
Imagine yourself hired by a new startup backed with few millions coming from venture capitalists.

Your mission: organize the development of the next killer app.

25 developers is too much to take care of each individually, so what decision(s) you would make to motivate them?

I will appreciate any answers from stock options to free cookies ;)

Of course the trick here (unless you are really a manager of a such startup), is put yourself in the shoes of one of those programmers.

EDIT: it's an imaginary context. The purpose of this story is to stimulate your wishes. I want to capture what motivates developers.

答:
Delegate.

Assuming that the 25 developers will be working on different aspects of the application, split them into sub-teams and nominate 1 member of each team to be the team leader. (NOTE: This role should move around as the project develops and the teams get reshuffled).

Now you have 5 team leads to motivate and they in turn have 4 developers to motivate.

You can concentrate on the "global" motivators (like stock options etc.) while your team leads can concentrate on the individual motivators (being allowed to leave early on a Wednesday).

Make sure you are consistent and the team leads communicate their actions with you and each other to avoid unnecessary frictions.

ContentLicense: CC BY-SA 2.5


问:
Is dependency injection essential for unit testing?
Is using dependency injection (DI) essential for unit testing?

I can't think of another alternative for isolating code so it can be tested. Also, all the examples I have ever seen use this pattern. Is that because it is the only viable option or are there other alternatives?

答:
No, dependency injection is not essential for unit testing.

Dependency injection helps if you have a class that needs a dependent class-instance to do some sub-processing. Instead of DI you can seperate the logic of a business-method into a data-gethering-part (that is not unit-testable) and a calculation part that can be unit-tested.

Example (using DI) This implementation depends on Employee, Account, ...

```<code> bool hasPermissionToTransferMoney(Employee employee, Account from, Account to, Money amount)
 {
     if (amount > 100 && employee.isStudent())
        return false;
     if (to.getOwner().getFamiliyName() == employee.getFamilyName() && ...
        return false; // cannot transfer money to himself;
     ...
 }
</code>```

After seperation of data-gathering and calculation:

```<code> bool hasPermissionToTransferMoney(Employee employee, Account from, Account to, Money amount)
 {
     return hasPermissionToTransferMoney(employee.isStudent(), employee.getFamilyName(), to.getOwner().getFamilyName(), ...);
 }

 // the actual permission calculation
 static bool hasPermissionToTransferMoney(boolean isStudent, string employeeFamilyName, string receiverFamilyName, ...)
     if (amount > 100 && isStudent)
        return false;
     if (receiverFamilyName == employeeFamiliyName && ...
        return false; // cannot transfer money to himself
     ...
 }
</code>```

The calculation part can be easily tested without dependency injection.

ContentLicense: CC BY-SA 3.0

Body:
No, dependency injection is not essential for unit testing.

Dependency injection helps if you have a class that needs a dependent class-instance to do some sub-processing. Instead of DI you can seperate the logic of a business-method into a data-gethering-part (that is not unit-testable) and a calculation part that can be unit-tested.

Example (using DI) This implementation depends on Employee, Account, ...

 bool hasPermissionToTransferMoney(Employee employee, Account from, Account to, Money amount)
 {
     if (amount > 100 && employee.isStudent())
        return false;
     if (to.getOwner().getFamiliyName() == employee.getFamilyName() && ...
        return false; // cannot transfer money to himself;
     ...
 }

After seperation of data-gathering and calculation:

 bool hasPermissionToTransferMoney(Employee employee, Account from, Account to, Money amount)
 {
     return hasPermissionToTransferMoney(employee.isStudent(), employee.getFamilyName(), to.getOwner().getFamilyName(), ...);
 }

 // the actual permission calculation
 static bool hasPermissionToTransferMoney(boolean isStudent, string employeeFamilyName, string receiverFamilyName, ...)
     if (amount > 100 && isStudent)
        return false;
     if (receiverFamilyName == employeeFamiliyName && ...
        return false; // cannot transfer money to himself
     ...
 }

The calculation part can be easily tested without dependency injection.

ContentLicense: CC BY-SA 4.0


问:
Connecting mobile apps to a web service; What is it called and where do I start?
I have some basic knowledge of iOS development and I want to now start connecting my apps to databases hosted on the internet, so that users will have access to remote / public data that pertains to my app.

My problem is that after searching the internet for some advice, I realised I don't even know what this type of programming is called? From my perusing it doesn't even appear to have a common moniker, and this is making it really difficult for me to find any advice on how to even begin learning to connect my apps to a web database.

So my questions are, what on earth is this discipline called? And, how can I get started in learning it?

答:
I use SudzC webservice generator every time, it will generate a complete set of required files
and it takes you less then 5 min to get started. Dont forget to watch the video tutorial, it will explain all you need to do.

http://sudzc.com/

Hope this help !!


答:
Dependency injection is not essential for unit testing

Inversion of control on other hand is essential when you want to swap one implementation for another.

Title: Is dependency injection essential for unit testing?

Body:
Is using dependency injection (DI) essential for unit testing?

I can't think of another alternative for isolating code so it can be tested. Also, all the examples I have ever seen use this pattern. Is that because it is the only viable option or are there other alternatives?


问:
Using BSD Licensed source code
Someone wrote a .NET library to use the Google Maps API (link to the project).  I downloaded the entire repository and there are only source files, no LICENSE.txt, readme, etc.  However, I guess Google makes you pick a license when creating a new project so the author specified "New BSD License".

What I would like to do is download the source and rework it (maybe include JSON.net, add features, etc) and keep it in my github account.

So I have a few questions related to this:

Is the license valid even though the author doesn't have an explicit file with his name, copyright, etc?

If the license is valid, then do I just put his name and year into that BSD License Template?

In general, if there is a license included with a project, how do I make sure I am doing right by the author?  Would I just leave their license information in tact and then add my own on top of it?

Am I over thinking this and some of these licenses just amount to a "do whatever you want just don't sue me" (kind of my feelings, since I would be delighted if anyone wanted to use my code for anything at all)?

答:
Without an explicit license file in the source code repository you are on difficult ground.

Without looking at the google code page, which isn't part of the project itself, just one repository for that code, there is no indication in the source code that any rights have been assigned to any third party. It may not have copyright notices, but that doesn't mean it isn't copyrighted.

As it is, all it takes is for the project to be removed from google code and you would have no way of demonstrating that you had any rights to use the code. So, in it's current state the project is an interesting curio, but with no legal reuse value to anyone else.

The best solution to this is to contact the author and ask him/her to add an explicit license to the code repository. You could even send a patch, with an explanation of why not adding a license file could result in people avoiding their project.

Title: Using BSD Licensed source code


问:
WCF to Java webservices interop seems surprisingly problematic. Any good resources?
With a recent project our .Net based dev team has been tasked with integrating with a whole host of java based web services around the world, and we really have had a surprisingly (well, we are certainly not surprised any more) large amount of issues because the XML generated by WCF is not accepted by the java services.

It also seems that there is not really that much good information to find on the subject, we have gotten some good tips from Yaron Nave's excellent WCF blog, http://webservices20.blogspot.com, and also on the MSDN WCF forum  http://social.msdn.microsoft.com/Forums/en-US/wcf/threads.

Are there anyone here who really feel that they got this down, and know the definitive resource on the subject? Would be interested in tips on books, blogs or any websites.

Edit:

I am torn on setting the answer accepted on this thread, because each of the two best answers has some value:

1. We will probably end up with doing more HTTP Webrequest implementations instead of fighting WCF.

2. But the WCF Express Interop Bindings 1.0 was also a very sensible tip.

答:
You'll have the same problems consuming PHP web services too.

Our only answer to this was to change the protocol type to REST rather than SOAP. We never got the SOAP stuff to interoperate, so much for Simple!


问:
Where are functional languages used?

Possible Duplicate:

  Functional Programming in Commercial Software

  Which problems domains are more suited  to functional programming solutions

I just wonder where do functional programming languages are used? Might be some good examples? Like rocket science or telecommunications?

答:
Well, here's a list of projects using Erlang:

http://en.wikipedia.org/wiki/Erlang_%28programming_language%29#Projects%5Fusing%5FErlang

The world doesn't revolve around building apps for tablets and mobile phones ;)

Usually functional languages are used when there is a need for a very high degree of abstraction, parallelism and scalability. This doesn't mean you cannot write code with these properties using any other language (non-functional), but the absence of side-effects on a purely functional language helps in these scenarios.

Erlang is a great example of this, since it was built from scratch to address problems that were "embarrassingly parelizable".

Also, even a language like Javascript can be used in a purely functional form, although it does let you mess up that model quite badly.

There is also Scala, that lets you program in a mix between functional (the preferred way), and procedural style. Scala is used, for instance, on the Twitter middleware layer to handle the absurd level of concurrency that they deal with.

Title: Where are functional languages used?


答:
Jane Street uses OCaml for trading.

Since the functional programming language ML was created for theorm proving: automated theorm proving and proof assistants

While it is not required, it is common to find AI programs written in functional langauges.

Writing games for the XBOX.

Title: Where are functional languages used?

Body:
Possible Duplicate:

  Functional Programming in Commercial Software

  Which problems domains are more suited  to functional programming solutions

I just wonder where do functional programming languages are used? Might be some good examples? Like rocket science or telecommunications?


答:
In my opinion, your observation is quite accurate. The high level implementations of XML based communication is usually not compatible with different platforms, even if they are both called "SOAP". Subtle differences in implementation, probably both within the scope of the standard implemented, create problems in real life use.

My recommendation for service providers:
Use a simple implementation rather than a very complex and theoretically better implementation. For example, don't include any extremely complex authentication schemes if you don't need them.

My recommendation for service consumers (you, I presume):
When communicating to a high level implementation on a different platform than yours, degrade to a lower level implementation. It suddenly becomes quite simple if you simply figure out what the actual XML to send is and then use normal good coding practices to accomplish that, as an alternative to insisting on using the high level implementation of your own platform.

Hope it wasn't too abstract. In short, when you're on the .NET platform connecting to a Java platform, you may want to simply assemble the headers and xml in a HttpWebRequest and send it off that way.

Title: WCF to Java webservices interop seems surprisingly problematic. Any good resources?

Body:
With a recent project our .Net based dev team has been tasked with integrating with a whole host of java based web services around the world, and we really have had a surprisingly (well, we are certainly not surprised any more) large amount of issues because the XML generated by WCF is not accepted by the java services.

It also seems that there is not really that much good information to find on the subject, we have gotten some good tips from Yaron Nave's excellent WCF blog, http://webservices20.blogspot.com, and also on the MSDN WCF forum  http://social.msdn.microsoft.com/Forums/en-US/wcf/threads.

Are there anyone here who really feel that they got this down, and know the definitive resource on the subject? Would be interested in tips on books, blogs or any websites.

Edit:

I am torn on setting the answer accepted on this thread, because each of the two best answers has some value:

1. We will probably end up with doing more HTTP Webrequest implementations instead of fighting WCF.

2. But the WCF Express Interop Bindings 1.0 was also a very sensible tip.


问:
Is it bad practice to name an unused variable with a single underscore?
Often when the syntax of the language requires me to name a variable that is never used, I'll name it _.

In my mind, this reduces clutter and lets me focus on the meaningful variables in the code. I find it to be unobtrusive so that it produces an "out of sight, out of mind" effect.

A common example of where I do this is naming subqueries in SQL.

```<code>SELECT *
FROM
(
    SELECT *
    FROM TableA
    JOIN TableB
        ON TableA.ColumnB = TableB.ColumnB
    WHERE [ColumnA] > 10
) _ --This name is required, but never used here
ORDER BY ColumnC
</code>```

Another example is a loop variable that isn't used.

```<code>array = [[] for _ in range(n)] # Defines a list of n empty lists in Python
</code>```

I use this technique very sparingly, only when I feel that a descriptive name adds nothing to the code, and in some sense takes away from it by adding more names to remember. In some ways I view it as similar to the var keyword in C#, which I also use sparingly.

My coworkers disagree. They say that even having a single (alphabetic) character name is better than _.

Am I wrong? Is it bad practice to do this?

答: All names should be meaningful. If _ was a well known standard at your company or in the wider community, then it would be meaningful as a "name that does not matter". If it's not, I would say it's bad practice. Use a descriptive name for what you refer to, especially since the name might matter in the future.


答:
I find it to be bad practice because

you should not have invisible variable in your code. If you feel you should the reason could probably be discussed.

the Go language uses this keyword to indicate that no variable is the destination of one of the multiple returns of a function. If your language hasn't multiple returns it's not needed. Your naming convention will hurt you the day you'll use a language using _ as a standard language notation.

(I don't know Python : is this construct really needed ?)

Title: Is it bad practice to name an unused variable with a single underscore?

Body:
Often when the syntax of the language requires me to name a variable that is never used, I'll name it _.

In my mind, this reduces clutter and lets me focus on the meaningful variables in the code. I find it to be unobtrusive so that it produces an "out of sight, out of mind" effect.

A common example of where I do this is naming subqueries in SQL.

```<code>SELECT *
FROM
(
    SELECT *
    FROM TableA
    JOIN TableB
        ON TableA.ColumnB = TableB.ColumnB
    WHERE [ColumnA] > 10
) _ --This name is required, but never used here
ORDER BY ColumnC
</code>```

Another example is a loop variable that isn't used.

```<code>array = [[] for _ in range(n)] # Defines a list of n empty lists in Python
</code>```

I use this technique very sparingly, only when I feel that a descriptive name adds nothing to the code, and in some sense takes away from it by adding more names to remember. In some ways I view it as similar to the var keyword in C#, which I also use sparingly.

My coworkers disagree. They say that even having a single (alphabetic) character name is better than _.

Am I wrong? Is it bad practice to do this?


答:
I would say that it's an acceptable practice.  This is a rare instance where I would consider the majority to be wrong and in need of updating their knowledge of recent programming ideas.  In many languages, particularly ML-based functional languages like Haskell and OCaml, it is extremely common to use _ as an "unused" variable.  Even Lua, which doesn't offer explicit language support for it, encourages the use of _ as a placeholder by convention.

Several languages (Haskell, Lua, and D I think off the top of my head) also offer a convention where variables that lead off with an underscore don't generate compiler warnings about "unused local variable" which makes _ the shortest unused variable name.  You could use something like _unused but I agree with you that it just makes clutter.


问:
Security Concerns with password storage in Scripting Languages (VBA)
The team I work with handles large amounts of consumer survey, and internal company metric data. Primarily the data is stored in a database, and we utilize various platforms and to work with that data, including MS Excel.

My peer has developed a suite of Excel/VBA files to take the raw data we get and upload it into a database. Unfortunately, after a code review we identified that the database password was displayed in the VBA code, in plain text, in several places per file. Being in a large enterprise organization we had a number of concerns about those files being available to more than just our team, and the database password being compromised.

The problem is, I feel the solution is just as bad, if not worse than the original problem. The plaintext passwords have been removed in the code of all of the VBA files, and an ancillary, helper file was created that requires the user to authenticate through our organizations LDAP system before gaining access to the database password. Being a scripting language (and being Excel), I feel there really aren't adequate precautions in place to secure the users password in the helper file. I feel that now instead of compromising access to a single database, we are potentially compromising access to the logins of anyone who uses these files.

To be fair, my peer has implemented a number of security minded techniques for securing the data in helper file. I just feel each one can easily be circumvented:

locking the VBA code [google search for vba password recovery]

using a custom "masked" password entry box [the password box may be masked, but it is still passed out of the box as plaintext]

not actually storing the user password in the file itself (he passes it on directly to the LDAP call) [a break point or stop statement can easily reveal the contents of what was passed]

setting the sheets to VeryHidden to prevent direct access [append .zip to filename, and ALL data in ALL worksheets is accessible]

As I'm not one to complain without a solution in mind, our organization already employs Active Directory/LDAP for authentication into our individual machines. My thought is that checking the logged in user (not a full user/password, just the user) against a white list of users on the database should be a sufficient alternative for authentication.

So My Question...

Am I being too paranoid about this? Is there another, more appropriate solution? I am pushing back fairly hard on this fix and I just wanted a sanity check before I start to involve others in yet another solution.

答:
You are being a bit paranoid, every solution to hide a password won't work against someone who really wants it, but there are better ways to solve this issue so some concern is warranted. Your idea is far worse than the current situation, with your idea everyone has access to the database that can use the scripts, any of them could easily do bad things to your database, and no one has to go through the trouble of figuring out the account used to access the database.

The best solution would be to create a small desktop app or web app that can be used to upload excel files or however your data comes, and then encrypt the connection string.


答:
Edit: Upon reflection, here is the main point: treat employees like people, not like machines or "resources".  Make sure they feel comfortable asking you questions or raising issues.  Make sure that you can accommodate people when they have personal issues, like a sick child or parent.  In other words, do your best to establish a rapport with them.  Also, 25 is still a small enough group to celebrate everyone's birthday with a cake. These little things make a world of difference.

Definitely stock options, so that the success of the company would have a significant impact on their own quality of life.  In addition to that, be open with them about what is going on in the business side of things.  The point is to make employees see at least some of the big picture in addition to their immediate responsibilities, so that they feel more like partners in the company, and less like cogs in a machine.

Good working conditions.  Comfortable chairs, fast machines, large monitors, keyboards and mice they are most comfortable with.  A window is nice...  Good air flow.  Buy them books on programming if they want to improve their skills.

Also, having a meal together regularly, like once a week, preferably with beer, is great for morale.  25 people may be a bit too many for that, though.  So maybe individual teams should have pizza and beer together once a week.  Payed for by the company, of course. :)

Title: If you were the manager of a team of 25 developers, how would you motivate them?

Body:
Imagine yourself hired by a new startup backed with few millions coming from venture capitalists.

Your mission: organize the development of the next killer app.

25 developers is too much to take care of each individually, so what decision(s) you would make to motivate them?

I will appreciate any answers from stock options to free cookies ;)

Of course the trick here (unless you are really a manager of a such startup), is put yourself in the shoes of one of those programmers.

EDIT: it's an imaginary context. The purpose of this story is to stimulate your wishes. I want to capture what motivates developers.


问:
Team work and agile development
I think this question related not only to agile but to teamwork in general.

When we are working in a team and each member is working a user story to complete how to avoid creation of duplicate classes and conflict?

I mean if my user story require the creation of class A and also my team member need the same class and created the same (he may create it with slightly different name), how would we plan so that we move smoothly?

答: User Stories are for communication with your customer. They are in customer's language and don't contain technical details like classes. When you start an iteration you should break down the User Stories in tasks. Tasks are in developer's language and can cover multiple stories. </p>

OwnerDisplayName: arjun

Title: Team work and agile development

OwnerDisplayName: hansmaad


答:
I agree with @hansmaad. Agile is about communication. As in, actually talking to people on a regular basis. A user story is a reminder to have a conversation.

If you're doing XP, are you pair programming? Are you rotating pairs?

If you're doing Scrum, are you holding a daily standup?

Are you writing unit tests? Do you have customer acceptance tests? Are you practicing continuous integration?

There's still a risk of developers duplicating functionality, but it's not as high.

Title: Team work and agile development

Body:
I think this question related not only to agile but to teamwork in general.

When we are working in a team and each member is working a user story to complete how to avoid creation of duplicate classes and conflict?

I mean if my user story require the creation of class A and also my team member need the same class and created the same (he may create it with slightly different name), how would we plan so that we move smoothly?

OwnerDisplayName: TrueWill


答:
It depends on the ecosystem that this code is going to live in. If _ is an accepted standard to indicate "dummy variable" / "unused output", then by all means, stick with it. If it's not, find out what is and use that.

Some programming languages (e.g. Haskell) even have this 'special' identifier built into their syntax for exactly the purposes you mention.


答:
In Python _ is definitively acceptable. It can however conflict with gettext alias  _().

Other common conventions are dummy, unused; alone or as prefix.

Some code analysis tools are aware of these conventions and will not issue unused variable warnings:

PyLint for _ or dummy

PyDev for any variable starting with _, unused or dummy


问:
Looking for good testing in multithreaded C or C++ open source projects
I have read a lot about the importance of unit testing, and testing in general.  In particular I have read about TDD which, in theory, seems like a good way to ensure effective test coverage for a project.

However, when I look at open source projects, or code that is available as open source, I am having difficulty finding good examples of testing in real projects that I can learn from.  In particular I haven't seen much in the way of unit testing (at least not that I can understand).

For example I just downloaded the source code for the Java HotSpot JVM.  I thought it would be very useful for me to look at and learn from because a JVM (written in C or C++) will have to deal with many complex issues associated with multithreading and low-level system interaction.  Which are the very same things that I'm having difficulty in figuring out how to develop unit tests for.  But unfortunately it seems like the amount of code written specifically for testing is quite limited.  There is a test directory but it looks like it contains examples of code that can be used to test various different bugs, rather than any formal regression tests or unit tests.

So my question is are there examples of open source projects that use unit testing that I could look at to learn from?  Something like a JVM is perfect for me because it is more complex than the project that I am working on, but would face many of the same issues associated with thread interaction and memory management.

答:
Take a look at gcc and some of the supporting libraries like GMP, MPFR, and MPC.

All of them have validation suites to verify that they compiled correctly.


问:
Confusion about proper use of * wildcard in SQL
Suppose I was writing an address book application where the details of each contact were stored in an SQL database.

A user wants to know all the details for a person whose name is "Bob [Someone]".

In such a case, would writing a query like this be okay?

```<code>SELECT *
FROM contacts
WHERE name LIKE 'Bob %';
</code>```

I'm confused because my professor said to avoid using the * wildcard but I can't think of an alternative way of writing it.

Is it okay to use the wildcard if I run this query on a seperate thread.

Thanks for your help.

答: The "*" in this case is pulling in all fields in the table. It has nothing to do with the search criteria "Bob %". In almost all cases you should list the fields you want returned explicitly.</p>


答:
```<code>SELECT Name, Birthday, Adress
FROM contacts
WHERE name LIKE 'Bob %';
</code>```

Title: Confusion about proper use of * wildcard in SQL

Body:
Suppose I was writing an address book application where the details of each contact were stored in an SQL database.

A user wants to know all the details for a person whose name is "Bob [Someone]".

In such a case, would writing a query like this be okay?

```<code>SELECT *
FROM contacts
WHERE name LIKE 'Bob %';
</code>```

I'm confused because my professor said to avoid using the * wildcard but I can't think of an alternative way of writing it.

Is it okay to use the wildcard if I run this query on a seperate thread.

Thanks for your help.


答:
The alternative is to name all the details in your SELECT clause explicitly - or better, all those details that you actually want.

The use of * is discouraged for two reasons:

it has to retrieve more data than a focused query for the data that you actually need, so it can waste resources.

it could encourage the client programmer to expect the fields to be returned in a particular order, and with a particular cardinality. If you then extract the 'first' field from the result set and display it, the result will look correct, until someone adds or changes the column definition of the underlying table, whereupon the previously working code suddenly breaks, with neither side feeling responsible.

Therefore, best practice is to explicitly select those columns that are actually wanted, and retrieve them by name rather than by position.


答:
Assuming that the whole name is in one field, and you don't have first and last separated into two columns, then your base query is fine.

If you can't use the * wild card, you can get each field individually, like this:

```<code>select name, phone, address from contacts where name like 'Bob%';
</code>```

Body:
Assuming that the whole name is in one field, and you don't have first and last separated into two columns, then your base query is fine.

If you can't use the * wild card, you can get each field individually, like this:

select name, phone, address from contacts where name like 'Bob%';


答:
Think of the * as a column selector rather than a wildcard.  The reason why your professor said that was because selecting all columns is an inefficient way of getting data, since you'll not likely need all the information that will be retrieved.

Contrarily, the '%' is a wildcard, and I think that's what you're confusing with '*'.  In your query, you're using '%' to specify anyone with name starting with 'Bob '.  Note that if you had used '*' for this, you would have been looking for anyone whose name is exactly 'Bob *'.


答:
It may be syntactically valid, and it might be OK as part of a standard.

With that said, it is something I would ask someone to change in a code review.  I would also never put it into a coding standard, and would try to remove it from an existing one. It's just more difficult to read, and not super meaningful.


答:
You can't stop every possible password interception technique.  So you just have to think about each technique that can be used, and how likely it is to be used.  If it is easy, and very likely to be used, then that is something that you probably shouldn't use.  If it is hard to do, though, and unlikely that someone will do it, then that might be OK.  Some security experts would probably disagree, but the reality is that you can't always fortify everything, all the time.

With that said, the idea of uploading the Excel file to a web app or desktop app that does the database load is a good one.  That way you only store the password in one place.

Title: Security Concerns with password storage in Scripting Languages (VBA)

Body:
The team I work with handles large amounts of consumer survey, and internal company metric data. Primarily the data is stored in a database, and we utilize various platforms and to work with that data, including MS Excel.

My peer has developed a suite of Excel/VBA files to take the raw data we get and upload it into a database. Unfortunately, after a code review we identified that the database password was displayed in the VBA code, in plain text, in several places per file. Being in a large enterprise organization we had a number of concerns about those files being available to more than just our team, and the database password being compromised.

The problem is, I feel the solution is just as bad, if not worse than the original problem. The plaintext passwords have been removed in the code of all of the VBA files, and an ancillary, helper file was created that requires the user to authenticate through our organizations LDAP system before gaining access to the database password. Being a scripting language (and being Excel), I feel there really aren't adequate precautions in place to secure the users password in the helper file. I feel that now instead of compromising access to a single database, we are potentially compromising access to the logins of anyone who uses these files.

To be fair, my peer has implemented a number of security minded techniques for securing the data in helper file. I just feel each one can easily be circumvented:

locking the VBA code [google search for vba password recovery]

using a custom "masked" password entry box [the password box may be masked, but it is still passed out of the box as plaintext]

not actually storing the user password in the file itself (he passes it on directly to the LDAP call) [a break point or stop statement can easily reveal the contents of what was passed]

setting the sheets to VeryHidden to prevent direct access [append .zip to filename, and ALL data in ALL worksheets is accessible]

As I'm not one to complain without a solution in mind, our organization already employs Active Directory/LDAP for authentication into our individual machines. My thought is that checking the logged in user (not a full user/password, just the user) against a white list of users on the database should be a sufficient alternative for authentication.

So My Question...

Am I being too paranoid about this? Is there another, more appropriate solution? I am pushing back fairly hard on this fix and I just wanted a sanity check before I start to involve others in yet another solution.


答:
The * is a shorthand for selecting all columns from the result set; the alternative way of writing this is to spell out all the columns you expect in the contacts table, e.g. SELECT id, name, email FROM contacts WHERE name LIKE 'Bob%'.

In layman's terms, SELECT name, email FROM ... means "tell me the names and e-mail addresses of ...", while SELECT * FROM ... means "tell me everything you know about ...".

The reason people discourage SELECT * are twofold: first of all, if you use it in production code, and the database changes for whichever reasons, your column ordering will be off, and you will be fetching results into the wrong variables. If you specify columns explicitly, you can rely on the correct number and ordering of result columns, and the query will fail loudly if the columns you specify do not match what was found in the database.

Another reason is performance. SELECT * means that the DBMS has to perform an extra lookup to get the list of columns. It also means that you haven't thought about what you really need, so chances are you'll be fetching more data than you need, which, considering the typical performance bottlenecks in web applications, is something you really want to avoid.

Finally; threads have absolutely nothing to do with this. Nothing at all. I wonder where you got that notion; it looks like you're still quite confused about SQL syntax.

TL;DR: SELECT * is OK for queries you fire manually, but you should avoid it in production code, because it can produce unexpected results and may lead to inefficient queries.


答: I use "dummy" for that sort of thing. Or "crap", if I'm just testing something out :) Name your variables to describe what they are. If they're dummy, unused variables, name them as such.</p>


问:
When programming: How much time is spend navigating/scrolling and how much typing?
When your programming you often have to go and look at other pieces of code for reference, search for something etc. I'm looking for some numbers on the ratio of time spend actually typing the code(coding) and the time spend going back and forth between other parts of the system, not even counting browsing the internet, reading documentation.

Ofcourse this depends on a large number of factors, probably also on your IDE, programming language etc. I just need some rough estimates, or researches on the subject.

Background:
I want to investigate how much network latency is tolerable for a programmer to work on virtual machines (if any).

答:
Depends on many factors.

Learning a new library?  A lot.
Have two monitors? Probably not much.
Dealing with code written by monkeys? Tons.
Reading/Writing documentation in a waterfall process? Tons.


问:
Why would I write a DSL instead of a form based RIA?
I've been reading some papers recently on domain specific languages (DSL), but none of them appear to address the advantages of a DSL over a rich internet application (RIA). In an RIA, instead of learning the domain language, the user is provided with domain objects as form fields, which abstracts the lexical definitions for the domain language. This seems more usable. What I am missing?</p>

答: Since the DSL is text, I can use text-based tools. Most notably I can generate code for the DSL with a shell script via metaprogramming. As others have said, the DSL doesn't prevent having an RIA as well.</p>


答:
This depends on the complexity of the domain. If it mainly consists of structured data, a visual editor may be more intuitive to use, but if the domain contains significant amounts of logic, experience has shown time and time again that visual editors are a poor tool for that.

Additionally, there are some very common, very useful tasks that are trivial with a character-based language (such as copy&paste, search&replace) but require a lot of effort to implement in a visual editor and are therefore often missing.

Title: Why would I write a DSL instead of a form based RIA?

Body: I've been reading some papers recently on domain specific languages (DSL), but none of them appear to address the advantages of a DSL over a rich internet application (RIA). In an RIA, instead of learning the domain language, the user is provided with domain objects as form fields, which abstracts the lexical definitions for the domain language. This seems more usable. What I am missing?</p>


答: A form restricts the possible expressions to just one type. In natural language terms, you can write anything you can imagine in English. What you can express with a form is much more limited: think Mad Libs for example.</p>


答: If you embed the DSL in a full programming language (Python, Ruby, Groovy, etc.) then you can you use the DSL to automate tasks.  </p>


问:
Bad idea to display mail server info in public github project?
I have the project for work that requires me to send e-mails to people using our work mail server. The server doesn't require authentication. Part of my project is using a Java-Helper I'm developing on GitHub. I don't know if I completely understand how it all works, but I'm guessing it would be a bad idea to have the server information available on GitHub for the world to see. Is this correct?

After thought: I'm not going to put it in the Java-Helper because that wouldn't be helpful for anyone but me. but I'm still curious to know the answer to this question :) Thanks!

答: I know of scrapers that just crawl around looking for this kind of information. I'd avoid it as much as possible. Even if it's secured and people couldn't use it... it doesn't sound like necessary information to have published.</p>


问:
Is it better to return NULL or empty values from functions/methods where the return value is not present?
I am looking for a recommendation here.  I am struggling with whether it is better to return NULL or an empty value from a method when the return value is not present or cannot be determined.

Take the following two methods as an examples:

string ReverseString(string stringToReverse) // takes a string and reverses it.
Person FindPerson(int personID)    // finds a Person with a matching personID.
```

In ReverseString(), I would say return an empty string because the return type is string, so the caller is expecting that.  Also, this way, the caller would not have to check to see if a NULL was returned.

In FindPerson(), returning NULL seems like a better fit.  Regardless of whether or not NULL or an empty Person Object (new Person()) is returned the caller is going to have to check to see if the Person Object is NULL or empty before doing anything to it (like calling UpdateName()).  So why not just return NULL here and then the caller only has to check for NULL.

Does anyone else struggle with this?  Any help or insight is appreciated.

答:
NULL should be returned if the application expects a data to be available but the data is not available.  For example,  a service that returns the CITY based on zipcode should return null if the city is not found. The caller can then decide to handle the null or blow up.

Empty list should be returned if there are two possibilities. Data
available or NO data available. For example a service that returns
the CITY(s) if the population is greater than certain number. It can
return a empty list if No data that satisfies the given criteria.


答:
I think it's wrong because:

1) It's harder to see as there's not many pixels.

2) If there's more than one _, how do you know which one? - or that a new developer has 'followed the rules' and kept their use extremely local in scope?

3) It's an practice that is not helpful.  Using single letter variable names is so old school (i.e. my original education!).  I'll see them... and then see comments added to say what the code does and that's a bad practice in today's world.  I use long variables names as much as possible so everyone, regardless of programming level or familiarity with the code can just "read it" almost like english.  Using 1 letter names is an extremely common practice with older code and with older programmers (again, includes me) but that does not make it ok.


问:
What to put in a try/catch?
Note on the question: this is not a duplicate, Efficient try / catch block usage? was asked after this one. The other question is the duplicate.

I was wondering what was the best way to use try/catch. Is it better to limit the content of the try block to the minimum or to put everything in it?

Let me explain myself with an example:

Code 1:

```<code>try {
  thisThrowsAnException();
}
catch (Exception e) {
  e.printStackTrace();
}
thisDoesnt();
</code>```

Code 2:

```<code>try {
  thisThrowsAnException();
  thisDoesnt();
}
catch (Exception e) {
  e.printStackTrace();
}
</code>```

Assuming that thisThrowsAnException()... well... can throw an exception and thisDoesnt()... I'm sure you got it.

I know the difference between the two examples: in case the exception is caught, thisDoesnt() will be called in the first case, not in the second. As it doesn't matter for me, because the throwing of that exception would mean the application should stop, why would one use a version better than the other?

答:
Its going to be a game-time decision for each one. If you have code that can throw exceptions that is not absolutely necessary for the program, then put it alone in the try block. That way in the catch block you can deal with where to go next.

A good design pattern for this is to have a helper method which can determine if an error is fatal (end the session, close the program, whatever) or not, and then rethrow or not based on the result of that check. Something like:

```<code>try{
    foo();
}
catch(Exception ex)
{
    bool rethrow = ExceptionHelper.Handle(ex);  //should return true if error is fatal, false if not
    if(rethrow) throw;
}
</code>```

Title: What to put in a try/catch?

Body:
Its going to be a game-time decision for each one. If you have code that can throw exceptions that is not absolutely necessary for the program, then put it alone in the try block. That way in the catch block you can deal with where to go next.

A good design pattern for this is to have a helper method which can determine if an error is fatal (end the session, close the program, whatever) or not, and then rethrow or not based on the result of that check. Something like:

try{
    foo();
}
catch(Exception ex)
{
    bool rethrow = ExceptionHelper.Handle(ex);  //should return true if error is fatal, false if not
    if(rethrow) throw;
}


问:
How should I test randomness?
Consider a method to randomly shuffle elements in an array. How would you write a simple yet robust unit test to make sure that this is working?

I've come up with two ideas, both of which have noticeable flaws:

Shuffle the array, then make sure its order differs from before. This sounds good, but fails if the shuffle happens to shuffle in the same order. (Improbable, but possible.)

Shuffle the array with a constant seed, and check it against the predetermined output. This relies on the random function always returning the same values given the same seed. However, this is sometimes an invalid assumption.

Consider a second function which simulates dice rolls and returns a random number. How would you test this function? How would you test that the function...

never returns a number outside the given bounds?

returns numbers in a valid distribution? (Uniform for one die, normal for large numbers of dice.)

I'm looking for answers offering insight into testing not only these examples but random elements of code in general. Are unit tests even the right solution here? If not, what sort of tests are?

Just to ease everyone's mind I'm not writing my own random number generator.

答:
Let it run a bunch of times and visualize your data.

Here's an example of a shuffle from Coding Horror, you can see that the algorithm is OK or not:

It's easy to see that every possible item is returned at least once (the boundaries are OK) and that the distribution is OK.

Title: How should I test randomness?


问:
How would I do a "Server over capacity" message with Django?
This probably isnt' a Django specific question, but I'm wondering how those "Server over capacity" messages are displayed.

Some examples:

Twitter's fail whale

Tumblr's Over capacity slash page

Drawception's over capacity message when new games are created.

答: One way to achieve this would to have a load balancer in between the servers and the users. If the load balancer determines that the server is taking too long to respond, or if the server is down, then the load balancer can redirect to a static "over capacity" page.</p>


问:
How to script the creation & configuration of a portable (vm-based?) Windows 7 dev environment?
I'm getting a new computer and would like to minimize the time spent configuring and maintaining dev environments on my various machines.

To that end, I'm thinking that creating a vm with my preferred ide and configuration and using that vm for development on all my machines.

I'd like to use Windows 7 as the vm's os.

For those who have tried or currently use an approach like this,

How can I keep the disk image synchronized without resorting to a thumb drive? What are pros/cons (if any).

As I do this first configuration manually, should I record my steps in the interest of scripting them later?

If so, what approach would you recommend for scripting? Cygwin + bash? Ant? Something else? Why?

Are there potential difficulties I should be aware of re: sharing a filesystem? For instance, in A) accessing vm files from the host machine or B) accessing the vm's HTTP server from the host machine?

答: I currently use vagrant for the same thing, but with linux boxes and many people use it this way. You might want to "package" a windows base box. I've never tried with windows so do not know how.</p>


问:
How to TDD that the correct results are returned
I'm starting a new project, and trying very very hard to use TDD to drive the design.  I've been pushing for years, and finally got approval to spend the extra time on this project to use it while I learn how to do it properly.

This is a new module, to tie into an existing system.  Currently, all data access happens through webservices, which for the most part are just a thin wrapper over database stored procedures.

One requirement is that for a given store, I return all Purchase Orders that are considered valid for this application.  A PO is considered valid if it's ship date falls withing a given range from the stores opening date (this is for new stores).

Now, I can't put this logic in the application code, as I'm not going to bring back a million POs just to get the dozen that apply to could apply to this store given the constraint above.

I was thinking, I could pass the date range to a GetValidPOs proc, and have it use those values to return the valid POs.  But, what if we add another requirement to what is considered a valid PO?

And how do I test this and verify it keeps working?  We are not using an ORM, and it's unlikely to happen.  And I can't call the DB in my test.

I'm stuck.

My other thought, is have some mocks that return valid data, others that return some bad data, and have the local repository throw an exception if bad data occurs, and test that the exception gets thrown if invalid data is returned by GetValidPOs proc (or the mock used in testing).

Does this make sense?  Or is there a better way?

UPDATE:
I am able to use EF it would seem.  Now I just need to figure out how to use it, and make it testable, while still being able to rely on stored procedures, and the difficulty of having data scattered across several databases.

答:
This is a major downside of stored procedures in the age of TDD. They have some real upsides, even now, but by definition any test that exercises a stored proc is not a unit test; it's an integration test at best.

The usual solution, assuming the architecture cannot change to use an ORM instead, is to not put these tests in the unit test suite; instead, put the tests in an integration suite. You can still run the test whenever you like to verify it works, but because the cost inherent in setting up the test (initializing a DB with the proper test data) is high and it touches resources your build-bot's unit-test agent may not have access to, it shouldn't be in the unit test suite.

You can still unit-test code that requires the data, by abstracting anything you cannot unit-test (ADO.NET classes) into a DAO class that you can then mock. You can then verify that the expected calls are made by consuming code and reproduce real-world behavior (such as finding no results) allowing testing of various use cases. However, the actual setting up of the SqlCommand to call the stored proc is pretty much the very last thing you can unit-test, by severing command creation from command execution and mocking the command executor. If this sounds like a lot of separation of concerns, it can be; remember, "there is no problem that cannot be solved by another layer of indirection, except for having too many layers of indirection". At some point you must say "enough; I just can't unit-test this, we'll do it in integration".

Other options:

Test the stored proc using a "short-lived" DBMS instance like SQLite. It's usually easier to do this when using an ORM, but the test can then be done "in-memory" (or with a pre-set database file included with the test suite). Still not a unit test, but it can be run with a high degree of isolation (the DBMS is part of the running process, and not something you connect to remotely that may be in the middle of someone else's conflicting test suite). The downside is that changes to the stored proc can happen in production without the test reflecting the change, so you have to be disciplined about making sure the change is first made in a test environment.

Consider upgrading to an ORM. An ORM with a Linq provider (virtually all the ones in common use have one) would allow you to define the query as a Linq statement; that statement can then be given to a mocked Repository that has an in-memory collection of test data to apply it to. You can thus verify the query is correct without even touching the DB (you should still run the query in an integration environment, to test that the Linq provider can correctly digest the query).


答:
Usually these settings are composed of a Web Server acting as a proxy to several application servers. Look at the architecture.

For these Server overload events, if any of the appservers can't process requests, they return a HTTP 50x status, in which case Nginx will serve a (generic) static error page.

Title: How would I do a "Server over capacity" message with Django?

Body:
This probably isnt' a Django specific question, but I'm wondering how those "Server over capacity" messages are displayed.

Some examples:

Twitter's fail whale

Tumblr's Over capacity slash page

Drawception's over capacity message when new games are created.


答:
Ah yes...SOAP, the vaunted holy grail of computing. A lingua franca that promised interop between systems around the world.

And then you get into the differences between SOAP implementations on Java and PHP and .NET. Or even between the WebSphere SOAP service and the Apache SOAP client. Never mind dealing with different WS-I compatability standards. Now please tell me why you need a compatibility standard for a protocol that was built for compatibility, talk about ironic (and I mean real irony, not the Alanis Morrissette brand of irony).

The only time you won't run into issues in getting two SOAP endpoints communicating is when they are both on the same platform and in most cases the platform will have a more efficient remote operation protocol.

What I'm saying here is that for the most part, SOAP is useless. Now lower case soap, I use that every day and I'm thankful that most people do the same.

That being said, if you're insisting on beating your head against a brick wall. Here is a good place to start Microsoft has a set of bindings to enable interop with most of the major Java servers. The fun part of course is finding out which ones work with which of the services you are integrating.


答:
To avoid namespace collisions, and allow for debugging, in case that variable name is your only clue, it might be better to call it "joined_ab_unused".

Inspired by Birfl.


答:
I will be the contrarian and point out that DSLs are often recommended inappropriately, because they are a more natural and flexible interface for programmers, and programmers like to create systems that are easy for themselves to use.

That means DSLs are best suited for features designed for programmers or highly trained and specialized users like IT departments.  Things like site-specific configuration/customization, script automation, or relatively infrequently-changed business logic.

DSLs can also be useful as intermediate representations, allowing the programmer to write code at higher layers in a more compact, better suited language, even if end users never see it.


答:
Yes, it's a bad practice for two reasons:

Prefixing a unused variable with an underscore isn't a widely accepted standard. It will likely be ignored the "uninitiated".

I've seen some people prefix private member variables with an underscore, and your standard would greatly confuse such people.


答:
What you're trying to do is to code in a nicer version of SQL which doesn't have the issue of forcing you to invent a name for something useless.

The underscore is almost invisible, so it looks like you are in that language. If only whitespace could be used as an identifier, it would be perfect, right?

But you are not in a different language, and what you're doing is not a clean way to make a language extension.


答:
It depends on the language.  In java, yes this is bad and can be a dangerous trend to add to your code, largely because tools that use reflection don't handle underscores very well, since they are outside of java variable naming conventions.  In python, this is also bad but not as bad.  In clojure , its 100% okay, and in fact, its idiomatic to use _'s as place holders in a let statement.

Remember that each language has its own entire syntax and set of idioms, so you have to evaluate good/bad in terms of these idioms, rather than in absolute terms.


问:
Is having a single `IndexWriter` instance in Lucene a good idea?
I am trying to understand how Lucene should be used.

From what I have read, creating an IndexReader is costly, so using a Search Manager shoulg be the right choice. However, a SearchManager should be produced by a NRTManager(which, by the way, should replace the IndexWriter for every add or delete operation performed). But in order to have a NRTManager, I should first have an IndexWriter, and here comes my problem.

The documentation says:

an IndexWriter is thread-safe

the constructor of this class takes a Directory object, so it seems creating an instace should be costly(as in the case of an IndexReader)

all changes are buffered and flushed periodically(so they seem to encourage using a single instance)

but:

the changes, although flushed will only be visible after commit or close

after finished making updates(add/delete), the instance should be closed

I also found this: https://stackoverflow.com/questions/5374419/forgot-to-close-the-lucene-indexwriter-after-adding-documents-to-the-index where it is said that not closing a writer might ruin everything

So what am I really supposed to do? Is having a single IndexWriter instance a good idea (make only commit and never close it)?

EDIT: What is more, if I use NRTManager, how can I make a commit? Is it even possible?

答:
Ok, how do we start. First of all this is written based on Lucene 3.6.
NRTManager is used for Near-Realtime-Scenarios where Writing and Reading is very close after each other. An Example would be Twitter (that is actually using a modified Version of Lucene). In these cases you are not suppost to close your IndexWriter as all changes that occure are being tracked by NRTManager.TrackingIndexWriter - use NRTManagerReopenThread to periodicly trigger refreshes on the Searcher Threads.

For non-realtime scenarios you rather want to use the SearcherManager to acquire IndexSearcher and an instance of IndexWriter to write Documents. After a set of Documents is written to the index (or on random base) use ReferenceManager.maybeRefresh (extended by SearcherManager) to refresh the Searcher Threads.

To sum up:

You can have a single instance of IndexWriter and commit your changes. You can as well have multiple threads of IndexWriter writing on one index with ConcurrentMergeScheduler.

Close your IndexWriter only if you are sure that you do not have any changes to do on the index (mind that it is very coastly to open an IndexWriter)

You never commit an NRTManager as all changes are being tracked.


问:
Refactoring Switch Statements and is there any real use for Switch Statements at all?
I was reading this article and was wondering, do we get rid of all switch statements by replacing them with a Dictionary or a Factory so that there are no switch statements at all in my projects.

Something did not quite add up.

The question is, do switch statements have any real use or do we go ahead and replace them with either a dictionary or a factory method (in using a factory method, of course, there will be a minimum use of switch statements for creating the objects using the factory...but that is about it).

答:
Seeing as how this is language-agnostic, fall-through code works best with switch statements:

```<code>switch(something) {
   case 1:
      foo();
   case 2:
      bar();
      baz();
      break;

   case 3:
      bang();
   default:
      bizzap();
      break;
}
</code>```

Equivalent with if, with a very awkward default case.  And keep in mind that the more fall-through there is, the longer the condition list will get:

```<code>if (1 == something) {
   foo();
}
if (1 == something || 2 == something) {
   bar();
   baz();
}
if (3 == something) {
   bang();
}
if (1 != something && 2 != something) {
   bizzap();
}
</code>```

(However, given what some of the other answers say, I feel like I've missed the point of the question...)

Body:
Seeing as how this is language-agnostic, fall-through code works best with switch statements:

switch(something) {
   case 1:
      foo();
   case 2:
      bar();
      baz();
      break;

   case 3:
      bang();
   default:
      bizzap();
      break;
}

Equivalent with if, with a very awkward default case.  And keep in mind that the more fall-through there is, the longer the condition list will get:

if (1 == something) {
   foo();
}
if (1 == something || 2 == something) {
   bar();
   baz();
}
if (3 == something) {
   bang();
}
if (1 != something && 2 != something) {
   bizzap();
}

(However, given what some of the other answers say, I feel like I've missed the point of the question...)


答:
Careful, _ already has an intrinsic meaning in some languages

In Python:

9.6. Private Variables and Class-local References

enter link description here“Private” instance variables that cannot be accessed except from inside an object don’t exist in Python. However, there is a convention that is followed by most Python code: a name prefixed with an underscore (e.g. _spam) should be treated as a non-public part of the API (whether it is a function, a method or a data member). It should be considered an implementation detail and subject to change without notice.

There's also another mention in the PEP 8 (Style Guide for Python Code):

Descriptive: Naming Styles

_single_leading_underscore: weak "internal use" indicator. E.g. from M import * does not import objects whose name starts with an underscore.

In C#:

It's generally used to mark private variables that have public/internal properties. But the practice is generally looked down on these days.

In JavaScript:

There is a library called underscore.js that uses the underscore as a prefix for non-standard prototype extensions.

Example:

```<code>var object = { some:'stuff' };
var newObject = _.clone(object);
</code>```

Which leads me to my point. What's wrong with the classic placeholder variable conventions.

```<code>var i, j, k, l; // iterator placeholders
var x, y, z, xx, yy, zz // value placeholders
var foo, bar, bas, fixx, buzz, qux, etc... // demonstration placeholders
</code>```

Why use a custom convention that some may misinterpret when there are plenty of common conventions available already?

Body:
Careful, _ already has an intrinsic meaning in some languages

In Python:

9.6. Private Variables and Class-local References

enter link description here“Private” instance variables that cannot be accessed except from inside an object don’t exist in Python. However, there is a convention that is followed by most Python code: a name prefixed with an underscore (e.g. _spam) should be treated as a non-public part of the API (whether it is a function, a method or a data member). It should be considered an implementation detail and subject to change without notice.

There's also another mention in the PEP 8 (Style Guide for Python Code):

Descriptive: Naming Styles

_single_leading_underscore: weak "internal use" indicator. E.g. from M import * does not import objects whose name starts with an underscore.

In C#:

It's generally used to mark private variables that have public/internal properties. But the practice is generally looked down on these days.

In JavaScript:

There is a library called underscore.js that uses the underscore as a prefix for non-standard prototype extensions.

Example:

var object = { some:'stuff' };
var newObject = _.clone(object);

Which leads me to my point. What's wrong with the classic placeholder variable conventions.

var i, j, k, l; // iterator placeholders
var x, y, z, xx, yy, zz // value placeholders
var foo, bar, bas, fixx, buzz, qux, etc... // demonstration placeholders

Why use a custom convention that some may misinterpret when there are plenty of common conventions available already?


答:
This would be bad in perl, which uses $_ (and sometimes _) as a special variable.

In general, I'd stay away from it just because the _ seems to be a language specifmetavariable. If I saw your code, I'd be in documentation looking for what _ was, until I realized it was just a dummy. Nothing wrong with DUMMY, $DUMMY, whatever.


答:
do we get rid of all switch statements by replacing them with a Dictionary or a Factory so that there are no switch statements at all in my projects.

No. Such absolutes are rarely a good idea.

Many places, a dictionary/lookup/factory/polymorphic dispatch will provide a better design than a switch statement but you still have to populate the dictionary. In certain cases, that will obscure what is actually going on and simply having the switch statement in-line is more readable and maintainable.

Title: Refactoring Switch Statements and is there any real use for Switch Statements at all?

Body:
I was reading this article and was wondering, do we get rid of all switch statements by replacing them with a Dictionary or a Factory so that there are no switch statements at all in my projects.

Something did not quite add up.

The question is, do switch statements have any real use or do we go ahead and replace them with either a dictionary or a factory method (in using a factory method, of course, there will be a minimum use of switch statements for creating the objects using the factory...but that is about it).


答:
Depends on which phase of the project you're in.

Initially there's a bunch of typing--I find that to be the case even when I'm tying in a lot of external stuff.

Once I have the structure of the application in place and the general flow of the thing constructed, it becomes more navigational and surgical.

Title: When programming: How much time is spend navigating/scrolling and how much typing?

Body:
When your programming you often have to go and look at other pieces of code for reference, search for something etc. I'm looking for some numbers on the ratio of time spend actually typing the code(coding) and the time spend going back and forth between other parts of the system, not even counting browsing the internet, reading documentation.

Ofcourse this depends on a large number of factors, probably also on your IDE, programming language etc. I just need some rough estimates, or researches on the subject.

Background:
I want to investigate how much network latency is tolerable for a programmer to work on virtual machines (if any).


问:
What happened to Borland Delphi?
I have the impression that Delphi isn't very popular anymore. But now at work I had to make some changes to an old Delphi program that we are still using. I used Borland Developer Studio 2006 and it was very pleasant and intuitive to work with, even though I had practically no previous exposure to it. Is Delphi still widely-used and I am simply not aware of it or are there other reasons for its decline? </p>

答: Delphi is alive as mentioned above not only because now it is owned by a company who cares, but also because there is a oss project fpc/Lazarus. It is inspired by Turbo Pascal/Delphi and has a very high level of compatibility with Delphi. Moreover, the current Delphi version uses fpc to compile for iOS target. This means that Embarcadero doesn't see this project as a threat, but rather as a partner. </p>

Title: What happened to Borland Delphi?


答:
Switch-statements vs subtype-polymorphism is an old problem and is often referred to in the FP community in discussions on the Expression Problem.

Basically, we have types (classes) and functions (methods). How do we code stuff so that its easy to add new types or new methods latter on?

If you program in OO style, its hard to add a new method (since that would mean refactoring all the existing classes), but its very easy to add new classes that use the same methods as before.

On the other hand, if you use a switch statement (or its OO equivalent, the Observer Pattern) then its very easy to add new functions but its hard to add new cases/classes.

Its not easy to have good extensibility in both directions, so when writing your code, determine whether to use polymorphism or switch statements depending on which direction you are more likely to extend latter on.


问:
How should I architect multi-language support for a group of applications?
I have about 8 web applications (all of them ASP.NET based), and I want to implement multiple language support for all of them and have an architecture that I can leverage on new web applications down the road. I would also like to try to centralize the admin piece (where all the text translations and other language specific resources reside), do you know of any tool or architectural pattern that might be useful in this case?

The only robust solution I can think of is to have a web application that manages the language support resources and all the other web applications connect to this centralized app/service, but I'm afraid that this solution will have a performance impact on all applications if not implemented the right way.

I would greatly appreciate any suggestions.

答:
You can start by defining many thing.

Define how to identify the culture in your API (ISO-639, LS-2012, ...)

This choice will change the way you store resources and access them.
Also, decide how to fallback through regions and neutral cultures.
Some languages have a very specific way to fallback between different cultures, some books would give you a great insight.

As you're going ASP.NET to choice is simple.

Define how to store each data type (strings, pictures, currencies...)

You will have to consider different access ways. Do you want to stay mobile and use simple files? Or can you afford keeping a database in a single place to handle everything?

Centralizing can become a problem is clients and consultants have to deal with translation. Using a text-file-based solution goes into source control revision easily, providing the good portable tool and libraries is great but isn't easy for non-techies.

Define access formats for all kinds of application

need to export for a specific technology (.resx, .po, .lang, xliff...)?

need random access from a server app via a (web)service?

need a unitary access to do translation?

In all cases, being able to export translations in a well-known format will give you the ability to use translation services. You will then need to be able to merge new translations with your existing ones.

Define how to deal with currencies

This is more a code concern which your API will not have to deal with entirely. But setting-up rules for all developers is a good thing.

Finally, make sure the API you will create can be ported to as many languages/technologies as needed. Using standard formats will be a essential choice because of the existing libraries (gettext, xliff) and tools.

Don't forget to handle plural forms (no items, one item, x items) and translation remarks (contextual information for each resource) which will solve a lot of problems.

Write everything you decided in a shared document to make sure everyone understands the why and how. If you're writing an API, documentation is... important.


问:
How can I manage changes between a local config file and a remote config file in a mobile application?
I have an application with a configuration file that is stored in the application bundle. This config file stores the names of images on a remote server. Whenever the application is started, I download the configuration file from the server and see if there are any changes or updates. If there are changes, I iterate over the array of configuration settings and download the changed images to the user's iPhone

I think that I will first list all of the name changes in an array, and after that start loading that changed images. However, I'm wondering if there is a better approach to solving this problem.

答:
You may want to use a simple version number attached to/near the file. Compare the server and client number (very low bandwidth usage) and work with it.

Version numbers can help you apply incremental upgrades to your config file to add/change/remove entries.


答:
Delphi is still alive and kicking, it is a great tool and the latest XE2 version brought many features such as 64bit compilation, iOS and MACOS compilation. So it is now a trully NATIVE Multi-Platform development tool.

It is really sad what Borland did to Delphi but Embarcadero seems to be changing the game, I use Delphi since version 4 and I´m currently on XE2, and this is by far the best version of Delphi ever released and since it is now multi-platform I would expect newer versions of Delphi to support Win32, Win64, MACOS, iOS, Android, Linux... all major platforms in the market.

The productivity of Delphi is incredible, and as a company owner I would never change our development platform, even if it is harder to find Delphi developers now, learning the language is really fast for a skilled DEVELOPER. In 2011 we hired 3 developers that didn´t know Delphi and now they have a very solid knowledge of the language and are producing many things really fast

Title: What happened to Borland Delphi?

Body: I have the impression that Delphi isn't very popular anymore. But now at work I had to make some changes to an old Delphi program that we are still using. I used Borland Developer Studio 2006 and it was very pleasant and intuitive to work with, even though I had practically no previous exposure to it. Is Delphi still widely-used and I am simply not aware of it or are there other reasons for its decline? </p>


问:
Storing data for use on Android and Windows Applications
I posted this last night on StackOverflow and was advised to move it over to StackExchange, thank you for taking a moment to look at my question.

I'm developing a project proposal for my final year project at University and as I aim to use programming languages I am currently not too familiar with I'm looking for some guidance - I can't include details of my project but hopefully you will understand what I'm after.

I'm going to be creating an Android application (in Java) and a Windows Application (in C#) that will ideally access, query and update a remotely hosted Database or set of XML files (this would most likely be over the Internet).

I've done some looking around the internet and SQLite seems like a safe-bet for cross-platform manipulation of the database; however I would like to keep the system as lightweight as possible and I'm wondering whether XML files may provide a better alternative? Anyone out there that has experience using SQLite and/or remotely hosted XML for the purposes of Android and/or C# development that could point me in the right direction?

If there is an alternative solution other than those I have mentioned I would be interested to hear about them too.

Thank you for taking the time to read my question.

Edit: The purpose of this application is for a small scale business, the data source would not need to be updated by more than one source but may be view from multiple sources (i.e. through multiple phones and a desktop PC). The database wouldn't be updating masses of data at a time (most likely single rows of a few tables at the most).

答:
When dealing with data & mobile devices, one of the first question is: "do you need to keep a local (in device) database for offline use or is it OK to ask a server some data everytime you need it?"

If you have to store a copy of your database on each device, having a common RDBMS (SQLite) is going to be a good thing. If the app starts for the first time, just download the db file locally. It will be easy to download it again and upgrade it incrementally with upgrade scripts (shared accross server and clients).

However, you won't be able to use the same code to access your database on both devices. Perhaps you can think of a way to generate the Data Access code in all the languages you need based on your database structure. This may (or may not) save you some time. Generating code with code is always a good experience anyway (see The Pragmatic programmer, rule 29 "Write Code That Writes Code").


答: One simple way to save bandwidth without much modification, would be to use the If-Modified-Since header in your download request.  Then continue to check the version number inside the file anytime it is downloaded, just in case the modified date on the file gets changed accidentally.

Title: How can I manage changes between a local config file and a remote config file in a mobile application?

Body:
I have an application with a configuration file that is stored in the application bundle. This config file stores the names of images on a remote server. Whenever the application is started, I download the configuration file from the server and see if there are any changes or updates. If there are changes, I iterate over the array of configuration settings and download the changed images to the user's iPhone

I think that I will first list all of the name changes in an array, and after that start loading that changed images. However, I'm wondering if there is a better approach to solving this problem.


问:
When is unit testing inappropriate or unnecessary?
It seems to be generally assumed (on Stack Overflow at least) that there should always be unit tests, and they should be kept up to date. But I suspect the programmers making these assertions work on different kinds of projects from me - they work on high quality, long-lasting, shipped software where bugs are A Really Bad Thing.

If that's the end of the spectrum where unit testing is most valuable, then what's the other end? Where are unit tests least valuable? In what situations would you not bother? Where would the effort of maintaining tests not be worth the cost?

答:
There is a trade-off between the cost of writing unit tests, and the value they add. Neglecting this risks the possibility of over-testing.

blueberryfields touched on one variable that affects the value of unit tests: stability of the project (or pace of development). I'd like to expand on that.

The value to having unit tests roughly follows the following plot (yay, MS Paint!):

In the first zone, the code is unstable to the point that unit tests will often need to be rewritten or entirely scrapped. This might be a prototype that you know won't be used. Or it might be a project where you are new to the programming language or framework (and are often needing to redo large amounts of code).

Unit tests are good for refactoring at the module level (i.e. changing functions). The problem is when code is unstable at the architectural level, where entire modules might be rewritten, removed, or completely redesigned. The unit tests then must be changed/removed/added, which is a burden.

At this stage, limiting to system level integration tests, or even manual testing is a better approach (which one you choose again being dependent on the cost of writing the test vs. the value you get).

The unit tests add the most value in the second zone, where code becomes stable above the module level, but not yet at the module level. If you have a stable codebase, and you are adding a module that has a high chance of staying, this is when unit testing is a big win.

Unit tests also begin to have less value when the stability of the code under test is very high. Testing a simple wrapper of a standard library function is one example where unit testing is overkill.

If a piece of code you are writing will likely never need to change, and you are confident you've got it right (maybe it's super simple?), there is less value to testing.

Unit testing becomes beneficial when the utility is greater than the cost, as shown in the below graph in zone II.

This cost line could be at different levels for different people (line 1 vs line 2). If you are new to the test framework used in a project, this increases the level, and makes the net utility less. A higher cost (line 2) shrinks the range that unit testing is appropriate.

The cost line doesn't necessarily need to be flat. Especially when you consider other variables such as project size, and whether a test framework already exists for the project, this might be so.


问:
Why is there a leading zero in HTML 4.01 version number?
I've never noticed this quirk until now, and it's screwing with my mind. Why was HTML 4.01 numbered with a leading zero, rather than as 4.1?</p>

答: I don't know for sure why it was done in this specific case.  But generally, it's done when someone sees the possibility that there may be more than 9 dot releases.  If you go from 4.1 to 4.2 to 4.3, you're rather stuck when you're at 4.9 and want to go to 4.10 because half the software out there is going to treat that as numerically equivalent to 4.1.  If you go from 4.01 to 4.02, you don't have a similar problem until you've made 99 dot releases.</p>


问:
Is it bad practice to name an unused variable with a single underscore?
Often when the syntax of the language requires me to name a variable that is never used, I'll name it _.

In my mind, this reduces clutter and lets me focus on the meaningful variables in the code. I find it to be unobtrusive so that it produces an "out of sight, out of mind" effect.

A common example of where I do this is naming subqueries in SQL.

```<code>SELECT *
FROM
(
    SELECT *
    FROM TableA
    JOIN TableB
        ON TableA.ColumnB = TableB.ColumnB
    WHERE [ColumnA] > 10
) _ --This name is required, but never used here
ORDER BY ColumnC
</code>```

Another example is a loop variable that isn't used.

```<code>array = [[] for _ in range(n)] # Defines a list of n empty lists in Python
</code>```

I use this technique very sparingly, only when I feel that a descriptive name adds nothing to the code, and in some sense takes away from it by adding more names to remember. In some ways I view it as similar to the var keyword in C#, which I also use sparingly.

My coworkers disagree. They say that even having a single (alphabetic) character name is better than _.

Am I wrong? Is it bad practice to do this?

答: I would avoid underscores at the beginning of vars unless you were certain they didn't tend to indicate something else in a given language or framework in heavy use. For instance, in Python, a double underscore tends to indicate a magic var. In JQuery and other JS libraries a single underscore tends to indicate a fallback var for namespace overwrites. It's also a popular naming convention for include files which in turn tend to carry over to code that handles includes in var form.</p>


答: Intuitively, it's because 4.01 is just a teeny bit different from 4.0, not different enough to be a 4.1 release. Many version numbering schemes would often make that a 4.0.1 release. The fact that it wasn't done this way makes me think that there may have been some known cases where the version number was being interpreted as a real number instead of as a version "number" string.</p>

Title: Why is there a leading zero in HTML 4.01 version number?

Body: I've never noticed this quirk until now, and it's screwing with my mind. Why was HTML 4.01 numbered with a leading zero, rather than as 4.1?</p>


问:
Design Patterns for Javascript
A lot of web frameworks have a MVC-style layout to code and approaching problems. What are some good similar paradigms for JavaScript? I'm already using a framework (jQuery) and unobtrusive js, but that still doesn't address the problem I run into when I have more complex web apps that require a lot of javascript, I tend to just end up with a bunch of functions in a single, or possibly a few files. What's a better way to approach this?</p>

答:
There are some recently added new articles that focus on implementing JavaScript Design Patterns and some of the Gang-of-Four Design Patterns using JavaScript:

JavaScript Design Patterns: Chain of Responsibility (Last updated February 20, 2012) - Although this article obviously focuses on Chain of Responsibility, it has links to many of the other GoF patterns implemented in JavaScript.

Essential JavaScript & jQuery Design Patterns (Last updated April 30, 2012)

Title: Design Patterns for Javascript


问:
The modern way to perform error handling...
I've been pondering this problem for a while now and find myself continually finding caveats and contradictions, so I'm hoping someone can produce a conclusion to the following:

Favour exceptions over error codes

As far as I'm aware, from working in the industry for four years, reading books and blogs, etc. the current best practice for handling errors is to throw exceptions, rather than returning error codes (not necessarily an error code, but a type representing an error).

But - to me this seems to contradict...

Coding to interfaces, not implementations

We code to interfaces or abstractions to reduce coupling. We don't know, or want to know, the specific type and implementation of an interface. So how can we possibly know what exceptions we should be looking to catch? The implementation could throw 10 different exceptions, or it could throw none. When we catch an exception surely we're making assumptions about the implementation?

Unless - the interface has...

Exception specifications

Some languages allow developers to state that certain methods throw certain exceptions (Java for example, uses the throws keyword.) From the calling code's point of view this seems fine - we know explicitly which exceptions we might need to catch.

But - this seems to suggest a...

Leaky abstraction

Why should an interface specify which exceptions can be thrown? What if the implementation doesn't need to throw an exception, or needs to throw other exceptions? There's no way, at an interface level, to know which exceptions an implementation may want to throw.

So...

To conclude

Why are exceptions preferred when they seem (in my eyes) to contradict software best practices? And, if error codes are so bad (and I don't need to be sold on the vices of error codes), is there another alternative? What is the current (or soon to be) state of the art for error handling that meets the requirements of best practices as outlined above, but doesn't rely on calling code checking the return value of error codes?

答:
I find that exceptions allow to write a more structured and concise code for reporting and handling errors: using error codes requires checking return
values after every call and deciding what to do in case of an unexpected result.

On the other hand I agree that exceptions reveal implementation details that should be hidden to the code invoking an interface. Since it is not possible to know a priori which piece of code can throw which exceptions (unless they are declared in the method signature like in Java), by using exceptions we are introducing very complex implicit dependencies between different parts of the code, which is against the principle of minimizing dependencies.

Summarizing:

I think exceptions allow a cleaner code and a more aggressive approach to testing and debugging because uncaught exceptions are much more visible and difficult to ignore than error codes (fail soon).

On the other hand, uncaught exception bugs that are not discovered during testing can appear in a production environment in the form of a crash. In certain circumstances this behaviour is not acceptable and in this case I think using error codes is a more robust approach.


问:
If you were the manager of a team of 25 developers, how would you motivate them?
Imagine yourself hired by a new startup backed with few millions coming from venture capitalists.

Your mission: organize the development of the next killer app.

25 developers is too much to take care of each individually, so what decision(s) you would make to motivate them?

I will appreciate any answers from stock options to free cookies ;)

Of course the trick here (unless you are really a manager of a such startup), is put yourself in the shoes of one of those programmers.

EDIT: it's an imaginary context. The purpose of this story is to stimulate your wishes. I want to capture what motivates developers.

答:
I agree with Dima and ChrisF. Except on one of Dima's points: stock options.

I know that this is a regional thing, but in many countries, stock options are taxed by the state at their actual value (inner value) when assigned or issued. This unless you can proof that the volatility does not allow to calculate an inner value.

I once ended up paying in taxes for my stock options much more than what they were worth. They had a value of $40 each when issued, but I could not exercise them for a year, and by then they were down under a dollar.

But back to your question:

Individual working times, great tools, influence in decision making, an environment free of politics (keep it away from them, so they can work).

Fringe benefits like a budget to spend on their own on tools, books, courses.

NO cubicles, at most 3 people in an office with more than 9 m2 per person. If possible, move the team in its own building or at least on its own floor. Let them personalize their desk - no desk police.

Eliminate phones from their desks (email without sound or instant messaging, again without sound, and telephone booths outside the offices with chairs and small desks for their laptops, no interruption of workflow without urgency). Have a secretary to handle incoming phone calls.

As little meetings as possible. Don't do them on Mondays (Mondays aren't fun anyway, some are still in the weekend, some lose the last energy to start through) or on Fridays (what did I just say about weekends), but Wednesdays are perfect (this gives a nice break in mid week).

Administrative rights on their machines. No first and second level support.

I would not like to be forced to eat with the bunch - I know I am different - as I need a break from being with the same people all day. But a croissant break for informal information exchange, a monthly evening out with no peer pressure to participate every time and with spouses (bowling, dinner) would do it for me.

To second ChrisF: I don't think that anybody can handle 25 direct reports. Form teams. And from time to time organize a competition between them.

OwnerDisplayName: malach