问:
Data service API design
We're designing a data service that will store a large number of statistics about stocks, including historical data. The client will be a web application, which will need to pull various bits of data to show in different places on the site.

Since the different places need to show different sets of statistics, it's not sensible for the service to simply offer one method which retrieves all the data that we have. Since there are so many different types of statistics, the service isn't aware of the type of each one and simply stores them by key.

We previously tried to deal with this by having a number of methods which would return data objects with varying levels of detail, for example getBasicStockInfo, getStockInfo, getFeaturedStockInfo, getStockDetails. The trouble I found with this was that it became tedious to add new items of data to the objects (need to change server code), and each one would get bloated over time as fields are added for some specific locations on the front end. On the other hand, it would be impractical to have a method for each location on the front end that returns the specific data that's needed in that location.

Does anyone have any ideas of how best to handle this situation?

One thing I'm considering is that the client would have to send a list of data keys for the data it wanted, and would get back a map of the statistics. I'm not sure if this is the way to go though, as the weight of parameters would get pretty heavy with the same ones being passed repeatedly from each location in the web app.

答:
Your situation sounds very similar to how SalesForce.com designed their "Core Calls" (link).

They made all "data" objects an extension of a base object so that they can easily create a new one while reusing the same methods.

Title: Data service API design


问:
Is the time spent customizing your dev machine environment worth it?
There are times when I am working on programming project and I get the itch to change some stuff in my environment (OSX or Linux). Vim might not being doing exactly
what I want, so instead of doing it the round about way I've been doing for a
couple months (sometimes years) I go and figure out the right way. Or I may be
doing something long handed in bash and I say to myself why don't I figure out
a better way.

The thing is when I go off and do this hours can fly by. Sometimes I
get stuck on trying to get what I want. I'll know I'm really close, so I don't give
up. I usually always get it eventually, but its after hours of tinkering and
googling. I hate the feeling of giving up and having to deal with something I
know could work better.

When I'm done I have a warm feeling knowing that my environment is a little more smooth
and personalized, but I wonder could my time be better spent. Where do I draw
the line? It seems with the all the UNIX-style tools there is an endless amount
to learn.

Always thought the sign of a superior programmer is someone who goes out of
their way to make the computer bend to their will. Am I doing it right? I figure
the bash shell, unix/linux, and vim will be around forever, so I see it as an investment.

But then again I just spend 3 hours trying to get some stupid thing the vimperator firefox
plugin to work right.

So I wondering what this community think about this.

答: I do stock MS Windows. I don't even bother changing anything. I just add the few apps I need (firefox+firebug+webdeveloper, chrome, that sort of thing) and Putty. Then I shell into the debian servers and there is no GUI environment setup there. I code there. I don't store keys, I don't store passwords in the browser, and I certainly don't store anything I can't live without on the local machine. Then if it stops working (crashed HD, theft, whatever) I just take it to the local recycler and buy another $400 box at Fry's. Oh, and I never ever buy software. This has served me well in the last 15 years. </p>

ContentLicense: CC BY-SA 2.5


问:
Does multiple inheritance violate Single Responsibility Principle?
If you have a class which inherits from two distinct classes, does not this mean that your subclass automatically does (at least) 2 things, one from each superclass?

I believe there is no difference if you have multiple interface inheritance.

To be clear, I believe that if subclassing multiple classes violates SRP, then implementing multiple (non-marker or basic interface (e.g. Comparable)) interfaces violates SRP too.

答:
The SRP is a guideline to avoid god-classes, which are bad, but it also can be taken too literally and a project starts balloon with tons of classes that can't really do anything without a handful being combined. Multiple inheritance/multiple interfaces can be a sign a class is getting too big, but it could also be a sign that your focus is far too granular for the task at hand and your solution is over-engineered, or it could simply be a perfectly valid use case for multiple inheritance and your worries are unfounded.

Software design is as much art as science, its a balancing act of many competing interests. We have rules to help avoid things we know are to far in one direction that cause problems, but those rules can just as easily take us to a place that is just as bad or worse than what we were trying to avoid in the first place.

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 3.0


问:
What makes a component or product "enterprise" software vs non-enterprise ready?

Possible Duplicate:

What is enterprise software, exactly?

What does “enterprise” means in relation to software architecture?

What makes a component or product "enterprise" software vs non-enterprise ready? Is it difficult to use? Is it support contacts? Is it reputation? Is it a level of testing? Is it integration support? Is it marketing? Is it the focus on the customer of the product?

What makes a piece of software "enterprise" software, rather than something that is for general consumption?

For example, Derby DB is for developers, and small apps, but it's not an "enterprise database".

答:
Enterprise ready means "suitable for use in an enterprise."

The needs of an enterprise are often different from those of an individual consumer. Enterprises often need things like: scalability, centralized management, security, robustness, ability to integrate with other systems, and so on.


问:
Why fewer IRQLs in 64-bit, even though an APIC has more interrupt lines?
As x86 computers shifted from 32-bit to 64-bit, they also shifted from using 8259-style Programmable Interrupt Controllers with 8 interrupt lines. (Or two multiplexed PICs for a total of 15 interrupt lines.)  Then, if you were to install 32-bit Windows for an operating system, Windows would implement 32 software IRQLs (Interrupt Request Levels) with IRQLs 3 through 26 (or so) being reserved for devices.

Then the x64 platform came along. You need a machine with an APIC, which has 256 interrupt lines, in order to install 64-bit Windows on it.  However, 64-bit Windows only implements 16 IRQLs.

So my question is, does anyone know why 64-bit Windows would implement fewer IRQLs than its 32-bit counterpart even though it has many more hardware interrupt lines at its disposal?

