答:
Sounds like the first issue is that you aren't supposed to apply time estimates to user stories.  You're supposed to take a story and apply "story points", which are a general estimate of complexity from 1 to INFINITY.  Story points are often run something like 1,2,3,5,8,13,20...  (Every organization has its own rules.)  They generally apply something like:

1 - You can do it in your sleep and it is hardly worth implementing.
2 - You understand this, and can get it done quickly with little risk of overrun.
3 - You understand this, but there might be a surprise or two.
5 - This is going to a little research, and has some small amount of risk.
8 - This is a large task, needs lots of research, and may not fit in a sprint.
13 - This is huge, and definitely won't fit in a sprint.  There's massive risk.
etc.

Generally, any user story that is an 8 or above needs to be broken down into smaller stories.

If you don't have the information to do this, you definitely should throw it back at the project manager and say that you need more information.

You really should only be estimating time once you have accepted the story into the sprint, but even then, there is less emphasis on this.  The idea is that once your team gets used to the pointing process, you can measure its rough output per sprint in story points, and plan that way.  You don't want to be planning on a shorter timescale than the sprint.  The idea here is that if you're breaking down tasks correctly so that the multiple stories fit in a sprint, and are in the 1-5 story point range, it means that they are well defined enough.

Also, it sounds like the PMs at your company don't understand what a "story" is.  A critical part of a "user story" is the exit criteria.  The exit criteria is a short sentence or two that describes unambiguously how it can be shown that this storage is completed.  Ideally, this should be something that your QA guys have said "yes, we can test for that".  The important bit is that the PMs have to understand that a user story is complete when the software meets the "exit criteria".  "But we didn't want that" doesn't cut it.  If they didn't want what was delivered, but it matched the exit criteria, they have to enter a new story.

There is certainly an element of "training the PMs" here.  They have to learn that vague stories result in large story points, and that if they defined the story to ambiguously to get what they want, they have to do it again.

Obviously if the stakeholders aren't gathering enough information, then you have to, and if you have to, then that's a lot more work, isn't it?  Long before my agile days, I had success by giving very large estimates, and explicitly saying that the estimates were so large to allow for the risk caused by the lack of information.  I had to assume the worst case for all questions, and estimated based on this worst case.  I found that managers were more willing to give more details when they saw it resulting in estimates going down.

This isn't gaming the system...this is perfectly valid.  If you don't know whether it is "A" or "B", you estimate based on which gives the largest estimate to cover your ass.


问:
When to start writing Exception Handling, Logging
When do you start writing your Exception Handling Code? When do you start writing Logging Statements.

For the purpose of elaborating this question, let us assume that we are on .NET platform with log4net logging but feel free to answer in a generic way.

Solution: A Windows Forms Project.
Projects: UI, BusinessRules, DataHandlers

So, do you go about writing your DataHandlers which does your Data Manipulations such as Create, Read, Update, Delete first.

Then follow it up with your Business Rules

And then your UI or any other permutation of the above.

Test your Application for Functionality.

And then start writing your Exception Handling Code and finally your Logging code?

When is a right time to start writing your Exception Handling code?

PS: In the book Clean Code, they say Write your try-catch-finally block first. That, prompted me to ask this question.

答:
You can implement auditing and exception handling as services. Application-level audit logging requires status data about each business transaction. The ability to monitor an application in a business or transactional context requires a monitoring interface within the service to send messages detailing the transaction's status specific to the service invocation. This requires each service to send a status message at critical steps in the business transaction. You can then build a real-time viewer to correlate status messages (based on the semantics of the message - e.g. transaction ID) with the services within the composite application. This provides an end-to-end view of the business transaction for SLA management, fault tracing and problem determination.

An audit service can then be implemented as a state machine that can consume and record messages based on criteria defined in its configuration. A generic exception handler can also use the audit service to support a centralized view of problems that occur in the enterprise SOA - to support exception-based monitoring. Any should-not-occur condition in the solution is instrumented to send an exception message to the exception handler.

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
Managing a website with version control?
The small website I built a long time ago is starting to pick up a little and I'm starting to run into problems with making changes. Originally, all the pages were .html and I would edit and test them offline to make sure everything worked. Then I realized how helpful php includes were, so I changed everything to .php and used includes. Without apache, I could no longer test offline, so with Filezilla, I would choose the "view/edit" option on files that were already on the server, edit them, and then have them uploaded again. This is what I've been doing so far and it's worked pretty well for the most part. I just save the temp file that filezilla creates, and let it upload it back to the server.

Yesterday, I realized that one of the javascript files I had worked on the day before had been replaced by an empty file. This was something to do with sublime text keeping the non-existent temp file open/filezilla uploading an empty file - I'm not really sure what happened, but it shouldn't have been able to happen. And now, I need to change the design of the site, and doing that one page at a time would be noticeable, so I need to do it offline first.

I would like to use version control and install apache so that I can completely test my site offline, but there are a couple problems I have with this. The first is that I have a Forum on the site. I could install mysql and export the tables, then import them offline, but then, while people are making posts on the website, the offline copy becomes out of date and I can no longer upload that back to the server. I also have some Python scripts on the site using WSGI. My webhost's settings are very specific, so if I wrote python scripts offline and ensured they were working, I wouldn't know if they were going to work online.

Should I edit everything offline and upload it all back to the server when it works? What happens if a php or python script executes one way on my local machine than on the server?

答:
I'm going to assume that you're using Windows, but this also works for Linux and Mac.

First, I recommend you install XAMPP on the computer you work on. It is a bundle of Apache, MySQL and PHP, install it and give you a basic configuration that should be good enough to test the basics. Your entire site then can reside on your PC and you save a lot of time on the uploading/testing. All you have to do is save the file and refresh the browser.

Second, I recommend you have a development version of your site on the same server that hosts the site. It looks like your site is not huge, so this shouldn't be a problem. What I do is have a www.mysite.com/dev directory which holds the entire site. After I make any change, I upload the changed files to the "dev" folder and test them. If all is well, I know that I can upload to the root folder and it will probably work as well. I protect the /dev directory with a .htaccess file.

So, in summary:

Make changes on your local copy of the site.

