答:
There are different ways to count coverage. Many tools check which lines are executed by tests, but they don't check that the tests actually test anything. So in theory you could have 100% coverage without a single assert in your tests, in effect testing nothing.

However, you say you have 70% coverage, but you don't catch 70% of problems. That is not uncommon, since quite often small subset of your code contains most of the problems. I think Code Complete says something along the lines that 20% of the code causes 80% of the bugs. That problematic area in your code is usually complex and that is why it's usually untested. So you might have good code coverage but the part that is not covered is the part that needs the tests most.

In this article Martin Fowler says test coverage is not a good measurement for quality of your code. It is a good way to find problematic areas in your code. So in your case, assuming your existing tests are good tests, you now should be able to pinpoint the problem area in your code - the remaining 30%.

Title: test coverage reality

Body:
I am NOT doing test driven development and I write my test classes after the actual code is written. In my current project I have a test coverage (Line coverage) of 70% for 3000 lines of Java code. I am using JUnit, Mockito and Sonar for testing. But I feel that I am not actually covering and catching 70% of the problems that can occur.

So my question is in theory is it possible to have a 100% Line coverage, but in reality it is meaningless because of low quality of the test code and maybe a 40% well written test code is much better than a bad 100% coverage? Or we can always say line coverage more or less gives the percentage of all covered issues?


问:
test coverage reality
I am NOT doing test driven development and I write my test classes after the actual code is written. In my current project I have a test coverage (Line coverage) of 70% for 3000 lines of Java code. I am using JUnit, Mockito and Sonar for testing. But I feel that I am not actually covering and catching 70% of the problems that can occur.

So my question is in theory is it possible to have a 100% Line coverage, but in reality it is meaningless because of low quality of the test code and maybe a 40% well written test code is much better than a bad 100% coverage? Or we can always say line coverage more or less gives the percentage of all covered issues?

答:
You're right, a line coverage metric is no guarantee that you have a comprehensive test.  Path coverage (ensuring that every possible route through the code is exercised at least once) is far more important.  However, path coverage is far more difficult to calculate than code coverage is, and code coverage is nonetheless useful (while a line that is covered isn't necessarily comprehensively tested, a line that isn't covered definitely isn't tested at all).

You should pay close attention to the points in your code where the flow of execution branches.  Ternary operations (var = foo()? bar(): baz()) should be of special interest because these are the points that can appear fully covered even when only one of the two available execution paths are followed.

It should also be mentioned that when a portion of the code is not covered by tests, it's often because it's a difficult portion of code to test for various reasons (extremely complicated logic, dependencies that can't be easily mocked, dependant on probabilistic events, intended to generate a probabilistic output, etc).  This is often also the kind of code where testing is most important.  If a module has 95% code coverage in its tests that's still not much use if the uncovered 5% is the part of the code that's mostly likely to harbour bugs.

If code is well designed with testing in mind (cohesive, loosely coupled, utilises dependency injection, etc) then very high code coverage of 90% or higher is definitely possible.  But of course, while it's a useful metric, a high coverage figure doesn't mean your code is well tested.

ContentLicense: CC BY-SA 3.0

Title: test coverage reality


问:
What if globals make sense?
I've got a value that many objects need. For example, a financial application with different investments as objects, and most of them need the current interest rate.

I was hoping to encapsulate my "financial environment" as an object, with the interest rate as a property. But, sibling objects that need that value can't get to it.

So how do I share values among many objects without over-coupling my design? Obviously I'm thinking about this wrong.

答:
In such situations I have successfully introduced (reused) the "context" term with sometimes multiple layers.

This means a singleton, thus "global" object store, from which these kind of objects can be requested. Codes that require them, include the header of the store, and use the global functions to get their object instances (like now, the interest rate provider).

The store may be either:

strictly typed: you include the headers for all the served types and so you can create typed accessors, like InterestRate getCurrentInterestRate();

or generic: Object getObject(enum obType); and only extend the obType enum with the new kinds (obtypeCurrentInterestRate).

The bigger the system, the more usable the latter solution is, for a quite small risk of using the wrong enum. On the other hand, with languages that allow forward type declarations, I think you can use typed accessors without including all the headers in the store.

One more note: you may have multiple instances of the same object type for different uses, like sometimes different Language value for the GUI and for printout, global and session level logs, etc, so the enum / accessor name should NOT reflect the actual type, but the role of the requested instance (CurrentInterestRate).

In the store implementation, you have to manage the context levels and context instance collections. A simple example is web service, where you have the global context (one instance for all requests for that object - problematic when having a server farm), and a context for each web session. You can also have contexts for each user, who may have multiple, parallel sessions, etc. With multiple servers you should use a kind of distributed cache for such things.

When the request comes in, you decide which context level the requested object is, get that context for the call. If the object is there, you send it back; if not, you create and store it at that context level, and return it. Of course, synchronize the creation section (and publish it to the distributed cache). The creation can be configurable plugin-like, best with languages allowing creating object instances by their class name (Java, Objective C, ...), but you can do that in C as well with pluggable libraries having factory functions.

Side note: the caller should NOT know too much about its own contexts, and the requested object's context level. Reasons: 1: it is easy to make mistake (or "clever tricks") by playing with these parameters; 2: the context level of the requested might change later. I mostly connect context information to the thread, so the object store has the information without extra parameters from the request.

On the other hand, the request may contain hint for the instance: like getting interest rate for a specific date. It should be the same "global" access, but multiple instances depending on the date (and leading different date values to the same instance between rate changes), so it is advisable to add a "hint" object to the request, used by the instance factory and not the store; and a keyForHint to the factory, used by the store. You can add these functions later, I just mentioned.

For your case this is a kind of overkill (only one object is served in global level), but for a quite small and simple extra code right now, you get a mechanism for further, perhaps more complex requirements.

Another good news: if you are in Java, you get this service from Spring without thinking too much, I just wanted to explain it in details.

Title: What if globals make sense?


答:
Configuration Files?

If you have values that are used "globally", please put them in a configuration file. Then each system and subsystem can reference this and pull the keys needed, make them read-only.

Title: What if globals make sense?

Body:
I've got a value that many objects need. For example, a financial application with different investments as objects, and most of them need the current interest rate.

I was hoping to encapsulate my "financial environment" as an object, with the interest rate as a property. But, sibling objects that need that value can't get to it.

So how do I share values among many objects without over-coupling my design? Obviously I'm thinking about this wrong.


问:
Ways to have a history of changes of database entries
What are ways to allow the versioning of database entries (data)?

Think of the content-managment-systems abilities to revert back changes of articles.

What are their pros/cons?

答:
You're probably aware of Sqlite db engine. The whole db is saved in a single file. The api also supports virtual file systems so basically you can organize the storage anywhere and with any format, just respond to read and write operations at particular file offsets. Possible applications for this could be encryption, compression and so on. The best part of it that the container layer should not know anything about databases, sql or sqlite file format, just obey xRead and xWrite callbacks. </p>

<p>One of the ideas was to implement time-machine feature. So any xWrite operation saves every segment it would overwrite in "undo" history and the user can choose a date in the past to see what the db contained (probably read-only mode). I don't have working example yet (there was a discussion about it at sqlite mail list), but probably other engines supply  VFS APIs so something similar is possible. And once it implemented, it should be compatible with database structures of any complexity. </p>

Body:
You're probably aware of Sqlite db engine. The whole db is saved in a single file. The api also supports virtual file systems so basically you can organize the storage anywhere and with any format, just respond to read and write operations at particular file offsets. Possible applications for this could be encryption, compression and so on. The best part of it that the container layer should not know anything about databases, sql or sqlite file format, just obey xRead and xWrite callbacks.

One of the ideas was to implement time-machine feature. So any xWrite operation saves every segment it would overwrite in "undo" history and the user can choose a date in the past to see what the db contained (probably read-only mode). I don't have working example yet (there was a discussion about it at sqlite mail list), but probably other engines supply  VFS APIs so something similar is possible. And once it implemented, it should be compatible with database structures of any complexity.


问:
Open source Projects which pays the developers?
Are there any Java open source projects that Pays the developers?

I came across this from a book : Programming Interviews Exposed.   Page #25

Are open-source projects preferable?

The vast majority of programming jobs have usually involved
  proprietary, closed-source projects, which some programmers find
  objectionable. There’s been a small shift in favor of more open
  software development, which provides more opportunities for people
  like yourself to participate in open-source projects and still be paid
  for that participation.

答:
Just adding to other awesome answers

if you are a student you can get paid for contribution by participating in Google Summer of Code. Google pays you to work for one of the accepted Open Source organization and many of them are based on Java.

Out of the 180 Accepted orgs about 40 had java projects this year


答:
One idea is to use "Insert-Only Databases". The basic idea is that you never delete or update data on a row.

Each table that is required to be tracked will have two datetime columns from and to. They start with the value NULL in each (beginning of time to end of time). When you need to "change" the row you add a new row, and at the same time you update the to in the previous row to Now and the from in the row you are adding to Now.

For more detailed info look at:

Ideas on database design for capturing audit trails

Best design for a changelog / auditing database table?

This technique is called AuditTrail to manage legacy data, and its kinda stores change history.

It looks like question of this nature is already posted:

https://stackoverflow.com/q/1051449/1437962

https://stackoverflow.com/q/201527/1437962

Title: Ways to have a history of changes of database entries

Body:
What are ways to allow the versioning of database entries (data)?

Think of the content-managment-systems abilities to revert back changes of articles.

What are their pros/cons?

ContentLicense: CC BY-SA 4.0


问:
In MATLAB, how can 'preallocating' cell arrays improve performance?
I was reading this article on MathWorks about improving MATLAB performance and you will notice that one of the first suggestions is to preallocate arrays, which makes sense. But it also says that preallocating Cell arrays (that is arrays which may contain different, unknown datatypes) will improve performance.

But how will doing so improve performance because the datatypes are unknown so it doesn't know how much contiguous memory it will require even if it knows the shape of the cell array, and therefore it can't preallocate the memory surely? So how does this result in any improvement in performance?

I apologise if this question is better suited for StackOverflow than Programmers but it isn't asking about a specific problem so I thought it fit better here, please let me know if I am mistaken though.

Any explanation would be greatly appreciated :)