答:
Because with a DOS  type system you broadly needed an IRQ for each event and so lots of IRQ levels to allow events to mask other events simply.  With a real OS you pretty much just need a single event and let the kernel figure everything else out (actually it's convenient to have a couple of levels for NMI and real-time).

So I'm guessing that with 64bit and knowing that you aren't backward compatible supporting some DOS app on a 386 they took the opportunity to simplify.


问:
How long does one have to wait to consider design change in code?
I had a few days ago. I was having trouble with threads. Had lots of questions asked on StackOverflow and honestly for the first time I did not get the answer I was looking for. Finally, I decided to do a huge re-design of my system code and magically within a few hours I found a solution.

So my question is, is it normal to often do a re-design if I get stuck with a problem or should I push on hard till I find a solution? Mind you this is the first time I was stuck for this long on a piece of code.

答: It's not uncommon to build something and then immediately refactor or redesign it.  In developing software we often decide on very specific details only while coding.  That can raise new ideas or issues that weren't considered during the original design.</p>


答:
Is there a specific reason to stick with the original "solution"? i.e. Backwards compatibility, other part(s) are reliant on that configuration, etc.? If not, I would say that's part of the normal design process.

Personally, just on a simple project I'll find myself refactoring either design or implementation until I've found a solution that works, but also is more efficient (the former being the most important) [red, green, refactor].

Take a more basic approach; Should you solve a problem in ASP.NET and keep brute-forcing problems, or move to [e.g.] perl where a library available would make it very simple to design? If the project doesn't have any other complications it probably makes sense to move to something that would make your life easier (as long as it meets the needs of the original project). However if, for example, the rest of the site is in ASP, it would stand to reason you would keep working on a solution instead of shifting the whole site over because of one problem (even at the expense of additional days of problem solving).

Title: How long does one have to wait to consider design change in code?

Body:
I had a few days ago. I was having trouble with threads. Had lots of questions asked on StackOverflow and honestly for the first time I did not get the answer I was looking for. Finally, I decided to do a huge re-design of my system code and magically within a few hours I found a solution.

So my question is, is it normal to often do a re-design if I get stuck with a problem or should I push on hard till I find a solution? Mind you this is the first time I was stuck for this long on a piece of code.


问:
Do I need to use an interface when only one class will ever implement it?
Isn't the whole point of an interface that multiple classes adhere to a set of rules and implementations?</p>

答:
I would answer that whether you need an interface or not does not depend on how many classes will implement it.  Interfaces are a tool for defining contracts between multiple subsystems of your application; so what really matters is how your application is divided into subsystems.  There should be interfaces as the front-end to encapsulated subsystems, no matter how many classes implement them.

Here's one very useful rule of thumb:

If you make class Foo refer directly to class BarImpl, you're strongly committing yourself to change Foo every time you change BarImpl.  You're basically treating them as one unit of code that's split across two classes.

If you make Foo refer to the interface Bar, you're committing yourself instead to avoid changes to Foo when you change BarImpl.

If you define interfaces at the key points of your application, you give careful thought to the methods that they should support and which they should not, and you comment the interfaces clearly to describe how an implementation is supposed to behave (and how not), your application will be a lot easier to understand because these commented interfaces will provide a sort of specification of the application—a description of how it's intended to behave.  This makes it much easier to read the code (instead of asking "what the heck is this code supposed to do" you can ask "how does this code do what it's supposed to do").

In addition to all of this (or actually because of it), interfaces promote separate compilation.  Since interfaces are trivial to compile and have fewer dependencies than their implementations, it means that if you write class Foo to use an interface Bar, you can usually recompile BarImpl without needing to recompile Foo.  In large applications this can save a lot of time.


问:
What do you look at first: the code or the design?
If you've just been introduced to a new project, what's the first thing you look for to get an idea of how it works?

Do you look for the design first?  If there is a design, what do you look for in it? Class diagrams or deployment diagrams or sequence diagrams or something else?

Or do you go straight for the code? If so, how do you understand how the different layers interact?

答: Then I look at the developer's README, TODO, and Changelog. If I don't understand why the software was written, how it was written, and where it's going... I don't use it. </p>


问:
Developing software for a company outside a company
I work for an IT company as a developer. We are currently working on a large software project, a multi-vendor automatic database clustering solution. We've upheld good coding standards and as a result our code is highly modular and reusable. Many of the modules we've developed could be of great benefit to the open-source community.

There are quite a few developers on our team that contribute to various open-source projects but so far we have not been successful with persuading the employer to consider open-sourcing some of the modules.

A few of us decided that we'd like to contribute code to open-source community while at the same time develop code for the company. Since our employer is not sympathetic towards this cause, contributing code we write during work hours is probably not an option. We have decided to take an alternate approach, write code during our spare time that we can use for both the company and open-source community.

We would like to know what are the caveats of this approach, pottential legal issues and whether someone has a similar experience so we could elaborate our plan further before putting it on the table at work.

答:
It is not uncommon for a company to have a statement claim they have copyright of all code you write while working for them, this has been allowed in the U.S. other countries may differ. In order to legally write code and release it as open source you would need permission in writing from your employer stating you have the rights to X code, or you would have to verify your employer has no such claim to your code.

Including open source code in your work code is also problematic, many companies have a no open source rule or a formal review process for including third party utilities. This is because software licensing can and has ruined companies, and software rights are still pretty grey in some cases so companies often elect to avoid the chance of getting burned by just using a blanket no outside code policy. Even if you company allows third party code you still would have to do your research on what license to release your open source code under, and there are many different options with varying degrees of corporate friendliness.

Unless you have a burning desire to contribute to the open source community and utilize that code in you job it would be best to avoid the potential mess or look for a position at a company more open to allowing you to work on open source projects.


问:
How mature is FreeBASIC?
A friend of mine is considering using FreeBASIC in a critical production environment. They currently use GWBasic, and they want to make a soft transition towards more modern languages. I am just worried that there might be undetected bugs in the software. I see that their version number is 0.22.0, which indicates, that it is not quite mature yet. I also read this discussion, without being able to conclude. Also on their Sourceforge pages there is no indication of whether it is Alpha or Beta (which anyways is not a very good indicator). Does anyone have own experience about the maturity, ideas on how to judge the maturity, or know of companies using FreeBASIC in a critical production environment?</p>

答:
Powerbasic is quite mature, and I would heartily recommend it, especially if dependability and great support are important to you. I personally don't use it anymore because it is not really designed for games programming - for which I use (and recommend) the cross-platform BlitzMax.

That being said, Freebasic should not be too much of a hurdle if you're coming from GWBasic, and seems to be reasonably stable as well. Documentation and forum support are better than average as well.

Still, if I were a company (as opposed to an individual) looking for a solution that will be there and supported for the foreseeable future, I would go with something like Powerbasic. here is a program that can convert QBasic to Powerbasic: http://www.powerbasic.com/support/downloads/files/QB2PBv2.zip

Hope this helps!
Russell

Title: How mature is FreeBASIC?


问:
Entity Framework Joining Tables With Ranged Foreign Key Relationships
I'm not sure if "Ranged Foreign Key Relationship" is an actual term or if I just made it up, but this is what I am talking about:

AgeGroup Table

```<code>int MinAge { get; set; }
int MaxAge { get; set; }
string Description { get; set; }
</code>```

Customer Table

```<code>public int CustomerID { get; set; }
public string Name { get; set; }`
public int Age { get; set; }
public virtual AgeGroup AgeGroup { get; set; }
</code>```

Given the above two tables, how can I join them using the (EntityFramework, DataAnnontations, DbContext) and be able to access Customer.AgeGroup.Description?

Consider the following example data:

AgeGroup

```<code>MinAge MaxAge Description
0      12     Youngin
13     19     Teenager
20     29     Twenties
30     39     Thirties
40     9999   Old
</code>```

Customer

```<code>CustomerID Name        Age
345        Joe Smith   17
493        Cobaltikus  31
631        Jane Doe    29
</code>```

How can I relate these? Cobaltikus has an Age of 31. There is no corresponding AgeGroup record with 31. The corresponding AgeGroup record is the one with MinAge = 30 and MaxAge = 39. I can do this easily in SQL, but how do you do it with EntityFramework?

```<code>SELECT
  AgeGroup.Description

FROM
  Customer,
  AgeGroup

WHERE
  Customer.CustomerID = 493
  AND AgeGroup.MinAge <= Customer.Age
  AND AgeGroup.MaxAge >= Customer.Age
</code>```

答:
The AgeGroup table should not be connected to the Customer table by way of a foreign key or Entity Framework construct.

The AgeGroup table is in fact a lookup table, but the lookup should occur at runtime, not compile time.

You should add some custom code to your model by way of a partial class; and encapsulate this lookup inside of either a property or a 'Get' method.

Here's some example code:

```<code>using System.Linq;

namespace CobaltikusProject.Models
{
    public partial class Customer
    {
        public string AgeGroup
        {
            get { return EFEntities.AgeGroups.Single(a => a.MinAge <= this.Age && this.Age <= a.MaxAge); }
        }
    }
}
</code>```

Body:
The AgeGroup table should not be connected to the Customer table by way of a foreign key or Entity Framework construct.

The AgeGroup table is in fact a lookup table, but the lookup should occur at runtime, not compile time.

You should add some custom code to your model by way of a partial class; and encapsulate this lookup inside of either a property or a 'Get' method.

Here's some example code:

using System.Linq;

namespace CobaltikusProject.Models
{
    public partial class Customer
    {
        public string AgeGroup
        {
            get { return EFEntities.AgeGroups.Single(a => a.MinAge <= this.Age && this.Age <= a.MaxAge); }
        }
    }
}


问:
How to contribute to jQuery?
I'm confused about the nature of the jQuery project.  It can be licensed under either the GPL or the MIT license, according to the comments in the project.  However, the jQuery web site provides a list of team members, as if this were a commercial product.

I have written some code to improve jQuery to work around a nasty bug in Internet Explorer and I would like to know what is the best way to propose my idea to the project.

答:
You'll find everything you need in jQuery's Getting Involved help page:

Filing Bugs and Building Test Cases

This is the best way to contribute to jQuery core. Please read through the full guide detailing How to Report Bugs.

Committing and Pull Requests

If you wish to contribute code to jQuery core please make sure you've first filed a bug report detailing your specific bug or feature request.

Next, create an account on Github (if you haven't done so already).

Create a fork of the jQuery Github project  (More details of forking). More details concerning how to build jQuery can be found in the Downloading jQuery guide.

Before you write any code be sure to create a new branch in your repository in which all the changes will be committed. More details about Git branches can be found in the Pro Git chapter on branches  and in the chapter on remote branches .

After your new branch has been pushed to your repository you can now send a pull request. Be sure to reference the bug(s) that you're fixing in the commit messages and in the pull request description (this helps us to track the changes easier).

We also have a number of Tips for jQuery Bug Patching detailing the exact commands that you need to run in order to properly contribute (and test).

The process seems rather typical of an open source project. The list of team members lists the jQuery board and core contributors, you can't expect everyone who ever committed a single line of code to the project to be listed there. I don't see what's concerning you with that list, every major open source project maintains some sort of lead/core contributors list.

Lastly, since your contribution is about a bug, make sure to search jQuery's issue tracker on whether the bug has already been reported, and if not, report it before doing anything else.

Title: How to contribute to jQuery?


问:
How to deal with code reuse philosophy?
I constantly find myself thinking about code reuse when starting a new project.

To what extent should I make my code reusable?

Should I limit it to the application scope or should I make it reusable outside of the project?

Sometimes, I feel like code reusability may stand in the way of a simple design. Please, share your own understanding and approach of code re-usability.

答:
The code has to work before it can be reused.  So that implies design and (primary) function should come before consideration of code reuse.

It's good to be thinking of reuse, and reusing components you've already written.  But it can sometimes be just as fast, if not faster, just to write the code and get it working.  After you have solved the original problem, you can refactor the code to make it more reusable.

Title: How to deal with code reuse philosophy?


问:
What is Curiosity's packet structure?
For NASA's Interplanetary Network, what does a packet look like? It's obviously a form of redundant protocol, stored at the receiver and with built back up. Is there any documentation on the packet structure or the communication protocol, which has to span 14 minute communications?</p>

答: I don't know about packet structure, but the basic enabling technology is Reed-Solomon coding.  "NASA Tech Briefs" has had articles about this in the past.</p>

Title: What is Curiosity's packet structure?


答:
This is from my experience, but still believe it can be applied and goes along the lines of what GlenH7 mentioned.

I work between 3 companies doing various projects. The companies are sisters of each other with some standard practices and work methodology, but are also unique in a lot of ways. With that said, I generally begin each project fresh and want to just get it done or show progress. Then if I run in to a scenario where I remember a piece of code or functionality that I wrote for a previous project, I'll do one of two things (time dependent):

Fastest Method

Copy the previous code from the the other project (don't have a lot of time) in to my current project.

Second-Fastest Method

Copy the previous code and place it in to a common library, then include that library in the current project (to make moving forward easier).

2b. If I make changes to the other (original) project, I'll refactor it to use the new library [but generally won't do so unless I have to re-touch that project].

Just be warned, test the heck out of the common libraries. Common libraries mean creating dependencies. Dependencies create points of failure. Although you may need something tweaked slightly for your current implementation, you don't know how it will change anything else using that library.

Title: How to deal with code reuse philosophy?

Body:
I constantly find myself thinking about code reuse when starting a new project.

To what extent should I make my code reusable?

Should I limit it to the application scope or should I make it reusable outside of the project?

Sometimes, I feel like code reusability may stand in the way of a simple design. Please, share your own understanding and approach of code re-usability.


答:
I guess it depends on how you define the responsibility. In the classic iostream example it doesn't violate the SRP.  The IOstream is responsible for managing one bidirectional stream.

After you run out of primitive responsibilities you move on to more generic high level responsibilities, after all how do you define the responsibility of your main entry point?  Its responsibility has to be 'be the main entry point' not 'everything my app does' otherwise it is impossible to not violate the SRP and produce an application.

Title: Does multiple inheritance violate Single Responsibility Principle?

Body:
If you have a class which inherits from two distinct classes, does not this mean that your subclass automatically does (at least) 2 things, one from each superclass?

I believe there is no difference if you have multiple interface inheritance.

To be clear, I believe that if subclassing multiple classes violates SRP, then implementing multiple (non-marker or basic interface (e.g. Comparable)) interfaces violates SRP too.


答: Speaking as an "enterprise" software developer, two of the key things are flexibility and scale.  We don't get to declare "Nobody in their right mind would ever assign over 256 separate descriptions to a product".  Nope, you have to do the work of making the software accommodate unlimited numbers of pretty much everything, no matter how little sense it makes, no matter how much faster it would be if we could restrict things to a fixed number.  Pretty much the only time we limit anything is so that sales can sell different versions of the software at different price points (e.g., the "small business version" might restrict you to only 10,000 products or five warehouses or four custom attributes).</p>

Body:
Possible Duplicate:

What is enterprise software, exactly?

What does “enterprise” means in relation to software architecture?

What makes a component or product "enterprise" software vs non-enterprise ready? Is it difficult to use? Is it support contacts? Is it reputation? Is it a level of testing? Is it integration support? Is it marketing? Is it the focus on the customer of the product?

What makes a piece of software "enterprise" software, rather than something that is for general consumption?

For example, Derby DB is for developers, and small apps, but it's not an "enterprise database".


答:
Remember the KISS and YAGNI:

Code re-usability better to be considered once you have your design document ready. This will allow you to see the section/parts of code that are going to be potentially duplicated.

Thus, when you don't have clear design then apply KISS and YAGNI approach in your work !

Title: How to deal with code reuse philosophy?


问:
A good way of creating XML files at run time
Please stare at this structure for a second :)

I should create such a thing all at run time. What are the values that we pass in at run time? the string values you see after "#" are passed in so for example AnimalBio, ClinBio, HumanGenome,etc... So I am thinking of declaring some methods like

```<code>void AddDeclaration(string str) ;
void AddSubClass(string parent, string child);
</code>```

such that when I call them they will create those XML-ish tags for me with the values I pass in such as HumnaBio.

These are around 15000 items that I am gonna add...
What is the best approach that you would suggest for doing this? Do you think using XMLDocument class is the best way of doing it? or do you think I should go with StringBuilder class and add these as strings, or other ways of doing it?

Thanks.

答:
In .NET, your best bet would be to take advantage of built-in XML serialization. This would let your class look and behave like a class and magically generate (and read from) your XML.

If I couldn't get this to go -- which can be a challenge depending on how the XML is specc'd -- you have a few options. One would be a completely custom Xml serialization using IXmlSerializable. Another is just a roll your own approach using XmlDocument or XmlTextWriter or many other Xml oriented classes in .NET. This approach should be generally avoided.


答: I think I would just write a simple document template processor that would take exactly the same XML you posted and go through and replace every "#"-denoted placeholder with a value you specify.  I think going through a resource-heavy XML object is overkill for what you're doing.  I don't know if there's a .NET equivalent to Velocity, but that's the direction I'd take.</p>

Title: A good way of creating XML files at run time

Body:
Please stare at this structure for a second :)

I should create such a thing all at run time. What are the values that we pass in at run time? the string values you see after "#" are passed in so for example AnimalBio, ClinBio, HumanGenome,etc... So I am thinking of declaring some methods like

```<code>void AddDeclaration(string str) ;
void AddSubClass(string parent, string child);
</code>```

such that when I call them they will create those XML-ish tags for me with the values I pass in such as HumnaBio.

These are around 15000 items that I am gonna add...
What is the best approach that you would suggest for doing this? Do you think using XMLDocument class is the best way of doing it? or do you think I should go with StringBuilder class and add these as strings, or other ways of doing it?

Thanks.


答:
There is no such thing as a "ranged foreign key relationship".  This is not something that relational databases handle (at least not with foreign keys).

The way to handle the link between customer and their age group is with a sub-query or a lookup query.  There is no way to do this with a navigation property in EF.  You could create a method on the data context based on a stored procedure that looks up the appropriate age group given a customer key.  This would be almost as easy to use in your code as a navigation property.

Title: Entity Framework Joining Tables With Ranged Foreign Key Relationships

Body:
I'm not sure if "Ranged Foreign Key Relationship" is an actual term or if I just made it up, but this is what I am talking about:

AgeGroup Table

```<code>int MinAge { get; set; }
int MaxAge { get; set; }
string Description { get; set; }
</code>```

Customer Table

```<code>public int CustomerID { get; set; }
public string Name { get; set; }`
public int Age { get; set; }
public virtual AgeGroup AgeGroup { get; set; }
</code>```

Given the above two tables, how can I join them using the (EntityFramework, DataAnnontations, DbContext) and be able to access Customer.AgeGroup.Description?

Consider the following example data:

AgeGroup

```<code>MinAge MaxAge Description
0      12     Youngin
13     19     Teenager
20     29     Twenties
30     39     Thirties
40     9999   Old
</code>```

Customer

```<code>CustomerID Name        Age
345        Joe Smith   17
493        Cobaltikus  31
631        Jane Doe    29
</code>```

How can I relate these? Cobaltikus has an Age of 31. There is no corresponding AgeGroup record with 31. The corresponding AgeGroup record is the one with MinAge = 30 and MaxAge = 39. I can do this easily in SQL, but how do you do it with EntityFramework?

```<code>SELECT
  AgeGroup.Description

FROM
  Customer,
  AgeGroup

WHERE
  Customer.CustomerID = 493
  AND AgeGroup.MinAge <= Customer.Age
  AND AgeGroup.MaxAge >= Customer.Age
</code>```


问:
For csv database extracts, how do map keys not create a dependency?
A lot of my work is done with .csv extracts (reports) from databases. As I have been programming in Clojure, I've received comments that relying on vector indexes creates dependencies. I understand why, and concur.

I am rewriting one of my programs to take advantage of the fact that each report's first row contain the column headings, and I could go after each row of data I want by map key. I am rewriting some code to zipmap the headings made into map keys and one row of data (at a time) so I can access the data I want. Here is an example.

```<code>(def bene-csv-inp  (fetch-csv-data "benetrak_roster.csv"))
(def bene-csv-cols (first bene-csv-inp))
(def bene-csv-data (rest bene-csv-inp))
(def zm1 (zipmap
     (map #(keyword %1) bene-csv-cols)
                        (first bene-csv-data)))
(zm1 :EmploymentStartDate)
"21-Jun-82"
</code>```

Does a higher level of extraction exist, and if so, what is it that would allow my code not to have to have to hard-code :EmploymentStartDate ? If my code has to know these keys, then how is that also not a dependency like an index?

Personally, I like going after the data with map keys, because it's less confusing and more informative than indexes. However, I believe I still have a dependency.

Thanks.

答: Well, you're no longer dependent on the order of the columns in the data, but you're now dependent on the column names.  If someone adds a column to an extract, even if it's in the middle, you're better off, because your code won't break.  If someone deletes or renames a column, you'll still have an issue.  If it's more likely that someone will rename a column than delete or move it, you'd be better off sticking with indexes.  I do agree that it's usually easier to understand code that refers to (hopefully) meaningful names than raw column numbers.  It should make debugging easier too, since if a column is missing you can report "No such column named 'EmploymentStartDate'" rather than "Missing column: 23".</p>


问:
Have you ever found yourself using a specific tool in favor of another just because it looks better?
I found that this was the case with Eclipse.
When I first started learning Java a lot of people told me to start with NetBeans because it's easier, comes with a lot of predefined functionality and most of the configuration is done by default. Indeed it seemed like an easy IDE but I just hated the way it looked. The UI to me was horrible.

Then I downloaded Eclipse. I was pretty impressed with it. Everything looked shiny, fonts looked awesome and the UI in general was amazing compared to NetBeans'. So I stayed with Eclipse.

Has something like this ever happen to you? Should the UI be of such a relevance to a programmer, is this bad ? The problem of the UI extends to everything for me, not only IDE's (e.g. even on linux I have to customize the WM the way I want before starting working with it).

答: Definitely. For instance, my Eclipse vs. NetBeans decision went in favor of NetBeans. Recently I started using Sublime Text editor. It's a good editor, but what differentiates it from dozens of other good editors out there is exactly the UI.</p>


问:
parsing terminology: comments+whitespaces vs actual code
In languages like c/c++ spacing and comments are ignored and only actual code gets into compiler.
I'm interested if there is accepted way of naming these two things?

comments & spacing

everything else (actual code)

Referring to comments & spacing as "comments & spacing" is quite annoying.
Any ideas?

答:
When whitespace and comments are discarded during parsing, you are left with the Abstract Syntax Tree (AST).

This is a structure representing the rest of the code and you can simply refer to that "thing" as the AST.

I don't believe there is a specific name for "comments & spacing" except for - comments & whitespace (I guess they don't really have a specific name because they are discarded during parsing to the AST).