Test changes locally (on http://localhost/yoursite)

Upload and test changes on yoursite.com/dev

Upload and confirm on yoursite.com.


答:
In my experience, if you don't write code with the appropriate error handling and logging from the beginning, it won't get done due to time pressures.  The most successful development efforts I have been on started out with time spent determining basic application structure, including coding standard, how errors would be handled, logging, basic architecture and test tools.

Otherwise, you'll find that you have tasks for version 2.0 like "Improve error handling" and "create logging system".  These will be cut in favor of new features, and because you have "too much to do", fixing all those bugs in the error cases you didn't think about.  (Which takes forever, because you have no logging system.

Title: When to start writing Exception Handling, Logging

Body:
When do you start writing your Exception Handling Code? When do you start writing Logging Statements.

For the purpose of elaborating this question, let us assume that we are on .NET platform with log4net logging but feel free to answer in a generic way.

Solution: A Windows Forms Project.
Projects: UI, BusinessRules, DataHandlers

So, do you go about writing your DataHandlers which does your Data Manipulations such as Create, Read, Update, Delete first.

Then follow it up with your Business Rules

And then your UI or any other permutation of the above.

Test your Application for Functionality.

And then start writing your Exception Handling Code and finally your Logging code?

When is a right time to start writing your Exception Handling code?

PS: In the book Clean Code, they say Write your try-catch-finally block first. That, prompted me to ask this question.


问:
How should I go about re-releasing a GPL-licensed project?
A few months ago we found a library licensed under GPL that fit the bill for what we were looking to do at that time. We included it in our codebase and all was fine. Now, a few frantic months of coding later, we've refactored the hell out of the library: it's more feature complete, more stable, fully unit tested, PSR-0 compatible, etc.

Now we would like to use the library in another one of our projects and that got me thinking, why not re-release the library?

The problem is that I don't have any idea on how to attribute the work the original developers have put in (which is actually that much refactored that it's kinda unrecognizable) when releasing the library as GPL again. Over time all the file documentation headers with the original credits have been replaced and all that remains is the LICENSE file which is an exact copy of the GPL v3 license.

I have absolutely no problem giving credit where it's due, but I would like to do it according to what is right in the FOSS world. Anyone can tell me how to proceed?

答: You probably need to go back to the original GPL source code base you started with, extract all the copyright attributions (if any) from that source code, and (re)add those copyright attributions to the files of any of your source code derived from that original source code base.</p>


答: I sense that you're not all that open to setting up a test server.  I don't blame you.  How about creating another hosting account and testing your site there?  Deploy it from SCM when you're testing.  When you're happy with it, deploy it to the 'real' domain.</p>

Title: Managing a website with version control?

Body:
The small website I built a long time ago is starting to pick up a little and I'm starting to run into problems with making changes. Originally, all the pages were .html and I would edit and test them offline to make sure everything worked. Then I realized how helpful php includes were, so I changed everything to .php and used includes. Without apache, I could no longer test offline, so with Filezilla, I would choose the "view/edit" option on files that were already on the server, edit them, and then have them uploaded again. This is what I've been doing so far and it's worked pretty well for the most part. I just save the temp file that filezilla creates, and let it upload it back to the server.

Yesterday, I realized that one of the javascript files I had worked on the day before had been replaced by an empty file. This was something to do with sublime text keeping the non-existent temp file open/filezilla uploading an empty file - I'm not really sure what happened, but it shouldn't have been able to happen. And now, I need to change the design of the site, and doing that one page at a time would be noticeable, so I need to do it offline first.

I would like to use version control and install apache so that I can completely test my site offline, but there are a couple problems I have with this. The first is that I have a Forum on the site. I could install mysql and export the tables, then import them offline, but then, while people are making posts on the website, the offline copy becomes out of date and I can no longer upload that back to the server. I also have some Python scripts on the site using WSGI. My webhost's settings are very specific, so if I wrote python scripts offline and ensured they were working, I wouldn't know if they were going to work online.

Should I edit everything offline and upload it all back to the server when it works? What happens if a php or python script executes one way on my local machine than on the server?


问:
Is it normal to feel like you forgot many things in language after a lapse?
I'm coming back to C++ after a month. I still didn't start practicing but seeing my old code gives me nauseous feeling like I'm seeing something new even with simple small code.

Is this normal? Will I retain everything as I'll start writing code back?

答:
Sounds about right to me. In my case, I have been using R for around 6 years, but these days there are long periods of time where I don't need to do any statistics in R, so there can be 3-6 month periods where I do not do a ton with it and let me assure you, there have been some scary moments where I am filled with self doubt when I can't get a simple dataset loaded. Fortunately it always comes back pretty quickly and stays with me if I am doing it a lot.

I have found this to be true for math (sometimes I goof up embarassing questions), simple statistics and about everything else I take a break from. The fortunate thing is that as I get better at things the relearning time goes down and in some cases ceases to exist at all. It also has motivated me to try and keep a project or two going in my free time where I bumble around with R and .NET. I think the conclusion is that it is not uncommon and you should not be worried, but you might want to do a bit of C++ in your free time to keep your skills sharp.


答:
In 2012 the best model is something like heroku or app harbor use -- you commit to a specified  repository and your stuff gets pushed up. Rollbacks and version history are easy because you are using a solid source control system to handle it all.

In the case of a static website, you can simulate this pretty easily using a script that just does the appropriate command line call to update a folder at your specified intervals.


问:
What is meant by "native support for a feature" in a programming language?
I went through a line somewhat like this "PHP has no native support for Unicode". Also i read that Python has native support for Unicode. Now you can call a function utf8_encode() in PHP to encode a string into Unicode and you can use a function unicode() in Python to convert a string to unicode. So what does it mean to support Unicode natively? Also some languages have native support for concurrency while some dont have a native support. So what is meant by

X language natively supports feature Y

答:
It means that to support a given feature, the developer doesn't need to use a component which is not embedded in the language itself, like an extension or a third party product.

For example, PHP has no native support for unicode, because every function which deals with strings in PHP itself doesn't support unicode. For example, in order to get a substring, you can't use substr, but need to use mb_substr, which requires to use the Multibyte String extension.

To have a native support of a given feature, it is not enough to just incorporate an extension in the source code trunk. Instead, PHP would have native support for unicode if unicode would be the default encoding, like in C# or Java.


答:
I'd read native in the contexts you've mentioned as built-in. If a language doesn't provide native support for some feature, you'll need to implement it yourself or find some library or module that provides it.

Another context where you'll see native a lot is with respect to applications on some platform or other. In those cases, it means compiled for the platform as opposed to being somehow interpreted or translated. A native iOS app is one that's written in a language like Objective-C and compiled to code that runs directly on the ARM family of processors (which is what you find in iOS devices).

Title: What is meant by "native support for a feature" in a programming language?

Body:
I went through a line somewhat like this "PHP has no native support for Unicode". Also i read that Python has native support for Unicode. Now you can call a function utf8_encode() in PHP to encode a string into Unicode and you can use a function unicode() in Python to convert a string to unicode. So what does it mean to support Unicode natively? Also some languages have native support for concurrency while some dont have a native support. So what is meant by

X language natively supports feature Y


答:
1) The longer the 'break' period the more you'll forget.

2) The "more" you used them originally, the longer they can last 'on break'.

Example:  I used UNIX and the VI editors for a year.  Then I was on windows only for 8 years.  So how were my skills when I returned?  Pretty good actually.  The fact that I had to do everything in vi and Unix for a solid year meant that when I returned I still found a solid base in my memory to return to.  However I would say that for a while I was back at a "4" (out of 10) compared to an "8" before.  However with a  bit of relearning thrown on top I got back to my "8".

Final note: It's very normal to forget a lot.  If we remembered every detail of everything perfectly forever, life would be very different.

Title: Is it normal to feel like you forgot many things in language after a lapse?

Body:
I'm coming back to C++ after a month. I still didn't start practicing but seeing my old code gives me nauseous feeling like I'm seeing something new even with simple small code.

Is this normal? Will I retain everything as I'll start writing code back?


答:
"X language natively supports feature Y" means you can use feature Y without any extension or any other effort to make it work. It is directly usable from the language itself.

For example you can say that,

"C++ language natively supports operator overloading."

"Java language natively supports automatic garbage collection", because you don't need to use any other libraries or tools that does automatic garbage collection. It comes with the langauge (and platform) itself.


答:
Yes, it is normal. After you start developing more and more software with that language, you'll forget less.

But even while you are still developing, you can forget some of the features of that language when you don't use it. So this is why we need a good reference book about that particular language.

If you are working with C++, you need a good understanding of the language. It is a very large language and you'll always need a good C++ reference.


答:
"Native support" at least in interpreted or JIT-compiled languages typically means code that's basically just a link to precompiled functionality that sits below the interpreter.

In JavaScript, for instance, if you alert window.open in Firefox, you'll probably see a function whose innards say something like "[native code]." While all references are fed to the interpreter and steps need to be taken to establish context and scope, the innards are basically cached and ready to go. window.open for instance, probably calls something from a browser's run-time environment.

This is different from the non-native objects and methods you or somebody else wrote, because in those cases all your statements need to be interpreted/evaluated.

If somebody were using the term in reference to a language that pre-compiles, I would assume they just meant all of the core language stuff that the compiler actually tokenizes and converts to machine code vs. the stuff you define yourself which is more about the structures and references used to link it all together.


答:
Most programming skills are universal.  Very little is language specific, especially with regard to what is good design and what is bad.  Thus the new skills you developed programming in other languages helped you see problems with old C++ code.

It's fairly normal.


问:
Best overview to modern C++ paradigms?
I used to write C++ extensively between 8 and 10 years ago.  I have since moved on to C# for professional reasons.  However, from time to time I see statements like

"If you're still manually tracking pointer references, you're doing it wrong"

or

"C++ is perfectly safe as long as you're using modern concepts like RAII and not manually allocating memory like a recovering C developer."

Both of those were standard procedure a decade ago.  I have seen that C++ has been improved considerably in recent times;  C++ 0x in particular seems like it has some new capabilities.  What's the best resource for a "C/old C++" programmer to get caught up on "modern" C++ patterns and practices?

答:
It may have more to do with the instructional materials than most other things, but 8-10 years ago it seems to me that the way the language was used differed a great deal to today.  The focus today is more on leveraging templates, type safety, and generic programming where before there was more fear of all that and people focused almost exclusively on the C with objects aspects.

Instructional materials are changing too.  While before the standard C++ beginning book would take you through printf, scanf, etc...you hardly even see these in books with a modern approach.

Some good books are any of the red books.  Exceptional C++, More Exceptional C++, C++ Template Metaprogramming, Modern C++ Design, Accelerated C++...

I think looking at where I currently work may be a good example.  I came here using C++ in a modern way and it seems that most developers don't even know what I'm doing or why.  Making objects with operator () in them for example... Had to comment the hell out of every occurence of bind() and eventually was told to scrap all that code.  The don't know what initializers do...  It's been really freaky and hard for me actually.

Title: Best overview to modern C++ paradigms?


答:
I'd consider that a misuse of the term.  For something to be "native" to a language there needs to be built in facilities for it.  Native support for something like unicode would have raw types in the language that implement unicode in some way.  Usually though this is not part of the language but part of a library.

IMHO calling something that appears in the language's default library or not doesn't make something native or not.

Some examples:

C++ has native support for classes.  C does not.  There is no language keywords or type facility that enables the writing and use of classes, you must code them by hand.

I would say though that C++ no more has a native string type than C does.  There's a basic_string template in the standard library, but this is not a language facility.

C++11 though would seem to actually have added Unicode support as new keywords and raw types were added to the language itself to facilitate working with Unicode values.

Hope that clarifies the difference I see.


问:
Is it wrong to use a boolean parameter to determine behavior?
I have seen a practice from time to time that "feels" wrong, but I can't quite articulate what is wrong about it. Or maybe it's just my prejudice. Here goes:

A developer defines a method with a boolean as one of its parameters, and that method calls another, and so on, and eventually that boolean is used, solely to determine whether or not to take a certain action. This might be used, for example, to allow the action only if the user has certain rights, or perhaps if we are (or aren't) in test mode or batch mode or live mode, or perhaps only when the system is in a certain state.

Well there is always another way to do it, whether by querying when it is time to take the action (rather than passing the parameter), or by having multiple versions of the method, or multiple implementations of the class, etc. My question isn't so much how to improve this, but rather whether or not it really is wrong (as I suspect), and if it is, what is wrong about it.

答:
I stopped using this pattern a long time ago, for a very simple reason; maintenance cost.   Several times I found that I had some function say frobnicate(something, forwards_flag) which was called many times in my code, and needed to locate all the places in the code where the value false was passed as the value of forwards_flag.   You can't easily search for those, so this becomes a maintenance headache.  And if you need to make a bugfix at each of those sites, you may have an unfortunate problem if you miss one.

But this specific problem is easily fixed without fundamentally changing the approach:

enum FrobnicationDirection {
  FrobnicateForwards,
  FrobnicateBackwards;
};

void frobnicate(Object what, FrobnicationDirection direction);
```

With this code, one would only need to search for instances of FrobnicateBackwards.   While it's possible there is some code which assigns this to a variable so you have to follow a few threads of control, I find in practice that this is rare enough that this alternative works OK.

However, there is another problem with passing the flag in this way, at least in principle.   This is that some (only some) systems having this design may be exposing too much knowledge about the implementation details of the deeply-nested parts of the code (which uses the flag) to the outer layers (which need to know which value to pass in this flag).   To use Larry Constantine's terminology, this design may have over-strong coupling between the setter and the user of the boolean flag.   Franky though it's hard to say with any degree of certainty on this question without knowing more about the codebase.

To address the specific examples you give, I would have some degree of concern in each but mainly for reasons of risk/correctness.   That is, if your system needs to pass around flags which indicate what state the system is in, you may find that you've got code which should have taken account of this but doesn't check the parameter (because it was not passed to this function).   So you have a bug because someone omitted to pass the parameter.

It's also worth admitting that a system-state indicator that needs to be passed to almost every function is in fact essentially a global variable.  Many of the downsides of a global variable will apply.   I think in many cases it is better practice to encapsulate the knowledge of the system state (or the user's credentials, or the system's identity) within an object which is responsible for acting correctly on the basis of that data.  Then you pass around a reference to that object as opposed to the raw data.  The key concept here is encapsulation.

Body:
I stopped using this pattern a long time ago, for a very simple reason; maintenance cost.   Several times I found that I had some function say frobnicate(something, forwards_flag) which was called many times in my code, and needed to locate all the places in the code where the value false was passed as the value of forwards_flag.   You can't easily search for those, so this becomes a maintenance headache.  And if you need to make a bugfix at each of those sites, you may have an unfortunate problem if you miss one.

But this specific problem is easily fixed without fundamentally changing the approach:

enum FrobnicationDirection {
  FrobnicateForwards,
  FrobnicateBackwards;
};

void frobnicate(Object what, FrobnicationDirection direction);

With this code, one would only need to search for instances of FrobnicateBackwards.   While it's possible there is some code which assigns this to a variable so you have to follow a few threads of control, I find in practice that this is rare enough that this alternative works OK.

However, there is another problem with passing the flag in this way, at least in principle.   This is that some (only some) systems having this design may be exposing too much knowledge about the implementation details of the deeply-nested parts of the code (which uses the flag) to the outer layers (which need to know which value to pass in this flag).   To use Larry Constantine's terminology, this design may have over-strong coupling between the setter and the user of the boolean flag.   Franky though it's hard to say with any degree of certainty on this question without knowing more about the codebase.

To address the specific examples you give, I would have some degree of concern in each but mainly for reasons of risk/correctness.   That is, if your system needs to pass around flags which indicate what state the system is in, you may find that you've got code which should have taken account of this but doesn't check the parameter (because it was not passed to this function).   So you have a bug because someone omitted to pass the parameter.

It's also worth admitting that a system-state indicator that needs to be passed to almost every function is in fact essentially a global variable.  Many of the downsides of a global variable will apply.   I think in many cases it is better practice to encapsulate the knowledge of the system state (or the user's credentials, or the system's identity) within an object which is responsible for acting correctly on the basis of that data.  Then you pass around a reference to that object as opposed to the raw data.  The key concept here is encapsulation.


答:
Context is important. Such methods are pretty common in iOS. As just one often-used example, UINavigationController provides the method -pushViewController:animated:, and the animated parameter is a BOOL. The method performs essentially the same function either way, but it animates the transition from one view controller to another if you pass in YES, and doesn't if you pass NO. This seems entirely reasonable; it'd be silly to have to provide two methods in place of this one just so you could determine whether or not to use animation.

It may be easier to justify this sort of thing in Objective-C, where the method-naming syntax provides more context for each parameter than you get in languages like C and Java. Nevertheless, I'd think that a method that takes a single parameter could easily take a boolean and still make sense:

file.saveWithEncryption(false);    // is there any doubt about the meaning of 'false' here?
```

Title: Is it wrong to use a boolean parameter to determine behavior?

Body:
I have seen a practice from time to time that "feels" wrong, but I can't quite articulate what is wrong about it. Or maybe it's just my prejudice. Here goes:

A developer defines a method with a boolean as one of its parameters, and that method calls another, and so on, and eventually that boolean is used, solely to determine whether or not to take a certain action. This might be used, for example, to allow the action only if the user has certain rights, or perhaps if we are (or aren't) in test mode or batch mode or live mode, or perhaps only when the system is in a certain state.

Well there is always another way to do it, whether by querying when it is time to take the action (rather than passing the parameter), or by having multiple versions of the method, or multiple implementations of the class, etc. My question isn't so much how to improve this, but rather whether or not it really is wrong (as I suspect), and if it is, what is wrong about it.


答:
To get a quick oversight of modern features presented quite well, you'd not go wrong viewing Herb Sutter's recent presentation, "Writing modern C++ code: how C++ has evolved over the years" of C++ features at //build/.

He talks about why its a better language than C# (of course - Microsoft changes its trousers regularly, and today they're wearing the C++ fashion so they will hype this up, just lke they hyped up C# as the answer to world hunger a decade ago) but in doing so he does describe all the good bits (like 'automatic' memory management and the STL classes) and then goes on to talk about the new bits from the C++0x standard.

Title: Best overview to modern C++ paradigms?

Body:
I used to write C++ extensively between 8 and 10 years ago.  I have since moved on to C# for professional reasons.  However, from time to time I see statements like

"If you're still manually tracking pointer references, you're doing it wrong"

or

"C++ is perfectly safe as long as you're using modern concepts like RAII and not manually allocating memory like a recovering C developer."

Both of those were standard procedure a decade ago.  I have seen that C++ has been improved considerably in recent times;  C++ 0x in particular seems like it has some new capabilities.  What's the best resource for a "C/old C++" programmer to get caught up on "modern" C++ patterns and practices?


答:
First off: programming is not a science so much as it is an art. So there is very rarely a "wrong" and a "right" way to program. Most coding-standards are merely "preferences" that some programmers consider useful; but ultimately they are rather arbitrary. So I would never label a choice of parameter to be "wrong" in and of itself -- and certainly not something as generic and useful as a boolean parameter. The use of a boolean (or an int, for that matter) to encapsulate state is perfectly justifiable in many cases.

Coding decisions, by & large, should be based primarily on performance and maintainability. If performance isn't at stake (and I can't imagine how it ever could be in your examples), then your next consideration should be: how easy will this be for me (or a future redactor) to maintain? Is it intuitive and understandable? Is it isolated? Your example of chained function calls does in fact seem potentially brittle in this respect: if you decide to change your bIsUp to bIsDown, how many other places in the code will need to be changed too? Also, is your paramater list ballooning? If your function has 17 parameters, then readability is an issue, and you need to reconsider whether you are appreciating the benefits of object-oriented architecture.


问:
Is there any technology for dynamic assignment of execution context for programs that target many platforms with widely varying runtime performance?
This may very well be nothing new and probably exists, but I've never learned about it and would like to.

The simplest way to be more specific is just to give an example.

I was on the bus and downloaded a Text to Speech appliation onto my Android phone.

I know that the speech synthesizer might run on my phone but probably runs on a remote server.

In the near future I bet the processors in phones will go up and some people will have phones that could do the work but some will not.

In the scenario I just describe, the ideal situation might be if the execution environment dynamically pulled code to locally execute and/or pushed code back to be remotely executed.

I realize there are plently of frameworks for remote object calling, but do any of them pre-suppose the above?

答:
Agent frameworks are designed to support agents being moved from machine to machine, sometimes they do it automatically.

JADE http://jade.tilab.com/ is an agent framework that will run on android


问:
Data structure for file search
I've asked this question before and I got a few answers/idea, but I'm not sure how to implement them.

I'm building a telecom messaging solution. Currently, I'm using a database to save my transaction/messages for the network stack I've built, and as you know it's slower than using a data structure (hash, linkedlist, etc...). My problem is that the data can be really huge, and it won't fit in the memory.

I was thinking of saving the records in a file and the a key and line number in a hash, then if I want to access some record then I can get the line number from the hash, and get it from the file. I don't know how efficient is this; I think the database is doing a way better job than this on my behalf.

Please share whatever you have in mind.

答:
A database solution can have different structures:

1-Using Random Access Method for Reading the File.

Using this approach, you don't need a database. You can open the file and use fseek (or similar method) to move to the desired row to perform your read. You may want to see a tutorial here: Random Access Function

2-Using database loaded table

This approach requires that you perform a load before you access the data. This complicates the solution slightly but the load should not be a problem if you use the database supplied loader and drop the indexes before load. To gain max. performance using this approach, you could build a clustering index on the desired key. This too will take few seconds even if you have millions of rows. At this point, your query will be very fast and nothing could probably beat this.

3-Using database External files (provided by Oracle and possibly by other databases)

This approach allows you to access rows using SQL without physical loading the file into the database. Advantages are ease of use by using SQL only and the fact that no database load need to be programmed or executed. You can dig further and see if such an access method allows partitioning without index build (assuming your data is already in order). It could then be very quick.

I would suggest that you try the solutions in the listed order and test the performance. I guess solution number 1 should be fastest if you have exact key.

Title: Data structure for file search


答:
Write it when you need it, but design for their inclusion from the start.

In other words: make it so there is a way to handle that logging capability, and add the actual nuts and bolts functionality (what messages it logs) later as the need arises.  On exceptions- add the catch(and finally if you've got that) before you write the throw.  That will help to keep from forgetting one and saving yourself an iteration or at worst a bug/crash.


答:
An Inverted Index seems to be what you seek.  The basic idea is:

The messages/files are saved on disk in their full structure.

Each word in the file has a row in a table in the database.

There's a link table that allows you to do a join between the words and a unique ID for each message/file.

For example, here's the 3 database tables as I would create:

```<code>CREATE TABLE words (
    word_id INT PRIMARY KEY,
    word TEXT
)
CREATE TABLE links (
    word_id INT FOREIGN KEY words(word_id),
    file_id INT FOREIGN KEY files(file_id),
)
CREATE TABLE files (
    file_id INT PRIMARY KEY,
    filename TEXT
)
</code>```

To find all filenames that contain the words "help" and "me":

```<code>SELECT filename
FROM files
INNER JOIN links l1 ON (files.file_id = l1.file_id)
INNER JOIN words w1 ON (l1.word_id = w1.word_id)
INNER JOIN links l2 ON (files.file_id = l2.file_id)
INNER JOIN words w2 ON (l2.word_id = w2.word_id)
WHERE w1.word = "help" AND w2.word = "me"
</code>```

That help?

Title: Data structure for file search

Body:
I've asked this question before and I got a few answers/idea, but I'm not sure how to implement them.

I'm building a telecom messaging solution. Currently, I'm using a database to save my transaction/messages for the network stack I've built, and as you know it's slower than using a data structure (hash, linkedlist, etc...). My problem is that the data can be really huge, and it won't fit in the memory.

I was thinking of saving the records in a file and the a key and line number in a hash, then if I want to access some record then I can get the line number from the hash, and get it from the file. I don't know how efficient is this; I think the database is doing a way better job than this on my behalf.

Please share whatever you have in mind.

Body:
An Inverted Index seems to be what you seek.  The basic idea is:

The messages/files are saved on disk in their full structure.

Each word in the file has a row in a table in the database.

There's a link table that allows you to do a join between the words and a unique ID for each message/file.

For example, here's the 3 database tables as I would create:

CREATE TABLE words (
    word_id INT PRIMARY KEY,
    word TEXT
)
CREATE TABLE links (
    word_id INT FOREIGN KEY words(word_id),
    file_id INT FOREIGN KEY files(file_id),
)
CREATE TABLE files (
    file_id INT PRIMARY KEY,
    filename TEXT
)

To find all filenames that contain the words "help" and "me":

SELECT filename
FROM files
INNER JOIN links l1 ON (files.file_id = l1.file_id)
INNER JOIN words w1 ON (l1.word_id = w1.word_id)
INNER JOIN links l2 ON (files.file_id = l2.file_id)
INNER JOIN words w2 ON (l2.word_id = w2.word_id)
WHERE w1.word = "help" AND w2.word = "me"

That help?


答:
This is not necessarily wrong but it can represent a code smell.

The basic scenario that should be avoided regarding boolean parameters is:

public void foo(boolean flag) {
    doThis();
    if (flag)
        doThat();
}
```

<p>Then when calling you'd typically call <code>foo(false)</code> and <code>foo(true)</code> depending on the exact behavior you want.</p>

<p><strong>This is really a problem because it's a case of bad cohesion. You're creating a dependency between methods that is not really necessary.</strong></p>

<p>What you should be doing in this case is leaving <code>doThis</code> and <code>doThat</code> as separate and public methods then doing:</p>

<pre class="lang-java prettyprint-override"><code>doThis();
doThat();
</code>```

or

doThis();
```

That way you leave the correct decision to the caller (exactly as if you were passing a boolean parameter) without create coupling.

Of course not all boolean parameters are used in such bad way but it's definitely a code smell and you're right to get suspicious if you see that a lot in the source code.

This is just one example of how to solve this problem based on the examples I wrote. There are other cases where a different approach will be necessary.

There is a good article from Martin Fowler explaining in further details the same idea.

PS: if method foo instead of calling two simple methods had a more complex implementation then all you have to do is apply a small refactoring extracting methods so the resulting code looks similar to the implementation of foo that I wrote.

Body:
This is not necessarily wrong but it can represent a code smell.

The basic scenario that should be avoided regarding boolean parameters is:

public void foo(boolean flag) {
    doThis();
    if (flag)
        doThat();
}

Then when calling you'd typically call foo(false) and foo(true) depending on the exact behavior you want.

This is really a problem because it's a case of bad cohesion. You're creating a dependency between methods that is not really necessary.

What you should be doing in this case is leaving doThis and doThat as separate and public methods then doing:

doThis();
doThat();

or

doThis();

That way you leave the correct decision to the caller (exactly as if you were passing a boolean parameter) without create coupling.

Of course not all boolean parameters are used in such bad way but it's definitely a code smell and you're right to get suspicious if you see that a lot in the source code.

This is just one example of how to solve this problem based on the examples I wrote. There are other cases where a different approach will be necessary.

There is a good article from Martin Fowler explaining in further details the same idea.

PS: if method foo instead of calling two simple methods had a more complex implementation then all you have to do is apply a small refactoring extracting methods so the resulting code looks similar to the implementation of foo that I wrote.


答:
Its not necessarily wrong, but in your concrete example of the action depending on some attribute of the "user"  I would pass through a reference to the user rather than a flag.

This clarifies and helps in a number of ways.

Anyone reading the invoking statement will realize that the result will change depending on the user.

In the function which is ultimately called you can easily implement more complex business rules because you can access any of the users attributes.

If one function/method in the "chain" does something different depending on a user attribute, it is very likely that a similar dependency on user attributes will be introduced to some of the other methods in the "chain".


问:
How to manage scope creep?
We often receive last minute requests from the business asking for an extra feature to be implemented.  The project manager is usually responsible for filtering out these requests as "must haves" or "nice to have", but there are cases where the business wants to squeeze all these features into a release.   Is there a good way to say NO to the business?  What steps can be taken to stop or minimize scope creep?</p>

答: Make sure they understand and expect to be paying you for i) support, ii) additions, and iii) maintenance once you are done the initial work before you start.  If they won't agree to it don't do the project.</p>

Title: How to manage scope creep?


问:
OOP :What are some of the situations in which class based design is better than interface based one?
I was reading  JDOM's website.

Why is the JDOM API defined in terms of concrete classes rather than interfaces?

Jason Hunter summarizes the arguments against an interface-based API for JDOM:

With interfaces everything becomes a factory, elements have to be 'imported' into new documents instead of just added, features like long-term serialization cannot be guaranteed, and the list goes on.

We started with interfaces actually. During our pre-release review to some peers we received the feedback we should try concrete classes. We did, and the design was much better for it.

I am a beginner designer. All the advice I have heard about till now is advising against using designing with concrete classes.

May be using concrete classes are appropriate in certain places. Are there any common class problems for which using concrete classes in design is okay?

答:
Please remember, regarding your question, that in Software Development there are several ways to solve a problem, and if some developer uses a technique different than yours, that doesn't means it solution is wrong.

One of those cases is "interfaces" versus (base) "classes". There are situations where the same goal can be achieve with both techniques.

To make things, more complicated, there are several uses of interfaces,
 just to mention:

one is to design a "contract" or "specification" without "implementation"

other, to add functuonality to an existing, not new, class or hierarchy of classes

complementary to previous, to allow share access among different objects, technologies, example: Enterprise Beans, CORBA, COM, WebServices

to emulate multiple inheritance

Your question applies to the first point.

When you want to develop a class hierarchy, not just a single class, and several classes are intended to share some specific features, you may want to start with a base class, even if it can be done with an interface.

And, leave interfaces for the others scenarios.

A good example are widgets (controls) libraries.

I suggest, that take a look to other programming languages how do they use interfaces & classes like: PHP, Delphi (Object Pascal), C#.

Cheers.

ContentLicense: CC BY-SA 4.0


答:
I like the approach of customizing behavior through builder methods that return immutable instances. Here's how Guava Splitter uses it:

private static final Splitter MY_SPLITTER = Splitter.on(',')
       .trimResults()
       .omitEmptyStrings();

MY_SPLITTER.split("one,,,,  two,three");
```

The benefits of this are:

Superior readibility

Clear separation of configuration vs. action methods

Promotes cohesion by forcing you to think about what the object is, what it should and shouldn't do. In this case it's a Splitter. You'd never put someVaguelyStringRelatedOperation(List<Entity> myEntities) in a class called Splitter, but you'd think about putting it as a static method in a StringUtils class.

The instances are pre-configured therefore readily dependency-injectable. The client doesn't need to worry about whether to pass true or false to a method to get the correct behavior.

Body:
I like the approach of customizing behavior through builder methods that return immutable instances. Here's how Guava Splitter uses it:

private static final Splitter MY_SPLITTER = Splitter.on(',')
       .trimResults()
       .omitEmptyStrings();

MY_SPLITTER.split("one,,,,  two,three");

The benefits of this are:

Superior readibility

Clear separation of configuration vs. action methods

Promotes cohesion by forcing you to think about what the object is, what it should and shouldn't do. In this case it's a Splitter. You'd never put someVaguelyStringRelatedOperation(List<Entity> myEntities) in a class called Splitter, but you'd think about putting it as a static method in a StringUtils class.

The instances are pre-configured therefore readily dependency-injectable. The client doesn't need to worry about whether to pass true or false to a method to get the correct behavior.


答:
B-Trees sound like exactly the data structure you might be looking for.

To quote the Wikipedia article:

...the B-tree is optimized for systems that read and write large blocks of data. It is commonly used in databases and filesystems.

Title: Data structure for file search


问:
What is the difference between an Array and a Stack?
According to Wikipedia, a stack:

is a last in, first out (LIFO) abstract data type and linear data structure.

While an array:

is a data structure consisting of a collection of elements (values or variables), each identified by at least one array index or key.

As far as I understand, they are fairly similar. So, what are the main differences? If they are not the same, what can an array do that a stack can't and vice-versa?

答:
An array is from the programmers perspective, fixed in place and size, you know where you are in it and where the whole thing is.  You have access to all of it.

With a stack, you sit on one end of it but have no idea of its size or how far you can safely go.  Your access to it is limited to the amount you have allocated, you often dont even know if when allocating the amount you wanted if you just slammed into the heap or program space.  Your view of a stack is a small array that you have allocated yourself, the size you wanted, you have control over and can see.  Your portion is no different than an array.  The difference lies in your array is tacked onto one end of another array for sake of argument and terminology, which you have no visibility of, no idea how big or small, and you cant touch it without possibly causing harm.  An array, unless global, is often implemented on the stack anyway, so the array and the stack share the same space for the duration of that function.

If you want to get into the hardware side, then it is processor specific of course, but generally the array is based off of a known starting point/address, the size is known by the compiler/programmer, and addresses are computed into it, sometimes using register offset addressing (load a value from the address defined by this base register value plus this offset register value, likewise when compiled it could be an immediate offset not necessarily register based, depends on the processor of course) which in assembly very much resembles accessing an array in high level code.  Likewise with the stack, if available, you can use register or immediate offset addressing, often though it uses a special register, either the stack pointer itself, or a register reserved by the compiler/programmer to be used for accessing the stack frame for that function.  And for some processors special stack access functions are used and/or required to access the stack.  You have push and pop instructions but they are not used as often as you would think and dont really apply to this question.  For some processors push and pop are aliases for instructions that can be used with any register, anywhere, not just the stack pointer on the stack, further removing push and pop from being related to this question.


问:
Pulling in changes from a forked repo without a request on GitHub?
I'm new to the social coding community and don't know how to proceed properly in this situation:

I've created a GitHub Repository a couple weeks ago. Someone forked the project and has made some small changes that have been on my to-do. I'm thrilled someone forked my project and took the time to add to it. I'd like to pull the changes into my own code, but have a couple of concerns.

1) I don't know how to pull in the changes via git from a forked repo.  My understanding is that there is an easy way to merge the changes via a pull request, but it appears as though the forker has to issue that request?

2) Is it acceptable to pull in changes without a pull request? This relates to the first one. I'd put the code aside for a couple of weeks and come back to find that what I was going to work on next was done by someone else, and don't want to just copy their code without giving them credit in some way. Shouldn't there be a to pull the changes in even if they don't explicitly ask you to? What's the etiquette here