答:
I don't know details of MATLAB's memory handling, so this is just an educated guess: Cell arrays are implemented so that the array itself contains only references (pointers) to the cells, which actually live in the heap. It definitely can't allocate memory for the actual cells in advance because, as you wrote, their size is unknown. However, it can pre-allocate the pointer array itself, since the size of the pointers is known.

When you think about it, it would be quite difficult to implement an array whose element size wouldn't be constant: how would you know where in the memory X[1234] lives, if the size of each element can be different? Therefore a layer of indirection (store constant-sized pointers pointing to the actual data) is quite useful. An alternative would be some sort of linked list, a different kind of trade-off.


答:
I think you can use triggers for each table and maintain the data in _history (or you can give any name) and on every insert, update, delete on main table will trigger your trigger and you can save the details in this table.Trigger mechanism is also available with SQLite database if you are using one.

This mechanism is useful for large projects as well. In this table you can log information of user who have made the changes along with the time-stamp of the changes. you then can restore your table to any of the time-stamp matching to your requirements.

Every Database has its own way to write and code triggers. If you are using SQLite visit SQLite.org for the syntax. For other databases you can visit their official sites.


答:
I'm doing a version of this now. for every record I have an Inserted Date, Modified date and and Active Record boolean flag. For the initial insert Inserted and Modified dates are both set to Now() (This example is in Access) and the Active record flag is set to true. then if I modify that record I copy the whole thing to a new record, changing the field(s) the user is changing, I leave the Insert date equal to the original and change the Modified date to Now(). I then flip the Active Record flag of the original record to false and the new record to true.
I also have a field for ModifiedRecordsParentID where I save the identity of the original record.

Then If I even need to query I can just return records where ActiveRecord = true and I will only get the most up to date information.


问:
Writing a new programming language - when and how to bootstrap datastructures?
I'm in the process of writing my own programming language which, thus far, has been going great in terms of what I set out to accomplish. However, now, I'd like to bootstrap some pre-existing data structures and/or objects.  My problem is that I'm not really sure on how to begin.

When the compiler begins do I splice in these add-ins so their part of the scope of the application?

If I make these in some core library, my concern is how I distribute the library in addition to the compiler--or are they part of the compiler?

I get that there are probably a number of plausible ways to approach this, but I'm having trouble with the setting my direction.  If it helps, the language is on top of the .NET core (i.e it compiles to CLR code).

Any help or suggestions are very much appreciated!

答:
When the compiler begins do I splice in these add-ins so their part of the scope of the application?

That depends on how the language is designed. If there is special syntax to define a list for example, then you should include the list. If there's not, then it should be part of a (standard) library and follow the rules of other libraries.

If I make these in some core library, my concern is how I distribute the library in addition to the compiler--or are they part of the compiler?

Again, if the language syntax requires the structures to function then maybe just include them in the compiler. Otherwise make them a library and bundle the library with the compiler, or make it a simple install dependency.


问:
Java Transaction Service without the application server
Is it possible to have a Java standalone application (no application server attached) that exposes some operations that a client can call and be the one to manage the transactions?

I was thinking this application to expose JNDI resources and get a hold of a java:comp/UserTransaction from there, get also a bean from there and call methods A, B and C on it and coordinate the transaction from the client?

The application I'm writing isn't complex enough so that I need a big application server around it so I'm thinking to have a standalone JTS inside it that the client could interact with from a transactions point of view.

I don't have much experience with distributed transactions and don't really know how to tackle the issue. Is it even possible? Am I getting myself into something beyond what a mere mortal (programmer) can handle?

How can I approach this?

答:
Simple JNDI serving is straightforward, distributed transaction management is hard

There is a fairly comprehensive tutorial on JNDI provided by Oracle. Although it appears dated (JDK 1.1.2 anyone?) the JNDI specification has not changed a lot in the intervening time and is still relevant. Carefully reading through the examples will provide you with enough information to be able to construct a standalone application capable of serving up internal objects in response to JNDI requests.

Are you sure you need distributed transactions?

Your second question is to do with handling distributed transactions. There are several ways to interpret a distributed transaction based on the level of collaboration between applications.

In the simple case you'd have a workflow like this:

Application A sends a work package to Application B over HTTP

Application B attempts to commit this to the database. If successful a 200 OK is returned, otherwise some error code is used.

Application A knows how to react to a failure appropriately.

Clearly you wouldn't need JNDI to implement this kind of workflow, other than perhaps to have your application (Application C) take the role of providing Application B with the database connection pool (Tip: use C3P0 for that).

In the complex case you'd have a workflow more like this:

Application A registers the start of a distributed transaction with Application C, and then works with the database to do some work.

Application A completes part of the overall transaction and hands over to Application B to finish it. Application A notifies Application C of the status.

Application B registers its part of the transaction with Application C and attempts to complete its work. If it fails, Application C knows how to orchestrate the rollback (perhaps using nested transaction management).

If you're looking for a workflow like the complex case, then I'd say you should be considering an application container to manage it. If not, then you may not even need JNDI.


问:
Are separate business objects needed when persistent data can be stored in a usable format?
I have a system where data is stored in a persistent store and read by a server application. Some of this data is only ever seen by the server, but some of it is passed through unaltered to clients.

So, there is a big temptation to persist data - whether whole rows/documents or individual fields/sub-documents - in the exact form that the client can use (eg. JSON), as this removes various layers of boilerplate, whether in the form of procedural SQL, an ORM, or any proxy structure which exists just to hold the values before having to re-encode them into a client-suitable form. This form can usually be used on the server too, though business logic may have to live outside of the object,

On the other hand, this approach ends up leaking implementation details everywhere. 9 times out of 10 I'm happy just to read a JSON structure out of the DB and send it to the client, but 1 in every 10 times I have to know the details of that implicit structure (and be able to refactor access to it if the stored data ever changes). And this makes me think that maybe I should be pulling this data into separate business objects, so that business logic doesn't have to change when the data schema does. (Though you could argue this just moves the problem rather than solves it.)

There is a complicating factor in that our data schema is constantly changing rapidly, to the point where we dropped our previous ORM/RDBMS system in favour of MongoDB and an implicit schema which was much easier to work with. So far I've not decided whether the rapid schema changes make me wish for separate business objects (so that server-side calculations need less refactoring, since all changes are restricted to the persistence layer) or for no separate business objects (because every change to the schema requires the business objects to change to stay in sync, even if the new sub-object or field is never used on the server except to pass verbatim to a client).

So my question is whether it is sensible to store objects in the form they are usually going to be used, or if it's better to copy them into intermediate business objects to insulate both sides from each other (even when that isn't strictly necessary)? And I'd like to hear from anybody else who has had experience of a similar situation, perhaps choosing to persist XML or JSON instead of having an explicit schema which has to be assembled into a client format each time.

答:
Your question should be whether the data will only ever be presented in one way.  What happens when in 6 months your customers decide that they want their screens changed around?  Or they want another application that uses some of the data that you're storing as JSON?  What if you need to search on it in a new way?  Need to tie the data into some reports?

Storing your data in it's presentation format makes all of this more difficult.  These are some of the reasons abstracting the data layer away from the presentation layer is generally considered a good idea.

However, if you KNOW that the UI is not going to change for a very long time, and you KNOW that your JSON strings will be essentially atomic, and you can write a consistent process that will simply serve your JSON and not need changing even when the JSON does, you could consider it.  I still wouldn't recommend it, though.


答:
The method we use for versioning database entries is to use an auditing table.  The table has a schema along the lines of:

```<code>Seq      - Int      ' Unique identifier for this table
Event    - Char     ' Insert / Update / Delete
TblName  - Char     ' Table that had field value changed
FldName  - Char     ' Field that was changed
KeyValue - Char     ' delimited list of values for fields that make up the PK of table changed
UsrId    - Char     ' User who made the change
OldValue - Char     ' Old value (converted to character)
NewValue - Char     ' New value (converted to character)
AddTs    - DateTime ' When the change was made
</code>```

We then have triggers on Insert / Update / Delete of the tables that we want to track.

Pros:

All the data is in one table

Can be setup to track all fields or specific fields in a table

Easy to show versioning on each field for a table

Cons:

Having all auditing information in one table results in an extremely large number of records

Lots of triggers needed

Body:
The method we use for versioning database entries is to use an auditing table.  The table has a schema along the lines of:

Seq      - Int      ' Unique identifier for this table
Event    - Char     ' Insert / Update / Delete
TblName  - Char     ' Table that had field value changed
FldName  - Char     ' Field that was changed
KeyValue - Char     ' delimited list of values for fields that make up the PK of table changed
UsrId    - Char     ' User who made the change
OldValue - Char     ' Old value (converted to character)
NewValue - Char     ' New value (converted to character)
AddTs    - DateTime ' When the change was made