As @delnan commented, whitespace and comments are discarded by the tokenizer and the rest is built into the parse tree, which is a pre-cursor to the AST, so you could effectively also use "parse tree" as a name.


答:
From the wiki-page:

Communications: Curiosity is equipped with significant telecom redundancy with several means of communication – an X band transmitter and receiver that can communicate directly with Earth, and a UHF Electra-Lite software-defined radio for communicating with Mars orbiters.

You'll probably find the exact information you're looking for in these two pdfs:

Mars Science Laboratory Telecommunications System Design

Recommendation for Space Data System Standards PROXIMITY-1 SPACE LINK PROTOCOL—
PHYSICAL LAYER

Recommendation for Space Data System Standards PROXIMITY-1 SPACE LINK PROTOCOL—
DATA LINK LAYER

Title: What is Curiosity's packet structure?

Body: For NASA's Interplanetary Network, what does a packet look like? It's obviously a form of redundant protocol, stored at the receiver and with built back up. Is there any documentation on the packet structure or the communication protocol, which has to span 14 minute communications?</p>


答:
Sometimes I find that copy & pasting few lines of code is a better solution. Even in human language, when you wanna say a sentence you said before just with a slight variation, you'll repeat it with the variation, because it makes less trouble for anyone.

However, if your large module needs to be used in a slightly different way that it doesn't support, don't clone it just to modify few lines because it's very probable that you will want to extend the functionality that both the base and the clone share in the future. Instead, just make it configurable or export the functionality that both the base and the clone share into another module that they will both use.