I may be over thinking this, but thanks for your input in advance. I'm pretty new to the hacker community, but I want to do what I can to contribute!

答:
1) To pull in somebody else's changes, first add a remote that points to their repository. For example:

```<code>git remote add soniakeys https://github.com/soniakeys/goptimize.git
</code>```

Then, you can fetch those changes into your repository (this doesn't change your code, yet):

```<code>git fetch soniakeys
</code>```

Finally, to merge those changes, make sure you're on your master branch and:

```<code>git merge soniakeys/master
</code>```

2) To be polite, you would normally ask the author whether it's okay to pull the changes. Just because they're on a public repository doesn't necessarily mean they are ready to pull. There might be further work to do, or perhaps intellectual property issues, or whatever. However, with published changes on an open source repository, asking is not strictly required.

Body:
1) To pull in somebody else's changes, first add a remote that points to their repository. For example:

git remote add soniakeys https://github.com/soniakeys/goptimize.git

Then, you can fetch those changes into your repository (this doesn't change your code, yet):

git fetch soniakeys

Finally, to merge those changes, make sure you're on your master branch and:

git merge soniakeys/master

2) To be polite, you would normally ask the author whether it's okay to pull the changes. Just because they're on a public repository doesn't necessarily mean they are ready to pull. There might be further work to do, or perhaps intellectual property issues, or whatever. However, with published changes on an open source repository, asking is not strictly required.


