答:
Clang is confused, having a default statement there is perfectly fine practice, it is known as defensive programming and is considered good programming practice (1). It is used plenty in mission-critical systems, though perhaps not in desktop programming.

The purpose of defensive programming is to catch unexpected errors that in theory would never happen. Such an unexpected error is not necessarily the programmer giving the function an incorrect input, or even an "evil hack". More likely, it could be caused by a corrupt variable: buffer overflows, stack overflow, runaway code and similar bugs not related to your function could be causing this. And in case of embedded systems, variables could possibly change because of EMI, particularly if you are using external RAM circuits.

As for what do write inside the default statement... if you suspect that the program has gone haywire once you ended up there, then you need some sort of error handling. In many cases you can probably just simply add an empty statement with a comment: "unexpected but doesn't matter" etc, to show that you have given thought to the unlikely situation.

(1) MISRA-C:2004 15.3.


问:
As a software architect, am I supposed to focus that much on analysing the logs and fixing other's bugs?
Since my graduation (late 2005) I was working for the same company as a c++ software engineer. A year ago I was promoted as a software architect but I have found myself involved more and more in qualification and fixing bugs, level 2 support.

50% of my time spent in Notepad++ analysing the software logs and trying to figure out what went wrong. 30% fixing other's bugs and the remaining (if any) reviewing developers spaghetti code.

I started hating this product and thinking about an exit strategy out of this company.

What do you think I can do in this situation? do you other software architect still fixing bugs in the code?

答:
I understand your frustration, but understand if you wrote the code or were the last to touch it, time is short, and they can reach you, many managers are going to go to you to fix it, regardless of your title.

Figuring that you still have friends in the development group that is in the crisis, you will help.  The problem is when they, and more importantly their management get used to you helping out, they keep coming back.  As the say "no good deed goes unpunished.”  If they can count on you to fix the problems, regardless of your title, you are just another developer, and someone else they can use.

It is a hard problem to solve, but my advice is:

Ask for the charge number for the project this non software architect project time.   I find project managers are not as eager to ask for your time, if they have to be accountable for it.

Talk your manager about how much time is being lost and to what groups or projects.  Your manager might tell you not to help them, and stay focused on his projects.  If so, then the other group comes and asks for help, you tell them your boss said not too.

Organize your work, keeping your priorities clear, and not be so responsive to outside your architecture projects.

Act like an architect, get your peers to see you as an architect, not as the same developer you have been all these years.  You have break others of the habit of treating you just as developer.

Good luck.

ContentLicense: CC BY-SA 3.0


问:
Why does Javascript treat days and months differently?
I've noticed that in JavaScript, when creating a Date, months are zero based, and days aren't.

For example:

```<code>var foo = new Date(2012, 1, 1)
</code>```

produces February 1st 2012

Why is this?

答:
It may also be that Javascript dates were meant to mimic java dates. Java has similarly used a zero based month since the beginning.

JDK API v1.0.2 : Date.getMonth()


问:
Is the carriage-return char considered obsolete
I wrote an open source library that parses structured data but intentionally left out carriage-return detection because I don't see the point. It adds additional complexity and overhead for little/no benefit.

To my surprise, a user submitted a bug where the parser wasn't working and I discovered the cause of the issue was that the data used CR line endings as opposed to LF or CRLF.

Hasn't OSX been using LF style line-endings since switching over to a unix-based platform?

I know there are applications like Notepad++ where line endings can be changed to use CR explicitly but I don't see why anybody would want to.

Is it safe to exclude support for the statistically insignificant percentage of users who decide (for whatever reason) to the old Mac OS style line-endings?

Update:

To clarify, supporting Windows line endings (ie CRLF) doesn't require CR token recognition. For efficiency purposes the lexer matches on a per-char basis. By silently ignoring CR chars, the CRLF token simplifies to LF. As such, the CRLF token itself could be considered an anachronism all its own but that's not what this question is about.

The last OS that provided system-wide support for CR style line endings was Mac OS 9. Ironically, the only application that still uses it as the default in OSX is Microsoft Excel.

答:
MS OS's from MSDOS onward use the combination CR+LF as a line separator (I think mostly because of matrix printers which need them).

So yeah, it's a bummer, but you still need support for the damned thing.


问:
How to become a more organized programmer?
I am a programmer that can code. But I find that I can get thing done, but not get thing do well or like most of the open source communities do. Well, I use some of the library from git hub. I find most of the programme is well structure. Also, a read me.

My question are:

Is that any common file structure or naming convention in the
community or this is just a matter of personal taste?

How to become a more organized programmer, instead of writing code
    just work. But more organized that let other easy to get in your
    project?

答:
Get feedback on your coding style from someone with more skill and experience.

The way I did it was I got a job where I and a senior programmer cooperated on projects, and he reviewed all the code I checked in. Once in a while he wrote me an email with everything that annoyed or puzzled him about my code. It took a while for me to find a style that both I and he were reasonably comfortable with, and we had some heated debates about some things, but all in all I learned a lot and we parted as friends.

Read books/articles about design patterns, apply different patterns to your problems and see which ones you think are useful in which situations.

Read books/articles about naming conventions and formatting styles. Different communities use different styles. It is generally a good idea to use a style that the people most likely to read your code will recognize.

Some concrete advice on structuring code:

When you see that some part of your code can be made simpler, do it.

When you see that some part of your code can be reused, make it a function and reuse it.

Don't be afraid to change the names of variables and functions if they are bad.

When you have an idea for something (a struct, function, class, pattern, anything) that can make your life easier, create it and use it.

Change your mind often. Each time you do, you learn something.

Taking the time to do this will of course slow you down in the beginning. As your code gradually gets more and more elegant, it will get easier to maintain and you will reap the benefits of your work.


问:
Different database for Membership and our web data or use just one?
Is better to keep our Membership stuff on the DefaultConnection and create another connection (another database) for our data? Or just one database for all?

If I have a MyAppContext and I want migrations for that context, It seems that I cannot have migrations for UserContext (In other words, I can just migrate one context)

So, having two different databases I can migrate or the users (maybe membership migration is weird) or the web data. Or, I can mix the UserContext and MyAppContext in one UserAndAppContext and migrate all in one place, but this mixing also seems weird.

What's the normal way to do this, one or two databases and what should be migrated?

答:
The 'normal' way is to keep it all in a single database.  Its just fewer moving pieces you have to keep track of in your application.  You can always move the member list into its own database should the need arise.

The only time I'd separate them from the start is if the long term plan would be for the membership list to reside on a physically separate server - perhaps in support of multiple applications.  This would let you assert the code wasnt doing JOINS that would not work in such a setup.


问:
Idea to develop a caching server between IIS and SQL Server
I work on a few high traffic websites that all share the same database and that are all heavily database driven. Our SQL server is max-ed out and, although we have already implemented many changes that have helped but the server is still working too hard.

We employ some caching in our website but the type of queries we use negate using SQL dependency caching.

We tried SQL replication to try and kind of load balance but that didn't prove very successful because the replication process is quite demanding on the servers too and it needed to be done frequently as it is important that data is up to date.

We do use a Varnish web caching server (Linux based) to take a bit of the load off both the web and database server but as a lot of the sites are customised based on the user we can only do so much.

Anyway, the reason for this question... Varnish gave me an idea for a possible application that might help in this situation.

Just like Varnish sits between a web browser and the web server and caches response from the web server, I was wondering about the possibility of creating something that sits between the web server and the database server.

Imagine that all SQL queries go through this SQL caching server. If it's a first time query then it will get recorded, and the result requested from the SQL server and stored locally on the cache server. If it's a repeat request within a set time then the result gets retrieved from the local copy without the query being sent to the SQL server. The caching server could also take advantage of SQL dependency caching notifications.

This seems like a good idea in theory. There's still the same amount of data moving back and forward from the web server, but the SQL server is relieved of the work of processing the repeat queries.

I wonder about how difficult it would be to build a service that sort of emulates requests and responses from SQL server, whether SQL server's own caching is doing enough of this already that this wouldn't be a benefit, or even if someone has done this before and I haven't found it? I would welcome any feedback or any references to any relevant projects.

答:
Citrix Netscaler provides this functionality.  http://blogs.citrix.com/2012/05/10/netscaler-datastream-enhancements-in-v10%E2%80%A6continuing-to-build-on-game-changing-adc-functionality/

I'm not a Citrix Rep, but we use the Netscaler for load-balancing, fail-over and GSLB.

Amazon, I believe uses Netscalers to manage their hosting service, so it's enterprise certified.

Basically, it works just like Squid except for SQL, plus other things like pointing all reads to one SQL svr and writes to another.  Cool stuff.

Don't know if there's an open-source equivalent product.

