问:
How to format this line according to PEP 8?
I'm trying to adhere to PEP 8, with a 78 character limit on the length of my lines.

I have the following statement:

```<code>startTime = time.strptime(request.GET.get('st', (dt.datetime.now() - dt.timedelta(days=1)).strftime("%d/%b/%Y:%H:%M:%S")), "%d/%b/%Y:%H:%M:%S")
</code>```

How should I format it so that it adheres to PEP8 (where should I break it into new lines?)

答:
You shouldn't break it into new lines, since the code itself is wrong.

First, you have code duplication. The compiler won't blame you and won't qualify it as an error, but programmers who will have to maintain your code later surely will.

By removing code duplication, instead of:

```<code>startTime = time.strptime(request.GET.get('st', (dt.datetime.now() - dt.timedelta(days = 1)).strftime("%d/%b/%Y:%H:%M:%S")), "%d/%b/%Y:%H:%M:%S")
</code>```

you get:

```<code>const dateFormat = "%d/%b/%Y:%H:%M:%S"
startTime = time.strptime(request.GET.get('st', (dt.datetime.now() - dt.timedelta(days = 1)).strftime(dateFormat)), dateFormat)
</code>```

Another error is that you're doing too much in a single line. Who are you writing for? The compiler, or other developers (including yourself in six months)?

If you're writing for a compiler, indeed, collapsing everything into a big mess may give you a few microseconds advantage of compile time and a few microseconds of advantage every time the app is running. Or maybe there is no gain. Or maybe such code is slower. You have to profile it to know.

If you're writing for humans, and you should, then don't be greedy with whitespace, newlines, intermediary variables and functions. For example, all those parentheses together are a maintenance nightmare. I could hardly find what is closed where. It's also hard to understand what the code is doing just by looking at it.

What about:

```<code>const dateFormat = "%d/%b/%Y:%H:%M:%S"
dayAgo = (dt.datetime.now() - dt.timedelta(days = 1)).strftime(dateFormat)
webResponse = request.GET.get('st', dayAgo)
startTime = time.strptime(webResponse, , dateFormat)
</code>```

Note that standards are good for they are. They are here for you, not the opposite. They should help you, not force you to spend hours doing meaningless changes.

If a standard tells that the line should be 80 characters long, but you have a perfectly valid case of a readable line with 81 characters in it, screw the standard.

In this particular case, the original line was indeed badly written, and it was a case where the standard gave you a hint that something was wrong. This is not always the case.

Body:
You shouldn't break it into new lines, since the code itself is wrong.

First, you have code duplication. The compiler won't blame you and won't qualify it as an error, but programmers who will have to maintain your code later surely will.

By removing code duplication, instead of:

startTime = time.strptime(request.GET.get('st', (dt.datetime.now() - dt.timedelta(days = 1)).strftime("%d/%b/%Y:%H:%M:%S")), "%d/%b/%Y:%H:%M:%S")

you get:

const dateFormat = "%d/%b/%Y:%H:%M:%S"
startTime = time.strptime(request.GET.get('st', (dt.datetime.now() - dt.timedelta(days = 1)).strftime(dateFormat)), dateFormat)

Another error is that you're doing too much in a single line. Who are you writing for? The compiler, or other developers (including yourself in six months)?

If you're writing for a compiler, indeed, collapsing everything into a big mess may give you a few microseconds advantage of compile time and a few microseconds of advantage every time the app is running. Or maybe there is no gain. Or maybe such code is slower. You have to profile it to know.

If you're writing for humans, and you should, then don't be greedy with whitespace, newlines, intermediary variables and functions. For example, all those parentheses together are a maintenance nightmare. I could hardly find what is closed where. It's also hard to understand what the code is doing just by looking at it.

What about:

const dateFormat = "%d/%b/%Y:%H:%M:%S"
dayAgo = (dt.datetime.now() - dt.timedelta(days = 1)).strftime(dateFormat)
webResponse = request.GET.get('st', dayAgo)
startTime = time.strptime(webResponse, , dateFormat)

Note that standards are good for they are. They are here for you, not the opposite. They should help you, not force you to spend hours doing meaningless changes.

If a standard tells that the line should be 80 characters long, but you have a perfectly valid case of a readable line with 81 characters in it, screw the standard.

In this particular case, the original line was indeed badly written, and it was a case where the standard gave you a hint that something was wrong. This is not always the case.


问:
use of LGPL libraries in closed source android software
I'm investigating the legal issues of using LGPL native libraries in a closed source Android software.

As for now, my research on the subject shows that using LGPL libraries in closed source software is doable, and that the requirements are not specially high.

On a regular application (for example a C closed source application), I would dynamically link the library, and distribute the binaries of the application along with the library with proper reference to it and instruction on how to replace this library with the version the user would like to. (I may be forgetting some stuff here but this is not the point of my question).

My question refers to Android software and JNI. Assuming I am building an Android software using JNI I do have :

My java source
A JNI folder including :

Android.mk file for the compilation of the application

the library source code

.cpp/.h files linking the source code with JNI

To compile my application, two steps are required :

Compilation of the library using NDK to generate a *.so file

Compilation of the Android application using Ant. The java code includes a System.loadlibrary("nameOfTheLibrary")

The problem I am facing is that the source code of the library is first compiled to a *.so file. This can be considered as derivative work, am I right ?

How could I include the native LGPL libraries and distribute it in a proper way to avoid any legal problems ?

答:
Your code is compiled to a .so. But that includes just your sources and any libraries linked statically, i.e. as .a. Libraries that were compiled separately to .so are separate.