We then have triggers on Insert / Update / Delete of the tables that we want to track.

Pros:

All the data is in one table

Can be setup to track all fields or specific fields in a table

Easy to show versioning on each field for a table

Cons:

Having all auditing information in one table results in an extremely large number of records

Lots of triggers needed


问:
Is it worth making a commit solely to resolve non-critical typos?
If I come across a non-critical typo in code (say, an errant apostrophe in a print(error) statement), is it worth making a commit to resolve that error, or should it simply be left alone?

Specifically, I'm curious about weighing the gumming-up of the commit log against the value of resolving these non-critical typos. I'm leaning toward resolving them. Am I being pedantic?

答:
Typos should be added as a commit. Fixing misspelled words or grammatical errors will increase the readability of your code.

Using a commit message such as "Fixed typo" or "Fixed typo in file.c" will help you distinguish these commits from other, major code commits.


答:
My personal feeling is that improving quality is worth the minor inconvenience of an additional commit log entry, even for small improvements. After all, small improvements count a lot when you factor in the broken window effect.

You might want to prefix it with a TRIVIAL: tag, or mark it as trivial if your VCS supports it.

Title: Is it worth making a commit solely to resolve non-critical typos?

Body:
If I come across a non-critical typo in code (say, an errant apostrophe in a print(error) statement), is it worth making a commit to resolve that error, or should it simply be left alone?

Specifically, I'm curious about weighing the gumming-up of the commit log against the value of resolving these non-critical typos. I'm leaning toward resolving them. Am I being pedantic?


答: You aren't being pedantic, and it is better to resolve them individually.  The more atomic a change is, the better -- you don't want a crashing bug fix to be mixed up with 500 comment/typo changes.</p>


问:
Should curly braces appear on their own line?
Should curly braces be on their own line or not? What do you think about it?

```<code>if (you.hasAnswer()) {
    you.postAnswer();
} else {
    you.doSomething();
}
</code>```

or should it be

```<code>if (you.hasAnswer())
{
    you.postAnswer();
}
else
{
    you.doSomething();
}
</code>```

or even

```<code>if (you.hasAnswer())
    you.postAnswer();
else
    you.doSomething();
</code>```

Please be constructive! Explain why, share experiences, back it up with facts and references.

答:
My personal preference is for the first method, probably because that's the way I first learned PHP.

For single-line if statements, I'll use

if (you.hasAnswer()) you.postAnswer();

If it's not you.postAnswer(); but something a lot longer, such as you.postAnswer(this.AnswerId, this.AnswerText, this.AnswerType); I'll probably revert to the first type:

```<code>if (you.hasAnswer) {
    you.postAnswer(this.AnswerId, this.AnswerText, this.AnswerType);
}
</code>```

I will never use a line-break, and I'll never use this method if there's also an else statement.

```<code>if (you.hasAnswer()) you.postAnswer();
else you.doSomething()
</code>```

is a theoretical possibility, but not one I'd ever use. This would have to be turned into

```<code>if (you.hasAnswer()) {
    you.postAnswer();
} else {
    you.doSomething();
}
</code>```

Body:
My personal preference is for the first method, probably because that's the way I first learned PHP.

For single-line if statements, I'll use

if (you.hasAnswer()) you.postAnswer();

If it's not you.postAnswer(); but something a lot longer, such as you.postAnswer(this.AnswerId, this.AnswerText, this.AnswerType); I'll probably revert to the first type:

if (you.hasAnswer) {
    you.postAnswer(this.AnswerId, this.AnswerText, this.AnswerType);
}

I will never use a line-break, and I'll never use this method if there's also an else statement.

if (you.hasAnswer()) you.postAnswer();
else you.doSomething()

is a theoretical possibility, but not one I'd ever use. This would have to be turned into

if (you.hasAnswer()) {
    you.postAnswer();
} else {
    you.doSomething();
}

ContentLicense: CC BY-SA 2.5


答:
In the General Case: Yes

It's always worth it to increase the maintainability of your software.

Just go for it.

If you're just about to ship a release...

... and if you're not the team leader, then check with him/her.

Regarding the content of the commit log...

I agree with others that you should at least write something make it distinct from "feature"-related commits, if it's only about fixing an isolated typo.

A common practice is to have some never-dying tasks in your issue tracker to track timeless and endless changes. For instance, it's not uncommon to have a task for:

large automated harmless cleanups (whitespaces sweeps),

grammar and typo hunting sprees,

build system modifications,

etc...

Just be cautious that these do not get used as throw-away task IDs for just about anything when people get lazy about creating correctly documented tickets. Especially if you reject commits that are not linked to an ID (which is a good thing, but large tasks like these will be even more attractive for lazy developers).


答:
For grammatical errors that may be seen by an end user, then yes, by all means it is worth making the commit as it is entirely possible that a user or QA may come along and report the error and it would need to be tracked. If it is already fixed then it could expedite the time it takes to resolve the issue.

If it is a grammatical error in comments around the code though, I wouldn't do anything about it unless it is part of changes to the actual code as well in which case you are updating the documentation of the code.


答:
Jboss and other application server vendors do offer a stand alone transaction manager that can be used stand-alone.

The JBoss Transaction Service (JBossTS) protects businesses from data corruption by guaranteeing complete, accurate business transactions for Java based applications (including those written for the JEE and EJB frameworks) thereby eliminating the risks and costs associated with time-consuming manual reconciliation following failures...

Title: Java Transaction Service without the application server

Body:
Is it possible to have a Java standalone application (no application server attached) that exposes some operations that a client can call and be the one to manage the transactions?

I was thinking this application to expose JNDI resources and get a hold of a java:comp/UserTransaction from there, get also a bean from there and call methods A, B and C on it and coordinate the transaction from the client?

The application I'm writing isn't complex enough so that I need a big application server around it so I'm thinking to have a standalone JTS inside it that the client could interact with from a transactions point of view.

I don't have much experience with distributed transactions and don't really know how to tackle the issue. Is it even possible? Am I getting myself into something beyond what a mere mortal (programmer) can handle?

How can I approach this?


问:
Implementing unit testing at a company that doesn't do it
My company's head of software development just "resigned" (i.e. fired) and we are now looking into improving the development practices at our company.  We want to implement unit testing in all software created from here on out.

Feedback from the developers is this:

We know testing is valuable

But, you are always changing the specs so it'd be a waste of time

And, your deadlines are so tight we don't have enough time to test anyway

Feedback from the CEO is this:

I would like our company to have automated testing, but I don't know how to make it happen

We don't have time to write large specification documents

How do developers get the specs now?  Word of mouth or PowerPoint slide.  Obviously, that's a big problem.  My suggestion is this:

Let's also give the developers a set of test data and unit tests

That's the spec.  It's up to management to be clear and quantitative about what it wants.

The developers can put it whatever other functionality they feel is needed and it need not be covered by tests

Well, if you've ever been in a company that was in this situation, how did you solve the problem?  Does this approach seem reasonable?

答:
It seems that you are mixing up two different kinds of tests: unit tests and system / acceptance tests. The former operate on a lower level, testing small pieces of code (typically individual methods), which usually reside deep inside the program, not directly visible to the users. The latter tests the whole program as seen by its users, on a much higher level of granularity. Thus, only the latter can be based on any form of system specification.

Separating the two issues makes it easier to start moving towards an improved development process. Start writing unit tests as soon as possible, regardless of how the software is (not) specified at high level. Whenever a developer creates or changes a method, it does something concrete, which can (and should) be unit tested. In my experience, even changing high level requirements do not typically affect these lower level code blocks dramatically: the code mostly needs to be rearranged, rather than thrown away or rewritten completely. Consequently, most of the existing unit tests will keep running fine.

One important condition to enable unit testing is: the deadlines should not be decided by management up front, but should instead be based on work estimates by the developers (who in turn should include in their estimation the time needed to write proper unit tests). Or, if the deadline is fixed, the scope of delivery should be negotiable. No amount of (mis)management can change the fundamental truth that a given number of developers can only deliver a certain amount of quality work in a given amount of time.

Parallel to this, start discussing the best way to clarify and document requirements and turn them into high level acceptance tests. This is a longer process of successive refinement, which can easily take years to get to a better, stable state across a whole organization. One thing seems fairly sure from your description: trying to fix constantly changing requirements by writing large specification documents up front is just not going to work. Instead, it is recommended to move towards a more agile approach, with frequent software releases and demonstrations to users, and lots of discussions about what they actually want. The user has the right to change his/her mind about the requirements any time - however, each change has its cost (in time and money). The developers can estimate the cost for each change request, which in turn enables the user / product owner to make informed decisions. "Surely, this feature change would be nice... but if it delays the release of this other crucial feature, and costs this much, let's put it into the backlog for now".

Getting users to define acceptance test cases and create test data is a great way to involve them more, and to build mutual confidence between users and developers. This forces both parties to focus on concrete, measureable, testable acceptance criteria, and to think use cases through in a lot more detail than typical. As a result, users get to check the current status of development first-hand with each release, and developers get more concrete, tangible measurement feedback about the status of the project. Note though that this requires greater commitment from users, and new ways of operation, which may be a tough thing to accept and learn.