Long-term... might want to look into Hadoop (http://hadoop.apache.org/) to solve the problem in a different way.


问:
What's your favourite quote about programming?
What's your favourite quote about programming?

One quote per answer, and please check for duplicates before posting!

答:
If you want to set off and go develop some grand new thing, you don't need millions of dollars of capitalization.  You need enough pizza and Diet Coke to stick in your refrigerator, a cheap PC to work on and the dedication to go through with it.

    — John Carmack

LastEditorDisplayName: Roger Pate

OwnerDisplayName: Roger Pate

ContentLicense: CC BY-SA 2.5


问:
Continous Delivery TFS
Is it possible to achieve Continuous Delivery using TFS e.g. Windows Service? There are > 1000 posts on how to use msdeploy with TFS for WEB projects.

I am trying to understand why there are no resources such as blogs, articles, msdn or best practises for Continuous Delivery for Windows service using TFS.

I am not sure tow to achieve the following without any working reference materials. This is so frustrating.

Archive existing codebase on Remote server for Service as well for Web project not on Integration Server please!

How To Stop services on Remote server not on Integration Server

Copy New code Base on Remote Server

Start Services

答:
It looks like there's a gap in continuous delivery and deployment.. But there are some tools that are really powerful and can fill in the gap!

I had the same problem a while ago and I found an amazing tool that saved my life, and everyones in my company that had to deploy manually our solution -every release- to all our customers. This tool is called Octopus Deploy.

In their Website they describe the product as:

Octopus Deploy is a user-friendly release management system for professional .NET developers.
  It enables automated, frequent, low-risk releases of ASP.NET applications and Windows Services into development, test, staging and production environments.

And it really does very well.
This is the way we set it up in my company:
We have a Git repository divided in three branches: dev-pre-pro.

As a continuous integration tool we use Hudson. Everytime Hudson compiles any of the three branches, it generates a Nuget Package (using OctoPack + MSBuild).

This packages can be consumed from our OctopusDeploy Administration site inside our domain. OctopusDeploy  basically pushes nuget packages to its "tentacles" (services installed in the machines where we want to deploy) and performs custom actions using PowerShell.

This way, using PS scripts you can copy your brand-new-just-compiled-solution to the selected environment, start/stop services before or after copying or even update your Database. Just let your imagination flow..

So after we compile the project in the CI tool (it could be done using TFS) we can go to OctopusDeploy's administration site and perform an update to any of our environments (dev-pre-pro) with just two clicks!

Ps.- I don't work for OD, but I think it's an amazing tool! ;)

Title: Continous Delivery TFS


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

答: There is no real reason to do anything. Interfaces are to help you and not the output program. So even if the Interface is implemented by a million classes there is no rule that says you have to create one. You create one so that when you, or anyone else who uses your code, wants to change something it percolates to all implementations. Creating an interface will aide you in all future cases where you might want to create another class that implements it.</p>

ContentLicense: CC BY-SA 4.0


问:
Why does Clang/LLVM warn me about using default in a switch statement where all enumerated cases are covered?
Consider the following enum and switch statement:

```<code>typedef enum {
    MaskValueUno,
    MaskValueDos
} testingMask;

void myFunction(testingMask theMask) {
    switch (theMask) {
        case MaskValueUno: {}// deal with it
        case MaskValueDos: {}// deal with it
        default: {} //deal with an unexpected or uninitialized value
    }
};
</code>```

I'm an Objective-C programmer, but I've written this in pure C for a wider audience.

Clang/LLVM 4.1 with -Weverything warns me at the default line:

Default label in switch which covers all enumeration values

Now, I can sort of see why this is there: in a perfect world, the only values entering in the argument theMask would be in the enum, so no default is necessary. But what if some hack comes along and throws an uninitialized int into my beautiful function? My function will be provided as a drop in library, and I have no control over what could go in there. Using default is a very neat way of handling this.

Why do the LLVM gods deem this behaviour unworthy of their infernal device? Should I be preceding this by an if statement to check the argument?

答:
The default statement wouldn't necessarily help.
If the switch is over an enum, any value that is not defined in the enum will end up executing undefined behaviour.

For all you know, the compiler can compile that switch (with the default) as:

```<code>if (theMask == MaskValueUno)
  // Execute something MaskValueUno code
else // theMask == MaskValueDos
  // Execute MaskValueDos code
</code>```

Once you trigger undefined behaviour, there is no going back.

Body:
The default statement wouldn't necessarily help.
If the switch is over an enum, any value that is not defined in the enum will end up executing undefined behaviour.

For all you know, the compiler can compile that switch (with the default) as:

if (theMask == MaskValueUno)
  // Execute something MaskValueUno code
else // theMask == MaskValueDos
  // Execute MaskValueDos code

Once you trigger undefined behaviour, there is no going back.


答:
As a software architect, am I supposed to focus that much on analyzing the logs and fixing other's bugs?

In a matter of speaking, 'Yes'.

Here's how I'd qualify my answer:

By default, you should let the software developers analyze the logs and fix the bugs.

However... You must be aware of defects that incurred a data loss, require an onerous database rollback, take a long time for developers to resolve, or require a customer apology.

As a rule, your direct reports should let you know about such defects.

You should create a culture in which your direct reports feel empowered to tell you about such defects, but not compelled to tell you about trivial ones.

More on #2:

These types of defects generally imply an architectural failing. When they do, you must understand the precise nature of the defect and architect a fix.

So by extension, you must be ready, willing, and able to sift through the logs and fix other people's bugs (even if you don't directly commit code to the source code repository).

Title: As a software architect, am I supposed to focus that much on analysing the logs and fixing other's bugs?

Body:
Since my graduation (late 2005) I was working for the same company as a c++ software engineer. A year ago I was promoted as a software architect but I have found myself involved more and more in qualification and fixing bugs, level 2 support.

50% of my time spent in Notepad++ analysing the software logs and trying to figure out what went wrong. 30% fixing other's bugs and the remaining (if any) reviewing developers spaghetti code.

I started hating this product and thinking about an exit strategy out of this company.

What do you think I can do in this situation? do you other software architect still fixing bugs in the code?


答:
50% of my time spent in Notepad++ analyzing the software logs and trying to figure out what went wrong. 30% fixing other's bugs and the remaining (if any) reviewing developers spaghetti code.

This is definitely a type of work that you are NOT supposed to do, for this role. According to my experience/observations, architect have to be involved in application design, improvements, technical requirement clarifications and potential performance issues (not checking logs everyday, but primarily analyzing sever issues/errors ) that needs to be addressed or avoided.

In another words, my point # 1 is - architects are the high level designers and system integrators with hands-on experience on how inner-workings of technology work/apply and need to be used.

If you have opportunity to assign and manage the code quality then your work management skills need to be improved. Thus, planning work should be your priority on "how to do the work" approach.

Point #2: if you the one of few developer on these application(s) - then this title is just another sugar glaze by company management to keep you in the same "fix it" role with a new  fancy title.


答:
Part of the answer would be to find an engineer who is willing to take on this load.

Of course, the reason this is a problem is that you find this work undesirable, which doesn't send the message that it is attractive to the other engineers, so they aren't eager to pick it up either.

I see two possibilities.

You were given the position of architect so you could work on bigger picture items.

In this case, you should mention to management that you are unable to work on these bigger picture items because nobody has stepped up to take on the lower-level support role.  That is then their problem to solve.

The title is largely ceremonial -- a bone thrown to you to keep you around.

In this case, managment may not be terribly interested in easing your support load.

--

One thing that will definitely not be helpful to your goal is adopting an attitude of contempt for the other developers and engineers that I see leaking through in your question.  You want these people to step up and confidently handle these problems so you don't have to (possibly making some mistakes along the way).  If they know that you'll just badmouth their solutions and fix it up for them afterwards, they're probably not going to ever step up.


答:
Better still:

```<code>typedef enum {
    MaskValueUno,
    MaskValueDos,

    MaskValue_count
} testingMask;

void myFunction(testingMask theMask) {
    assert(theMask >= 0 && theMask<MaskValue_count);
    switch theMask {
        case MaskValueUno: {}// deal with it
        case MaskValueDos: {}// deal with it
    }
};
</code>```

This is less error-prone when adding items to the enum. You can skip the test for >= 0 if you make your enum values unsigned. This method only works if you have no gaps in your enum values, but that is often the case.

Title: Why does Clang/LLVM warn me about using default in a switch statement where all enumerated cases are covered?

Body:
Consider the following enum and switch statement:

```<code>typedef enum {
    MaskValueUno,
    MaskValueDos
} testingMask;

void myFunction(testingMask theMask) {
    switch (theMask) {
        case MaskValueUno: {}// deal with it
        case MaskValueDos: {}// deal with it
        default: {} //deal with an unexpected or uninitialized value
    }
};
</code>```

I'm an Objective-C programmer, but I've written this in pure C for a wider audience.

Clang/LLVM 4.1 with -Weverything warns me at the default line:

Default label in switch which covers all enumeration values

Now, I can sort of see why this is there: in a perfect world, the only values entering in the argument theMask would be in the enum, so no default is necessary. But what if some hack comes along and throws an uninitialized int into my beautiful function? My function will be provided as a drop in library, and I have no control over what could go in there. Using default is a very neat way of handling this.

Why do the LLVM gods deem this behaviour unworthy of their infernal device? Should I be preceding this by an if statement to check the argument?

Body:
Better still:

typedef enum {
    MaskValueUno,
    MaskValueDos,

    MaskValue_count
} testingMask;

void myFunction(testingMask theMask) {
    assert(theMask >= 0 && theMask<MaskValue_count);
    switch theMask {
        case MaskValueUno: {}// deal with it
        case MaskValueDos: {}// deal with it
    }
};