问:
Is Google's Go a type-safe language?
this page http://golang.org/doc/go_faq.html writes:

although Go has static types the
  language attempts to make types feel
  lighter weight than in typical OO
  languages

So my question is exactly is it safely typed with generics (like C#) or loosely typed (like javascript) or optional (like option strict in Vb.Net)

答:
Go's map type is not thread-safe, it is statically typed. It does not have type inheritance, generic programming, assertions, method overloading, or pointer arithmetic either and for good reason.

Type safety and memory safety are long term aims, here in lie's a problem.

Type safety presents an overhead, in kilobytes and megabytes which is acceptable. Go is designed with MapReduce and "Big data", exobytes an petabytes of data, which presents performance issues with type safety, type checking (boxing / unboxing) creates overheads and takes cycles away from processing.

Type safety can be restrictive in sub-typing and polymorphism and in duck typing (cast object to object), this creates dangers and also a space where languages like Go are of great benefit. C++ and Java are not being replaced by Go, it is a new language to help distributed programming and massively parallel system.

The big statement by Bruce Eckel - "Go makes much more sense for the class of problems that C++ was originally intended to solve", is debatable. C++ is a very efficient language and the Boost implementation of MapReduce is very efficient.

Concurrency primitives are the future. Type safety has always been a very contentious topic and Go maybe the first language to address this issue in 20 years, or since Algol.

Title: Is Google's Go a type-safe language?


问:
What are the chances of Google's Go becoming a mainstream language?
Who here is learning Go? Are other companies looking at using it? Is it likely to become widely used?</p>

答:
It is already more popular than some languages.

There is a possibly, that Go is the most important language in 20+ years. It really does present some great benefits in terms of massive datasets, which social media sites, cloud computing, Search and Mobile present.

Sites like Facebook, Twitter, Linkedin, YouTube and Ad-Serving networks have much more use for Google Go than Ruby On Rails, at least in some contexts.


问:
What is the name for the programming paradigm characterized by Go?
I'm intrigued by the way Go abandons class hierarchies and seems to completely abandon the notion of class in the typical object oriented sense. Also, I'm amazed at the way interfaces can be defined without the type which implements that interface needing to know.

Are there any terms which are/can be used to characterize this type of programming methodology and language paradigm (or perhaps specific aspects of it)? Is the Go language paradigm sufficiently new and distinct from the classical OOP paradigm and sufficiently important in the history of computer programming to warrant a unique name?

答:
Concurrency primitives.

Communicating Sequential Processes or CSP is a paper by Charles Antony Richard Hoare, first published in 1985 by Prentice Hall International.

Erlang is a functional language and Go is structured, one might say that Erlang is the predicator to Go.


问:
Dynamic typing across the whole technology stack - where to enforce data validity?
Over the past year or two, I've been playing with newer technologies in my side projects. As a web developer, I've gone from the following (and still the following, at work):

The 'classic' technology stack

Web browser POSTs forms to...

a C#-coded web application server-side, communicating to...

external services via XML, then ultimately...

writing the application state to a SQL database.

To using a very different arrangement:

The fully-dynamic technology stack

Web browser submitting XmlHttpRequests to...

a JavaScript-coded Node.js server-side, communicating to...

other external services via RESTful services in JSON, ultimately...

writing the application state to a no-SQL database

It's gotten to the point where my whole stack has absolutely no enforcement of type or schema, anywhere.

Now, this has been just fine before, when consuming others' web services. It might have even been fine up until the SQL databases were ditched (along with their DB schemas). But now I'm stuck at:

Where do I declaratively define what is the valid structure of my business-domain data?

I want to enforce data validity before making any of my projects publically available - after all, what's to stop someone from just submitting invalid data to my services, and using it all as just a hacky free database provider? At some point, it has to be enforced that "this web service will only accept a collection of at least one X. X must contain A, B, and optionally C".

The first solution I thought of was to do validation inside my node.js, through a big block of imperative code/if-elses/etc. This felt wrong.

I have been using CouchDB, and for a while I thought that it might be best to put that validation code in the _update handlers. At least we're performing validation as part of persistence, but it's still an ugly imperative block.

Next, I looked into JSON schema languages. There is no standard as far as I can see, and I wasn't confident in the multiple solutions offered. I could roll my own, but then I'd only be expanding the body of non-standard JSON schema languages.

XML? I could put the X back into AJAX, and have them all schema-validated on the server side. That doesn't seem to follow the trends in software development, however. Neither would using an XML data store instead of a JSON CouchDB/BSON MongoDB persistence layer.

So, I'm stuck. Ideas?

TL;DR Where do I declaratively define the valid structure of my business-domain data when I am using no static Object Oriented language, and no schema-bound SQL database, in my technology stack? Is it possible that there must be some static typing (or DB schema, or validated XML) somewhere for a technology stack to make any sense? If so, where?

答:
Ditch the notion of types altogether.

The whole point of dynamic typing, at least in languages that get it mostly right, is that you don't have to think about types most of the time. Type-checks make sense in a pre-compiled language, because the compiler can then catch a lot of errors before you can even attempt to run the code, but when your code is interpreted or JIT-compiled, the benefits of static type checks are marginal and don't weigh up against the added flexibility that dynamic programming has to offer.

Instead of validating types, validate values - that is, if you want something to be numeric, run an 'is-numeric' check. If you want something to have a certain property, check if the property exists. If you want something to be in a certain range, check if it is in fact within the range. Etc. etc.

There are two philosophies to this: the more traditional check-before-you-go, that is, before dividing a by b, you make sure b is non-zero; and the easier-to-ask-forgiveness-than-permission route Python takes, that is, you just divide a by b, and then catch the divide-by-zero exception afterwards.

Unfortunately, there is no meaningful way of doing this declaratively that I am aware of. But then, the boundary between code and data is much blurrier in dynamic programming - code is also data that you can manipulate, and data can take the role of code. A piece of javascript code that validates a JSON object is just another chunk of text, and you can treat it as plain old data; you can even generate that text at run-time and then execute it (although you should be very careful about this, especially if you use data from untrusted sources in the code generation process).

As far as schemas go, again, checking strictly whether a given JSON object matches a schema is seldom required - instead, you just check whether the required properties are there, and whether your value-level invariants hold. If extra properties exist, that's fine - you just ignore them. If something is missing, you can either bail, or substitute a default value. And if something has the wrong type, again, you can bail (found a non-numeric string where a number was expected), or you can gracefully recover (substitute a default value, round, truncate, convert to boolean, etc.).

Another thing to consider is that XML is far more complex than JSON - XML has namespaces, attributes, entities, and you need to decide how to marshal between objects in your language and XML representations. In JSON, the choice is usually obvious - it's either scalar (int, float, string, boolean, null), a simple list (array), or a key-value collection (object).

Unfortunately, there are few languages (if any) that get transparent type casting right - Javascript, PHP, Python, they all require explicit type juggling occasionally, so you won't be able to reach the theoretically ideal situation.


答:
Sounds to me like you're about to create an inner platform to compensate the lack of semantics inherent to the language you chose.

Even schema definitions (be it XML DTD, or JSON schema or  mongoose schema) will not provide you the safety of statical analysis. All you can really use them for is to guarantee that your system doesn't silently run into undefined behavior and ultimately fail.

I am not really sure why you won't use a language, that simply provides this out of the box. Using a dynamically typed language and embedding type constraints into that seems to combine the worst of both worlds. Even more so, because modern statically typed languages are able to infer vast parts of those constraints implicitly.

Personally I suggest you take a look at Haxe's JavaScript backend. There's a site dedicated to node.js development with Haxe - you could start there. Haxe's anonymous types can quickly be used to tie in JSON sources in a type safe manner without any runtime overhead. Still, if you wish, its meta programming facilities allow you to automagically generate validation code from that at compile time.

Of course Haxe is by far not the only option out there to target JavaScript in a typesafe manner. So if you feel you need the benefits of static typing, the you should invest the time to find a language to your liking, that actually embeds this information right into its statically analyzable semantics.

Title: Dynamic typing across the whole technology stack - where to enforce data validity?

Body:
Over the past year or two, I've been playing with newer technologies in my side projects. As a web developer, I've gone from the following (and still the following, at work):

The 'classic' technology stack

Web browser POSTs forms to...

a C#-coded web application server-side, communicating to...

external services via XML, then ultimately...

writing the application state to a SQL database.

To using a very different arrangement:

The fully-dynamic technology stack

Web browser submitting XmlHttpRequests to...

a JavaScript-coded Node.js server-side, communicating to...

other external services via RESTful services in JSON, ultimately...

writing the application state to a no-SQL database

It's gotten to the point where my whole stack has absolutely no enforcement of type or schema, anywhere.

Now, this has been just fine before, when consuming others' web services. It might have even been fine up until the SQL databases were ditched (along with their DB schemas). But now I'm stuck at:

Where do I declaratively define what is the valid structure of my business-domain data?

I want to enforce data validity before making any of my projects publically available - after all, what's to stop someone from just submitting invalid data to my services, and using it all as just a hacky free database provider? At some point, it has to be enforced that "this web service will only accept a collection of at least one X. X must contain A, B, and optionally C".

The first solution I thought of was to do validation inside my node.js, through a big block of imperative code/if-elses/etc. This felt wrong.

I have been using CouchDB, and for a while I thought that it might be best to put that validation code in the _update handlers. At least we're performing validation as part of persistence, but it's still an ugly imperative block.

Next, I looked into JSON schema languages. There is no standard as far as I can see, and I wasn't confident in the multiple solutions offered. I could roll my own, but then I'd only be expanding the body of non-standard JSON schema languages.

XML? I could put the X back into AJAX, and have them all schema-validated on the server side. That doesn't seem to follow the trends in software development, however. Neither would using an XML data store instead of a JSON CouchDB/BSON MongoDB persistence layer.

So, I'm stuck. Ideas?

TL;DR Where do I declaratively define the valid structure of my business-domain data when I am using no static Object Oriented language, and no schema-bound SQL database, in my technology stack? Is it possible that there must be some static typing (or DB schema, or validated XML) somewhere for a technology stack to make any sense? If so, where?


答:
Yes, it is normal to forget. But as Crazy Eddie said, knowing good programming style and technique in one language is generally applicable to another, provided it is not too different. For example, techniques that work well in C++ might not translate well to something like Lisp (though Lisp experts might argue that Lisp skills make you better at everything).

I find that reading a book about a language will only get you so far as to be able to understand code in that language when you read it. To know how to write in it, you really need to do a non-trivial project with it. Once you accomplish that, you might forget a few details after an absence, but your skills will quickly return when needed. Only by building something in a language do you begin to get the intuitive sense of how its pieces fit together that you need in order to excel at it.


问:
Could Go work with other user interfaces than Web?
Go seems to be made for doing server side stuff for the web. What could I do if my boss suddenly dictated that he wants a Windows GUI for a Go application?</p>

答:
Have a look at Go OpenGL, which exposes core and extensions. There is no reason why Go couldn't be used in conjunction with GLEW (OpenGL Extension Wrangler Library) to make advanced visualisations from big data type scenarios.

Go Plot and Go SVG are out there, as I've just noticed a few hundred other bindings and library's to be found on the Go Language Resources.


问:
What alternatives are there for cross cutting concerns other than aspect oriented programming?
Aspect oriented programming promises to deal with cross cutting concerns, but I'm not completely sold on it yet. Have there been any other attempts to deal with this problem?</p>

答: In general tagging code elements with a declarative feature, but specifically the Attribute system  in the C#/.NET/Mono world.

OwnerDisplayName: mumtaz

LastEditorDisplayName: mumtaz


答:
Well as your programming stack does not care about types why should you.

The answer is that your users might. So what you want to do is enforce whatever business rules apply to your data.

This can be done by JavaScript on entered forms, by coding validation into your Node.js server code when a request is received, or, even encoding the rules in xsd and getting the parser to validate your xml input.

The point is you implement business rules validation not technical validation. That is you should be checking rules like "A three digit number between 001 and 700" which mean something to your end user, rather than "is this numeric". So if your user thinks "The night before christmas" is a valid date and your application can live with it then its a valid date.


问:
Learning the Operating Systems concepts and Programming Languages for elderly
I am not sure if this would be the right forum to ask the question (Please let me know and I will move the question to appropriate forum).

I would like to know what can be the best way for elders (in my case, my parents) to learn how  to program. I was looking at Qimo 4 kids as a possible platform so that my parents can have a closer look at Linux environments. But it seems like Qimo mostly consists of educational games. I also don't know about which programming language would make the best choice.

If anyone can provide me with information on how to go about with this "project", that would be grateful!!!

答:
Start them off with BASIC first. BASIC would be a very nice choice of programming language if they just want to do simple programming problems initially. This would let them understand how programming works when they solve small-sized problems like adding 2 numbers, making a calculator, taking user input, etc. Initially help them yourself, then let them ponder and explore it a bit. Tell them to solve regular-day problems in BASIC.

In case they want to then go for a "proper" programming language later on, my vote goes for Python. Here is a small excerpt from Wikipedia about Python:

Python is a general-purpose, high-level programming language whose
  design philosophy emphasizes code readability. Python claims to
  combine "remarkable power with very clear syntax"...

I myself being a long-time python programmer, I can very well say that it is a very good choice to start programming with. But, this answer is subjective, every user has his/her own preferences. Also, it depends on what all your parents are willing to learn. :)