Title: How to deal with code reuse philosophy?


问:
Public-private key pair handling on a Windows ecosystem
I've been thinking about how to architect an infrastructure for one of our business applications with the following requirement:

Data written by some user can only be read by that user and his superior and a 3rd person yet to be defined

I'm thinking in using some sort of asymmetric algorithm, such as RSA for data encryption.

We can generate a public-private key pair for each user and store the public key of each one openly on a database, but how should we handle the private key ?

If we just let the users manage their private key one day we will have a big headache if one of them loses his key.

If the private key becomes public somehow then the data would become public too, rendering the architecture invalid.

Our infrastructure is heavily Microsoft-oriented: All applications are ASP.Net MVC3, our dabatase is SQL Server 2005 and we use Active Directory for user authentication and basic data, such as e-mail/phone number.

How would you guys architect a solution to solve this problem ?

Bottom-line: This is not a banking or financial application, it's some kind of 360-degree personal feedback system.

EDIT:
Adding more requirements, hoping to make it more clear:

This database will be in production environment, where developers don't have access;

When the database is restored, developers should not be able to recover the data;

The DBA should not be able to view the data by SELECT'ing the rows on the tables;

EDIT 2: Bounty info.
Bounty went to the answer with more upvotes, although my personal feel is that none of the answers provided addressed the question correctly. For this reason, I'm granting the bounty but not marking the answer as correct.

答:
I would actually recommend against using a key recovery type scheme as you're suggesting.  In general, it's complicated, difficult to maintain, and there are easier ways of achieving your goals.

Schneier has some older articles on key recovery, with some embedded links to additional information.  They don't directly discuss your scenario, but there is a strong degree of relevance.

Key Recovery

Key Recovery #2

Instead, I would recommend using a hierarchical access model.

For simplicity, I'm assuming that the review comments are being stored in some sort of SQL DB structure.

Each entry will be tagged with two identifiers.  First is the employee's DB ID, the second is a group ID.  Groups will be defined based upon departments.

The user access table will keep track of the employee DB ID (could also be the primary key), what department ID the employee contributes to, and what department ID the employee can read from.

The "contributes to" department ID will be the department the employee belongs to.
The "can read from" department ID field would only be set if the user is a supervisor or is the "3rd party to be designated later".

Selects against the 360 review entries can then be joined against the user access table.

When supervisors change, all that has to be updated is the department ID they can read from.  Given your MS environment, it should be pretty easy to set up a scheduled task to synchronize AD information with access in the user access table.

One caveat:  It's worth noting that the DBAs will have access to all of the information.  Put some auditing / tracking in place to discourage their curiosity.  You would still have a similar problem with an encryption key scheme, although it might have been a different person with that ability to circumvent the security settings.

Some additional reading on securing the DB

You'll find the following links of interest for your particular configuration.  I selected MS SQL 2005, but the information for other versions can be switched with the drop down at the top of the pages.

MSDN DB Security considerations

Encrypting a column

Backup / Restore security

I think it's important to keep the overall sensitivity / security level of the application in mind.  You said this was for 360 style feedback, which I rate as needing to protect to prevent embarrassment / foster open communications.  A data breach wouldn't have catastrophic effects upon the company.

Given the relatively low and temporal value of the data, you shouldn't have too many backup files sitting around.  If people are afraid that what they said 3 years ago is going to come back to haunt them then they'll circumvent the feedback process and be less than forthcoming in their reviews.

If you're afraid of some lone wolf in the organization who will crack open the feedback and then spread the juicier tidbits, then I'm afraid you've got larger issues that aren't going to be solved with technology.  How to deal with that really isn't OT for P.SE since technology generally can't solve personnel problems.  Put some reasonable restrictions in place and have the CEO note that willfully violating those restrictions is grounds for termination.


答: Usually I don't refer to them at all in the parser, because the lexer discards them.  Inside the lexer, there's never a need to refer to them as a group.  In conversation, I think most people just consider comments to be implicitly included when you say "whitespace," unless you are specifically distinguishing between comments and whitespace at the time, which doesn't come up that often.</p>

Title: parsing terminology: comments+whitespaces vs actual code

Body:
In languages like c/c++ spacing and comments are ignored and only actual code gets into compiler.
I'm interested if there is accepted way of naming these two things?

comments & spacing

everything else (actual code)

Referring to comments & spacing as "comments & spacing" is quite annoying.
Any ideas?


答:
Yes, Hudson

Hudson is a continouos build engine which slowly is migrating into a distributed script engine, which just happens to be nice.   Nice in its approach to how things are done, nice in how errors are reported, and nice in how it looks.

This common trait shows though very quickly when using Hudson and was the main factor that caused us to stay with Hudson.

So, the graphics are not exceptional, but nice, and indicative of the Hudson program in general.

Title: Have you ever found yourself using a specific tool in favor of another just because it looks better?

Body:
I found that this was the case with Eclipse.
When I first started learning Java a lot of people told me to start with NetBeans because it's easier, comes with a lot of predefined functionality and most of the configuration is done by default. Indeed it seemed like an easy IDE but I just hated the way it looked. The UI to me was horrible.

Then I downloaded Eclipse. I was pretty impressed with it. Everything looked shiny, fonts looked awesome and the UI in general was amazing compared to NetBeans'. So I stayed with Eclipse.

Has something like this ever happen to you? Should the UI be of such a relevance to a programmer, is this bad ? The problem of the UI extends to everything for me, not only IDE's (e.g. even on linux I have to customize the WM the way I want before starting working with it).


问:
Does multiple inheritance violate Single Responsibility Principle?
If you have a class which inherits from two distinct classes, does not this mean that your subclass automatically does (at least) 2 things, one from each superclass?

I believe there is no difference if you have multiple interface inheritance.

To be clear, I believe that if subclassing multiple classes violates SRP, then implementing multiple (non-marker or basic interface (e.g. Comparable)) interfaces violates SRP too.

答:
Not at all.  In Java, you can have an interface that represents some sort of domain object--a Foo, for example.  It may need to be compared to other Foo objects, and so it implements Comparable (with the comparison logic externalized in a Comparator class); it may be that this object also needs to be Serializable, so that it can be transported across the network; and it may need to be Cloneable.  Thus the class implements three interfaces but does not have any logic within to support them beyond that supported by Foo.

That said, it's silly to take the SRP to extremes.  If a class defines more than one method, is it violating the SRP?  All Java Objects have a toString() method and an equals(Object) method, which means EVERY object in Java is responsible for both equality and self-representation.  Is that a bad thing?


问:
Testing my VB.NET code?
I'm having trouble developing unit testing approaches to testing both if the "code does what I want it to do", and testing "does my code work".

For example, I'm writing code to validate input that will be inserted into a database table, so I need to test if my code does what I want it to do - Good input is accepted, bad input is rejected.  Here's some of the code, in VB.NET:

```<code>    'Let's check if we are going to update all the fields that must be updated...
    If record.table.RequiredMustBeSuplied IsNot Nothing Then
        For Each req In record.table.RequiredMustBeSuplied
            If query.UpdateFields(req.Key).value Is Nothing Then
                Throw New ArgumentNullException
            End If
        Next
    End If
</code>```

So, for my unit test I would pass in a query without the proper update fields and expect that  it would result in a ArgumentNullException, and a corresponding test that passes.  The problem that happens to me is later on I'll notice a bug, and realize my code doesn't work correctly. For example, the correct code in this case was:

```<code>    'Let's check if we are going to update all the fields that must be updated...
    If record.table.RequiredMustBeSuplied IsNot Nothing Then
        For Each req In record.table.RequiredMustBeSuplied
            If query.UpdateFields(req.Key).value Is Nothing Then
                Throw New ArgumentNullException
            End If
        Next
    End If
</code>```