So you must generate separate .so files from the LGPL parts and separate .so from your code, which will be linked to the other .sos (this is the dynamic link that stops LGPL from applying further). All of those .so files than have to be packed into the .apk (the build system should place them in the right directory automatically) and the user can replace them and repack the .apk (and have to sign it with their key, but since any valid key will do, that's fine)

The build system should be able to define any number of shared library modules (I don't remember the details, I am compiling android libraries with CMake, so look at the documentation). And remember that the makefiles describing how to build the LGPL libraries are considered source by LGPL too.

ContentLicense: CC BY-SA 3.0


答:
While you have to rebuild the LGPL lib, that doesn't mean your app that links to it falls under the definition of derivative work - only that your work in rebuilding is.

So, as long as you release the code (contribute it back to the project, for example) that enables you to get it running on Android, you're going to be ok.

Title: use of LGPL libraries in closed source android software

Body:
I'm investigating the legal issues of using LGPL native libraries in a closed source Android software.

As for now, my research on the subject shows that using LGPL libraries in closed source software is doable, and that the requirements are not specially high.

On a regular application (for example a C closed source application), I would dynamically link the library, and distribute the binaries of the application along with the library with proper reference to it and instruction on how to replace this library with the version the user would like to. (I may be forgetting some stuff here but this is not the point of my question).

My question refers to Android software and JNI. Assuming I am building an Android software using JNI I do have :

My java source
A JNI folder including :

Android.mk file for the compilation of the application

the library source code

.cpp/.h files linking the source code with JNI

To compile my application, two steps are required :

Compilation of the library using NDK to generate a *.so file

Compilation of the Android application using Ant. The java code includes a System.loadlibrary("nameOfTheLibrary")

The problem I am facing is that the source code of the library is first compiled to a *.so file. This can be considered as derivative work, am I right ?

How could I include the native LGPL libraries and distribute it in a proper way to avoid any legal problems ?


问:
How should I start with Lisp?
I've been programming for years now, working my way through various iterations of Blub (BASIC, Assembler, C, C++, Visual Basic, Java, Ruby in no particular order of "Blub-ness") and I'd like to learn Lisp. However, I have a lot of intertia what with limited time (family, full time job etc) and a comfortable happiness with my current Blub (Java).

So my question is this, given that I'm someone who would really like to learn Lisp, what would be the initial steps to get a good result that demonstrates the superiority of Lisp in web development? Maybe I'm missing the point, but that's how I would initially see the application of my Lisp knowledge.

I'm thinking "use dialect A, use IDE B, follow instructions on page C, question your sanity after monads using counsellor D". I'd just like to know what people here consider to be an optimal set of values for A, B, C and perhaps D. Also some discussion on the relative merit of learning such a powerful language as opposed to, say, becoming a Rails expert.

Just to add some more detail, I'll be developing on MacOS (or a Linux VM) - no Windows based approaches will be necessary, thanks.

Notes for those just browsing by

I'm going to keep this question open for a while so that I can offer feedback on the suggestions after I've been able to explore them. If you happen to be browsing by and feel you have something to add, please do. I would really welcome your feedback.

Interesting links

Assuming you're coming at Lisp from a Java background, this set of links will get you started quickly.

Using Intellij's La Clojure plugin to integrate Lisp (videocast)

Lisp for the Web

Online version of Practical Common Lisp (c/o Frank Shearar)

Land of Lisp a (+ (+ very quirky) game based) way in but makes it all so straightforward

Install Clojure and Sublime 2 on MacOS an excellent getting started guide

Look at the Clojure in Action book. Worked for me.

答:
To get a good basic introduction to the language, read Peter Seibel's Practical Common Lisp. The book's excellent.

Setting up emacs and SLIME can be tricky for a newbie, where "tricky" varies in magnitude depending on your OS. As usual, Windows gets the short end of the stick, but people have done the hard part and written it up (SBCL, Emacs, SLIME).

Once that's out the way, Planet Lisp referenced an article recently describing how to set up Hunchentoot and nginx.

OS-specific edit: MCLIDE might be a good place to start. I installed it, but haven't had the chance to actually use it, so I can't say anything useful about it. It certainly looks interesting!

Edit: Eclipse has the Cusp plugin, too.

Title: How should I start with Lisp?

ContentLicense: CC BY-SA 2.5


问:
Host an MVC 3 with Razor syntax app on old server
I just started a new job, I have to create a web app for them and host it on their intranet on an Windows 2003 R2 server with SQL server 2008.

As said in the question, I'll work on a MCV3 with Razor syntax application.

I know that it won't work easily or even not work at all.

On a recent server you have to install something more (I don't remember the name) for the Razor to be understood. What about on this old server? Will I get it to work or should I tell them to buy a more up to date server?

答:
Install is pretty easy -- šljaker has that nailed.

The other trick is url handling. IIS7 makes it very easy to do a totally managed pipeline. For IIS6 you either need to resort to tricks like adding extensions onto your controllers -- such as the suggested pattern of http://www.example.com/somecontroller.mvc/someaction or a perhaps more palatable http://www.example.com/somecontroller/someaction.aspx to get IIS6 to use the aspnet_isapi module to handle the request. Another option would be to use a wildcard mapping but that creates a bit of extra strain for static content such as images and stylesheets which might or might not matter to you.

Personally, I would encourage them to upgrade the server OS if at all possible though, really not worth fighting with a 10 year old server stack for most things.


问:
How to make ASP .NET MVC website have a continuous process running?
This website is supposed to be a game where the players have some 'buildings' and these buildings produce resources. E.g. an iron mine may produce 30 pieces of iron ore per minute and automatically add it to the user's inventory. It doesn't matter whether the user is online or not, it should be running 24/7. So when the user does log in to their account, they will see their stack of iron ore has built up depending on how long it has been.

Some pointers in the right direction would be greatly appreciated :)

答:
It should not be your {whatever technology} website that should be doing this processing at all.

A background process of some sort should be doing the processing, and persisting it to the database intermittently.

That way other users can interact with the data whenever it needs to.

When you login to your website, it will interact with both the background process and the database to figure out your current state.


问:
Best Practices for calculating data in GIS-like web application
Let's assume that we have a simple GIS-like application, which presents (using Google Maps or anything similar) recorded tracks. Each track consists of points (data portions) with geo-data and additional information, like speed, altitude and similar attributes.

Basing on these additional params, I want to calculate some extra information, like average speed. What kind of data should web client receive and on which side is it the best to perform necessary calculations:

client side: client receives (via AJAX) pure array of data (points with additional params) and all the calculations are done in Javascript in the browser,

server side: client receives content ready to be put in the proper places, like value of average speed, and all the calculations are done on server.

Personally I was always choosing (somehow automatically)the  first option, as I thought (correct me, if I'm wrong) this gives me more flexibility. But, right now, after reading some docs and pages, I can see clearly, that I may be wrong. So, what is the best practice in such situation?

答:
I think the most important things in this case are Response time (on page load) and Responsivity (in the GUI during interaction).

There is a part of the application use case where some static, more or less constant data is sent to the browser, but thereafter the interaction with the user will determine what data will actually have to be calculated.

If you STORE processed-data in your server, prior to any possible request, you could end up with redundant storage space (since speed, acceleration, power, slope, are directly derived from position);

If you CREATE processed-data on demand for each request, you could end up with some processing overhead AND some impact in response time to process and send the data;

If you SEND raw data and populate derived data on the client side, this could collectively impact response time, because data would have to be sent and calculated anyway, just in different order than in the previous case, because computation is delegated to the client. It would be "good for you", and would create a good GUI responsivity for the client during interaction (the whole data would be available all the time) at the cost of a slower loading time;

I you just send the data from the server, and don't calculate anything until the user explicitly asks for it (for example, selecting a trajectory, or a segment of a trajectory), then you would have the best response time, and the responsivity of the interface would depend only on sheer data volume AND the strategy you use to perform calculations asynchronously (so as not to freeze the UI), providing clear visual indications of progress, like progress bars or spinning cursors.

I am an enthusiast cyclist and map-geek, and it seems to me that the last approach is the most widely adopted in sites like STRAVA and RideWithGPS. The most common scenario are tracks with just a few hundreds of points anyway, and the types of calculations are quite simple and well-suited to javascript algorithms (basic arithmetics and trigonometry).

Hope this helps!


问:
What is the proper way to distinguish between keywords and identifiers?
I'm aware that most modern languages use reserved words to prevent things like keywords from being used as identifiers.

Reserved words aside, let's assume a language that allows keywords to be used as identifiers. (For example, in Ruby a keyword can be used as a method name). During compilation, how would you deal with this ambiguity?

The lexing phase doesn't seem like a good fit because it would have to consider the tokens around it. The parsing phase also doesn't seem like a good fit since ideally the parser would work with tokens that are unambiguous.

If I had to design it myself, I suppose I would have the lexer yield an ambiguous token, then have another level that considers the ambiguous token in the context of the tokens around it, (e.g. does the ambiguous token follow a def keyword? Then it must be an identifier.) Then, I would hand the unambiguous tokens to the parser.

In languages that allow keywords to be used as identifiers, what is the standard way for the compiler to tell them apart?

答:
I don't think there is a standard way.

Sometimes you will see some lexer tricks that implements rules like "pure is a keyword only if the next token is the keyword native".

At other times the grammer may employ the fact that in some circumstances all or some keywords can be interpreted as identifiers without introducing ambuguity.


问:
Is it best to use "get" as a prefix for getters?
if I had a boolean (property) shouldAutoLogin is it better to name the getter getShouldAutoLogin or just shouldAutoLogin so that it reads more like English?

ex :

```<code>if(shouldAutoLogin){
    ...
}
</code>```

or

```<code>if(getShouldAutoLogin){
    ...
}
</code>```

答:
The naming convention for getters are normally,

getAutoLogin() if getting some string or object.

isAutoLogin() for boolean.


答:
I always find that code should be as human readable as possible. It helps to clearly define the intentions of the code.
In your case think about what both the positive and negative uses of your boolean and how it would impact readability and the intentions of your logic would be.

```<code>if(!shouldAutoLogin)
{
     ....
}
</code>```

versus

```<code>if(!getShouldAutoLogin)
{
    ....
}
</code>```

Which gives a clearer meaning to the intention of what the code is trying to do?

As others have suggested, I would even rename the variable to

```<code>isShouldAutoLogin
</code>```

or similar

Title: Is it best to use "get" as a prefix for getters?

Body:
if I had a boolean (property) shouldAutoLogin is it better to name the getter getShouldAutoLogin or just shouldAutoLogin so that it reads more like English?

ex :

```<code>if(shouldAutoLogin){
    ...
}
</code>```

or

```<code>if(getShouldAutoLogin){
    ...
}
</code>```

Body:
I always find that code should be as human readable as possible. It helps to clearly define the intentions of the code.
In your case think about what both the positive and negative uses of your boolean and how it would impact readability and the intentions of your logic would be.

if(!shouldAutoLogin)
{
     ....
}

versus

if(!getShouldAutoLogin)
{
    ....
}

Which gives a clearer meaning to the intention of what the code is trying to do?

As others have suggested, I would even rename the variable to

isShouldAutoLogin

or similar


问:
Should I encrypt files saved by my program
I'm trying to decide on what format I should save data in, and hopefully this question will help me come to a decision. The program I'm writing uses 'databases' in which word=meaning (not a dictionary, that was just an example). I don't really want people to be able to manually edit these 'databases' without my program easily, but at the same time I'm looking for interoperability between programming langauges (namely C#, PHP, Java and Objective C)

At the minute, the main contenders are SQLite, XML and SQL Server CE (although PHP doesn't have support for Server CE, but that doesn't have to be too much of an issue). Really, my question is, should I use encryption because I have read that it is often just as easy to decrypt? And if you support encryption, how do you deal with the encryption key - do I just generate a long, complicated string?

Or is binary enough? Nothing in the database is too critical, however I would like to have an isEditable 'key' so my program knows whether to allow edits or not. And I'd also like to use my own file extension.

答: If all you're looking for is to discourage external editing, while providing for interoperability among different implementation languages, consider simply compressing the file.  It'll look like line noise if opened in a text editor, but if you use a standard compression algorithm you should be able to find (or write) a file compression library for most popular languages.  You even get the benefit of saving storage space, if your data sets get large.</p>


问:
Modern practices for stored procedure-based applications
I work in a fairly large and old solution that has many entry points for different kinds of clients, with web sites for public access, web sites for internal access, some web sites and web services for partner companies access, etc.

All those applications use different (Microsoft-based) technologies, such as Classic ASP, ASP.NET WebForms, MVC 3, ASMX, DTSX, etc. The code has no standard, and many programmers with no experience on the codebase and in the business have coded their own way.

The central point of all the applications is a SQL Server database with tons of stored procedures that implement all the business rules. The applications are usually just a shell for the database. The data access is done with no framework or ORM (using pure ADO.NET, usualy rewriting everything from creating a connection to iterating through a data reader on each method, function or whatever).

What are the most modern best practices for creating an productive data access layer based on stored procedures?

For business reasons, we cannot rewrite the older applications (the customer won't pay for that, and the volume of daily work is too large for doing that internally). We also cannot use any third-party ORM (the architects are against it for "security reasons"). So, the improvements must be more like refactorings.

答:
Ah, the classic "1000 line business rule stored procedure, no unit tests, ball of mud application".

It allows production tweaks because you can just login to SQL server and update a little bit of SQL code and you don't need to redeploy your app.

Well, basically my advice is to stop putting new features business rules in the stored procedure layer for a start.

Anything that you are writing from scratch that accesses the database, and assuming you can't use ORM tools, only put your CRUD SQL in stored procedures. Keep your business rules in your code, and make sure it is unit tested.

You don't need to use ORM tools to achieve this, (although the "security reasons" excuse sounds like BS to me)

If you have multiple applications accessing a common database, you might want to look at introducing a common Service layer, to provide common functionality to multiple applications in a consistent manner.


答:
Naming a method in a cleverly readable way has advantages. Naming methods so that their intent and nature is easy to derive from the name ("getters have prefix get, boolean predicates, is") has advantages, too.

It's up to you to strike a balance, but in a large project benefits of consistency usually outweigh those of accidental cleverness.

Renaming a method to make the name both readable and convention-conformant is a nice daily exercise. In your particular case I'd consider something like isAutoLoginEnabled or getAutoLoginFlag.

OTOH you you have a bunch of conceptually similar methods that all can follow the pattern of shouldDoSomething, your original name can be fine, too.


问:
When being a technical genius is not enough to be a successful developer?
There has been a lot of discussion around the excellent question "Will high reputation in Stack Overflow help to get a good job?". I immediately agreed with JoshK that basically said "No" (I'll will explain why), but Joel chimed in with lot of convincing facts which made me upvote him as well.

My question is what other skills (other than being a technical genius) do you require from a developer? To get the job, or to keep it.

I believe being a genius is far from being enough. I have met many technical geniuses in various companies I have worked for that impressed me a lot, but sadly in lot of cases, they were simply fired after a few months or put in ivory towers (mainly because of internal mutiny from other developers). I've seen many in personal distress as a result of this which I understand.

That's why I'm a big fan of non-technical questions for technical positions. I like to know how the candidate will interact with others (including non-technical employees), how much consideration he will have for the business, if he will work for the desired outcome, and so on.

I would like to know what you require from your developers and WHY it's important (after all, you hire someone to write code, don't you? Why would you want him to be assertive?). Ideally, I'd like you to come up with an example question you would ask during interviews in support of your answer.

答: Persistance is a skill that I don't see mentioned very much. And it is a skill - the ability to make yourself work through a problem, even if you can't see the end. Many people don't do this; they work on momentum only, or just do the minimum to get by. Unfortunatly, there's no way to tell whether a person has this trait by talking to them. You really need to be able to talk to others that have worked with the person. References can do this, but that option is not always available.</p>


问:
Why do old C-style method names continue being used in modern languages?
I understand that in the earlier days of computing, shorter method names like printf made sense, because storage was limited. But why do modern languages like Python and Go still use the less readable names from the C APIs? Why don't they switch to a more readable form like print_format, the same goes for other names. I wouldn't mind having to write make_directory instead of mkdir in go.

People have suggested that this question has been asked before, but the questions I've found are about whether abbreviated names are bad practice. This question assumes that the answer to this question is usually yes.

答:
Because your assumption that "longer names are better readable" is simply not true!

On the contrary, the shorter a name, the higher the chances (other things being equal), that you can identify the name at once, like an icon.

But there's more: the chances that you confuse identifiers that have only a few differences is greater the longer the names are.

As always, there is a middle ground. A public method in an API should not be a single letter, and a temporary local variable must notbe a poem.


答: I tend to write getAutoLogin when I want the method to return a data type, like an int or a String. However, if I want to check if it's true or false (boolean), I simply swap the get to an is like this: getAutoLogin > isAutoLogin. I believe there is a naming convention for every language.


答:
Traditionally, getters are prefixed with get or is for the value.  This is often mentioned in java style guides.  For example Java Programming Style Guide (this is just one example).

The convention for such method names is occasionally enforced in tools that use reflection or expect certain styles of code.  For example, again in Java (though JSP's Expression Language), ${foo.bar} will be translated into the call foo.getBar() when the jsp is compiled.  The getValue() is enforced in this way so that it becomes more than just a convention.

As mentioned, the above examples are from Java.  This is a convention for Java.  Other languages have other conventions that should be looked at and likely followed too.  Some languages use properties (and can do other neat things with them like copy on request or read only).

Look into the style guides for your particular language choice.  It is probably a good idea to follow them when possible so that other coders, when reading your code, will more quickly be able to get into the code without trying to figure out your personal style.


问:
Where to load and store settings from a file?
I think this question should apply to most programs that load settings from a file. My question is from a programming point of view, and it is really how to deal with the loading of settings from a file in terms of different classes and accessibility. For instance:

If a program had a simple settings.ini file, should its contents be
loaded in a load() method of a class, or perhaps the constructor?

Should the values be stored in public static variables, or should
there be static methods to get and set properties?

What should happen in the event of the file not existing or not being readable? How would you let the rest of the program know it can't get those properties?

etc.

I'm hoping I'm asking this in the right place here. I wanted to make the question as language agnostic as possible, but I'm mainly focusing on languages that have things like inheritance - especially Java and C#.NET.

答:
In general (in my opinion), it's best to let the application deal with how the configuration is stored, and pass the configuration into your modules. This allows flexibility in how the settings are saved so that you can target files or webservices or databases or...

Plus, it puts the burden of "what happens when things fail" on the application, who knows best what that failure means.

And it makes it tons easier to unit test when you can just pass in a configuration object rather than having to touch the filesystem or deal with concurrency issues introduced by static access.


问:
Can TCP/IP Sequence and Acknowledgement numbers be controlled?
Normally TCP/IP Sequence and Acknowledge numbers are 32 bit. However, I need a way to shorten them to be 24 bit (it's an experiment in deep inspection firewalls).

Question: Is it possible to shorten the bit resolution of the Seq/Ack numbers in windows without the knowledge of the application? (which in this case is IIS)

I want to use those top 8 bits to store some session information.

答: I would think so, those numbers usually aren't exposed to the application layer, they're only used by the TCP/IP stack.  I'm not sure how you'd actually go about doing it, short of writing your own network driver, but I assume you've got a plan.</p>


答:
Theoretically, this could be done, but in practice, you'll probably need to find somewhere else to store that information. Each end of the connection is allowed to choose any arbitrary number it wants, but using anything other than a completely random number leaves a gaping vulnerability to certain types of attacks. This might be acceptable to you, if the machine in question is on a tightly controlled network, but because of how bad an idea this is, you will essentially need to build your own TCP layer; operating systems generally won't expose an API to shoot yourself in the foot like this.

And even then, you'll need to do this at both ends, since each end of the connection chooses its Sequence Number independently. And you'd need to make sure rollover is handled properly. If you really and truly insist on this, then that's fine, but the machines that you do it on will have issues properly talking TCP with anything else due to the issue of rollover, and you're going to need to rewrite a lot. You'll almost certainly be better served trying to find somewhere else to store that session information.

Title: Can TCP/IP Sequence and Acknowledgement numbers be controlled?

Body:
Normally TCP/IP Sequence and Acknowledge numbers are 32 bit. However, I need a way to shorten them to be 24 bit (it's an experiment in deep inspection firewalls).

Question: Is it possible to shorten the bit resolution of the Seq/Ack numbers in windows without the knowledge of the application? (which in this case is IIS)

I want to use those top 8 bits to store some session information.


问:
Throwing an exception for errors that can be fixed
Say I have a class like this:

```<code>public class MyObject
{
    public List<string> MyCollection { get; set; }
}
</code>```

And a method like this:

```<code>public void DoSomething(MyObject object)
{
    if(object.MyCollection == null)
    {
        // MyCollection must not be null
        // Should I...

        // a)
        object.MyCollection = new List<string>();

        // b)
        throw new ArgumentException("MyCollection can not be null");
    }
}
</code>```

I do not have control over MyObject. Normally I'd just instantiate the collection in the constructor and be done with it. Should I just instantiate the collection in my method, or throw an exception?

答:
What you've got here are called guard statements, and you absolutely should throw an exception if object.MyCollection is null.

Exceptions are meant for exceptional circumstances, and since you specify that object.MyCollection must not be null this would be indeed exceptional.  Just make sure the exception you throw is of a suitable type (for example an ArgumentNullException).


答:
Definitely B, it would be a violation of Single Responsibility Principle to do A since that's really not the purpose of that block of code.

my personal preference is only to do validation like that however on boundary methods; like web service endpoints or general API fascia of some nature, after that I find maintainability improved when the code let's improper usage just cause an error naturally (dereferencing for instance in your case), this way when what previously was invalid input becomes valid input, there's less code churn. Besides, an exception will be thrown if you use it, so why bother throwing your own exception?

This preference about often avoiding guard statements is mine and mine alone, take it with a grain of salt and only to mean that you should analyze your scenarios yourself to see what makes most sense to you, don't always use guard statements just because "best practices"

That said, for this particular case I tend to take advantage of the null coalesce operator; if I want to do something with a collection which I feel may be null for some reason, I'll instead deal with (thatCollection ?? new List<T>()) in place of it, so you end up treating a null list like an empty list as a part of your functions contract as opposed to meddling with somebody elses object which isn't your responsibility. This is only valid if you are not adding elements to the collection.

I take the approach I do just to be robust as it avoids future churn, though I make certain it's a valid behaviour within the functional requirements before I take that approach (it often is). Remember:

Be conservative in what you send, be liberal in what you accept

Title: Throwing an exception for errors that can be fixed

Body:
Say I have a class like this:

```<code>public class MyObject
{
    public List<string> MyCollection { get; set; }
}
</code>```

And a method like this:

```<code>public void DoSomething(MyObject object)
{
    if(object.MyCollection == null)
    {
        // MyCollection must not be null
        // Should I...

        // a)
        object.MyCollection = new List<string>();

        // b)
        throw new ArgumentException("MyCollection can not be null");
    }
}
</code>```

I do not have control over MyObject. Normally I'd just instantiate the collection in the constructor and be done with it. Should I just instantiate the collection in my method, or throw an exception?


问:
Very-Loose Coupling and Dependency Injection for Database Management
I'm currently setting up a MongoDB database for a web-app. I'm running node.js and using Mongoose to help manage mapping, validation ect.

I'm wondering if it's a good idea to really decouple MongoDB from my code, just on the off-chance we want to switch to something like CouchDB a little later. Specifically, I'd make a databaseManger module that is responsible for setting up Mongoose/Mongo, defining the mongoose models, managing replica sets, and doing some extra validation. This manager would export a generic API, and handle the details of the queries internally. The manager would then be passed around via dependency injection.

Does this make sense? Or am I kind-of redoing some of the mongoose functionality?

Any advice is appreciated.

答:
I always try and abstract out data access out of my application code. In node.js, I create repositories for managing data access to any top-level item (aggregate-root, in DDD terms).

Those repositories expose a very clean domain-friendly API to the application, which hides any implementation detail - such as whether it uses MySQL or MongoDB as a back-end. It also converts the raw database-returned data, into a proper domain object.

In a more traditional language, some of those methods would look like this (let's use an ad repository as an example):

```<code>Ad #find(id)
Ad[] #findAll()
Ad[] #findByVendor(vendor)
</code>```

Or, more asynchronously:

```<code>#find(id, cb)
#findAll(cb)
</code>```

Those callbacks should accept err, and then the constructed domain object(s) as the second data parameter.

Also, try and avoid just having basic CRUD interactions, instead try to expose things that actually have meaning in your application.

The other added benefit is that your application code is all much easier to test in isolation, because it's not talking to MongoDB or Mongoose directly.

Body:
I always try and abstract out data access out of my application code. In node.js, I create repositories for managing data access to any top-level item (aggregate-root, in DDD terms).

Those repositories expose a very clean domain-friendly API to the application, which hides any implementation detail - such as whether it uses MySQL or MongoDB as a back-end. It also converts the raw database-returned data, into a proper domain object.

In a more traditional language, some of those methods would look like this (let's use an ad repository as an example):

Ad #find(id)
Ad[] #findAll()
Ad[] #findByVendor(vendor)

Or, more asynchronously:

#find(id, cb)
#findAll(cb)

Those callbacks should accept err, and then the constructed domain object(s) as the second data parameter.

Also, try and avoid just having basic CRUD interactions, instead try to expose things that actually have meaning in your application.

The other added benefit is that your application code is all much easier to test in isolation, because it's not talking to MongoDB or Mongoose directly.


问:
What can REST API do that a API using HTTP URL query strings cannot do?
I'm learning about REST and had the chance to build a basic REST API.  After doing so, most of the material I read was internalized and I now have a better understanding of it.

However, I do not see any real difference yet as to the tangible benefits of using REST over the old way I was doing things, which was simple URL query strings.  It seems they both do the exact same things.  But with REST, it's cleaner, and standardized.

I thought REST had additional technical benefits.  If they do, what are they?  Or is REST simply that - an agreed way to implement and API?

答: There are no additional technical benefits. Many people simply think using a RESTful style makes for a cleaner interface. If nothing else, consumers can usually make inferences about how a RESTful API works (GET to fetch data, PUT and POST to create or save data, DELETE to delete, etc), whereas with random query strings they have to read the documentation a bit more closely.</p>


问:
When is it appropriate to start using the next revision of a tool when dogfooding?
Specifically, I am working on a tool that integrates a DVCS and build system, but I image the challenge I am facing would arise for anyone developing a "meta" tool (compiler, VCS, build system, test runner, etc.) that they wish to develop through "dogfooding".

My question is: in a scrum-style release process using the branching workflow, at what point do I start using a newer version of the tool in the development cycle of the tool?

I'm looking for a process to create balance between:

constantly use the develop version of the tool:  I find I am breaking my own development as changes get incorporated.

constantly use the master version of the tool: any issues I uncover through dogfooding are issues that have already been released.

答:
Based on the accepted answer, I'm going to expand on the branching workflow to maintain branches similar to the following:

master: merges with release-* upon closure

dogfood: branches from master; includes fixes identified while dogfooding; merges from develop when the software is deemed "stable" for internal use; the head of this branch can be moved back in time if needed

develop: branches from master; includes ongoing changes, bugfixes, and merges from dogfood and feature-* branches

feature-*: branches from develop; includes changes for a particular new feature

release-*: branches from dogfood when the software is deemded "stable" for external use; includes documentation updates and minor bugfixes prior to merging with master


答:
This is actually a really important question and it is often done wrongly as it is not given enough importance even though it is a core part of pretty much every application. Here are my guidelines:

Your config class, which contains all the settings should be just a plain old data type, struct/class:

```<code>class Config {
    int prop1;
    float prop2;
    SubConfig subConfig;
}
</code>```

It should not need to have methods and should not involve inheritance (unless it is the only choice you have in your language for implementing a variant field - see next paragraph). It can and should use composition to group the settings into smaller specific configuration classes (e.g. subConfig above). If you do it this way it will be ideal to pass around in unit tests and the application in general as it will have minimal dependencies.

You'll likely need to use variant types, in case configs for different setups are heterogeneous in structure. It is accepted that you'll need to put a dynamic cast in at some point when you read the value to cast it to the right (sub-)configuration class, and no doubt this will be dependent on another config setting.

You should not be lazy about typing in all the settings as fields by just doing this:

```<code>class Config {
    Dictionary<string, string> values;
};
</code>```

This is tempting as it means you can write a generalised serialisation class that doesn't need to know with what fields it's dealing, but it is wrong and I'll explain why in a moment.

Serialisation of the config is done in a completely separate class. Whatever API or library you use to do this, the body of your serialisation function should contain entries that basically amount to being a map from the path/key in the file to the field on the object. Some languages provide good introspection and can do this for you out of the box, others you'll have to explicitly write the mapping, but the key thing is you should only have to write the mapping once. E.g. consider this extract I adapted from the the c++ boost program options parser documentation:

```<code>struct Config {
   int opt;
} conf;
po::options_description desc("Allowed options");
desc.add_options()
    ("optimization", po::value<int>(&conf.opt)->default_value(10);
</code>```

Note that the last line basically says "optimization" maps to Config::opt and also that there is a declaration of the type that you expect. You want the reading of the config to fail if the type is not what you expect, if the parameter in the file is not really a float or an int, or doesn't exist. I.e. Failure should occur when you read the file because the problem is with the format/validation of the file and you should throw an except/return code and report the exact problem. You should not delay this to later in the program. That's why you should not be tempted to have a catch all Dictionary style Conf as mentioned above which won't fail when the file is read - as casting is delayed until the value is needed.

You should make the Config class read-only in some fashion - setting the contents of the class once when you create it and initialise it from file. If you need to have dynamic settings in your application that change, as well as const ones that don't, you should have a separate class to handle the dynamic ones rather than trying to allow bits of your config class to be not read-only.

Ideally you read in the file in one place in your program i.e. you only have one instance of a "ConfigReader". However, if you're struggling with getting the Config instance passed around to where you need it, it is better to have a second ConfigReader than it is to introduce a global config (which I'm guessing is what the OP means by "static"), which brings me to my next point:

Avoid the seductive siren song of the singleton: "I'll save you having to pass that class class around, all your constructors will be lovely and clean. Go on, it'll be so easy."
Truth is with a well designed testable architecture you'll hardly need to pass the Config class, or parts of it down through that many classes of your application. What you'll find, in your top level class, your main() function or whatever, you'll unravel the conf into individual values, which you'll provide to your component classes as arguments which you then put back together (manual dependency injection). A singleton/global/static conf will make unit testing your application much harder to implement and understand - e.g. it will confuse new developers to your team who will not know they have to set global state to test stuff. It will also prevent you from running unit tests in parallel.

If your language supports properties you should use them for this purpose. The reason is it means it will be very easy to add 'derived' configuration settings that depend on one or more other settings.
e.g.

```<code>int Prop1 { get; }
int Prop2 { get; }
int Prop3 { get { return Prop1*Prop2; }
</code>```

If your language doesn't natively support the property idiom, it may have a workaround to achieve the same effect, or you simply create a wrapper class that provides the bonus settings. If you can't otherwise confer the benefit of properties it is otherwise a waste of time to write manually and use getters/setters simply for the purpose of pleasing some OO-god. You'll be better off with a plain old field.

You might need a system to merge and take multiple configs from different places in order of precedence. That order of precedence should be well-defined and understand by all developers/user e.g. consider windows registry HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE.
You should do this functional style so that you can keep your configs read only i.e.:

```<code>final_conf = merge(user_conf, machine_conf)
</code>```

rather than:

```<code>conf.update(user_conf)
</code>```

I should finally add that of course if your chosen framework/language provides its own built-in, well-known configuration mechanisms you should consider the benefits of using that instead of rolling your own.

So. Lots of aspects to consider - get it right and it will profoundly affect your application architecture, reducing bugs, making things easily testable and sort of forcing you to use good design elsewhere.

Title: Where to load and store settings from a file?

Body:
I think this question should apply to most programs that load settings from a file. My question is from a programming point of view, and it is really how to deal with the loading of settings from a file in terms of different classes and accessibility. For instance:

If a program had a simple settings.ini file, should its contents be
loaded in a load() method of a class, or perhaps the constructor?

Should the values be stored in public static variables, or should
there be static methods to get and set properties?

What should happen in the event of the file not existing or not being readable? How would you let the rest of the program know it can't get those properties?

etc.

I'm hoping I'm asking this in the right place here. I wanted to make the question as language agnostic as possible, but I'm mainly focusing on languages that have things like inheritance - especially Java and C#.NET.

Body:
This is actually a really important question and it is often done wrongly as it is not given enough importance even though it is a core part of pretty much every application. Here are my guidelines:

Your config class, which contains all the settings should be just a plain old data type, struct/class:

class Config {
    int prop1;
    float prop2;
    SubConfig subConfig;
}

It should not need to have methods and should not involve inheritance (unless it is the only choice you have in your language for implementing a variant field - see next paragraph). It can and should use composition to group the settings into smaller specific configuration classes (e.g. subConfig above). If you do it this way it will be ideal to pass around in unit tests and the application in general as it will have minimal dependencies.

You'll likely need to use variant types, in case configs for different setups are heterogeneous in structure. It is accepted that you'll need to put a dynamic cast in at some point when you read the value to cast it to the right (sub-)configuration class, and no doubt this will be dependent on another config setting.

You should not be lazy about typing in all the settings as fields by just doing this:

class Config {
    Dictionary<string, string> values;
};

This is tempting as it means you can write a generalised serialisation class that doesn't need to know with what fields it's dealing, but it is wrong and I'll explain why in a moment.

Serialisation of the config is done in a completely separate class. Whatever API or library you use to do this, the body of your serialisation function should contain entries that basically amount to being a map from the path/key in the file to the field on the object. Some languages provide good introspection and can do this for you out of the box, others you'll have to explicitly write the mapping, but the key thing is you should only have to write the mapping once. E.g. consider this extract I adapted from the the c++ boost program options parser documentation:

struct Config {
   int opt;
} conf;
po::options_description desc("Allowed options");
desc.add_options()
    ("optimization", po::value<int>(&conf.opt)->default_value(10);

Note that the last line basically says "optimization" maps to Config::opt and also that there is a declaration of the type that you expect. You want the reading of the config to fail if the type is not what you expect, if the parameter in the file is not really a float or an int, or doesn't exist. I.e. Failure should occur when you read the file because the problem is with the format/validation of the file and you should throw an except/return code and report the exact problem. You should not delay this to later in the program. That's why you should not be tempted to have a catch all Dictionary style Conf as mentioned above which won't fail when the file is read - as casting is delayed until the value is needed.

You should make the Config class read-only in some fashion - setting the contents of the class once when you create it and initialise it from file. If you need to have dynamic settings in your application that change, as well as const ones that don't, you should have a separate class to handle the dynamic ones rather than trying to allow bits of your config class to be not read-only.

Ideally you read in the file in one place in your program i.e. you only have one instance of a "ConfigReader". However, if you're struggling with getting the Config instance passed around to where you need it, it is better to have a second ConfigReader than it is to introduce a global config (which I'm guessing is what the OP means by "static"), which brings me to my next point:

Avoid the seductive siren song of the singleton: "I'll save you having to pass that class class around, all your constructors will be lovely and clean. Go on, it'll be so easy."
Truth is with a well designed testable architecture you'll hardly need to pass the Config class, or parts of it down through that many classes of your application. What you'll find, in your top level class, your main() function or whatever, you'll unravel the conf into individual values, which you'll provide to your component classes as arguments which you then put back together (manual dependency injection). A singleton/global/static conf will make unit testing your application much harder to implement and understand - e.g. it will confuse new developers to your team who will not know they have to set global state to test stuff. It will also prevent you from running unit tests in parallel.

If your language supports properties you should use them for this purpose. The reason is it means it will be very easy to add 'derived' configuration settings that depend on one or more other settings.
e.g.

int Prop1 { get; }
int Prop2 { get; }
int Prop3 { get { return Prop1*Prop2; }

If your language doesn't natively support the property idiom, it may have a workaround to achieve the same effect, or you simply create a wrapper class that provides the bonus settings. If you can't otherwise confer the benefit of properties it is otherwise a waste of time to write manually and use getters/setters simply for the purpose of pleasing some OO-god. You'll be better off with a plain old field.

You might need a system to merge and take multiple configs from different places in order of precedence. That order of precedence should be well-defined and understand by all developers/user e.g. consider windows registry HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE.
You should do this functional style so that you can keep your configs read only i.e.:

final_conf = merge(user_conf, machine_conf)

rather than:

conf.update(user_conf)

I should finally add that of course if your chosen framework/language provides its own built-in, well-known configuration mechanisms you should consider the benefits of using that instead of rolling your own.

So. Lots of aspects to consider - get it right and it will profoundly affect your application architecture, reducing bugs, making things easily testable and sort of forcing you to use good design elsewhere.


问:
How should I architect a RESTful webservice to use 3rd party (i.e. Google, Facebook, Twitter) for authentication?
For my job we have a nice RESTful webservice we've built out that we use to drive a couple websites we have.  Basically the webservice lets you create and work with support tickets, and the website is responsible for the front end.  Any webservice requests use an auth header which we use to validate the user and their password for each call.

This year we're looking to expand our login options so that users on the website can log in via Google, Twitter, and Facebook (possibly others).  However I'm having a lot of trouble figure out how to architect this so the webservice can use the 3rd party authentication providers to ensure the users is who they say they are.  Is there any best practices out there for how to do this?

Currently we're thinking of having the website handle authenticating the users themselves, and then use a new setSessionId call that registers their current session with the webservice back end.  Each additional request to the webservice will pass along that sessionId and will validate it.  These seems okay, but I have that feeling in the back of my head that I'm not thinking this through and all my forum browsing and reading oauth and openid specs is just confusing me more.  Any tips for how to tackle this?

答:
I would definitely go with the solution it sounds like you've already figured out: implementing the 3rd party authentication on your client-facing website and then associating those 3rd party auth tokens with your website user accounts, and then finally trigger your setSessionID call on login.

Depending on your website architecture, you may find using a library like EveryAuth or Passport to be very helpful.


问:
Can a webservice that uses JSON over POST be classified as RESTful?
Recently I have started using a new(to me) paradigm for web services. I use the controller to accept JSON strings sent over POST, process it and return JSON strings. GET, PUT, DELETE and other methods throw HTTP 405.

This pattern is proving to be very efficient from the point of view of asynchronous web frameworks (vert.x and play to be particular), as well as from development effort point of view.

What I am confused about is that this neither seems to be SOAP nor REST. I don't think it is even JSON-RPC, since I am using my own headers like:

Request:

```<code>{
  'requestId':<generated req Id>,
  'token':<previously authenticated token>,
  'action':<controller defined action>,
  'parameters':[
    <array of parameters>
  ]

}
</code>```

Response:

```<code>{
  'result':'success/fail',
  'payload':{
     <payload>
   }
}
</code>```

EDIT: There is only one endpoint URL, something like https://my.domain.com/api

Can anyone give any ideas about what this paradigm can be classified as?

答:
The problem is that you are creating Yet Another Interface. This is rather RPC-like.

I'm not saying RPC is bad. RPC seems to be easier for programmers to understand naturally. You can probably do everything in REST that you can do in RPC, but you have to get used to thinking in terms of moving resources rather than calling functions.

With a RESTful API, if I want to delete a record I send a DELETE request to /thing/3 and it gets deleted. If I want to get it I use a GET. It's a standard that I don't have to think about or look up.

One nice thing about REST is you can just use your browser to look at the API and get some data to see what it looks like. You can't with yours.

With yours, I have to know what to put in the action parameter. Maybe I put in the word DELETE, but I have to look that up.

With REST, I know that a 404 means that the record does not exist. With yours, I have to look at the success parameter and then look up some error code.

Why create Yet Another Interface when one already exists?


答:
REST is not about functionality, but about style.  The idea behind it is not that it allows anything new but that it makes the API easier for people to learn and understand, and that it also makes for shorter, more readable URLs.

The other thing to keep in mind is that REST doesn't mean "no query parameters".  The idea is that in most APIs, a lot of the information is by nature hierarchical and so for that information, why not use the hierarchical structure inherent in an URL?  It makes the hierarchy explicit and this in turn often makes for more an API that is more flexible.  (Because it makes the developer think in hierarchical terms.)  Too often APIs based on parameters end up being an unholy mass of poorly organized options.

This is a "tangible benefit".  Good coding style in any domain can have direct impact in productivity and defect reduction.  Clear, consistent style in an API is especially important because an API is something that many developers will use, and something intended for use by the people who did not design and code the software.

Title: What can REST API do that a API using HTTP URL query strings cannot do?

Body:
I'm learning about REST and had the chance to build a basic REST API.  After doing so, most of the material I read was internalized and I now have a better understanding of it.

However, I do not see any real difference yet as to the tangible benefits of using REST over the old way I was doing things, which was simple URL query strings.  It seems they both do the exact same things.  But with REST, it's cleaner, and standardized.

I thought REST had additional technical benefits.  If they do, what are they?  Or is REST simply that - an agreed way to implement and API?


问:
estimation method at the "just finished definition phase"
We are basically using Waterfall life cycle methodology.
Requirement Analysis: I get a use case created by some one else.
Design (talking only about Low level design): I get some little feeling about how would I design it, may be either instantly/ or after some time.
Coding+Unit Testing: In case of unit Testing I am not using any TDD, but I am trying to get full code coverage, through mocks and etc. after the coding is done.

I am being asked about estimates just after the Requirement walk through.
Since I have only a fair amount of idea about how the design will look like, I have no way to say about estimates.
As for the coding part is considered, how can I get the total number of methods at the "just finished definition phase" (I never know how much will I be refactoring at this stage), Unit Testing with full code coverage: I haven't written a code, then How can I know how many behaviors are there to test for one method and hence time.

Is there some scientific way/ or other way to know this at this stage?

Note: I have already read this possible similar question.

I can break down all my tasks to small units, but I am having problem to give an estimate for each unit.

Edit1

This is part of my problem too it all started from here. Our Organization also unit tested (or correctly saying performed integration testing) manually or through emulators etc. So whenever some enhancements come for a particular client You need to create test data again, and what about any breaking changes You have introduced. So, I introducing Automated Unit Testing, but now there is again a problem for correct estimation which is necessary to give the organization farsighted view of "time estimate of creating a test suite with code" in simple words build to validation team.

Kindly help.

答:
When I need to provide estimates, after completing the analysis, I would do the following:
1. Look at the individual functions that we will be coding.
2. Use the total of all the functions as a count, and then divide these functions into simple, medium and hard level, which indicates again the amount of coding we need to do.

For each, I would allocate a time, based on my experience and how much I would take to complete it.

Now, for the total application, I will be getting a value, if I need to do the task myself.

Then, I start working on the fine tuning.

Like removing duplicate methods, adding in time for refactoring (which actually reduces the time if we use a tool to refactor and start refactoring as we code instead of refactoring after completion), little bit of margin of errors.

By following this method, even if there are any unforeseen delays, I will be able to deliver the task on time, and more often early.

One important thing that makes a difference is the technology to be used, and the skill level in that technology.

Like others said above, there is a risk at early stages of planning. The estimates need to be improved as the project starts and goes forward.

Resources, skillset, technology (existing/new) , all make a difference.


答:
If you are using .NET for programming the classes, you have different options like
Resources, web.config, or even a custom file.

If you use Resources or web.config, the data is actually stored in XML file, but, the loading is faster.

Retrieving the data from these files and storing them in another location will be like a double use of memory as these are loaded into memory by default.

For any other file or programming language, the above answer by Benedict will work.


问:
Component design: getting cohesion right
I currently have a set of components named DataValues, ValueParsers, ValueFormatters and ValueValidators. The first one defines an abstract base class DataValue and contains a whole load of implementations. The 3 other components each define in interface similar to their name (minus the "s"), and also contain a bunch of implementations of those. These 3 depend on DataValues. There are no further dependencies.

In other words, each component currently contains a whole inheritance hierarchy. I recently re-watched EP16 of Robert C. Martin's Clean Coders, where he points out this is one of the most common mistakes made in package design. This made me realize that this exact thing is going on for the here described packages.

The question then is how to best improve upon the current component design. Luckily none of those components have seen their first release yet, so things can still be moved around, and boundaries can still be redefined. Releases for these are on the horizon though, so I better get it right now.

What I'm thinking of doing now is to create a new component to hold the mentioned abstract class and interfaces for all these components. It would also contain the Exceptions of these components and perhaps some trivial implementations of the interfaces.

This new component would then be needed by all the current ones, and by all the ones needing the current ones. Then again, in this later category, there will be a number components that can just depend on the new and get rid of their current dependency on the much more concrete and unstable ones containing all the interface implementations.

This is great for the stable dependencies principle, and equally nice for the reuse release equivalence principle. It's however doing rather bad when it comes to the common closure and common reuse principles. Concretely this means that components that need the ValueParsers interface but don't care about the ValueValidators one will still depend on it as it is in the same package. They can thus be affected by it for no good reason. Then again, considering how abstract/stable this new component ends up being, I don't really see this causing much problems.

I'm looking for ideas on how to better draw the component boundaries and concerns or suggestions about the alternative I described.

答:
After discussing this with colleagues and getting a line of advise from Robert C Marin himself, I settled for the following satisfactory approach:

One component holds the interfaces for DataValues, ValueParssers, ValueValidators and ValueFormatters. This component also holds things such exceptions and implementations of these interfaces that are both trivial and general.

A second component holds the general but more complex implementations of these interfaces.

Making just this split already gets rid of most of the problems we currently have. The first component is very abstract and stable, and is required by a lot of other components. The second component is concrete and instable, and is needed only by a few components.

Further splitting of this second component might happen at a later point. And not all new concrete classes that derive from those interfaces will end up being it it, some might go into new or other existing components.


问:
Which things instantly ring alarm bells when looking at code?
I attended a software craftsmanship event a couple of weeks ago and one of the comments made was "I'm sure we all recognize bad code when we see it" and everyone nodded sagely without further discussion.

This sort of thing always worries me as there's that truism that everyone thinks they're an above average driver. Although I think I can recognize bad code I'd love to learn more about what other people consider to be code smells as it's rarely discussed in detail on people's blogs and only in a handful of books. In particular I think it'd be interesting to hear about anything that's a code smell in one language but not another.

I'll start off with an easy one:

Code in source control that has a high proportion of commented out
  code - why is it there? was it meant
  to be deleted? is it a half finished
  piece of work? maybe it shouldn't have
  been commented out and was only done
  when someone was testing something
  out? Personally I find this sort of
  thing really annoying even if it's just the odd line here and there, but when you see large blocks interspersed with the rest of the code it's totally unacceptable. It's
  also usually an indication that the rest of
  the code is likely to be of dubious
  quality as well.

答:
Code that cannot ever, logically enter the execution path.

var product = repository.FindProduct(id);

log.Info("Found product " + product.Name);

if (product != null)
{
    // This will always happen
}
else
{
    // **This won't ever happen**
}
```

<p>or</p>

<pre class="lang-cs prettyprint-override"><code>if (messages.Count > 0)
{
    // Do stuff with messages
}
else if (messages.Count == 1)
{
    // **I hope this code isn't important...**
}
</code>```

Body:
Code that cannot ever, logically enter the execution path.

var product = repository.FindProduct(id);

log.Info("Found product " + product.Name);

if (product != null)
{
    // This will always happen
}
else
{
    // **This won't ever happen**
}

or

if (messages.Count > 0)
{
    // Do stuff with messages
}
else if (messages.Count == 1)
{
    // **I hope this code isn't important...**
}


答: In addition to the accepted answer, you may be interested in looking at some of uncle bob martin's talks about clean architecture. There are several on YouTube for example.</p>

Title: Very-Loose Coupling and Dependency Injection for Database Management

Body:
I'm currently setting up a MongoDB database for a web-app. I'm running node.js and using Mongoose to help manage mapping, validation ect.

I'm wondering if it's a good idea to really decouple MongoDB from my code, just on the off-chance we want to switch to something like CouchDB a little later. Specifically, I'd make a databaseManger module that is responsible for setting up Mongoose/Mongo, defining the mongoose models, managing replica sets, and doing some extra validation. This manager would export a generic API, and handle the details of the queries internally. The manager would then be passed around via dependency injection.

Does this make sense? Or am I kind-of redoing some of the mongoose functionality?

Any advice is appreciated.


问:
Is node.js a good fit for background processing?
I'm slowly learning node.js and have a small project I want to start.  The project will have a lot of background processes (downloading data from external sites, parsing CSV files, etc.).

A big "win" for me and node is the fact it uses JavaScript for both client and server.  I code in Java and JavaScript in my day job but am also pretty good at Ruby.

But, like I said, it seems attractive to use one language everywhere and JS seems to fit that bill.

However, I haven't had much experience in using JS for running background jobs.  Ruby seems to excel at this.  And I'm not opposed to using it.  So what are your thoughts on going 100% JS for this?  I realize very large projects require custom solutions.  I'm just wondering if it's worth the effort.  Or, should I just stick with Ruby on those kind of chores?

Opinions appreciated.

Thanks

答:
If your background processes can run sequentially it can be pretty good.  At my last position, I had to write a number of pre-processors, exports and translation utilities for many data sources.  Using NodeJS was a breeze here.

If you aren't doing a lot of compute bound processing, simple manipulation of short strings, and integer parsing isn't so bad, if you need to manipulate images, it is probably not the best tool (though there are callable wrappers and modules that can work well).

Advice, stick to modules that use streams.  This can make it easier to pipe your processing to modules for that particular step.  If you look at how event-stream is used in gulp-jade for the gulp build tool for example, you can see how capable it is.

For CSV, you can use node-csv, which is pretty good at establishing a base for piping records to a processor stream.

For large-ish XML, where you want to do a single record at a time, I would look at node-halfstreamxml which reads through your XML stream using a SAX processor, and raises events for each node.  I would wrap that into a read/write-stream so you can raise your desired matches. Many xml-object parsers in node will attempt to read/parse the entire xml at once, and for say 100mb of xml that gets huge... where the halfstreamxml will read as a stream.

NOTE: there are other processors like xml-stream which will use expat (C library) underneath, that can give more performance, but less portable without a build environment.

In general, it's been a real joy to use...


答: Use TCP Options instead. They're fully supported by most if not all TCP implementations, they'll transit firewalls intact, etc.  Adding one to carry your session id would be pretty straightforward, and it won't mess with the SEQ/ACK rules.


问:
flow control solutions in Node.js - use async.waterfall?
Looking at node.js, and avoiding nesting callbacks. I found Async.js, can someone show me how can I rewrite this code using the async.waterfall method?

```<code>// db is a mongodb instance
db.open(function(err, client){
    client.createCollection("docs", function(err, col) {
         client.collection("docs", function(err, col) {
             for (var i = 0; i < 100; i++) {
                 col.insert({c:i}, function() {});
             }
             console.log('Insert done OK.');
         });
    });
});
</code>```

What problems does this naive solution with inner functions have, over the async method?

```<code>db.open(openAndInsert);

function openAndInsert(err, client) {
    var myCollection = "docs";

    client.createCollection(myCollection, openCollection);

    function openCollection(err, col) {
        client.collection(myCollection, insertIntoCollection);
    }

    function insertIntoCollection(err, col) {
        for (var idx = 0; idx < 100; idx += 1) {
            col.insert({c:idx}, function () {});
        }
        console.log('Insert done OK.');
    }
}
</code>```

The three levels of nesting in the original code seem like a code smell, but I'm not sure either my home rolled or the async solution are universally better. Would anyone prefer just leaving the nested functions as is? If so, how deep would the nesting have to be before going using some type of flow control?

答:
I would suggest both the separate functions along with async...  Also, bear in mind that Function.prototype.bind is incredibly powerful.

```<code>//open the connection first, because the client may need to be used for cleanup.
db.open(function(err, client){

    //run the tasks in series, passing the result of each to the next task
    async.waterfall([
        //bind collection method to run against "docs"
        //there is no need to create a wrapper function yourself for this
        client.collection.bind(client, "docs")

        //passes the resulting collection to addToDocs
        ,addToDocs

    ], completed); //run completed function at the end

    //will add 100 docs into the database
    function addToDocs(docs /*collection*/, cb) {
        //list of items to be run (async/parallel)
        var todo = [];
        for (var i=0; i<100; i++) {
            //bind the insert method against a new object for i, so it can be run later
            todo.push(docs.insert.bind(col, {c:i}));
        }

        //do all the inserts, then run the original callback
        async.parallel(todo, cb);

        //alternatively, you could have used async.series(todo, cb) to run one at a time.
    }

    function completed(err, results) {
        //close client resources, return connection to pool etc

        //handle any errors
        if (err) {
            console.log(err);
        }

        //any other work to be done
    }
});</code>```

I happen to like this pattern, where you have your logic at the top, and reference methods below...

NOTE: only function declarations will be hoisted to work properly, var foo = function(){...} will not.

Body:
I would suggest both the separate functions along with async...  Also, bear in mind that Function.prototype.bind is incredibly powerful.

//open the connection first, because the client may need to be used for cleanup.
db.open(function(err, client){

    //run the tasks in series, passing the result of each to the next task
    async.waterfall([
        //bind collection method to run against "docs"
        //there is no need to create a wrapper function yourself for this
        client.collection.bind(client, "docs")

        //passes the resulting collection to addToDocs
        ,addToDocs

    ], completed); //run completed function at the end

    //will add 100 docs into the database
    function addToDocs(docs /*collection*/, cb) {
        //list of items to be run (async/parallel)
        var todo = [];
        for (var i=0; i<100; i++) {
            //bind the insert method against a new object for i, so it can be run later
            todo.push(docs.insert.bind(col, {c:i}));
        }

        //do all the inserts, then run the original callback
        async.parallel(todo, cb);

        //alternatively, you could have used async.series(todo, cb) to run one at a time.
    }

    function completed(err, results) {
        //close client resources, return connection to pool etc

        //handle any errors
        if (err) {
            console.log(err);
        }

        //any other work to be done
    }
});

I happen to like this pattern, where you have your logic at the top, and reference methods below...

NOTE: only function declarations will be hoisted to work properly, var foo = function(){...} will not.


问:
What does "(say)" mean in this Java method in Hadoop The Definitive Guide?
What does "(say)" mean in this Java method?

Since Mapper and Reducer are separate classes, the type parameters have different scopes, and the actual type argument of KEYIN (say) in the Mapper may be different from the type of the type parameter of the same name (KEYIN) in the Reducer.  For instance, in the maximum temperature example from earlier chapters, KEYIN in replaced by longWritaeble for the Mapper and by Text for the Reducer.

From Hadoop The Definitive Guide, by Tom White, page 224 (scanned version of the page at 223 and 224).

答:
I read that (say) in this case as 'for example', i.e. type parameter of the others could also vary between the Mapper and the Reducer.

So, I'm parsing it to mean that KEYIN, KEYOUT, VALUEIN, VALUEOUT could each have different type arguments in the Reducer as compared to their corresponding Mapper arg types.


问:
BlazeDS: Server DTO method naming convention
I have the following field in Flex:

[Bindable] public var zIndex:uint;
```

<p>And I was trying to create the methods to process the calls in Java and I ran into a problem.</p>

<pre class="lang-java prettyprint-override"><code>1. public int getZIndex(); // Does not work.
2. public int getzIndex(); // Works.
</code>```

I thought that the letter following the get/set was supposed to be capitalized? Is there a reason for this? I couldn't find any documentation.

I found an answer on StackOverflow that states that the first one is the correct way to name an accessor/mutator.

答:
Found the answer after some further investigation.

[I]f the first two characters of the name are both upper case and if so leave it alone.

Section 8.8 of the JavaBean Spec by Sun states:

8.8 Capitalization of inferred names.

When we use design patterns to infer a property or event name, we need
  to decide what rules to follow for capitalizing the inferred name. If
  we extract the name from the middle of a normal mixedCase style Java
  name then the name will, by default, begin with a capital letter.

Java programmers are accustomed to having normal identifiers start
  with lower case letters. Vigorous reviewer input has convinced us that
  we should follow this same conventional rule for property and event
  names.

Thus when we extract a property or event name from the middle of an
  existing Java name, we normally convert the first character to lower
  case. However to support the occasional use of all upper-case names,
  we check if the first two characters of the name are both upper case
  and if so leave it alone. So for example,

      "FooBah" becomes "fooBah"

        "Z" becomes "z"

        "URL" becomes "URL"

We provide a method Introspector.decapitalize which implements this
  conversion rule.

```<code>JavaBeans Introspection -- Sun Microsystems -- 10/12/97
</code>```

Body:
Found the answer after some further investigation.

[I]f the first two characters of the name are both upper case and if so leave it alone.

Section 8.8 of the JavaBean Spec by Sun states:

8.8 Capitalization of inferred names.

When we use design patterns to infer a property or event name, we need
  to decide what rules to follow for capitalizing the inferred name. If
  we extract the name from the middle of a normal mixedCase style Java
  name then the name will, by default, begin with a capital letter.

Java programmers are accustomed to having normal identifiers start
  with lower case letters. Vigorous reviewer input has convinced us that
  we should follow this same conventional rule for property and event
  names.

Thus when we extract a property or event name from the middle of an
  existing Java name, we normally convert the first character to lower
  case. However to support the occasional use of all upper-case names,
  we check if the first two characters of the name are both upper case
  and if so leave it alone. So for example,

      "FooBah" becomes "fooBah"

        "Z" becomes "z"

        "URL" becomes "URL"

We provide a method Introspector.decapitalize which implements this
  conversion rule.

JavaBeans Introspection -- Sun Microsystems -- 10/12/97


答:
There are really two definitions of REST:

Representational State Transfer ("REST") as a principle for service design (not necessarily web service!), which suggests a uniform client-server interface where the server does not store the client context, e.g. "client has visited this page last".  As a general principle, RESTful services shuold request a specific resource -- e.g. an article, or an "order" object -- as well as an action to perform on that resource -- "get", "tag", "paint yellow", or whatever is necessary, so long as the same action for different types of resources gets the same name. So long as you follow these principles, your web service can be RESTful even if it does not use HTTP.  I don't see the specific resource being requested in your protocol , but then again, it may be defined by the URL.  EDIT: As you are not specifying the resource independently of the action, your service is not RESTful by this definition.

REST as a specific request format that uses HTTP as carrier protocol and HTTP request types like GET, POST, or DELETE to specify what type of action needs to be carried out.  Your service is obviously not RESTful by this definition.

The most general description of your protocol would be likely a service for remote procedure calls (RPC) over JSON, but which is not JSON-RPC.

To be clear, there is nothing wrong with not being RESTful or being RESTful.  Whatever suits your needs.

Title: Can a webservice that uses JSON over POST be classified as RESTful?

Body:
Recently I have started using a new(to me) paradigm for web services. I use the controller to accept JSON strings sent over POST, process it and return JSON strings. GET, PUT, DELETE and other methods throw HTTP 405.

This pattern is proving to be very efficient from the point of view of asynchronous web frameworks (vert.x and play to be particular), as well as from development effort point of view.

What I am confused about is that this neither seems to be SOAP nor REST. I don't think it is even JSON-RPC, since I am using my own headers like:

Request:

```<code>{
  'requestId':<generated req Id>,
  'token':<previously authenticated token>,
  'action':<controller defined action>,
  'parameters':[
    <array of parameters>
  ]

}
</code>```

Response:

```<code>{
  'result':'success/fail',
  'payload':{
     <payload>
   }
}
</code>```

EDIT: There is only one endpoint URL, something like https://my.domain.com/api

Can anyone give any ideas about what this paradigm can be classified as?


答:
Guard conditions should, IMO, only be used when you won't or can't reverse a proces.  Otherwise let the exception occur downstream where the value doesn't make sense.

Arguments to a function should meet the needs of the function, the only place that can guarantee that the correct values are provide is the calling site.

In your example, how would DoSomething know that an empty MyCollection will result in an acceptable action/value as a one with a dozen values in it.

Consider if MyCollection was BackupToBeforeDelete -- if you provide an empty list, the object doesn't get backed up, but does get deleted.


答:
Mandatory xkcd reference:

Let's say you design a language, or a next version of an existing language, and say "let's forget the old C-style names, I have a better idea". You rename mkdir to make_directory. Someone else, following the same way of thinking, invents create_directory, a third one create_dir, the next one new_directory, and so on. Now the programmers have a much harder time learning a new language or a new dialect, because instead of instantly recognizing what a command does and what parameters it expects, they have to read through the manual. By not having the same names and structure, it can be much more likely to have a different use or different order of parameters (if I remember correctly, .NET liked to do this in the beginning, some methods had the parameters like source, destination, others like destination, source). It makes programming either more error-prone, or much slower as the programmer has to read the manual every time he uses a function, because one can never be sure what parameters this function in this language in this version is using.

If ALL language designers could agree to change the C-style names for all future languages in exactly the same way, it might make some sense to do it. Good luck in achieving that!

Common roots and cultural heritage are not there without a reason.

Title: Why do old C-style method names continue being used in modern languages?

Body:
I understand that in the earlier days of computing, shorter method names like printf made sense, because storage was limited. But why do modern languages like Python and Go still use the less readable names from the C APIs? Why don't they switch to a more readable form like print_format, the same goes for other names. I wouldn't mind having to write make_directory instead of mkdir in go.

People have suggested that this question has been asked before, but the questions I've found are about whether abbreviated names are bad practice. This question assumes that the answer to this question is usually yes.


问:
Does a group of Select Statements count as a valid model?
I'm making a facebook app and I'm trying to follow MVC properly. But I was wondering if I had a class that was a bunch of fql queries (getting data from facebook) should I have keep these in a controller or a model?

According to Codeigniter's user guide "Models are PHP classes that are designed to work with information in your database". Since fql interacts with facebook's databases and not my own, would having a class full of what is basically just SQL Select statements count as valid model?

答: On an MVC pattern, a class that handles the data between the database and the application would be a valid model so long as the functions within it are related to the entity that the model represents. A CI model would inherit from the base model class of the framework to allow the user to use CI's syntax for handling data in the database. So I my answer is Yes it is a valid model but No it's not a valid CI model in some sense.</p>


问:
Difference between various Collection Generic Interfaces in C#
I have been playing around with C# for Windows and ASP.net MVC development for some time now. But I am still unclear on a few areas.  I am trying to understand the basic difference between and performance issues with using and interchanging similar kinds of Generic Collection Interfaces.

What is the basic difference between IEnumerable<T>, ICollection<T>, List<T>(Class)?

I seem to use and interchange them without seeing any problem in my applications. Also, are there any more similar generic collections like these that can be interchanged with those three?

答:
IQueryable:

query isn't executed until to really iterate over the items, maybe by doing a .ToList()

IEnumerable:

forward-only list of items. You can't get at "item 4" without passing items 0-3.
read-only list, you can't add to it or remove from it.
Still might use deferred execution.

IList:

random access to the full list
entirely in memory
supports adding and removing

ICollection:

Is between IEnumerable and IList.
What is "best" depends on your requirements. Usually though an IEnumerable is "good enough" if you only want to display items. At least always use the generic variant.


问:
Why use an OO approach instead of a giant "switch" statement?
I am working in a .Net, C# shop and I have a coworker that keeps insisting that we should use giant Switch statements in our code with lots of "Cases" rather than more object oriented approaches.  His argument consistently goes back to the fact that a Switch statement compiles to a "cpu jump table" and is therefore the fastest option (even though in other things our team is told that we don't care about speed).

I honestly don't have an argument against this...because I don't know what the heck he's talking about.

Is he right?

Is he just talking out his ass?

Just trying to learn here.

答:
One maintainability advantage of polymorphism that no-one has mentioned is that you will be able to structure your code much more nicely using inheritance if you are always switching on the same list of cases, but sometime several cases are handled the same way and sometime they aren't

Eg. if you are switching between Dog, Cat and Elephant, and sometimes Dog and Cat have the same case, you can make them both inherit from an abstract class DomesticAnimal and put those function in the abstract class.

Also, I was surprised that several people used a parser as an example of where you wouldn't use polymorphism. For a tree-like parser this is definitely the wrong approach, but if you have something like assembly, where each line is somewhat independent, and start with an opcode that indicates how the rest of the line should be interpreted, I would totally use polymorphism and a Factory. Each class can implement functions like ExtractConstants or ExtractSymbols. I have used this approach for a toy BASIC interpreter.


问:
What are the deliverables to give to the client for a web application ?
I have completed a web application which is basically developed in PHP and is just another regular web application. Usually when I deliver the final production release I just handover the code documentation and the architecture information to the client. However, for this particular project the client insists on having the complete in and out data about the project. </p>

<p>So I'm just wondering... What are the mandatory technical and non technical docs that I can give my client apart from the code and architecture documentations ? </p>

<p>(Also it would be kinda cool to hit the client about various stats and data about the project so that he would actually know the amount of work involved and how cool the product actually is.) </p>

答:
Be Wary

The potential documentation that you could give the client is virtually endless. Additional time required to generate documentation you don't already have is unpaid.

Why does the client want this documentation (over and above the source code)? What will be done with it? Who is it for?

The answers to these questions will help narrow the scope of what to deliver.

It is critical that you and the client agree upon exactly what documentation to deliver, and whether any additional effort will be compensated.

Don't play guessing games. Most technical documentation would be useless to the typical (non-technical) client.


问:
When to use REST to handle requests vs using AJAX to handle requests
On my web page, if I wish to display dynamic dropdowns (e.g city names based on country selected), I can do it using AJAX. But I can also do it using a REST call. So which should I use?

My problem is I really don't get the difference between REST and any other HTTP browser request.(a.k.a a form submit). I have looked at the formal definitions of REST and it seems identical to a HTTP request. So how is REST inherently different from AJAX?

答:
REST is using HTTP verbs GET, POST, PUT, DELETE to respectively get, insert, update, delete resources on a server. E.g. GET with url: controller/customer/{id}

The alternative is adding methods to a controller such as GetCustomerById(id), InsertCustomer(customer), UpdateCustomer(customer), DeleteCustomer(customer). This is what's known as a RPC approach. E.g. GET with url: controller/GetCustomerById?id={id}

One of the differences is, is that a REST api is kind of predictable. If you know REST and you know the name of the resource you want (e.g. Customer), then you can immediately jump in and use the REST controller with the standard verbs.

With an RPC approach, you need to know what methods are on your controller, what kind of arguments they take, etc. These signatures can vary from controller to controller, from app to app.

AJAX on the other hand is just an asynchronous way of placing the aforementioned requests, whether as a REST call or a RPC call.


问:
Unit testing in node.js and mocking modules
I'm trying to test this wrapper to request that I made:

// lib/http-client.js
var app = require('app'),
    request = require('request');

exports.search = function(searchTerm, next) {
  var options = {
    url: 'https://api.datamarket.azure.com/Bing/Search/Web',
    qs: {
      'Query': '\'' + searchTerm + '\'',
      'Adult': '\'Off\'',
      '$format': 'json',
      '$top': 10
    },
    auth: {
      user: app.get('bing identifier'),
      pass: app.get('bing identifier')
    }
  };

  request(options, function(err, res, body){

    if (err) return next(err);
    // TODO: parse JSON and return results
  });
};
```

<p>where <code>app</code> is an instance of express.  The question is, how do I test the function of this "module" without having to touch the internet? If I was to do this in other languages I would have mocked the request module but I don't know if that's the best way to do it in node.js.</p>

<pre class="lang-js prettyprint-override"><code>// NODE_PATH=lib

describe('Http Client', function(){
  it('should return error if transport failed', function(){
    var c = require('http-client'),
        results = 'foo';
    // request mock should return results when called
    c.search('foo', function(err, results){
      results.should.eql(res);
    });
    // TODO
  });
  it('should return an error if JSON parsing failed', function(){
    // TODO
  });
  it('should return results', function(){
    // TODO
  });
});
</code>```

答:
If your module has a constructor that takes the app and request as constructor arguments (in other words dependency injection), you can just provided a stubbed/mocked implementation of request in your test.

If not: I know you can override in tests what RequireJS returns when requiring something, so I would assume the same would be possible in node.js. So if you can change the configuration of the module loader in a test, you can configure it to return a stubbed/mocked implementation of request.

Personally, I'd go the dependency injection route. Having to configure your module loader in tests is a pain in the backside...