答:
Unless your parents have expressed a clear, strong desire to learn programming, I recommend against trying to teach them. Programming is hard, and requires a special way of thinking and a significant investment in time to reach the point where you feel like you know what you are doing. Unless they are motivated to learn, it might not be much more than a frustrating experience for them.

That being said, you probably want to teach them a language or system that provides a lot of immediate visual feedback without being too picky about getting things just right. Something like C or C++ might be too hard with having to worry about #including headers, compiling, linking, and learning how to fix errors at each step. Java might be a better choice, but it still a pretty verbose language. Python can be picky about indentation, but is otherwise pretty good.

Something that I saw recently was a presentation on a small DSL called PIE to allow kids to code simple games. The language was super simple, and when run it produced something that felt "real". Perhaps a custom language focused on programmer satisfaction rather than solving real-world problems might be a good choice.

Title: Learning the Operating Systems concepts and Programming Languages for elderly

Body:
I am not sure if this would be the right forum to ask the question (Please let me know and I will move the question to appropriate forum).

I would like to know what can be the best way for elders (in my case, my parents) to learn how  to program. I was looking at Qimo 4 kids as a possible platform so that my parents can have a closer look at Linux environments. But it seems like Qimo mostly consists of educational games. I also don't know about which programming language would make the best choice.