So, I was able to test for problems I know about (missing fields) but not a problem I don't know about (the difference between dbnull and nothing).  Is unit testing just not very good at finding these kinds of errors, or is there an approach someone could suggest?

答: Unit tests should be built based on requirements and constraints that you know about. They will only ever be as complete as your thought processes. The wonderful thing, however, is that when you encounter a bug that you had not foreseen or tested, you can create a new unit test that covers that case even before you implement the fix, and then you never have to worry about that bug again. (use TDD for the win)</p>

Title: Testing my VB.NET code?


问:
How secure is localstorage?
The question says it all really. I want to provide a service but I do not want to store any of the data myself in a database. With all the recent news of hacking etc it seems to me that it is nicer that clients have complete control over their data.

The problem is that the data stored is potentially sensitive. What I was going to do was... when a client visits the website there would be a question asking 'are you on a personal computer or a public computer'. If they are on a public computer the site would refuse access.

If they were on a personal computer it would then prompt them to set a password. All their data would then be encrypted with this password. Now obviously this is not too secure. The encryption method would be in JavaScript and their password in plain text so I assume it would be possible for a savvy user to locate the password in the localStorage and access the data.

I feel though that this isn't too much of a problem. If you are using a personal computer the chances of this happening are remote as... someone else would need access to their specific user account on the computer, someone else would need to know about the site... someone else would need to understand localStorage and how to access it. The sensitive data isn't any that will compromise their identity or much else. It just records something most people wouldn't like publicly published.

So really the question is, is localStorage secure enough?

Additional question.. how difficult is to wipe your localStorage? I wouldn't want users to
accidentally wipe their data.

Finally - is it even worth encrypting / decrypting their data as if you have the password you can access the site..

答:
How about getting a key from the server that is used to decrypt the localStorage data?

It could work like this:

When a session is established, the server returns a key.

That key is used to encrypt / decrypt the data in localStorage.

When the user leaves the page, the key is lost, preventing others from reading what's in localStorage.

This should only allow access while a user has an established session.

OwnerDisplayName: JasonS

Title: How secure is localstorage?


问:
Are there any FOSS operating systems available that conform to NASA's JPL coding standards?
I, like many others, have been completely enamored with the recent successful landing of Mar's Curiosity rover.  After reading a couple of articles, and following a few links, I've found a couple C based coding standards that NASA JPL uses to formalize their code and protect it from error. (See here and here.)

This has me curious.  Are there any open-source operating systems available that adhere to these coding standards that are available for common architecture, such as x86, x64 or possibly ARM?

答:
I don't know of an operating system explicitly developed with the rules mentioned in mind but according to a press release by Wind River VxWorks is used as an embedded Operating System.

The great benefit of these coding rules is that they simplify the code review process and formalize the environment. Some operating systems like Linux have coding style guidelines but they typically only cover syntax and don't have such rigid rules and they are probably not as closely reviewed as the code of NASA.

Some of the rules are also only relevant for embedded systems like no dynamic memory after initialization, or may cause problems like the need for IPC instead of functions pointers (this is especially true for operating systems).

An interesting open-source operating system is eCos as you can configure the parts of your OS, e.g. you can explicitly choose what parts you want to include in your system, POSIX compatibility, BSD sockets, TCP/IP stack...


问:
Exceptions or Error codes
We are building a web service(SOAP, .Net) which would be talking to (mostly) native clients (windows, C++) and we are wondering what is the best way to communicate errors to the client (e.g. SomethingBadHappened like login service not available or something like user not found) and haven't been able to decide between throwing exception to the client or using some kind of error code model to do the above.

What you would prefer on the handling on the client side: receiving a error code or handling a ServerFault exception which contains the reason for the error?

1) Why are we thinking exception: Because it would make server side code a lot more uniform

2) Why are we thinking error codes: Because we think it makes more sense from the client side perspective.

If 2) is really true we would probably want to go for error codes than exceptions? Is that the case here?

Also, would the answer change if we were talking to managed clients instead of native clients?

答:
I recently did a web service with the Java 6 libraries, which can report an exception back to the caller (I haven't looked into how as it is done automatically).

The ability to have the client provide a stack trace in the error report to the developer has been very useful (opposed to getting an approximate timestamp and then have to look it up in your logs, if you happen to log it).

So, seen from a developers point of view, use Exceptions.

Title: Exceptions or Error codes


问:
Is there a different usage rationale for abstract classes/interfaces in C++ and Java
According to Herb Sutter one should prefer abstract interfaces (all pure virtual functions) to abstract classes in C++ to decouple the implementation as far as possible. While I personally find this rule very useful, I have recently joined a team with many Java programmers and in the Java code this guideline does not seem to exist. Functions and their implementations are very frequently located in abstract classes.
So did I get Herb Sutter all wrong even for C++ or is there a general difference in the usage of abstract functions in C++ compared to Java. Are abstract classes with implementation code more sensible in Java than in C++ and if yes why ?</p>

答:
The principle holds for both languages, but you're not doing a fair comparison. You should compare C++ pure abstract classes with Java interfaces.

Even in C++, you can have abstract classes that have some of the functions implemented, but derive from a pure abstract class (no implementations). In Java, you'd have the same abstract classes (with some implementations), that can derive from interfaces (no implementations).

OwnerDisplayName: Martin

OwnerDisplayName: Luchian Grigore


答:
Sometimes it makes sense to have some default implementation. For example a generic PrintError(string msg) method that is applicable to all sub classes.

```<code>virtual PrintError(string msg) { cout << msg; }
</code>```

It can still be overridden if really required, but you can save the client some hassle by allowing them just call the generic version.

Title: Is there a different usage rationale for abstract classes/interfaces in C++ and Java

Body:
According to Herb Sutter one should prefer abstract interfaces (all pure virtual functions) to abstract classes in C++ to decouple the implementation as far as possible. While I personally find this rule very useful, I have recently joined a team with many Java programmers and in the Java code this guideline does not seem to exist. Functions and their implementations are very frequently located in abstract classes.
So did I get Herb Sutter all wrong even for C++ or is there a general difference in the usage of abstract functions in C++ compared to Java. Are abstract classes with implementation code more sensible in Java than in C++ and if yes why ?</p>

Body:
Sometimes it makes sense to have some default implementation. For example a generic PrintError(string msg) method that is applicable to all sub classes.

virtual PrintError(string msg) { cout << msg; }

It can still be overridden if really required, but you can save the client some hassle by allowing them just call the generic version.


答: Generally the same OO principles hold true for Java and C++. However, one big difference is that C++ supports multiple-inheritance while in Java you can only inherit from one class. This is the main reason why Java has interfaces I believe, to supplement for the lack of multiple inheritance and probably to restrict what you can do with it (since there is a lot of criticism over the abuse of multiple inheritance). So, probably in a Java programmers mind, there is a stronger distinction between abstract classes and interfaces. Abstract classes are used to share and inherit behavior while interfaces are simply used to add extra functionality. Remember, in Java you can inherit from only one class, but you can have many interfaces. In C++ however, pure abstract classes (i.e. a "C++ interface") are used to share and inherit behavior unlike the purpose of a Java interface (although you are still required to implement the functions), hence the usage is different from Java interfaces.

OwnerDisplayName: Jesse Good


问:
Do I need to use an interface when only one class will ever implement it?
Isn't the whole point of an interface that multiple classes adhere to a set of rules and implementations?</p>

答: One reason you still might want to introduce an interface in this case is to follow the Dependency Inversion Principle. That is, the module which uses the class will depend on an abstraction of it (i.e. the interface) instead of depending on a concrete implementation. It decouples high-level components from the low-level components.</p>


问:
Return interface or class
Suppose I have a method

```<code>public List<User> GetBatchOfUsers(IEnumerable<int> userIDs)
{
    List<User> users = new List<User>();

    // some database stuff

    return users;
}
</code>```

I have read that it would be better to return an interface (either IList or IEnumerable) as opposed to returning a List.  Some arguments I have heard for doing so is that it hides data, and gives the API developer the flexibility of changing the internal representation of the data at a later date.

My concern about just returning an IEnumerable is that you lose functionality, such as random access and the Count property.

I know that accepting an IEnumerable as a parameter makes sense, as it gives the consumer the best flexibility to send data to my method, the minimalist set of requirements for the method to operate.

What is the best practice for the return type?

答:
Generally speaking, you may start with interfaces, and only move to put the concrete type as the return type if you find that you use the extra methods more frequently than expected.

Well, if you return an interface, you retain more flexibility. You can change the implementation later to return a different concrete type. On the other hand, it obviously gives the caller less information, so they may not be able to perform certain operations. (For example: if you return List<T>, the caller can use ConvertAll etc... which they can't if you only declare that you return IList<T>.) In some situations it's worth specifying the concrete type.

Regarding Count or Sort method, there is no standard collection interfaces for that . However, you could write an extension method to sort or count any IList.

Title: Return interface or class


问:
Better way to search for text in two columns
Here is the scenario. I am making a custom blogging software for my site. I am implementing a search feature. It's not very sophisticated - basically it just takes the search phrase entered and runs this query:

```<code>$query="SELECT * FROM `blog` WHERE `title` LIKE '%$q%' OR `post` LIKE '%$q%'";
</code>```

Which is meant to simply search the title and post body for the phrase entered. Is there a better way to do that, keeping in mind how long it would take to run the query on up to 100 rows, each with a post length of up to 1500 characters? I have considered using a LIMIT statement to (sometimes) restrict the number of rows that the query would examine. Good idea?

答:
EHm, I agree with @Mike Brown Answer, With full text search, your blog will be better. Because  full text seerch user can type the second word and others.

First yout table must be MyISAM with ALTER TABLE blog ENGINE=MyISAM

and add your table column with full text.

so you will change your query like this

```<code>  $query="SELECT * FROM `blog` WHERE MATCH (title,post) AGAINST('+$q' IN BOOLEAN MODE)";
</code>```

I Hope it Help you. :)

Body:
EHm, I agree with @Mike Brown Answer, With full text search, your blog will be better. Because  full text seerch user can type the second word and others.

First yout table must be MyISAM with ALTER TABLE blog ENGINE=MyISAM

and add your table column with full text.

so you will change your query like this

  $query="SELECT * FROM `blog` WHERE MATCH (title,post) AGAINST('+$q' IN BOOLEAN MODE)";

I Hope it Help you. :)