This is less error-prone when adding items to the enum. You can skip the test for >= 0 if you make your enum values unsigned. This method only works if you have no gaps in your enum values, but that is often the case.


问:
Interface extension
Suppose that I have an input stream interface, which defines a method for reading data. I also have a seekable interface which defines a method for seeking. A natural way of defining a input file is then to implement both input stream and seekable.

I want to construct a data decoder from the input stream interface so I can read data from a file or from another stream. The problem is that I also want to implement seek functionality to the data decoder, since I want to be able to step individual records not raw bytes. This is not possible if I only provide an input stream, which does not have the bytewise seek method.

Should I skip the seekable interface and add the seek method to input stream instead and force all streams to at least leave it as a nop.

EDIT: The decoder does not need to seek if the client does not request a seek operation. Also the stream is associated with the decoder and cannot be changed after initialization

答:
I think this kind of problem can be easily fixed by decorating the object.
In your case, you're going to have your streams, using your stream interface, and a seeker stream decorator, which adds the seeking functionality you require. You can then decorate your streams with the seeking functionality whenever needed.</p>

Title: Interface extension


问:
What's a nice explanation for pointers?
In your own studies (on your own, or for a class) did you have an "ah ha" moment when you finally, really understood pointers? Do you have an explanation you use for beginner programmers that seems particularly effective?

For example, when beginners first encounter pointers in C, they might just add &s and *s until it compiles (as I myself once did). Maybe it was a picture, or a really well motivated example, that made pointers "click" for you or your student. What was it, and what did you try before that didn't seem to work? Were any topics prerequisites (e.g. structs, or arrays)?

In other words, what was necessary to understand the meaning of &s and *, when you could use them with confidence? Learning the syntax and terminology or the use cases isn't enough, at some point the idea needs to be internalized.

Update: I really like the answers so far; please keep them coming. There are a lot of great perspectives here, but I think many are good explanations/slogans for ourselves after we've internalized the concept. I'm looking for the detailed contexts and circumstances when it dawned on you.

For example:

I only somewhat understood pointers
  syntactically in C. I heard two of my
  friends explaining pointers to another
  friend, who asked why a struct was
  passed with a pointer. The first
  friend talked about how it needed to
  be referenced and modified, but it was
  just a short comment from the other
  friend where it hit me: "It's also
  more efficient." Passing 4 bytes
  instead of 16 bytes was the final
  conceptual shift I needed.

答:
Edited in support of the revised requirement of the question

My path to "post-pointer" understanding (if I recall correctly) went like this. I had some simple experience of assembly programming from when I was still mucking around with a BBC Micro so I had the concept of memory as a bunch of boxes (see below for this). This was reinforced by the use of arrays. However, I was going into the world of C and had to deal with strings and that meant pointers. In BASIC this was trivial, in assembler I never had to work with them, and now in classic C it's all pointers and stuff. Ah, but I can scuttle back to arrays with (null terminated) strings like this:

```<code>char s[] = "Hello, world!";
printf("%s",s);
</code>```

All well and good, that's just an array of chars (8 bits per character in my little world) with a zero character at the end to show where it ends. The printf just takes that array and runs over it printing it. But what if I want to pass this string into a function?

```<code>void print_str(char* p) {
  printf("%s",p);
}
</code>```

Is what the manual says, but what's that * all about? Hmm, char* means "pointer to a char". OK... lost me. Then it dawned on me that the char* makes p equivalent to s[0]. OK, I can use that, but I still haven't twigged what pointers are. I mean, how do I set some data with one of these things? Off to the manual again...

```<code>char* p = "Hello World!";
</code>```

As I write the above I'm saying to myself "declare a pointer to a char and set it equal to this array of characters". Somehow that pointer does away with the need for an array. Guess it's the compiler doing some stuff for me for a change. So how can I change the array with this pointer? I know that I could use the array version

```<code> s[2] = 'L';
</code>```

but what's the equivalent in "pointer speak"? Off to that manual again...

```<code>*(p+2) = 'L';
</code>```

I suppose that * simply means "the contents of the memory address" and (p+2) is s[2]. Which meant that the pointer p was... just... an... address... bong!