If anyone can provide me with information on how to go about with this "project", that would be grateful!!!


问:
Why do so many developers believe performance, readability, and maintainability cannot coexist?
While responding to this question, I began to wonder why so many developers believe a good design should not account for performance because doing so would affect readability and/or maintainability.

I believe that a good design also takes performance into consideration at the time it is written, and that a good developer with a good design can write an efficient program without adversely affecting readability or maintainability.

While I acknowledge that there are extreme cases, Why do many developers insist an efficient program/design will result in poor readability and/or poor maintainability, and consequently that performance should not be a design consideration?

答:
There are also some famous pieces of highly optimised code that will bend most peoples brains that support the case that highly optimised code is difficult to read and understand.

Here's the most famous I think.  Taken from Quake III Arena and attributed to John Carmak, although I think there's been several iterations of this function and it wasn't originally created by him (isn't Wikipedia great?).

```<code>float Q_rsqrt( float number )
{
    long i;
    float x2, y;
    const float threehalfs = 1.5F;

    x2 = number * 0.5F;
    y  = number;
    i  = * ( long * ) &y;                       // evil floating point bit level hacking
    i  = 0x5f3759df - ( i >> 1 );               // what the fuck?
    y  = * ( float * ) &i;
    y  = y * ( threehalfs - ( x2 * y * y ) );   // 1st iteration
    //      y  = y * ( threehalfs - ( x2 * y * y ) );   // 2nd iteration, this can be removed

    return y;
}
</code>```

Body:
There are also some famous pieces of highly optimised code that will bend most peoples brains that support the case that highly optimised code is difficult to read and understand.

Here's the most famous I think.  Taken from Quake III Arena and attributed to John Carmak, although I think there's been several iterations of this function and it wasn't originally created by him (isn't Wikipedia great?).

float Q_rsqrt( float number )
{
    long i;
    float x2, y;
    const float threehalfs = 1.5F;

    x2 = number * 0.5F;
    y  = number;
    i  = * ( long * ) &y;                       // evil floating point bit level hacking
    i  = 0x5f3759df - ( i >> 1 );               // what the fuck?
    y  = * ( float * ) &i;
    y  = y * ( threehalfs - ( x2 * y * y ) );   // 1st iteration
    //      y  = y * ( threehalfs - ( x2 * y * y ) );   // 2nd iteration, this can be removed

    return y;
}


问:
Algorithm which suggests synonyms based on some term?
Is there an algorithm which I can use in order to generate synonyms for some term (word) in respect of a spam. I am writing a simple spam filter.

For example, I set that the app must omit a word "viagra" and press a button which saves this term into a filter database. A script automatically creates synonyms of this word, such as: v.i.a.g.r.a, via_gra, via-gra, and similar. Or I filter a curse, and it generates all the tricks people use to have their curses appear in their comments.

答:
Instead of building a dictionary of aliases for the same noun, you could instead test if a given word is an alias of this noun.

You could use many algorithm for this, the simplest one being the Levenshtein distance algorithm. This algorithm computes the distance between two words, for instance a word in a mail and a word in a dictionary. For instance the distance between viagra and vi.agra is 1.

You could then define a threshold below which two words are assumed to be equal (for example, if the distance is lower than 30% of the size of the words).
You could enhance the distance algorithm to give lower weights for special characters (like a dash or underscore).

Another algorithm worth looking is the Damerau-Lenvenshtein distance algorithm, which is used to detect spelling mistakes.


答:
Welcome to the wonderful world of pattern recognition! This is an extremely hard task to get right. Whatever algorithm you use, the spammers will subvert it and somehow push messages that people recognize, but your program doesn't. You recognize letter substitutions, they move to numbers. You generalize over all characters, they use images. You use OCR, they invent something different.

It may not look it, but this is actually very near the absolute center of what artificial intelligence is about. If you had an algorithm so good that it equals human recognition, you shouldn't be working as a developer - you should get a tenured professorship at Harvard. Seriously.

Title: Algorithm which suggests synonyms based on some term?

Body:
Is there an algorithm which I can use in order to generate synonyms for some term (word) in respect of a spam. I am writing a simple spam filter.

For example, I set that the app must omit a word "viagra" and press a button which saves this term into a filter database. A script automatically creates synonyms of this word, such as: v.i.a.g.r.a, via_gra, via-gra, and similar. Or I filter a curse, and it generates all the tricks people use to have their curses appear in their comments.


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

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

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

答:
I see absolutely no connection with scrolling etc.  Having a ten-second latency isn't good, even if I wasn't going to type more than 360 characters that hour anyway.