问:
What parts of your coding standard contribute to quality code?
In response to This Question, I ask:   What are the best parts of your coding standard?

What are the best practices that help with code quality, reliability, maintainability, readability, etc.

Please include the language, the item from the standard, and the reason it improves your code.

答:
In Java.

Invoke the Eclipse source code formatter automatically every time a file is saved.

This means that source code changes are registered at the first commit afterwards, instead of some later time when a reformat is done.  This is good when doing "when was this changed" investigations.


答: If You need your collection to have a Count you can use ICollection<T>, which is general enough.

Title: Return interface or class

Body:
Suppose I have a method

```<code>public List<User> GetBatchOfUsers(IEnumerable<int> userIDs)
{
    List<User> users = new List<User>();

    // some database stuff

    return users;
}
</code>```

I have read that it would be better to return an interface (either IList or IEnumerable) as opposed to returning a List.  Some arguments I have heard for doing so is that it hides data, and gives the API developer the flexibility of changing the internal representation of the data at a later date.

My concern about just returning an IEnumerable is that you lose functionality, such as random access and the Count property.

I know that accepting an IEnumerable as a parameter makes sense, as it gives the consumer the best flexibility to send data to my method, the minimalist set of requirements for the method to operate.

What is the best practice for the return type?


问:
How can I test PHP skills in a interview?
My company needs to hire a PHP developer, but nobody has PHP knowledge in my company and we find difficult to test for PHP skills. If it were a C/Java developer I would ask him to write a quick implementation of the Game of Life, but PHP is a completely different language.

I saw this test with interest:

http://vladalexa.com/scripts/php/test/test_php_skill.html

Anyone else has more suggestions?

答:
The test you linked to is interesting, and Yannis Rizos's answer is great, but I think what is also important is this:

If you need a good developer do not look for PHP developer. Look for a good developer who knows PHP. That means, at least half of the interview you should be asking questions that do not have much to do with PHP syntax or PHP functions.

Ask him what is MVC, what is AJAX, how HTTP works, how REST works, how SQL joins work, some data structures, some performance basics (how you measure, how you improve), testing basics, security basics (XSS, XSRF, injections, how you defend), basic programming craft knowledge as applied to typical PHP domains - web, networking, data transformations, etc.

If he's good on that, proceed to asking him to write some simple code, pick some easy task that should not take long - like finding words with most vowels in a row in the text, or reversing each word in the text, or multiplying two matrices. You can also ask him to implement the Game of Life in PHP, if you like :)

If he passes that, then you can proceed to more tricky PHP questions, but don't put too much weight into this. He can read most of it in the manual, and what he can't read, he'll learn quite quickly if he's good. PHP is built to be simple, so if he's a good programmer, and has some working knowledge of PHP, he'll probably be able to catch up. If he knows how to program in general, then learning how to program in PHP is easier than the reverse - knowing PHP syntax minutia is not important if you don't understand what unit tests are for or how to get rid of XSS problems.


问:
How big does my project need to be for me to unit test it?
I assume that my project is decoupled enough to allow for unit testing. But how big, exactly, in terms of clases and functions does my project need to be to make unit testing worthwhile?

We all make mistakes and no one's perfect, but I consider myself a decent programmer to handle small projects' errors with stepping through. Or is unit testing a hard necessity no matter of what size your project is?

答:
Your project is big enough already.

In my experience, one class and one function have been sufficient to consider the need for unit testing.

```<code>    class Simple {
        boolean reallySimple() {
            return true; // how do we make sure it doesn't change to false?
        }
    }

    class SimpleTest {
        void assertReallySimple() {
            // ensure reallySimple return value isn't changed unexpectedly
            UnitTestFramework.assertTrue(new Simple().reallySimple());
        }
    }
</code>```

Body:
Your project is big enough already.

In my experience, one class and one function have been sufficient to consider the need for unit testing.

    class Simple {
        boolean reallySimple() {
            return true; // how do we make sure it doesn't change to false?
        }
    }

    class SimpleTest {
        void assertReallySimple() {
            // ensure reallySimple return value isn't changed unexpectedly
            UnitTestFramework.assertTrue(new Simple().reallySimple());
        }
    }


答:
It's simple: you don't need unit testing if you will discard the program after running it once.

If this seems excessive to you, consider what the alternative would mean. If there were some size below which unit testing doesn't pay, you would have to keep judging in your mind: "Have I reached the magic size yet? Should I start writing tests?" Now, programmers are notoriously bad at predicting the future, and they are notoriously bad at judging their own skill. Code that looks crystal-clear to you now will become incomprehensible, even to you, even by waiting a month. A project that you are absolutely, positively certain will never be used again, and that you keep around merely on the remote chance that you might want to look up how you solved something before, will be requested again, and will receive change requests.

It is therefore very likely that you will misjudge whether or not testing is helpful, and when you do start needing tests, you're already not 100% sure what the exact semantics to test actually are. Since I believe that all except trivial one-off programs profit from unit tests, I consider the cost of expending effort on tests that are never run again to be negligible against the risks of extending untested and ill-understood code.

Title: How big does my project need to be for me to unit test it?

Body:
I assume that my project is decoupled enough to allow for unit testing. But how big, exactly, in terms of clases and functions does my project need to be to make unit testing worthwhile?

We all make mistakes and no one's perfect, but I consider myself a decent programmer to handle small projects' errors with stepping through. Or is unit testing a hard necessity no matter of what size your project is?


答:
Unit tests are implemented to save time and improve:

bug tracking

refactoring and/or re-writing code

integration testing

regression testing, etc.

It is a must to write unit tests for relatively complex parts of the program.

If you are sure that writing unit tests now will not save your time in future, you can skip it. However, you never know, and personally I can't think of a case when it is cheaper (in sense of time, money and nerves) not to write unit tests but do all the testing manually instead.


答:
I've never bought into the "you must unit test everything" idea, though there are certainly folks out there who have (see gnat's answer!).

As far as I'm concerned, the main benefits of unit testing are:

Helping ensure changes don't break things.

Helping you design sensible interfaces to your classes (since it forces you to be a client to your own code).

Helping document how your code is expected to be used.

Basically you need to weigh the time it will take you to write & maintain tests against these factors.

Number 1 is usually sufficient to make it worth writing tests. In my experience, >95% of code gets modified sooner or later.


答:
Test as soon as you observe regressions happen or fear causing some with your edits and not noticing.

Kindle that fear, let it grow to an adequate size: the sooner you test, the better.

Please note: depending on your role in the project, unit tests may not be the only kind of tests you want to write.

Everybody is rightfully obsessed with unit tests, because of bad mainstream testing practices in the past; but if you never tested before, you really should focus on testing in general, unit testing alone isn't going to solve world's problems.


答: Your specifications should cover conditions that is known in the system artifacts, such as schema and business rules. However, as many developers do, the jump into code without taking the time to study the database design or even the specific requirements. This makes constructing complete test cases error prone because the development activity becomes mingled with design activity. Usually programming dominates since it consumes most of the effort and time. My point is you can avoid many problems if you take the time to design and spec out the problem at hand before coding.</p>

Title: Testing my VB.NET code?

Body:
I'm having trouble developing unit testing approaches to testing both if the "code does what I want it to do", and testing "does my code work".

For example, I'm writing code to validate input that will be inserted into a database table, so I need to test if my code does what I want it to do - Good input is accepted, bad input is rejected.  Here's some of the code, in VB.NET:

```<code>    'Let's check if we are going to update all the fields that must be updated...
    If record.table.RequiredMustBeSuplied IsNot Nothing Then
        For Each req In record.table.RequiredMustBeSuplied
            If query.UpdateFields(req.Key).value Is Nothing Then
                Throw New ArgumentNullException
            End If
        Next
    End If
</code>```

So, for my unit test I would pass in a query without the proper update fields and expect that  it would result in a ArgumentNullException, and a corresponding test that passes.  The problem that happens to me is later on I'll notice a bug, and realize my code doesn't work correctly. For example, the correct code in this case was:

```<code>    'Let's check if we are going to update all the fields that must be updated...
    If record.table.RequiredMustBeSuplied IsNot Nothing Then
        For Each req In record.table.RequiredMustBeSuplied
            If query.UpdateFields(req.Key).value Is Nothing Then
                Throw New ArgumentNullException
            End If
        Next
    End If
</code>```

So, I was able to test for problems I know about (missing fields) but not a problem I don't know about (the difference between dbnull and nothing).  Is unit testing just not very good at finding these kinds of errors, or is there an approach someone could suggest?