答:
First issue: in order to "give the developers a set of test data and unit tests", you first must write those unit tests, which is a job of developers. Unit tests doesn't replace the specification neither: the spec is intended to have an abstraction level higher to the unit tests.

Second issue: it seems that you want the maximum unit test coverage. In this case, yes, it will cost too much time and money to write both tests and code in a context where the requirements constantly change. Instead, decide what parts of the code are critical, and unit test only those parts. In many cases, the requirements which change are not affecting the critical parts of the product. A customer (or CEO, or whatsoever) usually asks to move this panel to the right, or change the color of this title from red to green: things nobody cares about and which doesn't require intensive testing. On the other hand, a customer will never ask to change the hash algorithm from SHA512 to SHA256 or to change the way you store sessions, while it's those parts which will require the most testing.

Title: Implementing unit testing at a company that doesn't do it

Body:
My company's head of software development just "resigned" (i.e. fired) and we are now looking into improving the development practices at our company.  We want to implement unit testing in all software created from here on out.

Feedback from the developers is this:

We know testing is valuable

But, you are always changing the specs so it'd be a waste of time

And, your deadlines are so tight we don't have enough time to test anyway

Feedback from the CEO is this:

I would like our company to have automated testing, but I don't know how to make it happen

We don't have time to write large specification documents

How do developers get the specs now?  Word of mouth or PowerPoint slide.  Obviously, that's a big problem.  My suggestion is this:

Let's also give the developers a set of test data and unit tests

That's the spec.  It's up to management to be clear and quantitative about what it wants.

The developers can put it whatever other functionality they feel is needed and it need not be covered by tests

Well, if you've ever been in a company that was in this situation, how did you solve the problem?  Does this approach seem reasonable?


答:
My experience with making the transition

For many years I was under the misapprehension that I didn't have enough time to write unit tests for my code. When I did write tests, they were bloated, heavy things which only encouraged me to think that I should only ever write unit tests when I knew they were needed.

Recently I've been encouraged to use Test Driven Development and I found it to be a complete revelation. I'm now firmly convinced that I don't have the time not to write unit-tests.

In my experience, by developing with testing in mind you end up with cleaner interfaces, more focussed classes & modules and generally more SOLID, testable code.

Every time I work with legacy code which doesn't have unit tests and have to manually test something, I keep thinking "this would be so much quicker if this code already had unit tests". Every time I have to try and add unit test functionality to code with high coupling, I keep thinking "this would be so much easier if it had been written in a de-coupled way".

Comparing and contrasting the two experimental stations that I support. One has been around for a while and has a great deal of legacy code, while the other is relatively new.

When adding functionality to the old lab, it is often a case of getting down to the lab and spending many hours working through the implications of the functionality they need and how I can add that functionality without affecting any of the other functionality. The code is simply not set up to allow off-line testing, so pretty much everything has to be developed on-line. If I did try to develop off-line then I would end up with more mock objects than would be reasonable.

In the newer lab, I can usually add functionality by developing it off-line at my desk, mocking out only those things which are immediately required, and then only spending a short time in the lab, ironing out any remaining problems not picked up off-line.

My advice

It seems like you have started off well, any time you are going to make big changes to your development workflow, you have to make sure that everyone is involved in making that decision, and ideally that most people have bought into it. From your question, it looks like you've got this right. If people don't have an enthusiasm for the idea, it is doomed to either fail or generate bad will.

Unless you can present a compelling business case, I would not recommend a ground up implementation of unit tests and specifications for your whole system. As I mention above, if a system isn't designed with testing in mind, it can be very difficult to write automated tests for it.

Instead I would recommend starting small and using the the Boy Scout Rule:

Always leave the campground cleaner than you found it.

If while you are implementing something on this codebase, you can identify the specific tests required to test the existing behaviour and transition from the old behaviour to the new, then you have both documented the change in spec and made a start on implementing units tests for your system.

Modules which you don't touch don't get unit tests, but if you aren't touching them then it is probably because they are already thoroughly tested in use and need no changes, or they are never used.

What you want to avoid is wasting a whole load of developer effort writing tests which are never going to be needed (YAGNI works just as well for test code as for production code *8'), never going to be used again and demoralise people into thinking that tests are useless after all.

Summary

Start small, build trust in the tests incrementally and gain business value from developing tests when and where they benefit your team the most.


答:
Yes, you should absolutely do this, particularly early on in a project.

Why? Two points:

You likely won't know if a typo is "critical" or not until it is too late. Some fixes probably don't get fixed because everyone thinks it won't be a big deal. Until it is.

Fixing a typo early on and deliberately will be much easier than fixing it after several hundred lines of code/function calls have been made with it. Again, temporary hacks can become semi-permanent surprisingly quickly. This is why I have to deal with objects that have both "CollapseAll" AND "ColapseAll" methods.


答:
The first thing to do is concentrate not on testing, but on getting the overall process right. No point testing anything if you don't fully understand what it's supposed to do!

So.. specs first, and documented specs that do not change (well, not immediately). You must look at getting those done. I'd recommend a web site where the users can upload the specs, or type them in directly. You can also link that to a bug tracker and a guide on progress of the project.

Chances are, that's all you really need. You can add unit testing to that internally and management need never know that the developers are doing unit tests. In a way, that's the way its supposed to be.

You will still need to do system testing, but that too can be linked to the project management website, once released, the test team (even if that is another lucky developer on rotation) can update it with tests they've used to see if the whole thing hangs together.

I honestly don't think this is going to change overnight, if you're used to getting 'word of mouth' specs, then the battle is almost entirely going to change this behaviour - and you're going to get resistance to this. A user (or BA or PM or whoever) who is used to saying "just make it do x" and now needs to write it all down is not going to respond well, chances are they'll write vague spec documents and then clarify them with word-of-mouth updates. So forget unit testing, and start on the big problem you have with the development lifecycle.


问:
Algorithm to figure out appointment times?
I have a weird situation where a client would like a script that automatically sets up thousands of appointments over several days. The tricky part is the appointments are for a variety of US time zones, and I need to take the consumer's local time zone into account when generating appointment dates and times for each record.

Appointment Rules:

Appointments should be set from 8AM to 8PM Eastern Standard Time, with breaks from 12P-2P and 4P-6P. This leaves a total of 8 hours per day available for setting appointments.

Appointments should be scheduled 5 minutes apart. 8 hours of 5-minute intervals means 96 appointments per day.

There will be 5 users at a time handling appointments. 96 appointments per day multiplied by 5 users equals 480, so the maximum number of appointments that can be set per day is 480.

Now the tricky requirement: Appointments are restricted to 8am to 8pm in the consumer's local time zone. This means that the earliest time allowed for each appointment is different depending on the consumer's time zone:

Eastern: 8A

Central: 9A

Mountain: 10A

Pacific: 11A

Alaska: 12P

Hawaii or Undefined: 2P

Arizona: 10A or 11A based on current Daylight Savings Time

Assuming a data set can be several thousand records, and each record will contain a timezone value, is there an algorithm I could use to determine a Date and Time for every record that matches the rules above?

答:
I thought of an algorithm I think will work for this

I'll start by creating a structure to track appointments as they get set. It can be something as simple as this:

```<code>class Day
{
    public DateTime Date { get; set; }
    public List<DateTime> AssignedTimes { get; }

    // Assigns the next available time to a record,
    // or returns false if no time is available
    public bool AssignNextAvailableTime(MyRecord record, int minHour)
    {
        // Get the next available time after minimum hour,
        // based off of the list of already AssignedTimes,
        // and whatever other logic is needed
        var nextAvailableTime = GetNextAvailableTime();

        if (nextAvailableTime == DateTime.MinValue)
            return false;

        record.AppointmentDateTime = nextAvailableTime;
        AssignedTimes.Add(nextAvailableTime);

        return true;
    }
}
</code>```

Loop through the most restrictive records (Hawaii or Undefined), and assign them to a date and time, adding a day if needed. Here's an example to demonstrate:

```<code>List<Day> days = new List<Day>();

foreach(var record in records.Where(r => r.TimeZone == null || r.TimeZone == "Hawaii"))
{
    foreach(var day in days)
        if (day.AssignNextAvailableTime(record, 14))
            break;

    if (record.AppointmentDateTime == null)
    {
        var day = new Day();
        day.AssignNextAvailableTime(record, 14);
        days.Add(day);
    }
}
</code>```

Do the same thing with the rest of the time zones, going from the most restrictive to the least restrictive.

The end result will be that every record is assigned a date and time that is between 8a and 8p in the consumer's local time, and the dates/times will be as compact as possible, meaning the minimal number of days will be used to schedule all the appointments

Body:
I thought of an algorithm I think will work for this

I'll start by creating a structure to track appointments as they get set. It can be something as simple as this:

class Day
{
    public DateTime Date { get; set; }
    public List<DateTime> AssignedTimes { get; }

    // Assigns the next available time to a record,
    // or returns false if no time is available
    public bool AssignNextAvailableTime(MyRecord record, int minHour)
    {
        // Get the next available time after minimum hour,
        // based off of the list of already AssignedTimes,
        // and whatever other logic is needed
        var nextAvailableTime = GetNextAvailableTime();

        if (nextAvailableTime == DateTime.MinValue)
            return false;

        record.AppointmentDateTime = nextAvailableTime;
        AssignedTimes.Add(nextAvailableTime);

        return true;
    }
}

Loop through the most restrictive records (Hawaii or Undefined), and assign them to a date and time, adding a day if needed. Here's an example to demonstrate:

List<Day> days = new List<Day>();

foreach(var record in records.Where(r => r.TimeZone == null || r.TimeZone == "Hawaii"))
{
    foreach(var day in days)
        if (day.AssignNextAvailableTime(record, 14))
            break;

    if (record.AppointmentDateTime == null)
    {
        var day = new Day();
        day.AssignNextAvailableTime(record, 14);
        days.Add(day);
    }
}

Do the same thing with the rest of the time zones, going from the most restrictive to the least restrictive.

The end result will be that every record is assigned a date and time that is between 8a and 8p in the consumer's local time, and the dates/times will be as compact as possible, meaning the minimal number of days will be used to schedule all the appointments


答:
I would create an interface for the timezones using military (24 hour) time.

As in, for timezone x,
EST= time;
CST = time + 1;
MST = time + 2;

and so on.

So, you could pass the timezone to your appointment function, and then time would be automatically calculated when you create or edit an appointment.  In the appointment function, you could easily put in if/then logic for breaks, like:

```<code>    if((time>12:00 && time<14:00) || (time>16:00 && time<18:00)){
    //code for break time, no appointments made here, timezone lets you use the current timezone you're in
    }
</code>```

Title: Algorithm to figure out appointment times?

Body:
I have a weird situation where a client would like a script that automatically sets up thousands of appointments over several days. The tricky part is the appointments are for a variety of US time zones, and I need to take the consumer's local time zone into account when generating appointment dates and times for each record.

Appointment Rules:

Appointments should be set from 8AM to 8PM Eastern Standard Time, with breaks from 12P-2P and 4P-6P. This leaves a total of 8 hours per day available for setting appointments.

Appointments should be scheduled 5 minutes apart. 8 hours of 5-minute intervals means 96 appointments per day.

There will be 5 users at a time handling appointments. 96 appointments per day multiplied by 5 users equals 480, so the maximum number of appointments that can be set per day is 480.

Now the tricky requirement: Appointments are restricted to 8am to 8pm in the consumer's local time zone. This means that the earliest time allowed for each appointment is different depending on the consumer's time zone:

Eastern: 8A

Central: 9A

Mountain: 10A

Pacific: 11A

Alaska: 12P

Hawaii or Undefined: 2P

Arizona: 10A or 11A based on current Daylight Savings Time

Assuming a data set can be several thousand records, and each record will contain a timezone value, is there an algorithm I could use to determine a Date and Time for every record that matches the rules above?

Body:
I would create an interface for the timezones using military (24 hour) time.

As in, for timezone x,
EST= time;
CST = time + 1;
MST = time + 2;

and so on.

So, you could pass the timezone to your appointment function, and then time would be automatically calculated when you create or edit an appointment.  In the appointment function, you could easily put in if/then logic for breaks, like:

    if((time>12:00 && time<14:00) || (time>16:00 && time<18:00)){
    //code for break time, no appointments made here, timezone lets you use the current timezone you're in
    }


问:
Is there any reason to use varchar over text columns in a database?
Is varchar just a remnant from before text came around, or are there use cases where you would want to use a varchar?  (Or char for that matter..)

(I use Postgres and MySQL (MyISAM) daily, so those are what I'm most interested in, but answers for other databases are of course welcome.  ^_-)

答:
Databases are intensely concerned with performance--speed and minimizing storage.  In most other parts of the computer world, you are not going to be bothered about how many characters are in your character string; it could be one, it could be the entire contents of an encyclopedia; it's all just a string.  In fact, a lot of languages don't even bother you about whether it's a string or a number.

But as computers get faster and gain more memory, people put more data into their databases and do fancier queries.  For a database CPU and memory are just as limiting today  as they were in the days of 64Kb main memory and 10Mb hard drives (on mainframe computers).

A fixed number of bytes is a lot easier to deal with than a variable length number.  10 bytes is a lot easier to deal with than 1,000,000.  So your database wants you to give it a clue so it can give you a gigabyte of results from terrabytes of data in microseconds.  If you're not using your database that hard, you won't need the speed it's offering and will be annoyed at the needless questions.  But if you do need the performance, you'll be happy to give it some hints.

As noted in the other answers, use char if it always uses a certain number of characters, varchar if the length can vary but it doesn't get too large (my guess is most DB's treat it as a char or text depending on size), and text if it could be any length.  If your SQL tries to use a text column, it might be best to summarize it somehow and put it in a char or small varchar column also, then do where's and order by's  on that.  Of course, that's only if performance matters to you.


答: If you're worried about gumming up the commit log, then you're doing something else wrong.  :-)  Frequent commits are a good thing!  I commit typo fixes all the time.  Get 'em in the codebase ASAP and speed up the dev cycle!</p>