That there is the sound of enlightenment. I suddenly twigged pointers (it was a long time ago, we old timers didn't "grok" until later). It was just indirection.

Original:

OK, my 2c worth:

Imagine memory is a bunch of boxes. Each box has a number on the side (the address). Each box contains a number (the contents). You can work with these boxes in 2 ways: variables (I want the contents of box N), pointers (I want the contents of box whatever is in box N ). Pointers are simply indirection.

And for the big answer that covers everything you will ever need to know - read this.

Title: What's a nice explanation for pointers?

Body:
Edited in support of the revised requirement of the question

My path to "post-pointer" understanding (if I recall correctly) went like this. I had some simple experience of assembly programming from when I was still mucking around with a BBC Micro so I had the concept of memory as a bunch of boxes (see below for this). This was reinforced by the use of arrays. However, I was going into the world of C and had to deal with strings and that meant pointers. In BASIC this was trivial, in assembler I never had to work with them, and now in classic C it's all pointers and stuff. Ah, but I can scuttle back to arrays with (null terminated) strings like this:

char s[] = "Hello, world!";
printf("%s",s);

All well and good, that's just an array of chars (8 bits per character in my little world) with a zero character at the end to show where it ends. The printf just takes that array and runs over it printing it. But what if I want to pass this string into a function?

void print_str(char* p) {
  printf("%s",p);
}

Is what the manual says, but what's that * all about? Hmm, char* means "pointer to a char". OK... lost me. Then it dawned on me that the char* makes p equivalent to s[0]. OK, I can use that, but I still haven't twigged what pointers are. I mean, how do I set some data with one of these things? Off to the manual again...

char* p = "Hello World!";

As I write the above I'm saying to myself "declare a pointer to a char and set it equal to this array of characters". Somehow that pointer does away with the need for an array. Guess it's the compiler doing some stuff for me for a change. So how can I change the array with this pointer? I know that I could use the array version

 s[2] = 'L';

but what's the equivalent in "pointer speak"? Off to that manual again...

*(p+2) = 'L';

I suppose that * simply means "the contents of the memory address" and (p+2) is s[2]. Which meant that the pointer p was... just... an... address... bong!

That there is the sound of enlightenment. I suddenly twigged pointers (it was a long time ago, we old timers didn't "grok" until later). It was just indirection.

Original:

OK, my 2c worth:

Imagine memory is a bunch of boxes. Each box has a number on the side (the address). Each box contains a number (the contents). You can work with these boxes in 2 ways: variables (I want the contents of box N), pointers (I want the contents of box whatever is in box N ). Pointers are simply indirection.

And for the big answer that covers everything you will ever need to know - read this.


答: There are solutions for what you want: above mentioned AppFabric cache (code name "Velocity") or Memcached.</p>

Title: Idea to develop a caching server between IIS and SQL Server

Body:
I work on a few high traffic websites that all share the same database and that are all heavily database driven. Our SQL server is max-ed out and, although we have already implemented many changes that have helped but the server is still working too hard.

We employ some caching in our website but the type of queries we use negate using SQL dependency caching.

We tried SQL replication to try and kind of load balance but that didn't prove very successful because the replication process is quite demanding on the servers too and it needed to be done frequently as it is important that data is up to date.

We do use a Varnish web caching server (Linux based) to take a bit of the load off both the web and database server but as a lot of the sites are customised based on the user we can only do so much.

Anyway, the reason for this question... Varnish gave me an idea for a possible application that might help in this situation.

Just like Varnish sits between a web browser and the web server and caches response from the web server, I was wondering about the possibility of creating something that sits between the web server and the database server.

Imagine that all SQL queries go through this SQL caching server. If it's a first time query then it will get recorded, and the result requested from the SQL server and stored locally on the cache server. If it's a repeat request within a set time then the result gets retrieved from the local copy without the query being sent to the SQL server. The caching server could also take advantage of SQL dependency caching notifications.

This seems like a good idea in theory. There's still the same amount of data moving back and forward from the web server, but the SQL server is relieved of the work of processing the repeat queries.

I wonder about how difficult it would be to build a service that sort of emulates requests and responses from SQL server, whether SQL server's own caching is doing enough of this already that this wouldn't be a benefit, or even if someone has done this before and I haven't found it? I would welcome any feedback or any references to any relevant projects.


问:
Is there a way to check if redistributed code has been altered?
I would like to redistribute my app (PHP) in a way that the user gets the front end (presentation) layer which is using the API on my server through a web service.
I want the user to be able to alter his part of the app but at the same time exclude such altered app from the normal support and offer support on pay by the hour basis. </p>

<p>Is there a way to check if the source code was altered?
Only solution I can think of would be to get check sums of all the files then send it through my API and compare them with the original app. Is there any more secure way to do it so it would be harder for the user to break such protection? </p>

答:
Nope, you cannot trust any data the client sends you. It can and will be spoofed.

Spending engineering time adding tests is a tradeoff vs what value you expect to lose from these modifications going undetected.

You should stipulate the modification terms in your license, and that should give you enough ground to act.


答: There are many serial devices that rely on CR as an end to the data stream before the ETX is sent. It is a convention that will never go away.

Title: Is the carriage-return char considered obsolete

Body:
I wrote an open source library that parses structured data but intentionally left out carriage-return detection because I don't see the point. It adds additional complexity and overhead for little/no benefit.

To my surprise, a user submitted a bug where the parser wasn't working and I discovered the cause of the issue was that the data used CR line endings as opposed to LF or CRLF.

Hasn't OSX been using LF style line-endings since switching over to a unix-based platform?

I know there are applications like Notepad++ where line endings can be changed to use CR explicitly but I don't see why anybody would want to.

Is it safe to exclude support for the statistically insignificant percentage of users who decide (for whatever reason) to the old Mac OS style line-endings?

Update:

To clarify, supporting Windows line endings (ie CRLF) doesn't require CR token recognition. For efficiency purposes the lexer matches on a per-char basis. By silently ignoring CR chars, the CRLF token simplifies to LF. As such, the CRLF token itself could be considered an anachronism all its own but that's not what this question is about.

The last OS that provided system-wide support for CR style line endings was Mac OS 9. Ironically, the only application that still uses it as the default in OSX is Microsoft Excel.


答: I never had much of a problem with pointers in C, but that may be because I had to learn assembler first. It was actually a relief not to have to manage addresses myself any more. So maybe the answer (assuming this is something you're teaching) is to give students an emulated assembly language to work with. They will figure it out in the process of writing anything more sophisticated than "Hello, world."

Title: What's a nice explanation for pointers?

Body:
In your own studies (on your own, or for a class) did you have an "ah ha" moment when you finally, really understood pointers? Do you have an explanation you use for beginner programmers that seems particularly effective?

For example, when beginners first encounter pointers in C, they might just add &s and *s until it compiles (as I myself once did). Maybe it was a picture, or a really well motivated example, that made pointers "click" for you or your student. What was it, and what did you try before that didn't seem to work? Were any topics prerequisites (e.g. structs, or arrays)?

In other words, what was necessary to understand the meaning of &s and *, when you could use them with confidence? Learning the syntax and terminology or the use cases isn't enough, at some point the idea needs to be internalized.

Update: I really like the answers so far; please keep them coming. There are a lot of great perspectives here, but I think many are good explanations/slogans for ourselves after we've internalized the concept. I'm looking for the detailed contexts and circumstances when it dawned on you.

For example:

I only somewhat understood pointers
  syntactically in C. I heard two of my
  friends explaining pointers to another
  friend, who asked why a struct was
  passed with a pointer. The first
  friend talked about how it needed to
  be referenced and modified, but it was
  just a short comment from the other
  friend where it hit me: "It's also
  more efficient." Passing 4 bytes
  instead of 16 bytes was the final
  conceptual shift I needed.


答:
Is there a way to check if the source code was altered? Only solution I can think of would be to get check sums of all the files then send it through my API and compare them with the original app. Is there any more secure way to do it so it would be harder for the user to break such protection?

No, you can not trust the code metrics from client. Because, that code might be hacked/modified or spoofed during the transportation. Unless, your clients do not communicate with your API through trusted secure channels, there is no way to validate the authenticity of information.

Basically, you need to come up with securing your channel of communication through certificates or SSL, as well as identification/registration of client applications.

Title: Is there a way to check if redistributed code has been altered?

Body:
I would like to redistribute my app (PHP) in a way that the user gets the front end (presentation) layer which is using the API on my server through a web service.
I want the user to be able to alter his part of the app but at the same time exclude such altered app from the normal support and offer support on pay by the hour basis. </p>

<p>Is there a way to check if the source code was altered?
Only solution I can think of would be to get check sums of all the files then send it through my API and compare them with the original app. Is there any more secure way to do it so it would be harder for the user to break such protection? </p>


问:
What's the difference between syntax and semantics?
I've always thought that referring to the syntax of a language was the same as referring to the semantics of a language. But I've been informed that apparently that's not the case. What's the difference?</p>

答:
You did not specify whether you only refer to programming languages or to general languages used in programming, so my answer is about data languages (such as XML, RDF, data type systems etc.):

Brian L. Meek in his seven golden rules for producing language-independent standards (1995) writes that "one language's syntax can be another's semantics". He refers to the words "syntax" and "semantic" used in data description: so if you stumble upon these words in a specification of some data format, you should better replace both words with "Potrzebie" to make clear that you must work out the meaning for yourself.

The relation between syntax and semantic, at least in exactly specified data, can better be described by the term "encoding". Semantic is encoded in syntax. As recordings can be nested, one language's syntax is another's semantics. If one goes beyond the realm of data, this nesting can be virtually infinite, as described by Umberto Eco as "unlimited semiosis".

To give a an example:

XML syntax (the stuff with all these brackets) is syntax with an XML Infoset (an abstract tree) as semantic.

An XML Infoset as syntax can express a record in some XML data format as semantic, for instance an RDF/XML document that encodes an RDF graph.

An RDF graph (the stuff with URI References) as syntax encodes a graph of abstract resources as semantic.

A graph of abstract resources as syntax encodes a conceptual model as semantic.

People usually stop at some level and take it as semantic, but in the end there is no final semantic unless some human being interprets the data in his mind. As soon as one tries to express semantic in form of data, it becomes syntax.


问:
Should I use a parser generator or should I roll my own custom lexer and parser code?
What specific advantages and disadvantages of each way to working on a programming language grammar?

Why/When should I roll my own? Why/When should I use a generator?

答:
If you have never, ever written a parser I would recommend you do it.  It is fun, and you learn how things work, and you learn to appreciate the effort that parser and lexer generators save you from doing the next time you need a parser.

I would also suggest you try reading http://compilers.iecc.com/crenshaw/ as it has a very down-to-earth attitude towards how to do it.


问:
Web versus desktop development - is web development worse?
As a longtime desktop developer looking at doing our first large-scale web application, what are the pros and cons of doing web development?

Is developing a web application much worse than developing a desktop app?  E.g., is it more tedious or annoying?  Is the time to market much worse?  Is the web platform excessively limiting?  If the answer to any of these is yes, then why?

(And how does developing a Flash or Silverlight app compare?)

答:
No

It's painful if you don't know what you're doing or don't plan correctly, but that's true with any development. It is easier to bottle the application in a desktop application, but then you lose the accessibility that is provided by coding for a web application.

I would make the choice between desktop and web based on the desired use. I see many applications written web based that shouldn't be because they don't know how to code desktop applications. I don't see many desktop applications that should be web based though, and I think that's something to consider. If you need the centralized storage, remote accessibility, and UI traits then sure.

I can't comment of Flash or Silverlight because I use neither.


答:
Much of the tediousness comes from the work necessary to make everything work in all browsers.  Since you do most likely not need be on the bleeding edge you can leverage the work done by others, by choosing a suitable web framework instead of handrolling your own.

Which one to use, strongly depends on what language environment you are currently used to.  You may want to edit the question to provide that information.

Title: Web versus desktop development - is web development worse?

Body:
As a longtime desktop developer looking at doing our first large-scale web application, what are the pros and cons of doing web development?

Is developing a web application much worse than developing a desktop app?  E.g., is it more tedious or annoying?  Is the time to market much worse?  Is the web platform excessively limiting?  If the answer to any of these is yes, then why?

(And how does developing a Flash or Silverlight app compare?)


答:
All answer here are very good. Indeed most of the time you don't need to implement a different interface. But there are case where you may want to do it anyway. Here is some case where I do it :

The class implement another interface that I don't want to expose

Happen often with adapter class that bridge third party code.

```<code>interface NameChangeListener { // Implemented by a lot of people
    void nameChanged(String name);
}

interface NameChangeCount { // Only implemented by my class
    int getCount();
}

class NameChangeCounter implements NameChangeListener, NameChangeCount {
    ...
}

class SomeUserInterface {
    private NameChangeCount currentCount; // Will never know that you can change the counter
}
</code>```

The class use a specific technology that shouldn't leak trough

Mostly when interacting with external libraries. Even if there is only one implementation I use an interface to ensure that I don't introduce unnecessary coupling with the external library.

```<code>interface SomeRepository { // Guarantee that the external library details won't leak trough
    ...
}

class OracleSomeRepository implements SomeRepository {
    ... // Oracle prefix allow us to quickly know what is going on in this class
}
</code>```

Cross layer communication

Even if only one UI class ever implements one of the domain class, it allow for better seperation between those layer and most importantly it avoid cyclic dependency.

```<code>package project.domain;

interface UserRequestSource {
    public UserRequest getLastRequest();
}

class UserBehaviorAnalyser {
    private UserRequestSource requestSource;
}

package project.ui;

class OrderCompleteDialog extends SomeUIClass implements project.domain.UserRequestSource {
    // UI concern, no need for my domain object to know about this method.
    public void displayLabelInErrorMode();

    // They most certainly need to know about *that* though
    public UserRequest getLastRequest();
}
</code>```

Only a subset of the method should be available to most object

Mostly happen when I have some configuration method on the concrete class

```<code>interface Sender {
    void sendMessage(Message message)
}

class PacketSender implements Sender {
    void sendMessage(Message message);
    void setPacketSize(int sizeInByte);
}

class Throttler { // This class need to have full access to the object
    private PacketSender sender;

    public useLowNetworkUsageMode() {
        sender.setPacketSize(LOW_PACKET_SIZE);
        sender.sendMessage(new NotifyLowNetworkUsageMessage());

        ... // Other details
    }
}

class MailOrder { // Not this one though
    private Sender sender;
}
</code>```

So in the end I use interface for the same reason that I use private field : other object shouldn't have access to stuff they shouldn't access. If I have a case like that, I introduce an interface even if only one class implement it.

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

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

Body:
All answer here are very good. Indeed most of the time you don't need to implement a different interface. But there are case where you may want to do it anyway. Here is some case where I do it :

The class implement another interface that I don't want to expose

Happen often with adapter class that bridge third party code.

interface NameChangeListener { // Implemented by a lot of people
    void nameChanged(String name);
}

interface NameChangeCount { // Only implemented by my class
    int getCount();
}

class NameChangeCounter implements NameChangeListener, NameChangeCount {
    ...
}

class SomeUserInterface {
    private NameChangeCount currentCount; // Will never know that you can change the counter
}

The class use a specific technology that shouldn't leak trough

Mostly when interacting with external libraries. Even if there is only one implementation I use an interface to ensure that I don't introduce unnecessary coupling with the external library.

interface SomeRepository { // Guarantee that the external library details won't leak trough
    ...
}

class OracleSomeRepository implements SomeRepository {
    ... // Oracle prefix allow us to quickly know what is going on in this class
}

Cross layer communication

Even if only one UI class ever implements one of the domain class, it allow for better seperation between those layer and most importantly it avoid cyclic dependency.

package project.domain;

interface UserRequestSource {
    public UserRequest getLastRequest();
}

class UserBehaviorAnalyser {
    private UserRequestSource requestSource;
}

package project.ui;

class OrderCompleteDialog extends SomeUIClass implements project.domain.UserRequestSource {
    // UI concern, no need for my domain object to know about this method.
    public void displayLabelInErrorMode();

    // They most certainly need to know about *that* though
    public UserRequest getLastRequest();
}

Only a subset of the method should be available to most object

Mostly happen when I have some configuration method on the concrete class

interface Sender {
    void sendMessage(Message message)
}

class PacketSender implements Sender {
    void sendMessage(Message message);
    void setPacketSize(int sizeInByte);
}

class Throttler { // This class need to have full access to the object
    private PacketSender sender;

    public useLowNetworkUsageMode() {
        sender.setPacketSize(LOW_PACKET_SIZE);
        sender.sendMessage(new NotifyLowNetworkUsageMessage());

        ... // Other details
    }
}

class MailOrder { // Not this one though
    private Sender sender;
}

So in the end I use interface for the same reason that I use private field : other object shouldn't have access to stuff they shouldn't access. If I have a case like that, I introduce an interface even if only one class implement it.


问:
Remembering user credentials in standalone Application
I'm developing a standalone application using java, I have a Login screen, wherein user enters his username and password. For each instance of the application, user have to enter his credentials. From a usability standpoint, I thought of keeping a remember me check Button. My question is, as I am not using any database, how do I persist the user details. I have some rough thoughts, storing them in a property file and retrieving. I think there may be better approaches than the one I had. Any Ideas and suggestions? </p>

答:
It's not uncommon to store user credentials in a file.  It is common to use a text file where each line is a delimited set of user credentials, like the following.

```<code>user123:s8Z6dRBXxNHsh+qBLz1Tuw==
user789:EQrcOUm6Wau+VuBX8g+IPg==
</code>```

The format is not important, but it is good practice to avoid storing clear-text passwords. The credentials above use a cryptographic hash function that generates an "irreversible" byte array, which is then Base64 encoded to reduce it to ASCII characters.  This is known as a "password digest".  When a person enters their password, it is first converted to the digest form which is then compared with the stored digest.

SHA1 is the recommended hash function, and I use Base64 because it it produces smaller digests that hex encoding.  Here's some sample code:

```<code>import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.apache.commons.codec.binary.Base64;

public class TestAnything {

   public static void main(String[] args) {
      try {
         System.out.println(pwdDigest("coverme"));
      }
      catch(NoSuchAlgorithmException e) {
          e.printStackTrace();
      } catch (UnsupportedEncodingException e) {
         e.printStackTrace();
      }
   }

   static String pwdDigest(String password) throws NoSuchAlgorithmException,  UnsupportedEncodingException {
      MessageDigest md = MessageDigest.getInstance("SHA-1");
      byte[] digestBytes = md.digest(password.getBytes("UTF-8"));
      return new String(Base64.encodeBase64(digestBytes), "ASCII");
   }
}
</code>```

It is also important where you store this file.  Simply hashing your password is not a sufficient means of protecting your data. The credentials file should be inaccessible to the end user.  Although SHA-1 is irreversible algorithmically, it is susceptible to brute-force and rainbow-table attacks, and therefore must remain securely stored. Especially for weak passwords.

Presumably, you are using a password because you are protecting some data or resource that the user would otherwise not have access to.  There is no sense password protecting an application if there is no data, or if the data is otherwise accessible to the user from the file system.  So I'm not sure what you are protecting -- you say you have no data-base.

If you are protecting data on the local file-system, and it is only accessible to one user, I would suggest encrypting the data using an AES cipher and using the user's password digest as the encryption key.  The draw-back to this is that the user can never change their password.

If you are protecting data on a shared file-system, or a time-share PC, data should probably be stored in an access controlled directory and accessed using some asymmetric key system like RSA.

If you are protecting access to a remote service, the passwords should be stored on the remote system.

So we really need to know what you are protecting.

Body:
It's not uncommon to store user credentials in a file.  It is common to use a text file where each line is a delimited set of user credentials, like the following.

user123:s8Z6dRBXxNHsh+qBLz1Tuw==
user789:EQrcOUm6Wau+VuBX8g+IPg==

The format is not important, but it is good practice to avoid storing clear-text passwords. The credentials above use a cryptographic hash function that generates an "irreversible" byte array, which is then Base64 encoded to reduce it to ASCII characters.  This is known as a "password digest".  When a person enters their password, it is first converted to the digest form which is then compared with the stored digest.

SHA1 is the recommended hash function, and I use Base64 because it it produces smaller digests that hex encoding.  Here's some sample code:

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.apache.commons.codec.binary.Base64;

public class TestAnything {

   public static void main(String[] args) {
      try {
         System.out.println(pwdDigest("coverme"));
      }
      catch(NoSuchAlgorithmException e) {
          e.printStackTrace();
      } catch (UnsupportedEncodingException e) {
         e.printStackTrace();
      }
   }

   static String pwdDigest(String password) throws NoSuchAlgorithmException,  UnsupportedEncodingException {
      MessageDigest md = MessageDigest.getInstance("SHA-1");
      byte[] digestBytes = md.digest(password.getBytes("UTF-8"));
      return new String(Base64.encodeBase64(digestBytes), "ASCII");
   }
}

It is also important where you store this file.  Simply hashing your password is not a sufficient means of protecting your data. The credentials file should be inaccessible to the end user.  Although SHA-1 is irreversible algorithmically, it is susceptible to brute-force and rainbow-table attacks, and therefore must remain securely stored. Especially for weak passwords.

Presumably, you are using a password because you are protecting some data or resource that the user would otherwise not have access to.  There is no sense password protecting an application if there is no data, or if the data is otherwise accessible to the user from the file system.  So I'm not sure what you are protecting -- you say you have no data-base.

If you are protecting data on the local file-system, and it is only accessible to one user, I would suggest encrypting the data using an AES cipher and using the user's password digest as the encryption key.  The draw-back to this is that the user can never change their password.

If you are protecting data on a shared file-system, or a time-share PC, data should probably be stored in an access controlled directory and accessed using some asymmetric key system like RSA.

If you are protecting access to a remote service, the passwords should be stored on the remote system.

So we really need to know what you are protecting.


问:
What do you optimize for?
Generally speaking, what type of optimizations do you typically slant yourself towards when designing software?

Are you the type that prefers to optimize your design for

Development time (i.e., quick to write and/or easier to maintain)?

Processing time

Storage (either RAM, DB, Disc, etc) space

Of course this is highly subjective to the type of problems being solved, and the deadlines involved, so I'd like to hear about the reasons that would make you choose one form of optimization over another.

答:
Elegance.

If your code is well designed, it will have several effects:

It will be easier to maintain (cutting costs for the customer)

It will be easier to optimize (for JIT or full compilers)

It will be easier to replace (when you think of a better solution)

Title: What do you optimize for?


答:
A checksum / hashing algorithm like you're suggesting will work well enough.

It's not foolproof, as you suggest.  But it doesn't need to be.  The people who can "crack" the protection mechanism you're putting in place are the same people who won't be utilizing your hourly services for support.

All likely scenarios that involve support effort on your part will lead you to discovering the modified code.  So I'd say that what you've suggested is sufficient.  Go for it and give it a try.


问:
As a software architect, am I supposed to focus that much on analysing the logs and fixing other's bugs?
Since my graduation (late 2005) I was working for the same company as a c++ software engineer. A year ago I was promoted as a software architect but I have found myself involved more and more in qualification and fixing bugs, level 2 support.

50% of my time spent in Notepad++ analysing the software logs and trying to figure out what went wrong. 30% fixing other's bugs and the remaining (if any) reviewing developers spaghetti code.

I started hating this product and thinking about an exit strategy out of this company.

What do you think I can do in this situation? do you other software architect still fixing bugs in the code?

答:
As a software architect, am I supposed to focus that much on analysing
  the logs and fixing other's bugs?

Supposed to? yes and no. You're in charge of the totality of the product quality and evolution path - make it work tomorrow, but also make it work next year.

Does that mean lending a helping hand to solve tough issues? Absolutely - at least I do. You can't make the product work tomorrow if your customers leave you.

Does that mean you should devote ALL of your time to that? Absolutely not. You're in charge of TOTALITY of the quality and evolution. Devoting that much time to chasing issues is counter productive.

You're supposed to be proactive:

Initiate education plans so other people (dev/support) can lift the load. "teach a man to fish" and all that jazz.

Invent ways and develop tools to support faster and easier defect analysis and root cause isolation. If you find this boring, other, possibly less talented or experienced developers find this not just boring, but also difficult and maybe even daunting. Help them overcome this by technology.

Start an effort to raise the quality of the product - simplify, modularize, create testing frameworks - lead by example, not by whining and threatening to quit.

Make sure developers know what you're doing - but also your managers. An architect role is much more about relations with other people then it is about coding and analysis. As much as you might hate this, politics play a key here. Making sure your peers see your accomplishments makes it easier to convince them later that you're right. If you're not there yet, back your claims by research and POCs.

If all else fails, and only after spending time to try to make things better, talk to your manager. Say that your skills are better used in planning and design phases and see what can be done to change the current situation. Your product might be in a pinch and your manager's answer might be "we need you for this thing right here, right now". I would insist on a long term plan though - how are we going to change the current situation.

I see the role of an architect a privilege. You get to influence the product in a way not many other people can - the only one theoretically more influential than you are is he product R&D manager (and, possibly, marketing) - but he's way to busy managing.


答: Have you considered hosting the frontend on your servers, then accepting uploads from the client? That way you can keep a record of whether or not they've customized it by whether or not they've submitted an updated version, and you have the file locally to compare if it's ever in doubt. </p>


答:
The way the .NET guys solved this problem was to introduce a property IsSeekable that allow to know if a Stream can be seeked. If not and you call Seek() anyway, it throws an exception. It's not very polymorphic but it's simple and works reasonably well in practice. It allows Stream to be passed around freely and each method can optimise for seeking if it want. The downside is that any method that want to use Seek() need to check the property before.

A more object oriented approach would be to create the interface SeekableInputStream that derives from both Seekable and InputStream. That way a class that needs to seek like your data adapter can require that specific interface and be guaranteed that seek will work. Better yet, the compiler will warn you if you try to send an invalid InputStream to such method. Other method can accept any class that implements InputStream, including those that implement SeekableInputStream. The downside to this method is that if you pass your SeekableInputStream around a lot then once its downcasted to InputStream the information about its seekability is lost and you need to cast it to SeekableInputStream back again if you really to optimise when you can seek.

Title: Interface extension

Body:
Suppose that I have an input stream interface, which defines a method for reading data. I also have a seekable interface which defines a method for seeking. A natural way of defining a input file is then to implement both input stream and seekable.

I want to construct a data decoder from the input stream interface so I can read data from a file or from another stream. The problem is that I also want to implement seek functionality to the data decoder, since I want to be able to step individual records not raw bytes. This is not possible if I only provide an input stream, which does not have the bytewise seek method.

Should I skip the seekable interface and add the seek method to input stream instead and force all streams to at least leave it as a nop.

EDIT: The decoder does not need to seek if the client does not request a seek operation. Also the stream is associated with the decoder and cannot be changed after initialization


问:
Behavior-Driven Development / Use case diagram
Regarding growing of Behavior-Driven Development imposing acceptance testing, are use cases diagram useful or do they lead to an "over-documentation"?

Indeed, acceptance tests representing specifications by example, as use cases promote despite of a more generic manner (since cases, not scenarios), aren't they too similar to treat them both at the time of a newly created project?

From this link, one opinion is:

Another realization I had is that if you do UseCases and automated
  AcceptanceTests you are essentially doubling your work. There is
  duplication between the UseCases and the AcceptanceTests. I think
  there is a good case to be made that UserStories + AcceptanceTests are
  more efficient way to work when compared to UseCases +
  AcceptanceTests.

What to think about?

答:
In my opinion and in an Agile perspective:

Use cases, Class diagrams, Sequences Diagrams and other UML stuff are excellent conversation tools. They are really neat when you need to sketch or explain ideas on a white board for example to make sure we get a common understanding of what need to be achieved at the moment of the conversation.

After the conversation happened they should be discarded/erased/not kept.

So to answer your question, yes they are over documentation if you attend to put them in a document. But as I explained, their most interesting feature is not to be stored in pages of design documents but to be used as tools to help conversation within the team.


问:
What is meant by 4 GL?
I came across the term 4GL(generation language) in reading about Oracle ADF Busniess components . I want to know what exactly is 4GL ?

This is the actual quote from the book Oracle Fusion Guide:

Oracle ADF Business Components is the business services layer of choice in Oracle Fusion
      application development. Compared to other persistence layers, ADF Business Components
      provides exceptional built-in business application functionality and maximally declarative
      experience that makes it a perfect match for those who seek an end-to-end fourth generation
      language (4GL) Java EE development architecture.

答:
The best explanation is one that covers all the generations:

1st-gen is the machine opcodes. These are the binary (hexadecimal if you please) codes the computer actually understands and works with at the hardware level.

2nd-gen is assembly language. These are human-readable labels for the actual opcodes, making it easier for a human to write a program without having to remember or constantly reference the numeric opcodes and location addresses of registers and logic/arithmetic units, etc.

3rd-gen are most of the languages programmers actually code in today that are intended to produce programs that run on the computer as applications: C/C++, Basic/VB, Pascal/Delphi, etc. These languages are compiled into assembly language files, then references between those files are linked together and the results digested into machine code, but third-generation languages provide constructs such as logic loops, variables, and object-oriented principles in a form that make them easy for humans to work with and understand. They abstract a lot of the low-level logical thinking, allowing programmers to think in slightly bigger steps (though a key part opf computer science education is teaching students to think in small enough steps that a computer can follow).

4th-gen are languages invented to communicate with other programs. Markup languages (XML/HTML), query languages (SQL), scripting languages (JavaScript), even some of your higher-level communications protocols like HTTP and SOAP are considered fourth-generation languages. These are not, directly, compiled into machine instructions; they instead exist to be interpreted by another program which then performs the task it was asked to do by the program it received.

To be honest, there's not a very clear dividing line anymore between 3rd-gen and 4th-gen. Some clearly are one or the other, like C/C++ (3rd) and SQL (4th). But, for instance, is Java considered 3rd-gen, because it's intended to create programs that are "applications" in their own right? Or is it 4th-gen, because Java's not compiled into machine code but instead into an intermediate language of bytecodes, that are then interpreted by a virtual machine environment (most of which are in turn hosted by some other program like a web browser or web server) that actually does what the programmer's code tells it to? The same could be asked of .NET languages like C#/VB, and of most of the functional languages, which require runtimes that hide all the nitty-gritty imperative logic and side-effects, so the programmer can think in more mathematical, evaluatory terms.

Title: What is meant by 4 GL?


答:
No, web applications have different trade-offs than desktop applications.  Each has their strengths to my mind.  While there are strengths like a single deployment, there is the trade-off of knowing which browsers do you support and what screen resolution are you expecting the customer to have?  While you do have control over the server hardware there is the question of how much traffic do you expect and how well will it scale?  For those that have done web development for years these can be sore spots much like I'd imagine you have some development tasks that you find to be a major pain, no?

A Flash app may or may not be a web application to my mind.  Something like AIR can make some Flash stuff run on the desktop now and some applications are built on that,e.g. Twhirl, so it isn't immediately that cut and dry.


问:
Different database for Membership and our web data or use just one?
Is better to keep our Membership stuff on the DefaultConnection and create another connection (another database) for our data? Or just one database for all?

If I have a MyAppContext and I want migrations for that context, It seems that I cannot have migrations for UserContext (In other words, I can just migrate one context)

So, having two different databases I can migrate or the users (maybe membership migration is weird) or the web data. Or, I can mix the UserContext and MyAppContext in one UserAndAppContext and migrate all in one place, but this mixing also seems weird.

What's the normal way to do this, one or two databases and what should be migrated?

答:
I respectfully disagree with this answer. Having different data in different databases on the  same server can provide significant advantages:

Users can "own" one database and have full control of it, but be highly restricted or even denied access altogether in the other. This is a virtual necessity for a schema governing application security; the account used to validate a user should be able to do no more or less. What they log in with here will determine what they should get access to in the main database.

Different databases can have different purposes, different target applications, different performance demands, and thus different schema designs. One schema could be set up to be hit fast and hard by a battery of automated systems that input raw data; narrow, deep, somewhat denormalized tables optimized for pure speed. Then another database could target user applications, and thus have a more normalized structure based on needs for proper organization, hierarchical structure and integrity. A mediator can pipe the data from one into the other, respecting the need for speed on one side and producing the normalized, hierarchical structure needed by the other.

Keeping schemas that are targeted by different applications separate keeps those schemas, well, separate. A change needed by one application to its schema thereby doesn't necessarily have to affect another. If you're juggling half a dozen different user applications, each with subtly different needs, not having to make sure one change to one app doesn't break any of the five others is huge.

Separate DBs for separate data also allows much easier migration. Say you have three departments of your business in one office building in Chicago, each using an app targeting a DB in a server in the back room. Then, you move your helpdesk services to Abilene, cause it's cheaper. The database needed by the helpdesk app needs to be close to the helpdesk computers geographically. What's easier? Creating a backup, pushing it down onto a new server in Abilene, and pointing a few data replication jobs at the new server over a VPN or leased line? Or, extricating a big chunk of the existing schema, which may have been allowed to become entwined with the schema of other apps (since, you know, the tables are in the same DB, so why not set up the foreign keys, right?), setting up a new database with those tables from scratch, migrating all the data over, then testing all three departments' apps for regression?

Separate DBs mean smaller schemas means smaller backups means faster (and more granular) restores.

More moving parts it may be, but that's not always a bad thing. It's only a problem when the parts don't fit together well, or aren't "well-oiled" and don't move in sync, or the entire function of the larger entity depends on this one tiny delicate part. These are things to take in consideration, but are by no means supposed to be a deterrent to a more distributed data model.


问:
What would one call this architecture?
I have developed a distributed test automation system which consists of two different entities. One entity is responsible for triggering tests runs and monitoring/displaying their progress. The other is responsible for carrying out tests on that host. Both of these entities retrieve data from a central DB.

Now, my first thought is that this is clearly a server-client architecture. After all, you have exactly one organizing entity and many entities that communicate with said entity.

However, while the supposed clients to communicate to the server via RPC, they are not actually requesting services or information, rather they are simply reporting back test progress, in fact, once the test run has been triggered they can complete their tasks without connection to the server. The request for a service is actually made by the supposed server which triggers the clients to carry out tests.

So would this still be considered a server-client architecture or is this something different?

答:
Have you considered using 0MQ (Zero Message Queue)?

They demonstrate the use of a parallel processing model using a ventilator/sink.

The ventilator pushes tasks to a collection of workers that handle tasks in parallel. When a worker finishes it pushes the result to the sink.

Here's the diagram:

Source: 0MQ - The Guide

The library supports communications over most/all of the common interfaces (ex sockets, pipes, IPC, etc) and the examples have working code for all of the most common languages.

A server-client architecture doesn't really work here, as that would require a lot of unnecessary overhead to maintain the connection streams. A pub/sub (ie publisher/subscriber) model fits a lot better.

OwnerDisplayName: Chris

Title: What would one call this architecture?


问:
Open Source License that prevents re-selling
I have an open source project that is a add-in to TFS (ie it is for developers and those using TFS.)

It is currently using the GPL.  But it occurs to me that the GPL does not really represent what I am trying to do with my license.

I want my code to be free to everyone who wants to use it.  And if you modify it and use it then that is great too.  You should not have to open source your modifications.

But I would like to block someone from building my code and selling it.  Or modifying it and selling it. (Anyone that wants to do that should have to negotiate a separate license with me.)

Is there an open source license that prevents re-selling, but allows full non-vending use for a person/company that downloads it?

答:
First Why? Unless there is a high probability of this happening (in which case, you should be seeing your attorney now anyway, it appears that you are suffering from the I-am-afraid-someone-will-take-from-me syndrome.

In all seriousness, what are you concerned about, and why would someone purchase your code from someone else if it is free from you?  And if the value added by the 3rd party is enough to warrant purchasing, why would you want to stop them?  In other words, that would be a good thing for you (bigger ecosystem), not a bad thing.

Actual answer here:

I suggest you take the following BSD license and add a 4th bullet point that says something like this.

```<code>    * Redistribution of this software in source or binary forms shall be free
      of all charges or fees to the recipient of this software.
</code>```

However, I am not an attorney, so I further suggest that you run this by a good one.

```<code>Copyright (c) <year>, <copyright holder>
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the <organization> nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
</code>```

Body:
First Why? Unless there is a high probability of this happening (in which case, you should be seeing your attorney now anyway, it appears that you are suffering from the I-am-afraid-someone-will-take-from-me syndrome.

In all seriousness, what are you concerned about, and why would someone purchase your code from someone else if it is free from you?  And if the value added by the 3rd party is enough to warrant purchasing, why would you want to stop them?  In other words, that would be a good thing for you (bigger ecosystem), not a bad thing.

Actual answer here:

I suggest you take the following BSD license and add a 4th bullet point that says something like this.

    * Redistribution of this software in source or binary forms shall be free
      of all charges or fees to the recipient of this software.

However, I am not an attorney, so I further suggest that you run this by a good one.

Copyright (c) <year>, <copyright holder>
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the <organization> nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


问:
What are the downsides of implementing a singleton with Java's enum?
Traditionally, a singleton is usually implemented as

```<code>public class Foo1
{
    private static final Foo1 INSTANCE = new Foo1();

    public static Foo1 getInstance(){ return INSTANCE; }

    private Foo1(){}

    public void doo(){ ... }
}
</code>```

With Java's enum, we can implement a singleton as

```<code>public enum Foo2
{
    INSTANCE;

    public void doo(){ ... }
}
</code>```

As awesome as the 2nd version is, are there any downsides to it?

(I gave it some thoughts and I'll answer my own question; hopefully you have better answers)

答:
Some problems with enum singletons:

Committing to an implementation strategy

Typically, "singleton" refers to an implementation strategy, not an API specification. It is very rare for Foo1.getInstance() to publicly declare that it'll always return the same instance. If needed, the implementation of Foo1.getInstance() can evolve, for example, to return one instance per thread.

With Foo2.INSTANCE we publicly declare that this instance is the instance, and there's no chance to change that. The implementation strategy of having a single instance is exposed and committed to.

This problem is not crippling. For example, Foo2.INSTANCE.doo() can rely on a thread local helper object, to effectively have a per-thread instance.

Extending Enum class

Foo2 extends a super class Enum<Foo2>. We usually want to avoid super classes; especially in this case, the super class forced on Foo2 has nothing to do with what Foo2 is supposed to be. That is a pollution to the type hierarchy of our application. If we really want a super class, usually it's an application class, but we can't, Foo2's super class is fixed.

Foo2 inherits some funny instance methods like name(), cardinal(), compareTo(Foo2), which are just confusing to Foo2's users. Foo2 can't have its own name() method even if that method is desirable in Foo2's interface.

Foo2 also contains some funny static methods

```<code>    public static Foo2[] values() { ... }
    public static Foo2 valueOf(String name) { ... }
    public static <T extends Enum<T>> T valueOf(Class<T> enumType, String name)
</code>```

which appears to be nonsensical to users. A singleton usually shouldn't have pulbic static methods anyway (other than the getInstance())

Serializability

It is very common for singletons to be stateful. These singletons generally should not be be serializable. I can't think of any realistic example where it makes sense to transport a stateful singleton from one VM to another VM; a singleton means "unique within a VM", not "unique in the universe".

If serialization really does make sense for a stateful singleton, the singleton should explicitly and precisely specify what does it means to deserialize a singleton in another VM where a singleton of the same type may already exist.

Foo2 automatically commits to a simplistic serialization/deserialization strategy. That is just an accident waiting to happen. If we have a tree of data conceptually referencing a state variable of Foo2 in VM1 at t1, through serialization/deserialization the value becomes a different value - the value of the same variable of Foo2 in VM2 at t2, creating a hard to detect bug. This bug won't happen to the unserializable Foo1 silently.

Restrictions of coding

There are things that can be done in normal classes, but forbidden in enum classes. For example, accessing a static field in the constructor. The programmer has to be more careful since he's working in a special class.

Conclusion

By piggybacking on enum, we save 2 lines of code; but the price is too high, we have to carry all the baggages and restrictions of enums, we inadvertently inherit "features" of enum that have unintended consequences. The only alleged advantage - automatic serializability - turns out to be a disadvantage.

Body:
Some problems with enum singletons:

Committing to an implementation strategy

Typically, "singleton" refers to an implementation strategy, not an API specification. It is very rare for Foo1.getInstance() to publicly declare that it'll always return the same instance. If needed, the implementation of Foo1.getInstance() can evolve, for example, to return one instance per thread.

With Foo2.INSTANCE we publicly declare that this instance is the instance, and there's no chance to change that. The implementation strategy of having a single instance is exposed and committed to.

This problem is not crippling. For example, Foo2.INSTANCE.doo() can rely on a thread local helper object, to effectively have a per-thread instance.

Extending Enum class

Foo2 extends a super class Enum<Foo2>. We usually want to avoid super classes; especially in this case, the super class forced on Foo2 has nothing to do with what Foo2 is supposed to be. That is a pollution to the type hierarchy of our application. If we really want a super class, usually it's an application class, but we can't, Foo2's super class is fixed.

Foo2 inherits some funny instance methods like name(), cardinal(), compareTo(Foo2), which are just confusing to Foo2's users. Foo2 can't have its own name() method even if that method is desirable in Foo2's interface.

Foo2 also contains some funny static methods

    public static Foo2[] values() { ... }
    public static Foo2 valueOf(String name) { ... }
    public static <T extends Enum<T>> T valueOf(Class<T> enumType, String name)

which appears to be nonsensical to users. A singleton usually shouldn't have pulbic static methods anyway (other than the getInstance())

Serializability

It is very common for singletons to be stateful. These singletons generally should not be be serializable. I can't think of any realistic example where it makes sense to transport a stateful singleton from one VM to another VM; a singleton means "unique within a VM", not "unique in the universe".

If serialization really does make sense for a stateful singleton, the singleton should explicitly and precisely specify what does it means to deserialize a singleton in another VM where a singleton of the same type may already exist.

Foo2 automatically commits to a simplistic serialization/deserialization strategy. That is just an accident waiting to happen. If we have a tree of data conceptually referencing a state variable of Foo2 in VM1 at t1, through serialization/deserialization the value becomes a different value - the value of the same variable of Foo2 in VM2 at t2, creating a hard to detect bug. This bug won't happen to the unserializable Foo1 silently.

Restrictions of coding

There are things that can be done in normal classes, but forbidden in enum classes. For example, accessing a static field in the constructor. The programmer has to be more careful since he's working in a special class.

Conclusion

By piggybacking on enum, we save 2 lines of code; but the price is too high, we have to carry all the baggages and restrictions of enums, we inadvertently inherit "features" of enum that have unintended consequences. The only alleged advantage - automatic serializability - turns out to be a disadvantage.


问:
Find the new coordinates using a starting point, a distance, and an angle
Okay, say I have a point coordinate.

```<code>var coordinate = { x: 10, y: 20 };
</code>```

Now I also have a distance and an angle.

```<code>var distance = 20;
var angle = 72;
</code>```

The problem I am trying to solve is, if I want to travel 20 points in the direction of angle from the starting coordinate, how can I find what my new coordinates will be?

I know the answer involves things like sine/cosine, because I used to know how to do this, but I have since forgotten the formula. Can anyone help?

答:
SOHCAHTOA

Sine = Opposite/Hypotenuse
Cosine = Adjacent/Hypotenuse
Tangent = Opposite/Adjacent

In your example:

```<code>Sine(72) = Y/20 -> Y = Sine(72) * 20
Cosine(72) = X/20 -> X = Cosine(72) *20
</code>```

The problem is you have to be careful with what quadrant you are in. This works perfectly in the upper right quadrant, but not so nice in the other three quadrants.

Body:
SOHCAHTOA

Sine = Opposite/Hypotenuse
Cosine = Adjacent/Hypotenuse
Tangent = Opposite/Adjacent

In your example:

Sine(72) = Y/20 -> Y = Sine(72) * 20
Cosine(72) = X/20 -> X = Cosine(72) *20

The problem is you have to be careful with what quadrant you are in. This works perfectly in the upper right quadrant, but not so nice in the other three quadrants.


问:
Review tests first
I am going to adopt TDD in our team and one of the ideas I have is to review tests first. So one would write interfaces, mocks, and tests first, submit them for a code review and once interfaces and tests (think specification) are approved an actual implementation can be written (theoretically, can be done by another developer). I wonder how viable this idea is?</p>

答:
IMHO it sounds a lot like a waterfall development model, where the specifications of the 1980's have been replaced with Tests. i.e. "Must complete step X before you can start step Y". "Dev writes design and any other dev can implement" ... I am almost certain that in the real world it will fail to deliver good product and productivity. Too much time will be wasted making "perfect" tests, leaving not enough time to write robust, quality code. As soon as you set the expectation that developers are interchangeable like Construction site laborers (no disrespect), your management team will believe it, and tasks will be scheduled accordingly.

Waterfall is out of favor and is considered last centuries methodology, however there is nothing wrong with it if that is what you are trying to achieve, and in a few situations TDD combined with Waterfall might be a preferable approach (I am thinking outsourcing to sweat shops where the job goes to the lowest bidder....).

Developing by starting with tests is a great approach, however, requiring the completion of tests before code starts is likely to reproduce the entire class of problems that Waterfall and "design before code" created, and these are easily avoided.

I would suggest you look towards a more flexible approach - such as "Tests should be first reviewed at 30% of allocated task time, and final review at the 80%." This allows the code and tests to evolve together, but clearly sets the expectations that the tests are at least as important than the code.

Final acceptance then requires both code and tests to be complete and reviewed.

Title: Review tests first


答:
4GL is a bit of a nebulous term.

It is an attempt to describe a language were the programmer is able to solve a domain specific problem without having to worry about problems that are not specific to the domain (like storage/memory/communication). All these low level constructs are abstracted away by the language.

There are have been many attempts to achieve this over the years none have been "very" successful. This is usually because to be effective the problem domain that the language covers is very specific (and thus has a limited audience (that does not mean that they are not popular just that the audience is small)).

Of course because the term is not well defined there is also some abuse of the term. Sometimes it can be used to define frameworks where you just plug in modules of code and the infrastructure takes care of all the low level stuff while the plugin deals only with items at the domain level.

Title: What is meant by 4 GL?

Body:
I came across the term 4GL(generation language) in reading about Oracle ADF Busniess components . I want to know what exactly is 4GL ?

This is the actual quote from the book Oracle Fusion Guide:

Oracle ADF Business Components is the business services layer of choice in Oracle Fusion
      application development. Compared to other persistence layers, ADF Business Components
      provides exceptional built-in business application functionality and maximally declarative
      experience that makes it a perfect match for those who seek an end-to-end fourth generation
      language (4GL) Java EE development architecture.


答:
I think it depends on the maturity/life-cycle phase of the particular feature as to how useful the diagrams are to the process.

For new features and documenting outside in intent of features that are otherwise uncovered  by automated acceptance tests, diagrams are useful.  After adequate tests are in place, a bit less useful.

Nevertheless, they have value regardless of what and when.  If you  go to the trouble of creating them, hang onto them.  Perhaps treat them differently than traditionally prescribed.  Contrary to the RUP, don't treat them as living documents that get updated -- simply as a one time effort most useful and applicable to only a certain instant in time.  The drawings may not be "the" basis, but they were a basis for the decisions and design of the feature.

Title: Behavior-Driven Development / Use case diagram

Body:
Regarding growing of Behavior-Driven Development imposing acceptance testing, are use cases diagram useful or do they lead to an "over-documentation"?

Indeed, acceptance tests representing specifications by example, as use cases promote despite of a more generic manner (since cases, not scenarios), aren't they too similar to treat them both at the time of a newly created project?

From this link, one opinion is:

Another realization I had is that if you do UseCases and automated
  AcceptanceTests you are essentially doubling your work. There is
  duplication between the UseCases and the AcceptanceTests. I think
  there is a good case to be made that UserStories + AcceptanceTests are
  more efficient way to work when compared to UseCases +
  AcceptanceTests.

What to think about?


答:
Personally, I would be afraid to write tests first. The question is, what if the tests passed?

Let's say I spent a lot of effort up front to write good test codes.

After I completed the main code, it is very hard to resist to immediately try these tests.

Now what if the tests passed? Does it mean my code is correct to my best knowledge? Probably not, but I'll probably take the passing of the tests as the excuse to conclude the task.

If I don't have the tests up front, I'll spend a lot of efforts to review the code to "prove" it's correct.

When a problem is complicated enough, one's brain power is strained, and waning through time; I would rather budget the earlier time to reason about the main problems.

Title: Review tests first

Body: I am going to adopt TDD in our team and one of the ideas I have is to review tests first. So one would write interfaces, mocks, and tests first, submit them for a code review and once interfaces and tests (think specification) are approved an actual implementation can be written (theoretically, can be done by another developer). I wonder how viable this idea is?</p>


问:
Integrating feature request functionality directly into the business software you write?
What are relative merits of something like a button on a piece of custom bizware that says, "press me to ask for a feature" or "click here if something didn't work right".

The problem I'm trying to remedy is the general lack of formality surrounding feature requests.  Most specifically, the rate at which I receive walk-ups from end-users.  Taken one at a time, it can be beneficial, but sometimes it can hinder productivity on the larger scale.

Has anyone done something like this and has it been a general success or alternately somewhat a waste of time.  My instincts are not giving me a hint here.

答:
'Thick' desktop apps often include a 'feedback' menu item, grouped under the 'help' or 'about' menu.  I think that is about as close to a standard as you will find in that respect.

In another respect, if you have a new or troublesome feature, adding some method of directly launching that feedback interface might make sense.  As it matures, remove it to clean up and further simplify the interface.

By embedding the activator for the feedback interface on each feature of interest or concern, you can do things like pre-populating the feedback form by including specific contextual information in a bit of a hidden state if it helps understand what the user was doing.  Make the user aware each time you are gathering more information than they explicitly provide in the feedback form, perhaps even including a summary of that information.  They will not like to find out later they were giving information seemingly without "consent."

There is a risk that by including this feedback activation at several points within the guts of the application that the user will activate the feedback interface for features that they want to give information or raise concerns about which do not directly correspond with the feature the interface was launched from.  They may do this because the feedback activator they launched from was more convenient, most familiar with (or remember seeing the activation control for feedback in one spot but not others), or because they may not realize you populate the form with context information to a hidden or subdued area.  With this in mind, be aware that the context information you pull in may not be valid or related in any way to the problem or concern or feedback at hand.  It is only valid when the feedback interface is activated from the feature of concern.