问:
SQL: empty string vs NULL value
I know this subject is a bit controversial and there are a lot of various articles/opinions floating around the internet. Unfortunatelly, most of them assume the person doesn't know what the difference between NULL and empty string is. So they tell stories about surprising results with joins/aggregates and generally do a bit more advanced SQL lessons. By doing this, they absolutely miss the whole point and are therefore useless for me. So hopefully this question and all answers will move subject a bit forward.

Let's suppose I have a table with personal information (name, birth, etc) where one of the columns is an email address with varchar type. We assume that for some reason some people might not want to provide an email address. When inserting such data (without email) into the table, there are two available choices: set cell to NULL or set it to empty string (''). Let's assume that I'm aware of all the technical implications of choosing one solution over another and I can create correct SQL queries for either scenario. The problem is even when both values differ on the technical level, they are exactly the same on logical level. After looking at NULL and '' I came to a single conclusion: I don't know email address of the guy. Also no matter how hard i tried, I was not able to sent an e-mail using either NULL or empty string, so apparently most SMTP servers out there agree with my logic. So i tend to use NULL where i don't know the value and consider empty string a bad thing.

After some intense discussions with colleagues i came with two questions:

am I right in assuming that using empty string for an unknown value is causing a database to "lie" about the facts? To be more precise: using SQL's idea of what is value and what is not, I might come to conclusion: we have e-mail address, just by finding out it is not null. But then later on, when trying to send e-mail I'll come to contradictory conclusion: no, we don't have e-mail address, that @!#$ Database must have been lying!

Is there any logical scenario in which an empty string '' could be such a good carrier of important information (besides value and no value), which would be troublesome/inefficient to store by any other way (like additional column). I've seen many posts claiming that sometimes it's good to use empty string along with real values and NULLs, but so far haven't seen a scenario that would be logical (in terms of SQL/DB design).

P.S. Some people will be tempted to answer, that it is just a matter of personal taste. I don't agree. To me it is a design decision with important consequences. So i'd like to see answers where opion about this is backed by some logical and/or technical reasons.

答: I think Dean Hardings answer covers this really nicely. That said I would like to mention that when talking about NULLs vs empty strings at the DB level you should have a think about your other data types. Would you store min date when no date is supplied? or -1 when no int is supplied? Storing a value when you have no value means you then have to keep track of a whole range of non values. At least one for each data type (possibly more as you get cases where -1 is an actual value so you need to have some alternative etc). If you need/want to do something "fudgy" at the application level that is one thing but their is no need to pollute your data.</p>

Title: SQL: empty string vs NULL value


答:
Some time ago I found a nice post: Why unit testing  speeds up development.
It can help you answer the question.

...What if the codebase... was provided with a substantial set of unit tests. A set that would say : “if all tests succeed, I guarantee that code still does what it should do” and if a test fails it exactly shows you where some behavior is broken . This is great, I could change the code to add things I want without wandering if the code still does what it should do, I just run the... tests and I have faith. This is a great world to be in as a software engineer. I noticed that I could advance way faster...

I have “faith”.

This is probably the most important reason why unit tests speed up development in a enterprise context.

I can trust that everything still works if all tests pass. If tests fail they will point out exactly where the problem lays...

...you have to have a high unit test coverage and good unit tests. When these conditions are respected you’ll find yourself in a situation that the effort for adding new functionality ‘s is almost independent of the size of the application and that in the long run it will speed up development.

Michael Feathers introduced in one of his books two ways of working with changes in code:

edit and pray,

cover and modify.

It does not matter how big is the code base.


问:
Is it wise to be going back and forth between two programming languages?
I have been writing quite a lot of PHP for nearly two years. Now I am doing .NET (mainly c#) development. However, sometimes I go back and do some php.

My main question is, is it wise for me to continue doing this or should I continue development in C#? Would this harm me in the long run (mind you my main goal is not to be a jack o all trades) or is it a good practice to be doing?

答: It shouldn't harm you in the long run, being proficient in a number of languages makes you a well-rounded developer. Using "the right tool to do the right job" is the ultimate goal and being versed in different languages helps you achieve that as you know what else is out there and can make a well informed decision about what platform/framework/language to use to get something done.</p>


答:
Using two languages at the same time is nothing. It’s not uncommon for programmers to use several different languages every day. Different tasks and different technologies require different languages.

Just today, I’ve already used four or five different languages, and that’s interesting because I haven’d done any programming so far. All I’ve done is work on a presentation.

As a good programmer it’s essentially required that you know your way around in several languages, and the only way of attaining (and then preserving) reasonable fluency is by using those languages.

Title: Is it wise to be going back and forth between two programming languages?

Body:
I have been writing quite a lot of PHP for nearly two years. Now I am doing .NET (mainly c#) development. However, sometimes I go back and do some php.

My main question is, is it wise for me to continue doing this or should I continue development in C#? Would this harm me in the long run (mind you my main goal is not to be a jack o all trades) or is it a good practice to be doing?


答:
is it a good practice to be doing?

It is an excellent practice. Moreover, I would recommend expanding your list of languages regularly by trying out a new one.

Languages and technologies go in and out of favor very quickly, in a matter of a few years. For example, Objective C took off with an amazing strength after being nearly dead for two and a half decades - an eternity by the standards of this industry!

It does not matter much that you are planning to "not be a jack o all trades": if you are planning to remain in the industry long enough, it is very safe to assume that you would have to switch your technology stack at least once throughout your career. Using multiple languages now keeps you prepared to switch on a reasonably short notice.


答:
In Python, use only the standard library, and if you can't avoid using another library, explain why somewhere. Someday that lib may need to be replaced and it would be nice to know where to start.

Also, keep it very very simple.

Title: What parts of your coding standard contribute to quality code?

Body:
In response to This Question, I ask:   What are the best parts of your coding standard?

What are the best practices that help with code quality, reliability, maintainability, readability, etc.

Please include the language, the item from the standard, and the reason it improves your code.


答:
"Should I unit test this" can usually be answered by answering the following question: "Is it important that this function works properly, and is it important for me to know when it stops working?"

Of course, it's a lot more complicated than that, but that's a good way to start. Eventually you'll also weigh whether the code is already being tested by virtue of being used in another function, or whether your time would be better spent in another function, etc.


答: You return what is prudent for the method you're defining. Is what you're doing returning a series of items (the focus is on the items), or is it returning a collection of items (the focus is on the collection as a whole)? Is it worthwhile to allow variance in the implementation of the collection? If it will never make sense to use a generator or HashSet then just use the List.

Title: Return interface or class


答:
Specific to the example method: You're right that returning IEnmuerable<T> would mean you would lose the functionality of Count and indexing (although you could use LINQ methods Count() and ElementAt(), which are implemented efficiently if the type they're used on actually implements IList<T>).

If you returned IList<T>, you would lose some functionality, but the gain in generality is probably worth it.

But even better would be something between IEnumerable<T> and IList<T>, because it most likely doesn't make sense for the consumer to mutate the returned collection, but it does make sense for him to use Count or indexing.

In .Net 4.5, there is such interface: IReadOnlyList<T>.

Title: Return interface or class


答:
It looks like the answers on both sides of the fence can be summed up in this:

Design well, and put interfaces where interfaces are needed.

As I noted in my response to Yanni's answer, I don't think you can ever have a hard and fast rule about interfaces. The rule needs to be, by definition, flexible. My rule on interfaces is that an interface should be used anywhere you're creating an API. And an API should be created anywhere you're crossing the boundary from one domain of responsibility into another.

For (a horribly contrived) example, let's say you're building a Car class. In your class, you'll certainly need a UI layer. In this particular example, it takes the form of an IginitionSwitch, SteeringWheel, GearShift, GasPedal, and BrakePedal. Since this car contains an AutomaticTransmission, you don't need a ClutchPedal. (And since this is a terrible car, there is no A/C, radio, or seat. As a matter of fact, the floorboards are missing too - you just have to hang on to that steering wheel and hope for the best!)

So which of these classes need an interface? The answer could be all of them, or none of them - depending on your design.

You could have an interface that looked like this:

```<code>Interface ICabin
    Event IgnitionSwitchTurnedOn()
    Event IgnitionSwitchTurnedOff()
    Event BrakePedalPositionChanged(int percent)
    Event GasPedalPositionChanged(int percent)
    Event GearShiftGearChanged(int gearNum)
    Event SteeringWheelTurned(float degree)
End Interface
</code>```

At that point, the behavior of those classes becomes part of the ICabin Interface/API. In this example the classes (if there are some) are probably simple, with a few properties, and a function or two. And what you are implicitly stating with your design is that these classes exist solely to support whatever concrete implementation of ICabin you have, and they cannot exist on their own, or they are meaningless outside of the ICabin context.

It's the same reason that you don't unit-test private members - they exist only to support the public API, and thus their behavior should be tested by testing the API.

So if your class exists solely to support another class, and conceptually you view it as not really having it's own domain then it's fine to skip the interface. But if your class is important enough that you consider it grown up enough to have it's own domain, then go ahead and give it an interface.

EDIT:

Frequently (including in this answer) you'll read things like 'domain', 'dependency' (frequently coupled with 'injection') that don't mean a thing to you when you're beginning to program (they sure didn't mean anything to me). For domain, it means exactly what it sounds like:

The territory over which dominion or authority is exerted;
          the possessions of a sovereign or commonwealth, or the
          like. Also used figuratively. [WordNet sense 2]
          [1913 Webster]