When typing flat-out, I probably go about 60 wpm, or 1 wps.  (I've been objectively tested at 87 wpm.)  Given about six characters per word in tests like that, we're talking about 6 characters per second.  Ideally, each would appear on the screen before the next keypress, so I can easily keep track of where I am and correct typos immediately.  Bear in mind that I'm thinking about what I'm typing, so having to divert any cognition to the act of typing is a real limitation.

Since I don't know how bursty my typing is, I'd say that 0.1 second is the maximum acceptable latency from all causes.  That's network latency both ways, any latency in bringing up my personal VM, everything.  Anything more is going to be a drain on productivity.


问:
Drawbacks to entirely Ajax driven CMS
I'll try to keep this question as specific as possible..

I'm about to start building an API for an upcoming project. I'm currently thinking PHP/Symfony2. It will be a farily simple HTTP-based api for CRUD on the site's models (and relationships between them).

There will also need to be a CMS for users. Traditionally when building a CMS (if it's bespoke) I'd just use some standard MVC based approach, but for this particular project I'm thinking I could build it using Ajax calls to the API that will already exist.

My question is essentially to decide which way to go, but to keep it specific I'd like to know what drawbacks there might be.

In favour of this, it should reduce duplication of controller logic, why have /api/model/save/ and /cms/model/save doing very similar things?

Currently the only two drawbacks I can think of are that:

It may be hard to support a wide range of browsers. For this particular scenario, this shouldn't be a problem - but who knows what might happen in the future?

Some parts of the site would require traditional PHP logic or an extension to the API (for any parts not part of the core API itself), for example to handle admin authentication.

Is there anything I've missed, some overwhelming reason not to take this approach?

答:
The other issue you might run into is maintaining state (you mentioned authentication) but as your system gets more complex, you might have to lean heavily on cookies to know what's happened, persist user IDs across requests etc.

I wouldn't try to discourage you from this approach, but make sure that you keep this in mind as you do your planning as it could spiral out of control if you don't have a plan for it.

OwnerDisplayName: Adam

Title: Drawbacks to entirely Ajax driven CMS

OwnerDisplayName: gaffleck


答:
I don't know the particulars of the project, but I think your main problem is this:

Do you trust your user with everything?

If you use AJAX, the user may alter it and call your API in an undesired way. Which, in turn, means that you have to design your API so that it's secure. That would definitely slow you down.

I'd advise you to not do it, unless it's a research example: there's too much to loose and too many ways to screw it up.

Title: Drawbacks to entirely Ajax driven CMS

Body:
I'll try to keep this question as specific as possible..

I'm about to start building an API for an upcoming project. I'm currently thinking PHP/Symfony2. It will be a farily simple HTTP-based api for CRUD on the site's models (and relationships between them).

There will also need to be a CMS for users. Traditionally when building a CMS (if it's bespoke) I'd just use some standard MVC based approach, but for this particular project I'm thinking I could build it using Ajax calls to the API that will already exist.

My question is essentially to decide which way to go, but to keep it specific I'd like to know what drawbacks there might be.

In favour of this, it should reduce duplication of controller logic, why have /api/model/save/ and /cms/model/save doing very similar things?

Currently the only two drawbacks I can think of are that:

It may be hard to support a wide range of browsers. For this particular scenario, this shouldn't be a problem - but who knows what might happen in the future?

Some parts of the site would require traditional PHP logic or an extension to the API (for any parts not part of the core API itself), for example to handle admin authentication.

Is there anything I've missed, some overwhelming reason not to take this approach?


问:
What is the appeal of Systems Hungarian?
In a now deleted question titled "What naming guidelines do you follow?", the author says:

Also I prefer to code using hungarian notation from Charles Simonyi.

I've run in to several programmers who still prefer to use Hungarian, mostly of the Petzold/Systems Hungarian flavor.  Think dwLength = strlen(lpszName).

I've read Making Wrong Code Look Wrong, and I understand the rationale for Apps Hungarian, where domain-type information is included in the variable names.  But I don't understand the value in attatching the compiler type to the name.

Why do programmers still persist on using this style of notation?  Is it just inertia?  Are there any benefits that outweigh the decreased readability?  Do people just learn to ignore the decorators when reading the code, and if so, how do they continue to add value?

EDIT:
A lot of answers are explaining the history, or why it is no longer relevant, both of which are covered in the article I cited.

I'd really like to hear from anyone out there who still uses it.  Why do you use it?  Is it in your standard?  Would you use it if it wasn't required?  Would you use it on a new project?  What do you see as the advantages?

答: I am also curious to see rationale. We know why they used it in the past: lack of IDE support for type information. But now? Simply put, I think it is a tradition. C++ code always looked like this, so why change things? Besides, when you build on top of previous code that used Hungarian notation, it would look quite strange when you suddenly stop using that...


问:
Should program behavior be modified using a config file or environmental variables?
I'm referring to *nix command line applications primarily, where you want to permanently modify the behavior from defaults.

Environmental variables are easily understood and implemented, usually requiring the user to modify their ~/.bashrc for a permanent change. However, namespace collision might be a problem (but unlikely if you're careful).

On the other hand, a lot of programs use ~/.programrc config files.

Is it simply verbosity? If your program only has 2 configuration settings, then a simple export APP_SETTING=1 works just fine. However if you're starting to offer 5+ options then it should be time to start looking into a config file?

答:
There are many other pressures:

Writing a config file requires write permission on the file system (in fact, it requires a file system in the first place!). Environment variables can be set even if you are running a rescue system from a CD.

Environment variables can be set quickly and temporarily just for one invocation, which is much better for use in small shell scripts. (Rewriting and re-rewriting a config file risks destroying the original settings if the process doesn't terminate correctly. Temporary values die automatically.)

A config file can be passed around easily to some other user or pre-installed with a distribution. Telling someone how to use environment variables is much harder. You wouldn't believe how much harder it is to get normal people to type CDG_VERBOSITY=5 cdg correctly then just cdg.

Environment variables may or may not get inherited properly if your program farms out work to other processes. A config file is always there.

There can be surprisingly low limits on the size of the environment that can be passed to a process on some systems. The file system is much, much more forgiving.

If you need to change settings after program start, telling a process to re-read its config file is a well-known idiom. Changing the environment of a running process can be trickier.

Reading a config file hits the disk, which is massively slower than reading from the environment. A config file would be grossly inappropriate for something like grep, which is usually invoked on data that are entirely in memory.


问:
Is it wrong to use a boolean parameter to determine behavior?
I have seen a practice from time to time that "feels" wrong, but I can't quite articulate what is wrong about it. Or maybe it's just my prejudice. Here goes:

A developer defines a method with a boolean as one of its parameters, and that method calls another, and so on, and eventually that boolean is used, solely to determine whether or not to take a certain action. This might be used, for example, to allow the action only if the user has certain rights, or perhaps if we are (or aren't) in test mode or batch mode or live mode, or perhaps only when the system is in a certain state.

Well there is always another way to do it, whether by querying when it is time to take the action (rather than passing the parameter), or by having multiple versions of the method, or multiple implementations of the class, etc. My question isn't so much how to improve this, but rather whether or not it really is wrong (as I suspect), and if it is, what is wrong about it.

答:
I can't quite articulate what is wrong about it.

If it looks like a code smell, feels like a code smell and - well - smells like a code smell, it's probably a code smell.

What you want to do is:

1) Avoid methods with side-effects.

2) Handle necessary states with a central, formal state-machine (like this).


问:
Data structure for file search
I've asked this question before and I got a few answers/idea, but I'm not sure how to implement them.

I'm building a telecom messaging solution. Currently, I'm using a database to save my transaction/messages for the network stack I've built, and as you know it's slower than using a data structure (hash, linkedlist, etc...). My problem is that the data can be really huge, and it won't fit in the memory.

I was thinking of saving the records in a file and the a key and line number in a hash, then if I want to access some record then I can get the line number from the hash, and get it from the file. I don't know how efficient is this; I think the database is doing a way better job than this on my behalf.

Please share whatever you have in mind.

答:
You could try Lucene. It's a full text search library which offers powerful features through a simple API. It's written in Java, but there's a .NET version, Lucene.net.

I've used it many on Web/desktop projects to implement enterprise search functionality.

Title: Data structure for file search


问:
How do you deal with the anxiety of not knowing enough?
I just finished college a couple of months ago and I'm taking time out to improve my knowledge. I love programming but I feel like I don't know enough to be confident if I went for an interview. Last night I was browsing through questions and came across a question that asks interviewees how to work out a linked list. I learned these at college but if I was asked on the spot how to do it I wouldn't know. So that's another thing added to the list of what to learn.

This is when the anxiety hit me because I have so much to learn in so little time (at least it feels that way). Upon introspection, I think this anxiety is related to my perfectionism even though being perfect isn't rational e.g. Shakespeare and Einstein failed 80% of the time.

So the questions are, have you felt this anxiety of not knowing enough? If so, how did you deal with it? I suppose there's a point in time when you begin to feel comfortable in your abilities?

答: The best way to learn, is to do.  Admitting to your self that you don't know something is the beginning of knowledge.  If I were you, instead of taking time out trying to learn what you think you need to learn  I would put myself out there and try to find a job.  Get some interviews under your belt, then you can get an idea of what you need to know to pass an interview. Who knows, you just might get a job and then you can have a corporate-funded learning experience surrounded by experienced people who can help you on your journey.  Remember, knowledge is a journey, not a destination.</p>


问:
How to deal with static utility classes when designing for testability
We are trying to design our system to be testable and in most parts developed using TDD. Currently we are trying to solve the following problem:

In various places it is necessary for us to use static helper methods like ImageIO and URLEncoder (both standard Java API) and various other libraries that consist mostly of static methods (like the Apache Commons libraries). But it is extremely difficult to test those methods that use such static helper classes.

I have several ideas for solving this problem:

Use a mock framework that can mock static classes (like PowerMock). This may be the simplest solution but somehow feels like giving up.

Create instantiable wrapper classes around all those static utilities so they can be injected into the classes that use them. This sounds like a relatively clean solution but I fear we'll end up creating an awful lot of those wrapper classes.

Extract every call to these static helper classes into a function that can be overridden and test a subclass of the class I actually want to test.

But I keep thinking that this just has to be a problem that many people have to face when doing TDD - so there must already be solutions for this problem.

What is the best strategy to keep classes that use these static helpers testable?

答:
This is definitely an opinionated question/answer but for what it's worth I thought I'd throw my two cents in. In terms of TDD style method 2 is definitely the approach that follows it to the letter. The argument for method 2 is that if you ever wanted to replace the implementation of one of those classes - say an ImageIO equivalent library - then you could do it whilst maintaining confidence in the classes that leverage that code.

However, like you mentioned, if you use a lot of static methods then you will end up writing a lot of wrapper code. This might not be a bad thing in the long run. In terms of maintainability there are certainly arguments for this. Personally I would prefer this approach.

Having said that, PowerMock exists for a reason. It is a fairly well known issue that testing when static methods are involved is seriously painful, hence the inception of PowerMock. I think you need to weigh up your options in terms of how much work it will be to wrap all of your helper classes vs. using PowerMock. I don't think it's 'giving up' to use PowerMock - I just feel that wrapping the classes allows you more flexibility in a large project. The more public contracts (interfaces) you can provide the cleaner the separation between intent and implementation.

OwnerDisplayName: Benedikt

OwnerDisplayName: BeRecursive


答: I would test these classes using Groovy. Groovy is simple to add to any Java project. With it, you can mock out the static methods quite easily. See Mocking Static Methods using Groovy for an example.</p>

Title: How to deal with static utility classes when designing for testability

Body:
We are trying to design our system to be testable and in most parts developed using TDD. Currently we are trying to solve the following problem:

In various places it is necessary for us to use static helper methods like ImageIO and URLEncoder (both standard Java API) and various other libraries that consist mostly of static methods (like the Apache Commons libraries). But it is extremely difficult to test those methods that use such static helper classes.

I have several ideas for solving this problem:

Use a mock framework that can mock static classes (like PowerMock). This may be the simplest solution but somehow feels like giving up.

Create instantiable wrapper classes around all those static utilities so they can be injected into the classes that use them. This sounds like a relatively clean solution but I fear we'll end up creating an awful lot of those wrapper classes.

Extract every call to these static helper classes into a function that can be overridden and test a subclass of the class I actually want to test.

But I keep thinking that this just has to be a problem that many people have to face when doing TDD - so there must already be solutions for this problem.

What is the best strategy to keep classes that use these static helpers testable?

OwnerDisplayName: trevorism


答:
As a reference for all who are also dealing with this problem and come across this question I'm going to describe how we decided to tackle the problem:

We are basically following the path outlined as #2 (wrapper classes for static utilities). But we only use them when it is too complex to provide the utility with the required data to produce the desired output (i.e. when we absolutely have to mock the method).

This means we don't have to write a wrapper for a simple utility like the Apache Commons StringEscapeUtils (because the strings they need can easily provided) and we do not use mocks for static methods (if we think we might need to it's time to write a wrapper class and then mock an instance of the wrapper).