问:
FizzBuzz - really?
When it comes to "interview test" questions, the subject of FizzBuzz often comes up. There is also a Coding Horror post about it.

Now, if you bother reading sites such as this, you are probably less likely to be in the demographic of programmers who would find FizzBuzz anything but trivial.

But is it really true that 99% of programmers will struggle with it?

Really?

What is the evidence to back this up?

Some real-life examples would be very helpful in answering this question.

答:
I think that 99% of programmers who apply for a job (and don't get it) may struggle over it.  But not 99% of programmers that are productively holding a job.

That's the nature of our modern job-seeking process.  Many people who apply are not qualified.

That Coding Horror post also speaks to the way we teach Computer Science nowadays.  In the past (particularly at MIT), you were required to learn things like Lisp, which pretty much requires you to grasp concepts like recursion.

Nowadays people are taught Java because it is widely used in industry, and the focus has shifted to syntax rather than deep programming thinking.  I don't dislike Java; in fact, I think it's an ideal first programming language.  But I have not seen my instructors teach deep programming principles with it.

Title: FizzBuzz - really?


问:
Entry level engineer question regarding memory management
It has been a few months since I started my position as an entry level software developer. Now that I am past some learning curves (e.g. the language, jargon, syntax of VB and C#) I'm starting to focus on more esoteric topics, as to write better software.

A simple question I presented to a fellow coworker was responded with "I'm focusing on the wrong things." While I respect this coworker I do disagree that this is a "wrong thing" to focus upon.

Here was the code (in VB) and followed by the question.

Note: The Function GenerateAlert() returns an integer.

```<code>Dim alertID as Integer = GenerateAlert()
_errorDictionary.Add(argErrorID, NewErrorInfo(Now(), alertID))
</code>```

vs...

```<code> _errorDictionary.Add(argErrorID, New ErrorInfo(Now(), GenerateAlert()))
</code>```

I originally wrote the latter and rewrote it with the "Dim alertID" so that someone else might find it easier to read. But here was my concern and question:

Should one write this with the Dim AlertID, it would in fact take up more memory; finite but more, and should this method be called many times could it lead to an issue? How will .NET handle this object AlertID. Outside of .NET should one manually dispose of the object after use (near the end of the sub).

I want to ensure I become a knowledgeable programmer that does not just rely upon garbage collection. Am I over thinking this? Am I focusing on the wrong things?

答:
"Premature optimization is the root of all evil (or at least most of it) in programming." - Donald Knuth

When it comes to your first pass, just write your code so that it's correct and clean. If it is later determined that your code is performance-critical (there are tools to determine this called profilers), it can be re-written. If your code is not determined to be performance-critical, readability is far more important.

Is it worth digging into these topics of performance and optimization? Absolutely, but not on your company's dollar if it's unnecessary.


答:
For your average .NET program, yes, it's overthinking. There may be times where you'll want to get down to the nuts and bolts of exactly what's going on inside of .NET but this relatively rare.

One of the difficult transitions I had was switching from using C and MASM to programming in classic VB back in the 90's. I was used to optimizing everything for size and speed. I had to let go of this thinking for the most part and let VB do it's thing in order to be effective.

Title: Entry level engineer question regarding memory management

Body:
It has been a few months since I started my position as an entry level software developer. Now that I am past some learning curves (e.g. the language, jargon, syntax of VB and C#) I'm starting to focus on more esoteric topics, as to write better software.

A simple question I presented to a fellow coworker was responded with "I'm focusing on the wrong things." While I respect this coworker I do disagree that this is a "wrong thing" to focus upon.

Here was the code (in VB) and followed by the question.

Note: The Function GenerateAlert() returns an integer.

```<code>Dim alertID as Integer = GenerateAlert()
_errorDictionary.Add(argErrorID, NewErrorInfo(Now(), alertID))
</code>```

vs...

```<code> _errorDictionary.Add(argErrorID, New ErrorInfo(Now(), GenerateAlert()))
</code>```

I originally wrote the latter and rewrote it with the "Dim alertID" so that someone else might find it easier to read. But here was my concern and question:

Should one write this with the Dim AlertID, it would in fact take up more memory; finite but more, and should this method be called many times could it lead to an issue? How will .NET handle this object AlertID. Outside of .NET should one manually dispose of the object after use (near the end of the sub).

I want to ensure I become a knowledgeable programmer that does not just rely upon garbage collection. Am I over thinking this? Am I focusing on the wrong things?


答:
Should one write this with the Dim AlertID

Readability is important. In your example though, I'm not sure that you're really making things that more readable. GenerateAlert() has a good name and it's not adding a lot of noise. There are probably better uses of your time.

it would in fact take up more memory;

I suspect it doesn't. That's a relatively straight-forward optimization for the compiler to make.

should this method be called many times could it lead to an issue?

Using a local variable as an intermediary makes no impact on the garbage collector. If GenerateAlert() new's up memory, then it will matter. But that will matter regardless of the local variable or not.

How will .NET handle this object AlertID.

AlertID isn't an object. The result of GenerateAlert() is the object. AlertID is the variable, which if it's a local variable is simply space associated with the method to keep track of things.

Outside of .NET should one manually dispose of the object after use

This is a dicier question that depends on the context involved and the ownership semantics of the instance provided by GenerateAlert(). In general, whatever created the instance should delete it. Your program would likely look significantly different if it were designed with manual memory management in mind.

I want to ensure I become a knowledgeable programmer that does not just relay upon garbage collection. Am I over thinking this? Am I focusing on the wrong things?

A good programmer uses the tools available to them, including the garbage collector. It's better to overthink things than to live oblivious. You might be focusing on the wrong things, but since we're here, you might as well learn about it.


答:
As my co-worker always used to say:

Make it work

Fix all bugs make it work flawless

Make it S.O.L.I.D.

Apply optimization if it is performing slow

In another words, always keep in mind KISS (keep it simple stupid). Because over-engineering, over-thinking some code logic may be an issue to change logic next time. However, keeping code clean and simple is always good practice.

However, by time and experience you would know better which code smells and would need optimization pretty soon.


答:
Martin Fowler has an article that talks briefly about how to refactor a static global into something more flexible.  Basically you make it into a singleton then modify the singleton so that it supports overriding the class of the instance with a subclass (and if needed move the logic that creates the instance to a separate class that can be sub-classed, which you would do if creating the super-class instance then replacing it later is a problem).

Of course, you have to weigh the problems with singletons (even substitutable singletons) vs. the pain of passing the same object everywhere.

As far as the "financial environment" object - it's convenient to program on the first pass, but when you are done you have added some extra dependencies.  Classes that just need an interest rate now only function when passed a financial environment object, which will make them difficult to reuse when you don't happen to have a financial environment object lying about.  So I would discourage passing it widely.

Title: What if globals make sense?


答:
I figure I would throw my comments together into a full answer:

Data Model

User - The abstraction of your user:

UserId

TimeZone

Appointment - A scheduled appointment:

AppointmentId

UserId

DateRange (5 minutes starting at a UTC timestamp)

Day - Borrowing heavily from your answer Rachel, this object will be a derived list of all appointments for a single Day...

BUT... The idea of a single Day is a floating concept.  Depending on what TimeZone the user is coming from then one persons Day may overlap another persons Day, therefore Day is relative to a users Timezone, and thus the DateRanges in the Appointments for that Day could be completely different depending on what Timezone we are talking about.

To Fetch a Day's Appointments: Given a Timezone, determine the list of static DateRanges, 8am-8pm with breaks.  Next fetch all the Appointments by DateRange that fall within this.

Concurrency

The active schedule is time sensitive and represent a limited quantity resource that users are competing for (you have to look at it in these terms).  Locking the Appointment table during validation and scheduling for a single user is necessary to preven double booking.

Algorithm

Once you have fetched a Day for a given user and their respective Timezone:

Loop through the static Day DateRange's and make sure that the requested appointment time falls within one of these ranges.

Next loop through the already scheduled appointments and make sure that the requested appointment time does not overlap with any existing scheduled appointments.

If these validations pass then create a new Appointment with its appropriate DateRange and persist.

Lather rinse and repeat...


答:
I think part of why it is such a popular question is because there is more then one way of answering it, and depending on which way the candidate chooses to go can give you an insight about how they code. Some great examples can be seen here if you have 10K rep on Stack Overflow.

As to the 99% statistic, check where that number comes from. It is probably biased. If it is based off entry-level programmers interviewing for their first job, then yes I can see that being possible, especially if the majority of their candidates are coming straight out of college. I can actually think of someone who probably would write out a 100 condition if statement as a solution to that problem.

Title: FizzBuzz - really?

Body:
When it comes to "interview test" questions, the subject of FizzBuzz often comes up. There is also a Coding Horror post about it.

Now, if you bother reading sites such as this, you are probably less likely to be in the demographic of programmers who would find FizzBuzz anything but trivial.

But is it really true that 99% of programmers will struggle with it?

Really?

What is the evidence to back this up?

Some real-life examples would be very helpful in answering this question.


问:
Should we use an outside CMS?
I work at a web design/development shop.  Everything we do is centered around the Joomla! CMS.  I'm a bit worried-if anything goes wrong with Joomla (major security flaw revealed, Joomla folds and ceases development) we're sunk.

I'm meeting with the CEO to plan the next few steps for our company.  Should I recommend that we create our own in-house CMS or am I just being paranoid about a single point of failure?

答:
I think you are just being too paranoid. Creating your own CMS is not like creating a Hello World program - it will require a significant effort to create one as well as maintaining, adding new features, etc.

Your fear can also be put in the context of say, jQuery - our website is heavily reliant on jQuery - what if jQuery dies? Should we just write our own extensive js library? Likewise to any programming language. Likewise to any tool that you use. What if Microsoft fails, should we write our own Outlook to make sure our email communication will not cease to exist?

Title: Should we use an outside CMS?


问:
Should a server "be lenient" in what it accepts and "discard faulty input silently"?
I was under the impression that by now everyone agrees this maxim was a mistake. But I recently saw this answer which has a "be lenient" comment upvoted 137 times (as of today).

In my opinion, the leniency in what browsers accept was the direct cause of the utter mess that HTML and some other web standards were a few years ago, and have only recently begun to properly crystallize out of that mess. The way I see it, being lenient in what you accept will lead to this.

The second part of the maxim is "discard faulty input silently, without returning an error message unless this is required by the specification", and this feels borderline offensive. Any programmer who has banged their head on the wall when something fails silently will know what I mean.

So, am I completely wrong about this? Should my program be lenient in what it accepts and swallow errors silently? Or am I mis-interpreting what this is supposed to mean?

The original question said "program", and I take everyone's point about that. It can make sense for programs to be lenient. What I really meant, however, is APIs: interfaces exposed to other programs, rather than people. HTTP is an example. The protocol is an interface that only other programs use. People never directly provide the dates that go into headers like "If-Modified-Since".

So, the question is: should the server implementing a standard be lenient and allow dates in several other formats, in addition to the one that's actually required by the standard? I believe the "be lenient" is supposed to apply to this situation, rather than human interfaces.

If the server is lenient, it might seem like an overall improvement, but I think in practice it only leads to client implementations that end up relying on the leniency and thus failing to work with another server that's lenient in slightly different ways.

So, should a server exposing some API be lenient or is that a very bad idea?

Now onto lenient handling of user input. Consider YouTrack (a bug tracking software). It uses a language for text entry that is reminiscent of Markdown. Except that it's "lenient". For example, writing

```<code>- foo
- bar
- baz
</code>```

is not a documented way of creating a bulleted list, and yet it worked. Consequently, it ended up being used a lot throughout our internal bugtracker. Next version comes out, and this lenient feature starts working slightly differently, breaking a bunch of lists that (mis)used this (non)feature. The documented way to create bulleted lists still works, of course.

So, should my software be lenient in what user inputs it accepts?

答:
The ideal behavior, conceptually, is to do what can be done safely, while simultaneously ensuring that someone who can fix any problems is somehow notified about them.  In practice, of course, the latter constraint is often impossible to meet directly, and so the question becomes best to deal with dubious inputs.

One thing which can be very helpful in the design of a protocol, formatting spec, or "language" is to have a means of distinguishing four categories of potential non-understood items:

Things which should be filtered out if not understood.

Things which should be ignored if not understood, but nonetheless retained if data needs to be passed on (perhaps in some sort of wrapper to indicate that it has passed through at least one stage that didn't understand it)

Things which should generate a warning if not understood, but should not prevent an attempt at data recovery (e.g. within a web page, an object whose type is unknown, but whose end within the file is well-defined, might be rendered as a red "X" without preventing the remainder of the page from being rendered.)

Things which would indicate that anything that can't understand them is apt to have severe and unrecoverable problems elsewhere (e.g. an indicator that remaining data is compressed, and which anything that would be understood by anything which could perform the required uncompression).

Having a well-defined convention by which apps which can read any version of a data format will be able to recognize which category is appropriate for anything generated in compliance with later versions is a much better approach than attempting to wedge in ad-hoc compatibility measures later on.  For example, if a file format has lines of the form "Tag: Value", one could specify that the first character of any tag will indicate the category in which it belongs; for tags of the silent-ignore categories, one could have the first character also indicate the version of the standard for which the tag is expected to be valid (so that if a "silent-ignore" tag claims to be present in version 3 of the standard, a parser for version would silently ignore it, but a parser for version 3 or later would squawk if it couldn't parse it).

The most important thing in any case is to avoid converting ambiguous or misunderstood data into erroneous data.  In some cases, it may be better to refuse to propagate ambiguous data at all, though in other cases it may be better to propagate it precisely as received in case the recipient would regard it as unambiguous.  What's truly dangerous if not downright evil is the conversion of data using varying assumptions, e.g. converting a list of dates like:

```
01/12/12
13/12/12
99/12/12
```

into a list of dates like

```
2012-01-12
2012-12-13
1999-12-12
```

Even if one had a list with a few erroneously-entered dates, it may be possible for a human given a list in the original format to determine which format was correct, and flag dubious values for further research (checking against other records, etc.)  Rendering the dates in the latter format, however, would hopelessly and unrecoverably garble them.

OwnerDisplayName: romkyns

Body:
The ideal behavior, conceptually, is to do what can be done safely, while simultaneously ensuring that someone who can fix any problems is somehow notified about them.  In practice, of course, the latter constraint is often impossible to meet directly, and so the question becomes best to deal with dubious inputs.

One thing which can be very helpful in the design of a protocol, formatting spec, or "language" is to have a means of distinguishing four categories of potential non-understood items:

Things which should be filtered out if not understood.

Things which should be ignored if not understood, but nonetheless retained if data needs to be passed on (perhaps in some sort of wrapper to indicate that it has passed through at least one stage that didn't understand it)

Things which should generate a warning if not understood, but should not prevent an attempt at data recovery (e.g. within a web page, an object whose type is unknown, but whose end within the file is well-defined, might be rendered as a red "X" without preventing the remainder of the page from being rendered.)

Things which would indicate that anything that can't understand them is apt to have severe and unrecoverable problems elsewhere (e.g. an indicator that remaining data is compressed, and which anything that would be understood by anything which could perform the required uncompression).

Having a well-defined convention by which apps which can read any version of a data format will be able to recognize which category is appropriate for anything generated in compliance with later versions is a much better approach than attempting to wedge in ad-hoc compatibility measures later on.  For example, if a file format has lines of the form "Tag: Value", one could specify that the first character of any tag will indicate the category in which it belongs; for tags of the silent-ignore categories, one could have the first character also indicate the version of the standard for which the tag is expected to be valid (so that if a "silent-ignore" tag claims to be present in version 3 of the standard, a parser for version would silently ignore it, but a parser for version 3 or later would squawk if it couldn't parse it).

The most important thing in any case is to avoid converting ambiguous or misunderstood data into erroneous data.  In some cases, it may be better to refuse to propagate ambiguous data at all, though in other cases it may be better to propagate it precisely as received in case the recipient would regard it as unambiguous.  What's truly dangerous if not downright evil is the conversion of data using varying assumptions, e.g. converting a list of dates like:

01/12/12
13/12/12
99/12/12

into a list of dates like

2012-01-12
2012-12-13
1999-12-12

Even if one had a list with a few erroneously-entered dates, it may be possible for a human given a list in the original format to determine which format was correct, and flag dubious values for further research (checking against other records, etc.)  Rendering the dates in the latter format, however, would hopelessly and unrecoverably garble them.


问:
Why does F# have an interactive mode but not C#?
F# comes out of the box with an interactive REPL. C# has nothing of the sort and is in fact kinda difficult to play around without setting up a full project (though LINQpad works and its also possible to do via powershell).

Is there something fundamentally different about the languages that allows F# to have the interactive console but makes it difficult to implement it for C#?

Since many years later people are still coming to this question I should note that now there are many options. You can use powershell (pre-installed on every modern windows machine) to play with the .Net framework. Or you can use LINQpad to prototype arbitrary c# code. Or you can use ScriptCs or you can use an online jsfiddle-type environment like Complify.net or Jsil. Lots of options.

答:
Mono has a C# repl: http://www.mono-project.com/CsharpRepl

It even has a GUI version that allows you to directly manipulate graphics objects, or create Gtk# widgets:


答:
I wouldn't create an in-house CMS unless your company has plenty of time and money to burn (as tsOverflow already said in his answer - creating a CMS is a huge task).

Plus, Joomla is open source, so it's very unlikely that it will cease development anytime soon.

I'd be worried if my whole company was centered around a closed source commercial product, because if the company that makes it closes or just decides to drop the product, then I would have a problem.

Even if a big company like Microsoft won't close tomorrow - of course they can decide to drop a product anytime, especially if it's not one of their flagship products like Windows (think VB 6, FoxPro...).

But any community-driven open source project with a large user base (like Joomla) won't likely die.

Even if the whole core development team would stop working on Joomla tomorrow, there are so many people who depend on it that some of them would have formed a new core development team (or forked the project and continued with a new name) after a few days.

Things like this happen in the OSS world all the time - Joomla itself was "created" that way, too.

Title: Should we use an outside CMS?

Body:
I work at a web design/development shop.  Everything we do is centered around the Joomla! CMS.  I'm a bit worried-if anything goes wrong with Joomla (major security flaw revealed, Joomla folds and ceases development) we're sunk.

I'm meeting with the CEO to plan the next few steps for our company.  Should I recommend that we create our own in-house CMS or am I just being paranoid about a single point of failure?


问:
Working with Git on multiple machines
This may sound a bit strange, but I'm wondering about a good way to work in Git from multiple machines networked together in some way. It looks to me like I have two options, and I can see benefits on both sides:

Use git itself for sharing, each machine has its own repo and you have to fetch between them.

You can work on either machine even if the other is offline. This by itself is pretty big I think.

Use one repo that is shared over the network between machines.

No need to do git pulls every time you switch machines, since your code is always up to date.

Never worry that you forgot to push code from your other non-hosting machine, which is now out of reach, since you were working off a fileshare on this machine.

My intuition says that everyone generally goes with the first option. But the downside I see is that you might not always be able to access code from your other machines, and I certainly don't want to push all my WIP branches to github at the end of every day. I also don't want to have to leave my computers on all the time so I can fetch from them directly. Lastly a minor point is that all the git commands to keep multiple branches up to date can get tedious.

Is there a third handle on this situation? Maybe some third party tools are available that help make this process easier? If you deal with this situation regularly, what do you suggest?

答:
The first of your two alternatives is the answer. That's implied by the "D" in "DVCS". Each user has their own local instance of the repository, and the repositories talk amongst themselves in manageable ways.

You could do your second alternative, but the problem is, there's only one repository working directory. So the work tree can be in only one state at a time--there's no Joe working on one branch and Jane working on another. So developers can overwrite each other's changes, mangle each other's work. Why, it's like not having version control at all!

There's a middle ground called, having a bare repository on a network drive, and having individual users check in and out of it. This separates your WIP work (which yes, you keep locally) from the work you publish up to the repository. It's not "save" up--it's "publish". The work you want your peers to see and use.

Title: Working with Git on multiple machines


答:
I deal with both of your proposed solutions daily. There are two key concepts to handling them well.

Use topic branches. I believe production history should be pristine. As a result I spend a great deal of time making my production branch's history logical, replicable, and debuggable. When using multiple machines, however, you occasionally need to commit work in progress. Use a topic branch. You can pull and push this branch from both machines with little effort, and when it's ready to merge into master or production rebase it to create a more maintainable history.

Using one repo shared over a network is fine, unless you're also sharing it with other users. We use a shared repository for scripts, creatively named the scripts repository. At first it seemed like a good idea as the repo doesn't change often, but over time it's become quite a nightmare. It's easy to overwrite one another's work, and you end up spending as much time air traffic controlling who's deploying the repository as you do working in it.

The best solution is keeping a local repository on each machine and sharing topic branches between them via a remote. Commit work in progress to those branches as often as you'd like. As long as you're willing to rebase them into a more intelligible history, it's quite effective in practice.

If you find yourself working on more than one topic branch throughout the day but don't want to push each one individually to the remote, git push <remote> will by default push all matching branches to <remote>. This default will change in a later version of git, but can be overrode by setting push.default in a configuration file or by specifying the matching refspec:

```<code>git push <remote> :
</code>```

Title: Working with Git on multiple machines

Body:
This may sound a bit strange, but I'm wondering about a good way to work in Git from multiple machines networked together in some way. It looks to me like I have two options, and I can see benefits on both sides:

Use git itself for sharing, each machine has its own repo and you have to fetch between them.

You can work on either machine even if the other is offline. This by itself is pretty big I think.

Use one repo that is shared over the network between machines.

No need to do git pulls every time you switch machines, since your code is always up to date.

Never worry that you forgot to push code from your other non-hosting machine, which is now out of reach, since you were working off a fileshare on this machine.

My intuition says that everyone generally goes with the first option. But the downside I see is that you might not always be able to access code from your other machines, and I certainly don't want to push all my WIP branches to github at the end of every day. I also don't want to have to leave my computers on all the time so I can fetch from them directly. Lastly a minor point is that all the git commands to keep multiple branches up to date can get tedious.

Is there a third handle on this situation? Maybe some third party tools are available that help make this process easier? If you deal with this situation regularly, what do you suggest?

Body:
I deal with both of your proposed solutions daily. There are two key concepts to handling them well.

Use topic branches. I believe production history should be pristine. As a result I spend a great deal of time making my production branch's history logical, replicable, and debuggable. When using multiple machines, however, you occasionally need to commit work in progress. Use a topic branch. You can pull and push this branch from both machines with little effort, and when it's ready to merge into master or production rebase it to create a more maintainable history.

Using one repo shared over a network is fine, unless you're also sharing it with other users. We use a shared repository for scripts, creatively named the scripts repository. At first it seemed like a good idea as the repo doesn't change often, but over time it's become quite a nightmare. It's easy to overwrite one another's work, and you end up spending as much time air traffic controlling who's deploying the repository as you do working in it.

The best solution is keeping a local repository on each machine and sharing topic branches between them via a remote. Commit work in progress to those branches as often as you'd like. As long as you're willing to rebase them into a more intelligible history, it's quite effective in practice.

If you find yourself working on more than one topic branch throughout the day but don't want to push each one individually to the remote, git push <remote> will by default push all matching branches to <remote>. This default will change in a later version of git, but can be overrode by setting push.default in a configuration file or by specifying the matching refspec:

git push <remote> :


答:
There are plenty of times when it makes sense to make your own CMS.  But general web site publishing is not one of those.

On the security end of things, its six of one, half dozen of the other.  Sure, a home grown CMS wont be subject to known exploits.  But on the other hand, it wont be as thoroughly vetted as a major open source project like Joomla, and will more likely have bigger unknown vulnerabilities.

And since Joomla is open source, if development stops on it, you'll likely be able to keep developing with it for quite a long time afterwards.

In short, if Joomla is working for you, I wouldnt switch.

Title: Should we use an outside CMS?


答:
I believe C# is primarily object-oriented. To write even simplest code, you should divide it into multiple classes. To use REPL, you would need to write lots of code.

F# being primarily functional doesn't have this problem and you can easily write even complex code in straightforward fasshion and convert it into object/s later.

It is easier to write a single line of function than to write class, that spans many lines.

Title: Why does F# have an interactive mode but not C#?

Body:
F# comes out of the box with an interactive REPL. C# has nothing of the sort and is in fact kinda difficult to play around without setting up a full project (though LINQpad works and its also possible to do via powershell).

Is there something fundamentally different about the languages that allows F# to have the interactive console but makes it difficult to implement it for C#?

Since many years later people are still coming to this question I should note that now there are many options. You can use powershell (pre-installed on every modern windows machine) to play with the .Net framework. Or you can use LINQpad to prototype arbitrary c# code. Or you can use ScriptCs or you can use an online jsfiddle-type environment like Complify.net or Jsil. Lots of options.


问:
Windows Physical Direct Memory Mapping
I'm a bit disappointed there is almost no discussion of this no matter where I look so I guess I'll have to ask.

I'm writing a cross platform memory bench marking application which requires direct physical address mapping rather than virtual addressing.

EDIT
The solution would look something like the Linux/Unix system calls:

```<code>int fd = open("/dev/mem", O_RDONLY);
mmap(NULL, len, PROT_READ, MAP_SHARED, fd, PHYSICAL_ADDRESS_OFFSET);
</code>```

which will require the kernel to either give you a virtual page mapping to the desired physical address or return that it failed. This does require supervisor privileges but that is ok.

I have seen a lot of information about shared memory and memory mapped files but all of these reside on disc and are thus not really useful when I'm trying to make a system dependent read. It is very similar to writing an IO driver although I do no need write permissions to the physical address.

This site gives an example of how to do it on a driver level using the Windows Driver Kit:

NT Insider: Sharing Memory between drivers and applications

This solution would probably require Visual Studio which currently I do not have access to. (I have downloaded the WDK api but it complained about my use of GCC for Windows).

I'm traditionally a Linux programmer so I'm hoping there might be something really simple I'm missing. Thanks in advance if you know something I don't!

答: I don't think your understanding of MAP_FIXED is correct. That tells the kernel to put the mapped memory at the given virtual address within the process address space.  User-mode processes always use virtual addressing.  In short, I don't think you can do what you are asking in Windows or any flavor of Unix or Linux.</p>

Title: Windows Physical Direct Memory Mapping


答:
I've read the Coding Horror article you mention, and my opinion is that Jeff is right... but when is the last time he got interviewed?

When you are interviewed, you are usually in high stress, and you often have to answer to theoretical questions (no intellisence, no google, no resharper, ... only your memory troubled by stress). That's the same in tests. Stress doesn't help you.

I've noticed that the only way to know if someone is suitable for a position is to work with him for a while... Just take the last 10 persons you hired out of 100 (maybe more), how much was a really good hire???

An employer should hire a problem solver, not a code monkey that know about modulos.

You can't test "for a while all applicants", so interviewing them is required. That's why I focus my questions on that (problem solving) and do past reference check.

My opinion is that the FizzBuzz is dangerous for the company that is looking for developers to substain its growth.

Title: FizzBuzz - really?


答:
I believe it's mostly a historic thing. REPL environments have always been associated with functional languages, ML family languages included, and F# stays true to that tradition. Keep in mind that interactive environment is something that users coming from functional background take for granted, lack of such a feature would be put VS and - by extension - F#, at a disadvantage.

On the other hand, no such feature has been commonplace in the OOP community.

There are however REPLs available for many non-functional languages, including C, Java or C#. Also while it's a far cry from a full-fledged REPL, the Autos feature in VS shows that it's certainly doable with C#.


答:
Use DVCS to edit history

If you are concerned about a clean commit history, consider doing your main work in feature branches. If you happen to work with a distributed VCS, you can easily edit your commit history before pushing it to the main branch. If you are on SVN, try Git -- it can interact bidirectionally with Subversion, and you can also edit history before actually committing to Subversion.

Keep common sense otherwise

If you don't want to or cannot edit commit history, there is no functional reason to do an early or an atomic commit for a minor typo that does not affect automatic tests or compilation. In this cases, in my opinion, keeping the commit history clean should be more important than doing really atomic commits. Mixing one or two typo corrections with a "regular" modification won't harm any potential review process. You might however want to group several trivial corrections into one commit, perhaps when "cleaning up" after a bigger coding session.

Note that functional bugs still should be committed ASAP in an atomic commit.

The general tone of the answers here seems to suggest a "commit everything fast" strategy even for minor typos. I tend to disagree and welcome discussion.


答:
The reason that there's not much discussion of physical memory mapping for user space apps is that user space apps can't GET physical memory mappings. Part of the definition of running in user space is that you are running in a virtual address space private to your process.

mmap with MAP_FIXED just lets you tell the system where to put the memory in your process address space. In other words, you get to specify the virtual address where the memory will show up. That's NOT a physical address in any way shape or form.

Title: Windows Physical Direct Memory Mapping

Body:
I'm a bit disappointed there is almost no discussion of this no matter where I look so I guess I'll have to ask.

I'm writing a cross platform memory bench marking application which requires direct physical address mapping rather than virtual addressing.

EDIT
The solution would look something like the Linux/Unix system calls:

```<code>int fd = open("/dev/mem", O_RDONLY);
mmap(NULL, len, PROT_READ, MAP_SHARED, fd, PHYSICAL_ADDRESS_OFFSET);
</code>```

which will require the kernel to either give you a virtual page mapping to the desired physical address or return that it failed. This does require supervisor privileges but that is ok.

I have seen a lot of information about shared memory and memory mapped files but all of these reside on disc and are thus not really useful when I'm trying to make a system dependent read. It is very similar to writing an IO driver although I do no need write permissions to the physical address.

This site gives an example of how to do it on a driver level using the Windows Driver Kit:

NT Insider: Sharing Memory between drivers and applications

This solution would probably require Visual Studio which currently I do not have access to. (I have downloaded the WDK api but it complained about my use of GCC for Windows).

I'm traditionally a Linux programmer so I'm hoping there might be something really simple I'm missing. Thanks in advance if you know something I don't!


问:
How can I maintain proficiency in multiple languages?
How can I maintain proficiency (if not expertise) in multiple languages?

In any large organization it seems necessary to know more than one language.  For example, this week I've looked at if not written code in the following languages.

VBA

C

C#

Java

Thankfully they're all imperative languages, or I would have lost my mind.

I struggled for a day or so with the C as it's been a while (read: years) since I've used it seriously.

What tips, habits, and training is there for keeping up your knowledge in so many languages?

答: Well, use them regulary. For example, I'm not doing much in C now, but whenever I need a little one-off program that reformats text files or whatever, I do it in C just to keep in touch with that language, even if the same program in Java would be more beautiful/shorter/easier to understand.</p>


答:
Is there something fundamentally different about the languages that allows F# to have the interactive console but makes it difficult to implement it for C#?

Yes.

F# is a descendant of the ML programming language, which in turn was heavily influenced by languages like Lisp and Scheme. Those languages were designed from day one to have three nice properties.

First, those languages do not really have statements the way you think of them in C#. Rather, almost everything is an expression that has a value, so an evaluate-and-then-print-the-value mechanism makes sense in almost every situation.

Second, those languages discourage programming with side effects, so you can make evaluations without worrying that you’re going to be messing up global state.

Third, most of the work you do in those languages is “at the top level”; there is typically no enclosing “class” or “namespace” or other context.

By contrast, C# emphasizes programming control flow with statements that produce side effects, and those statements are always in multiple nested containers -- a namespace, a class, a method, and so on.

So these are all things that make it harder for C# to have a REPL, but certainly not impossible. We’d just need to figure out what the semantics are for statements and expressions that appear outside of the usual context, and what the semantics are of mutations that change name bindings, and so on.

Why does F# have an interactive mode but not C#?

Because the F# team decided that having a REPL loop was a priority-one scenario for them. The C# team historically has not. Features do not get implemented unless they are the highest priority features that fit into the budget; until now, a C# REPL has not been at the top of our list.

The Roslyn project has a C# REPL (and will eventually have a VB REPL as well, but it is not ready yet.)  You can download a preview release of it to see how you like it at

http://www.microsoft.com/en-us/download/details.aspx?id=27746


答:
I vote yes. Check them in.
I've worked for a company that hated people checking stuff in. I mean almost anything.The code reviews were extensive and so if you checked in a change that just fixed a typo you got moaned at. You can imagine the state of the code. Actually the code wasn't dreadful, but it oozed like treacle rather than flowed like wine.</p>