In the terms of my example - let's consider the IgnitionSwitch. In a meatspace car, the ignition switch is responsible for:

Authenticating(not identifying) the user (they need the correct key)

Providing current to the starter so it can actually start the car

Providing current to the ignition system so it can continue to operate

Shutting off current so the car will stop.

Depending on how you view it, in most (all?) newer cars there's a switch that prevents the key from being removed from the ignition while the transmission is out of Park, so this could be part of its domain. (Actually it means I need to rethink and redesign my system...)

Those properties make up the domain of the IgnitionSwitch, or in other words, what it knows about and is responsible for.

The IgnitionSwitch is not responsible for the GasPedal. The ignition switch is completely ignorant of the gas pedal in every way. They both operate completely independent of one another (though a car would be fairly worthless without both of them!).

As I originally stated, it depends on your design. You could design an IgnitionSwitch that had two values: On (True) and Off (False). Or you could design it to authenticate the key provided for it, and a host of other actions. That's the hard part of being a developer is deciding where to draw the lines in the sand - and honestly most of the time it's completely relative. Those lines in the sand are important though - that's where your API is, and thus where your interfaces should be.

Title: Do I need to use an interface when only one class will ever implement it?

Body: Isn't the whole point of an interface that multiple classes adhere to a set of rules and implementations?</p>

Body:
It looks like the answers on both sides of the fence can be summed up in this:

Design well, and put interfaces where interfaces are needed.

As I noted in my response to Yanni's answer, I don't think you can ever have a hard and fast rule about interfaces. The rule needs to be, by definition, flexible. My rule on interfaces is that an interface should be used anywhere you're creating an API. And an API should be created anywhere you're crossing the boundary from one domain of responsibility into another.

For (a horribly contrived) example, let's say you're building a Car class. In your class, you'll certainly need a UI layer. In this particular example, it takes the form of an IginitionSwitch, SteeringWheel, GearShift, GasPedal, and BrakePedal. Since this car contains an AutomaticTransmission, you don't need a ClutchPedal. (And since this is a terrible car, there is no A/C, radio, or seat. As a matter of fact, the floorboards are missing too - you just have to hang on to that steering wheel and hope for the best!)

So which of these classes need an interface? The answer could be all of them, or none of them - depending on your design.

You could have an interface that looked like this:

Interface ICabin
    Event IgnitionSwitchTurnedOn()
    Event IgnitionSwitchTurnedOff()
    Event BrakePedalPositionChanged(int percent)
    Event GasPedalPositionChanged(int percent)
    Event GearShiftGearChanged(int gearNum)
    Event SteeringWheelTurned(float degree)
End Interface

At that point, the behavior of those classes becomes part of the ICabin Interface/API. In this example the classes (if there are some) are probably simple, with a few properties, and a function or two. And what you are implicitly stating with your design is that these classes exist solely to support whatever concrete implementation of ICabin you have, and they cannot exist on their own, or they are meaningless outside of the ICabin context.

It's the same reason that you don't unit-test private members - they exist only to support the public API, and thus their behavior should be tested by testing the API.

So if your class exists solely to support another class, and conceptually you view it as not really having it's own domain then it's fine to skip the interface. But if your class is important enough that you consider it grown up enough to have it's own domain, then go ahead and give it an interface.

EDIT:

Frequently (including in this answer) you'll read things like 'domain', 'dependency' (frequently coupled with 'injection') that don't mean a thing to you when you're beginning to program (they sure didn't mean anything to me). For domain, it means exactly what it sounds like:

The territory over which dominion or authority is exerted;
          the possessions of a sovereign or commonwealth, or the
          like. Also used figuratively. [WordNet sense 2]
          [1913 Webster]

In the terms of my example - let's consider the IgnitionSwitch. In a meatspace car, the ignition switch is responsible for:

Authenticating(not identifying) the user (they need the correct key)

Providing current to the starter so it can actually start the car

Providing current to the ignition system so it can continue to operate

Shutting off current so the car will stop.

Depending on how you view it, in most (all?) newer cars there's a switch that prevents the key from being removed from the ignition while the transmission is out of Park, so this could be part of its domain. (Actually it means I need to rethink and redesign my system...)

Those properties make up the domain of the IgnitionSwitch, or in other words, what it knows about and is responsible for.

The IgnitionSwitch is not responsible for the GasPedal. The ignition switch is completely ignorant of the gas pedal in every way. They both operate completely independent of one another (though a car would be fairly worthless without both of them!).

As I originally stated, it depends on your design. You could design an IgnitionSwitch that had two values: On (True) and Off (False). Or you could design it to authenticate the key provided for it, and a host of other actions. That's the hard part of being a developer is deciding where to draw the lines in the sand - and honestly most of the time it's completely relative. Those lines in the sand are important though - that's where your API is, and thus where your interfaces should be.


答:
There is an upside and a downside to this.

Here's the upside...

As others mentioned, being able to learn new and work with many languages and programming tools is almost essential to having a long career in programming. Things change over the years, tools/languages come and go. Sure, there are some people who're content to be programming in the same mainframe COBOL they used in the 1980's but this is a relatively rare situation. Most programmers end up changing tools/languages several times over the course of their career. Sometimes you may get hired because you do know some older technology or know all of languages a company is working with.

The downside is...

Some employers will see you as a "jack of all trades, master of none" and reject your application without giving you a chance. They're looking for a narrow expert in a specific area, not simply a good, well rounded, programmer. Sometimes you may get cut off by HR because you don't have "5 years of continuous experience in [X]". You may be able to avoid this by tailoring your resume to fit the job but this may not help you in a technical interview.

To me, the upside is much better but you do need to be aware that a minority of organizations view it as a negative.


答:
When you were doing PHP development did you write javascript or SQL? In your C# development you could still be using both of those. It isn't quite so cut and dry as using one programming language.

If you are happy doing it, don't worry about it. If you don't want to be doing both (or either) then you have a problem.


问:
What are the Top Developer Productivity Tools/Plugins for Java in Eclipse?
I personally use CodeRush in Visual Studio 2010 to do refactoring, write code faster with templates and generally navigate my code 10 times faster than stock VS.  Recently, I've been working on another Android app and got to thinking...What are the top productivity plugins for Eclipse?

Preferably free. I'm looking for plugins that help write in Java, not PHP or Rails or any of the other languages Eclipse supports.

答:
There are some really helpful plugins to increase productivity, my favourites are:

moreunit

jautodoc

http://www.etc.to/eclipse_bookmarks_plugin

http://andrei.gmxhome.de/anyedit/index.html

OwnerDisplayName: cloudyster


问:
Is there a way to compare and record changes to code without VCS?
I'm working for a client that has no version control system in place. I want to record changes to code without having to add all changes to a spreadsheet. I'm restricted to using Notepad++ so would a plugin or macro for this be another option?</p>

答:
Version control systems are those systems that allows you to capture changes and create a history for files. That's their purpose and the main reason for which they were created.

Therefore if you would like to record changes you should use a version control system, any one out there will do. Nevertheless you should still make and informed decision, and pick the most appropriate one.

Story:
At my current job, during my initial employment weeks, I've received a task of creating a notifications service to be integrated into one of the companies internal applications. It happened that at the exact time the Configuration Manager, that was supposed to give me access to the company's source repository went on holiday. I've simply installed a VCS (Mercurial) locally and continued my work. When the CM came back from holidays, I've committed all my work into the company's repository.

Morale: even if there is no VCS available you can always use one locally.


答:
According to Kent Beck in his answer to Stack Overflow question How deep are your unit tests?, you should test the code that you tend to get wrong.

If I don't typically make a kind of mistake (like setting the wrong variables in a constructor), I don't test for it.


问:
Pass ID or Object?
When providing a business logic method to get a domain entity, should the parameter accept an object or an ID? For example, should we do this:

```<code>public Foo GetItem(int id) {}
</code>```

or this:

```<code>public Foo GetItem(Foo foo) {}
</code>```

I believe in passing objects around, in their entirety, but what about this case where we're getting an object and we only know the ID? Should the caller create an empty Foo and set the ID, or should it just pass the ID to the method? Since the incoming Foo will be empty, except for the ID, I don't see the benefit of the caller having to create a Foo and set its ID when it could just send the ID to the GetItem() method.

答:
Just the single field being used for the lookup.

The caller doesn't have a Foo, it's trying to get one.  Sure, you can make a temporary Foo with all other fields left blank, but that only works for trivial data structures.  Most objects have invariants that would be violated by the mostly-empty-object approach, so avoid it.

Title: Pass ID or Object?


答:
I certainly agree with your conclusion. Passing an id is preferred for some reasons:

It is simple. interface between components should be simple.

Creating a Foo object just for the id means creating false values. Someone can make a mistake and use these values.

int is more platform-wide and can be declared natively in all modern languages. To create a Foo object by the method caller, you'll probably need to create a complex data structure (like json object).

Title: Pass ID or Object?

Body:
When providing a business logic method to get a domain entity, should the parameter accept an object or an ID? For example, should we do this:

```<code>public Foo GetItem(int id) {}
</code>```

or this:

```<code>public Foo GetItem(Foo foo) {}
</code>```

I believe in passing objects around, in their entirety, but what about this case where we're getting an object and we only know the ID? Should the caller create an empty Foo and set the ID, or should it just pass the ID to the method? Since the incoming Foo will be empty, except for the ID, I don't see the benefit of the caller having to create a Foo and set its ID when it could just send the ID to the GetItem() method.