问:
Using C++ but not using the language's specific features, should switch to C?
I'm developing a NES emulator as a hobby, in my free time.  I use C++ because is the language I use mostly, know mostly and like mostly.

But now that I made some advance into the project I realize I'm not using almost any specific features of C++, and could have done it in plain C and getting the same result. I don't use templates, operator overloading, polymorphism, inheritance. So what would you say? should I stay in C++ or rewrite it in C?

I won't do this to gain in performance, it could come as a side effect, but the idea is why should I use C++ if I don't need it?

The only features of C++ I'm using is classes to encapsulate data and methods, but that can be done as well with structs and functions, I'm using new and delete, but could as well use malloc and free, and I'm using inheritance just for callbacks, which could be achieved with pointers to functions.

Remember, it's a hobby project, I have no deadlines, so the overhead time and work that would require a re-write are not a problem, might be fun as well. So, the question is C or C++?

答:
I am a very beginner, so here comes my 2 bits.

I am learning C and C++ at Wibit.net with some nice basic videotutorials, maybe they can help you a lot to take a overview of the "situation" (not an ad!)

I advice you to change to C, just to learn, as you are a hobbyist, this will be a pleasure, not a problem.

I advice more. Do it in both languages. Compare the way and solutions you will find and use. I am sure it will be not "so easy" as you are expecting... but sure you will learn a lot!


问:
Is there a case study that convincingly demonstrates that clean code improved development?
I'm in my first real job as programmer and what I see is just the "Big Ball of Mud" code (without useful comments too), but I like to do clean code, and it's really hard for me to code in a worse way.

I'm searching for some study case where the usage of clean code (I see various definitions here of what is clean code) improved the development and maintainability.

答:
I know this will go against the grain here but time to market, getting the requirements right, having the right funding, good marketing, the right price point and plain good luck have far more influence on a software products success than code quality.

This is NOT to say code quality should be ignored, but, you should acknowledge it is just one of many factors.

There are many examples of simply horrible code in hugely successful products (e.g. the original Apple OS which left its thread management to the applications).

I cannot think of any examples of beautiful code overcoming a badly conceived or overpriced product.

So if its time to market vs. pretty code, time to market should take priority!

ContentLicense: CC BY-SA 3.0


问:
To reorganize code, what to choose between library and service?
I want to reorganize a large application with lot of code duplication into multiple components. Plus, some code is also duplicated over other applications.

The common set of functionality that can be taken out of main application is clearly defined.

Now, do I write a library or do I write a service for this functionality;
so that all such applications continue to work and there is only one code-base (of common functionality) to maintain ?

答:
There's a good reason why every heavily-used, broadly-developed Linux application is structured as a executable (e.g., /usr/bin/blarf) that handles the command line input and output, and a library (e.g., /usr/lib/libblarf.so).  The idea is that the real work happens inside library functions or methods, that can be called by any program that wants to perform the operation, and that the command-line interface is just one of possibly many ways to ask for that to happen.  For example, the Subversion version control system has libsvn, which is used by both the svn command and the various GUIs.

When you say "do I write a library or do I write a service", I assume by "library", you mean something like libsvn, and that by "service", you mean something like a REST interface.  I'd say, start by refactoring the library out of your main program, and then build a service that uses the library if you feel the need.


答:
To add to mattnz's answer, if you haven't already I would say specifically check out Code Complete: A Practical Handbook of Software Construction by Steve McConnell.  Besides the fact that it will likely improve your coding, he cites numerous studies throughout the book about how various coding practices affect the quality of programs.

As an example (from the book):

Another study of a different 450 routines (which is just an unusual
  coincidence) found that routines with the highest coupling-to-cohesion
  ratios had 7 times as many errors as those with the lowest
  coupling-to-cohesion ratios and were 20 times as costly to fix (Selby
  and Basili 1991).

Also it used to be the number one answer to the question What is the single most influential book every programmer should read? (though I see the answers to this question were recently reorganized in a lame way)

Title: Is there a case study that convincingly demonstrates that clean code improved development?

Body:
I'm in my first real job as programmer and what I see is just the "Big Ball of Mud" code (without useful comments too), but I like to do clean code, and it's really hard for me to code in a worse way.

I'm searching for some study case where the usage of clean code (I see various definitions here of what is clean code) improved the development and maintainability.


问:
What is a generic term for name/identifier? (as opposed to label)
I need to refer to a number of things that have both an identifier value (used in code and configuration), and a human-readable label. These things include:

database columns

dropdown items

subapplications

objects stored in a dictionary

I want two unambiguous terms. One to refer to the identifier/value/key. One to refer to the label.

As you can see, I'm pretty settled on the latter :) For the former, identifier seems best (not everything is strictly a key, and value and name could refer to the label; although, identifier usually refers only to a variable name), but I would prefer to follow an established practice if there is one.

Is there an established term for this? (Please provide a source.) If not, are there any examples of a choice from a significant source (Java APIs, MSDN, a big FLOSS project)?

(I wasn't sure if this should be posted here or to English Language & Usage. I thought this was the more appropriate expert audience. Happy to migrate if not.)

答: Such things are usually called "opaque identifiers".  The have no intrinsic meaning (e.g., they're not the next monotonically-increasing integer value of some database column), you cannot expect to perform any operation on them other than mapping to the label and the object itself (e.g., you can't concatenate it with something to get something else), etc..


问:
Forking an open source project: should one create a new changelog file? Should restart version number?
I am going to fork an open source project. Would you recommend to create a new changelog file or to update the original one? Would it be reasonable to increment its version number or would it be better to reset it?</p>

答:
There's a lot to be said for resetting the version number to major+1.0.0, although some folks prefer 1.0.0 (which seems seriously wrong).  Most importantly, it says "this is based on the major.*something*.somethingelse level of the forked package, but from here forward it's different".  For example, Secure Sockets Layer (SSL) had 1.0 and 2.0, and the replacement Transport Layer Security (TLS) started at 3.0.

And yes, reset the changelog.


问:
What is the correlation between the quality of the software development process and the quality of the product?
I used to believe the practicing "good" software development methods tends to yield a better product in the long run. However, I've seen quite a few cases where "quick-and-dirty" \ "brute-force" \ "copy-paste" programming appeared to give decent results quicker, and cheaper. This appears especially in cases where time to market is more critical then maintenance overhead.

Is there a correlation between the quality of the development process and techniques and the quality of the product?

答:
There is zero correlation here, as you note in your question.

The software development process is aimed at solving management and project problems - making sure the project is completed on time and on budget, requirements are identified and fed back to the team, bugs identified early, and so on.

As they say, pick two: "Cost, Speed, Quality".

Utilising a quality software development process is about managing costs and timeframes (note: not specifically minimising, but ensuring predictability). A lot of low-process projects deliver great software, and a lot of high-process projects deliver a dog.


问:
Shared memory multiprocesses
I'm building an multi processes application and I need to save session ID, the sessions ID is 32 bit, and of course it can't be used twice in its lifetime, I'm currently using DB that saves all the ID in a table, and I do the following,

ID table is (int key, char used(1)) //1 is used, 0 is not
1. lock table
2. get one key for one sessions
3. update used field in it to used
4. unlock

After the session is finished the process use below to free key,
1. lock table
2. update used field in it to not used
4. unlock

I'm really wondering whether this is a good/fast implementation. and please note it's multi processes application.

答: Did you try memcached? It's fast, it has atomic updates, it does not have all the rest of database overhead. Not as fast as raw shared memory, but probably session registration is not your bottleneck anyway?</p>

Title: Shared memory multiprocesses


答:
The fact that you have "code duplication" means that your code is running in-process so I would go with a library.  That is going to wrap up your code for you anyway so as Ross Patterson one should always go with that option and build on on top of the library.

Out-of-process is always going to be slower but there may be advantages.  You could go with Rest, WS, XML-RPC, or even a service bus (especially when doing asynchronous calls).  However, it depends totally on how you need to reach your code.

If there is no direct need or requirement for an out-of-process solution I would avoid it.

Title: To reorganize code, what to choose between library and service?

Body:
I want to reorganize a large application with lot of code duplication into multiple components. Plus, some code is also duplicated over other applications.

The common set of functionality that can be taken out of main application is clearly defined.

Now, do I write a library or do I write a service for this functionality;
so that all such applications continue to work and there is only one code-base (of common functionality) to maintain ?


问:
Benchmarking CPU processing power
Provided that many tools for computers benchmarking are available already, I'd like to write my own, starting with processing power measurement.

I'd like to write it in C under Linux, but other language alternatives are welcome.

I thought starting from floating point operations per second, but it is just a hint.

I also thought it'd be correct to keep track of CPU number of cores, RAM amount and the like, to more consistently associate results with CPU architecture.

How would you proceed to the task of measuring CPU computing power?

And on top of that: I would worry about a proper minimum workload induced by concurrently running services; is it correct to run benchmarking as a standalone (and possibly avulsed from the OS environment) process?

答:
Having competed in hardware benchmarking(you know, overclocking the hardware and competing whos machine calculates the Pi the quickest kind of stuff) and also written some benchmarking software code myself, first and foremost I want to say that benchmarking hardware accurately is very complicated subject. It is a blend between what you want to benchmark, how you want to benchmark it, where you want to benchmark it and most importantly why you want to benchmark.

Let me discuss these properties in detail.

What:
There are different kind of things to benchmark in any given system. You might want to benchmark for example memory bandwidth or latency. Or hard drive write/read latency/bandwidth. Or for example "CPU speed" in a generic way. However, it is probably not as simple as that, which brings me to the next point...

How:
As there are different things to benchmark, there are different ways to benchmark. For example, one could benchmark CPU/GPU GFLOPS by a simple naive matrix multiplication. This operation might or might not have any correlation with common performance charasteristics of the piece of hardware in question. A CPU scoring well in a matrix multiplication benchmark might not score as well for example in a data compression benchmark. There are multiple variables which have an impact the result and perhaps the most important one is the underlying microarchitecture and how well the code in question can take advantage of it's strengths and avoid it's weaknesses. So it all boils down to implementation. A single benchmark is a single implementation of the algorithm used!

Where:
It is completely different ball to play to carry out benchmarks in a virtual environment such as inside a virtual machine, as compared to running as a process inside a multitasking operating system, or as compared to running the code as the only instance on the said machine(that is, without OS or drivers or watsoever in the way, directly booting x86-based machine from a custom MBR to real-mode and working your way from there.). The more the target machine has "other" code running in "background" the less reliable the benchmark results are going to be. So running a benchmark on a server with high CPU load isn't going to produce very reliable results. Likewise, since on most modern operating systems the operating system and it's kernel provide an layer of abstraction, the kernel settings and parameters have some impact on performance of processes. For example process/thread priorities and process/thread scheduling parameters can have very measurable impact on the benchmark results. As a general rule, the less you have going on on the machine the better, so the ideal environment would be to dedicate the said piece of hardware solely to the purpose of benchmarking.

Why:
What purpose is the benchmark trying to fill? Do you want to try to give something like a theoretical indication of performance for a given piece of hardware in running that specific algorithm/set of algorithms(without forgeting that a benchmark simply benchmarks that implementation of that algorithm)? Or are you trying to mimic "real world performance" of the said piece of hardware as closely as possible? It all depends, because obviously performance in matrix multiplication has little to do with performance in serving webpages or database queries.

Of course these points are very vague, but what I'd want people to have in mind when they talk about benchmarks in terms of hardware performance is that it depends, it is merely an indicator and is always case specific. There is just so much you can do with writing truly fast code that it's not even funny to try to talk about benchmark results (say a very tailored implementation of some arbitrary task which is optimized for a certain instruction set extensions, a certain cache sizes, certain branch misprediction penalty, certain level of instruction level parallelism and a certain memory access latency) between different kinds of CPUs. It is all about trying to take advantage of hardware strenghts and avoiding the weaknesses.

tl;dr: It is hard to get it right(if that's even possible), you want to know some low-level concepts of the target hardware and be aware that everything is case specific. There can never be universal benchmark.

Title: Benchmarking CPU processing power


问:
Why is C++ backward compatibility important / necessary?
As far as I understand it is a wide-spread opinion within the C++ community that certain features of C++ (including some features inherited directly from C), while still usable in themselves, do not fit well with the most recent C++ best practices.
For example, I read a comment on this site stating that new / delete should be avoided altogether in favor of smart pointers.

In view of this, I often wonder why backward compatibility with C and earlier C++ features is still important: to my knowledge there is no 100% compatibility, but most of C and C++ are contained in C++11 as a subset.

So, maybe it would be possible / make sense to drop earlier C++ features (e.g. the mentioned new / delete) from a future C++ standard so that it is impossible to use them in new code.

Existing code could still be maintained using the appropriate compiler. Interoperability between legacy and new code would be supported through separate compilation. One could continue to use the earlier standard or adopt the more recent one, only mixing the two would not be possible: a developer /team would have to clearly choose which programming style they want to use. The most flexible solution would be to have compiler options to switch on and off certain features (e.g. no new / delete allowed).

Would this be a viable strategy for encouraging the adoption of modern C++ practices? Are there technical problems (e.g. compiling existing templates,
ABI compatibility) that make such a change too difficult or even impossible?

答: I think Bjarne's view as of late has been that C and C++ should have been unified as a single language. I think that this could imply that his view is that C++ should be a replacement for C, and as such compatibility with C is important in such view. </p>


问:
Practical considerations for HTML / CSS naming conventions (syntax)
Question: what are the practical considerations for the syntax in class and id values?

Note that I'm not asking about the semantics, i.e. the actual words that are being used, as for example described in this blogpost. There are a lot of resources on that side of naming conventions already, in fact obscuring my search for practical information on the various syntactical bits: casing, use of interpunction (specifically the - dash), specific characters to use or avoid, etc.

To sum up the reasons I'm asking this question:

The naming restrictions on id and class don't naturally lead to any conventions

The abundance of resources on the semantic side of naming conventions obscure searches on the syntactic considerations

I couldn't find any authorative source on this

There wasn't any question on SE Programmers yet on this topic :)

Some of the conventions I've considered using:

UpperCamelCase, mainly as a cross-over habit from server side coding

lowerCamelCase, for consistency with JavaScript naming conventions

css-style-classes, which is consistent with naming of css properties (but can be annoying when Ctrl+Shift+ArrowKey selection of text)

with_under_scores, which I personally haven't seen used much

alllowercase, simple to remember but can be hard to read for longer names

UPPERCASEFTW, as a great way to annoy your fellow programmers (perhaps combined with option 4 for readability)

And probably I've left out some important options or combinations as well.  So: what considerations are there for naming conventions, and to which convention do they lead?

答:
Bounty or not, to some extent the choice will always be a "matter of preference" - after all, how would you feel if the W3C recommended (or even imposed) a certain convention that you didn't feel was right?

Having said that, though, I personally prefer the lowerCamelCase convention, and I'll give the reasons and practical considerations I've used to make up my mind - I'll do so by a process of elimination, using the numbering from your question:

(5.) justnoteasilyreadablebecauseyoudontknowwherewordsstartandend.

(6.) ASABOVEPLUSITSANNOYINGLIKESOMEONESHOUTING.

(4.) historical_incompatibility_plus_see: Mozilla Dev Documentation.

(3.) a-bit-trickier-to-explain... as you mention, selectability in text editors is one issue (as with underscores, depending on the editor), but for me it's also the fact that it reminds me of the syntax reserved for vendor-specific keywords, even if those start with a hyphen as well as having words separated by them.

So this leaves your (1.) and (2.), UpperCamelCase and lowerCamelCase, respectively. Despite the mental link to Java classes (which are, by a more clearly defined convention, UpperCamelCase), CSS class names seem, to me, to be better off starting with a lowercase letter. Perhaps that is because of XHTML element and attribute names, but I guess you could also make the case that having CSS classes use UpperCamelCase would help to set them apart. If you need another reason, lowerCamelCase is what the W3C uses in examples for good class names (though the URL itself, annoyingly, disagrees with me).

I would advise against (4.), (5.) and (6.), for the reasons stated above, but suppose that arguments could be made for either of the other three.

Whether or not you (or anyone else for that matter) agree with me on this matter is up to you though. The fact that you haven't got a definite answer quoting authoritative sources by now can be taken as a hint that there isn't such a thing as a definite standard on this issue (else we'd all be using it). I'm not sure that's necessarily a bad thing.


问:
Letting go of a project
I've been the sole developer of a niche product for my company for nearly 6 years.  I've grown quite attached to the project and I enjoy working on it.  However, it was the decision of management to take the project out of my hands and move it under the wings of another team.

Unfortunately, I'm having a hard time letting go of the project.  I'm sad to see it leave my hands since I've put so much time into it and enjoyed working on it, but it also allows me to work on new things.  I've even caught myself being a bit hostile to the other team, which is poor on my part.

How can I convince myself to just let it go?

答: If the other team is capable of handling it well, then no worries. You can see the project doing well and you can be happy. Only if they screw it, will your hard work be in vein. So you can let go and move on.</p>

Title: Letting go of a project


答:
Useful benchmarks compare time for actual work with respect to real-world problems; e.g., transcoding video, calculating complex mathematical formulae, rending 3d models, etc.

While as a rule benchmarks measure nothing more important than how fast a system ran the benchmark, at least in these cases you can correlate the result to things you may have found yourself spending time on. It's still not perfect, but it's better than a tight loop of a single function.

Also bear in mind that a single algorithm can be tuned to a specific chip. AMD and Intel, for example, classically differ on how many logic units they dedicate to floating-point versus integer math. So writing your code to use one or the other will necessarily favor a specific chip family. There's really no getting away from this reality; you absolutely cannot write a neutral benchmark.

So instead of picking sides, several benchmarking suites simply use existing popular software (e.g. ffmpeg for video transcoding). The idea is that it's the software users will be running anyway, so the benchmark should reflect the user's expected experience with that software. That's the theory, at least. But of course depending on which software you pick, you're still going to bias the results.

Also, bear in mind that most of the zero-work benchmark ideas  you may come up with (tight loops running a single operation) will often be optimized away by the compiler into something completely different than what you anticipated. Some chips will do similar optimizations on-the-fly, meaning you end up measuring something completely different than what you coded. Again, best advice is time the machine doing something useful. If the chip can optimize that code, then that's exactly what you want the benchmark to reflect.

Title: Benchmarking CPU processing power

Body:
Provided that many tools for computers benchmarking are available already, I'd like to write my own, starting with processing power measurement.

I'd like to write it in C under Linux, but other language alternatives are welcome.

I thought starting from floating point operations per second, but it is just a hint.

I also thought it'd be correct to keep track of CPU number of cores, RAM amount and the like, to more consistently associate results with CPU architecture.

How would you proceed to the task of measuring CPU computing power?

And on top of that: I would worry about a proper minimum workload induced by concurrently running services; is it correct to run benchmarking as a standalone (and possibly avulsed from the OS environment) process?


答:
I would look at it from the other direction. Will you gain anything by rewriting the code in C? Even on a purely hobbyist project, there's a cost associated with a rewrite like that. If nothing else there's what I suppose would be called opportunity cost -- i.e., the other things you could have done in that time if you weren't wasting your time rewriting it in C.

Bottom line: unless you think the code is really likely to be used in some environment where access to C++ is really limited (or nonexistent), it would be a pointless waste of time at very best. At least in my experience, it usually goes well beyond that very quickly -- thinking back over code I've written in C++ that had to be converted to C, I can pretty clearly remember that even in quite a few cases where it seemed like it should be trivial, I was using a lot more features specific to C++ than I initially realized. To have much hope of being useful at all, you'd pretty much have to target C89/90, in which case you quickly get reminded of things like having to define all variables at the beginning of a block instead of where they're actually used.

In short, unless you're pretty sure rewriting in C will provide a real benefit, there are almost inevitably a lot better things to do.

Title: Using C++ but not using the language's specific features, should switch to C?

Body:
I'm developing a NES emulator as a hobby, in my free time.  I use C++ because is the language I use mostly, know mostly and like mostly.

But now that I made some advance into the project I realize I'm not using almost any specific features of C++, and could have done it in plain C and getting the same result. I don't use templates, operator overloading, polymorphism, inheritance. So what would you say? should I stay in C++ or rewrite it in C?

I won't do this to gain in performance, it could come as a side effect, but the idea is why should I use C++ if I don't need it?

The only features of C++ I'm using is classes to encapsulate data and methods, but that can be done as well with structs and functions, I'm using new and delete, but could as well use malloc and free, and I'm using inheritance just for callbacks, which could be achieved with pointers to functions.

Remember, it's a hobby project, I have no deadlines, so the overhead time and work that would require a re-write are not a problem, might be fun as well. So, the question is C or C++?


答:
That's always a tough situation.  You've worked hard on something, it's become a part of you, and something outside your control makes you move on.  I've had to face the same challenge many times, it's an integral part of software development, perhaps moreso than other jobs because there's always the opportunity/temptation to keep improving software.

Chances are after six years you need to move on to improve yourself more than the project needs someone else to run it.  Perhaps your management sees this about you more clearly than you can see yourself.  It might be the case they're doing this because they feel it's in your best own interest.  Hard to say all the way over here across the Intertubes.

Two pieces of philosophy to help you through the transition.  Personally, I lean on the Serenity Prayer in times like this, it's just so appropriate:

God, grant me the serenity to accept the things I cannot change,

  Courage to change the things I can,

  And wisdom to know the difference.

Alternatively, Makers have a different spin that applies after six years of work.  It's not meant for software, but:

Title: Letting go of a project

Body:
I've been the sole developer of a niche product for my company for nearly 6 years.  I've grown quite attached to the project and I enjoy working on it.  However, it was the decision of management to take the project out of my hands and move it under the wings of another team.

Unfortunately, I'm having a hard time letting go of the project.  I'm sad to see it leave my hands since I've put so much time into it and enjoyed working on it, but it also allows me to work on new things.  I've even caught myself being a bit hostile to the other team, which is poor on my part.

How can I convince myself to just let it go?


答:
Work life is like ladders. Every good step of yours will take it higher on the ladder. This means you will be away from the lower steps as you go up and will eventually have more number of steps below you. If you fall in love with one step, you won't be able to go up and might be someone stepping upward may have to step over you. This may hurt you or throw you out of the ladder.

The art of growing is to create something for the followers/team-members to take over (Effectively). This also need your effort to help grow your subordinates to be able to effectively take up your role, so that you can rise up and take a higher role. Do not have hard feeling about letting go a project. If you are a true leader, it will not go away, but you will be at an abstract level on top of this.

OOAD fits here too, it becomes abstract or generalization as you go up.

What you should focus is how effectively you can mentor the team that will take care of the project and ensuring that any future queries from them be resolved and also ensure that they need to bother you the least for specific things, but may take your advise on broader things.

This should make you feel stronger, in-control and efficient. This will also reflect your competence to the management in the most positive way.

Do not keep hard feeling or obsessions for the work you do and pass on. Lefe is all about achieving milestones. Sitting on a milestone does not take you further.

Title: Letting go of a project


答:
Bjarne Stroustrup wanted to build a useful language based on C because it was

Already popular within s/w community

Supported low level programming as well as some high level features

Lots of code was already written in C

There was no plans to have aggressive marketing budget to make C++ popular on its own   as an individual language.

Instead of reinventing the wheel and introducing new syntax, Stroustrup chosen to build the new language on existing base itself (Like C was developed based on earlier language).

C++ is not fully backward compatible with C, wherever it's needed it has drawn a line. e.g.

unsafe implicit typecasting is not allowed C++

inline, enum and const were introduced with C++ and later
adopted by C

Title: Why is C++ backward compatibility important / necessary?

Body:
As far as I understand it is a wide-spread opinion within the C++ community that certain features of C++ (including some features inherited directly from C), while still usable in themselves, do not fit well with the most recent C++ best practices.
For example, I read a comment on this site stating that new / delete should be avoided altogether in favor of smart pointers.

In view of this, I often wonder why backward compatibility with C and earlier C++ features is still important: to my knowledge there is no 100% compatibility, but most of C and C++ are contained in C++11 as a subset.

So, maybe it would be possible / make sense to drop earlier C++ features (e.g. the mentioned new / delete) from a future C++ standard so that it is impossible to use them in new code.

Existing code could still be maintained using the appropriate compiler. Interoperability between legacy and new code would be supported through separate compilation. One could continue to use the earlier standard or adopt the more recent one, only mixing the two would not be possible: a developer /team would have to clearly choose which programming style they want to use. The most flexible solution would be to have compiler options to switch on and off certain features (e.g. no new / delete allowed).

Would this be a viable strategy for encouraging the adoption of modern C++ practices? Are there technical problems (e.g. compiling existing templates,
ABI compatibility) that make such a change too difficult or even impossible?


问:
How to remember the details (Core APIs) of one computer language?
I found my self often paused to check a certain usage of one core API when writing either javascript or Ruby. I am wondering how the other guys doing? Is it necessary to remember every Core API usages?

It the answer is yes, how did you guy do it efficiently?

答:
You're not going to be able to magically acquire and retain all of the API documentation for a language. I think it is a pretty natural progression when starting something new to just dive in and start working on it. During the process, you'll run into errors or need a function that you don't know the name of, and you'll look it up. Ruby's documentation (for example) is pretty fast to navigate.

It may be something that you only have to look up once, and after that, you've committed it to memory. Other things you may need to solve a problem, and you will never use them again. As your documentation grows, you should not be looking at the same things over and over again - you should be exploring new parts of the documentation and growing as a developer.


答:
Are there conceptual reasons or technical problems (e.g. compiling existing templates) that make such a change undesirable or even impossible?

Some features are deprecated, and you get a warning (with appropriate error checking level), and if you enable option that turns warnings into errors, you get the desired effect.

Now imagine when lots of features would be removed, or changed drastically. That would make lots of programs not compiling. For large projects that is unacceptable. Who would go over 300kLOC-2MLOC code to fix all failures?

With backward compability, upgrading the compiler is much simpler. You still have to fix some code, but number of failures is acceptable.

To your edit :

How you compile/link your application, depends on the build system.

If you use makefiles, it is fairly simple (not so simple in complex systems), to add new rules to build separate libraries. c code would be compiled using gcc, c++ code using specific version of g++, and new c++11 code compiled (again) with possible different g++ version, into separate shared libraries. The final application would then link to those libraries. Off course, you have to make sure that all compilers are using the same ABI.


答: Don't remember the actual API details.   Remember where to find the API details.</p>

Title: How to remember the details (Core APIs) of one computer language?

Body:
I found my self often paused to check a certain usage of one core API when writing either javascript or Ruby. I am wondering how the other guys doing? Is it necessary to remember every Core API usages?

It the answer is yes, how did you guy do it efficiently?


答:
The best way to handle a situation like this is to make sure your attention is completely occupied by a new project. In other words, don't give yourself idle time to wonder how the new team is ruining your life's work. ;-)

If you find yourself having to communicate with the new team on fairly frequently (I imagine they might come to you with questions often) then you should set up a weekly meeting with them, and ask them to hold all questions until the meeting (except support emergencies, of course). That way they are encouraged to be self-sufficient and you aren't constantly required to think about the old project and what they are doing to your poor baby without your supervision. These meetings will probably get shorter and shorter until they won't have any questions for you, in which case you can take it off the calendar.

You've said you now have time to work on new things: get to work!

Title: Letting go of a project


问:
In hindsight, is basing XAML on XML a mistake or a good approach?
XAML is essentially a subset of XML. One of the main benefits of basing XAML on XML is said to be that it can be parsed with existing tools. And it can, to a large degree, although the (syntactically non-trivial) attribute values will stay in text form and require further parsing.

There are two major alternatives to describing a GUI in an XML-derived language. One is to do what WinForms did, and describe it in real code. There are numerous problems with this, though it’s not completely advantage-free (a question to compare XAML to this approach). The other major alternative is to design a completely new syntax specifically tailored for the task at hand. This is generally known as a domain-specific language.

So, in hindsight, and as a lesson for the future generations, was it a good idea to base XAML on XML, or would it have been better as a custom-designed domain-specific language? If we were designing an even better UI framework, should we pick XML or a custom DSL?

Since it’s much easier to think positively about the status quo, especially one that is quite liked by the community, I’ll give some example reasons for why building on top of XML might be considered a mistake.

Basing a language off XML has one thing going for it: it’s much easier to parse (the core parser is already available), requires much, much less design work, and alternative parsers are also much easier to write for 3rd party developers.

But the resulting language can be unsatisfying in various ways. It is rather verbose. If you change the type of something, you need to change it in the closing tag. It has very poor support for comments; it’s impossible to comment out an attribute. There are limitations placed on the content of attributes by XML. The markup extensions have to be built "on top" of the XML syntax, not integrated deeply and nicely into it. And, my personal favourite, if you set something via an attribute, you use completely different syntax than if you set the exact same thing as a content property.

It’s also said that since everyone knows XML, XAML requires less learning. Strictly speaking this is true, but learning the syntax is a tiny fraction of the time spent learning a new UI framework; it’s the framework’s concepts that make the curve steep. Besides, the idiosyncracies of an XML-based language might actually add to the "needs learning" basket.

Are these disadvantages outweighted by the ease of parsing? Should the next cool framework continue the tradition, or invest the time to design an awesome DSL that can’t be parsed by existing tools and whose syntax needs to be learned by everyone?

P.S. Not everyone confuses XAML and WPF, but some do. XAML is the XML-like thing. WPF is the framework with support for bindings, theming, hardware acceleration and a whole lot of other cool stuff.

答:
Your objections to XML have nothing to do with using it as a GUI description language; they are all complaints about working with XML syntax that apply equally to any form of XML.

So it sounds like you just don't like XML.

You're right, it may not be the optimal choice for editing by hand, but for a GUI description language I'd make some counter-arguments:

(IMHO,) GUIs are graphical and ought to be laid out graphically. The file format isn't really that important, because you really shouldn't be editing it by hand. (Text-based is nice for source-control's sake, but verbosity isn't a problem.)

Besides the parser being available, XML is also easy to validate: you can write a DTD or XML Schema and then use generic tools to tell you if your file is legal. This is going to be very useful for a GUI description language. Doing the same in JSON or YAML isn't as straightforward.

If you're really unhappy with writing XAML directly, there's nothing preventing you developing a new format and then compiling that into XAML. For example, you could come up with a straightforward mapping from JSON to XAML, so you can have its JSON's lighter syntax (and the ability to comment-out attributes), and then generate the XAML when you build your app. People rarely write HTML directly any more, but HTML is still a great format.


问:
Lone Programmer vs. Everything Else
I guess you could call me a "MicroISV" because it's basically just me doing the work to create a product to be sold commercially. I'm sure there are many out there like me, so here's my question:

Besides the programming/coding aspect to get your code out the door, do you DIY or vendor-out everything else? For example, web site creation, internet marketing, accounting/taxes, company minutes, customer support, setting up ecommerce/banking, server management, procurement, etc.

All of those activities seem to be out of the realm of what I'm good at or have the patience/time for, but I don't know if the alternative is too untrustworthy or too expensive to make it worthwhile to try to farm out these tasks to someone else (like a local company, vendors on oDesk, etc.).

I can certainly understand wanting to keep all these tasks "in-house" (i.e. me) to protect strategy, plans, code, private things like bank account numbers, but is it really that much of a risk to outsource these tasks? What is your experience?

答:
We have a simple rule in our company, as we are a small software house.

Can we do it as well as a third party

Will we save more money by doing the work internally or would it be more cost effective to work on another project

Do we really have time for the additional work

Is there any other elements that internal staff may not be aware of such as legislation etc.

The answers to simple questions like this should help you make an informed choice.

I hope this helps a little.

ContentLicense: CC BY-SA 2.5

Title: Lone Programmer vs. Everything Else


答:
I don't think it's necessary to remember the API details, but more the global API structure and setup. Be sure to know how things are structured, so you know what to look/search for when you need the details.

This way you will always find what you need after one search on the web.


答: Both of your premises are wrong. Smart pointers are a performance-hit, and C is far from obsolete: Windows and UNIX system calls are defined in terms of C.  In fact, just about every OS in wide use today, except Symbian, uses C interfaces.  So if you want to have a language that supports system-level programming, you can't get away from new, delete, raw pointers and all of the things that you dogmatically believe are bad.</p>


答: You would effectively be talking about defining an entire new language- which is what's already happening with the numerous proposed C++ replacements over the years. I think that it's telling that none of them have actually succeeded in replacing C++.</p>


问:
How to decide whether to implement an operation as Entity operation vs Service operation in Domain Driven Design?
I am reading Evans's Domain Driven Design. The book says that there are entity and there are services. If I were to implement an operation, how to decide whether I should add it as a method on an entity or do it in a service class?

e.g. myEntity.DoStuff() or myService.DoStuffOn(myEntity)?

Does it depend on whether other entities are involved? If it involves other entities, implement as service operation? But entities can have associations and can traverse it from there too right?

Does it depend on stateless or not? But service can also access entities' variable, right? Like in do stuff myService.DoStuffOn, it can have code like

```<code>if(myEntity.IsX) doSomething();
</code>```

Which means that it will depend on the state?

Or does it depend on complexity? How do you define complex operations?

答:
Does it depend on whether other entities are involved? If it involves other entities, implement as service operation?

This is one good rule of thumb. Another: logic that describes a fundamental fact about the entity and is used in multiple use cases probably belongs into the entity. Logic that is use case specific probably doesn't. Both of these are variants of the Single Responsibility Principle.

But entities can have associations and can traverse it from there too right?

Yes, but entities should not be tightly coupled like that. Except perhaps in cases where one entity "contains" another and they are already tightly coupled conceptually.

Or does it depend on complexity? How do you define complex operations?

That's just a basic rule of code cleanliness: if a piece of code becomes too large and complex, break it up. If you have an operation as part of an entitry that containes more code than the rest of the entity together and you've already had to refactor it into sub-operations, you should think about moving it out of the entity entirely.


答:
You have to separate clean code from the real goals: reducing cost of fixing defects after deployment and reducing unnecessary rework. When you talk about "writing clean code to make it have fewer bugs", you're talking religion. When you're talking about "reducing the defect rate by 10% saving 2 man-months of effort on the project", you're talking management. Clean code is a tool to improve the initial quality of the codebase and thereby lowering the total cost, but it is one of many.

The following paper explains why getting it right the first time matters from a cost perspective: http://www.cs.umd.edu/~mvz/pub/eworkshop02.pdf


答:
Just pick the most intuitive/simple one for the corresponding situation.

To illustrate this more clearly, let me pick more specific names than "myEntity" and "DoStuff"

```<code>   myService.process(myData) // fits perfectly.

   myStatefulThingy.reset() // fits perfectly.
</code>```

In the first case, myData/myEntity is merely some data passed to a service. In the second one, it's a self contained operation.

I recommend that in the first case, myData/myEntity is not altered while in the second case myStatefulThingy/myEntity is the only thing which gets modified.

Title: How to decide whether to implement an operation as Entity operation vs Service operation in Domain Driven Design?

Body:
I am reading Evans's Domain Driven Design. The book says that there are entity and there are services. If I were to implement an operation, how to decide whether I should add it as a method on an entity or do it in a service class?

e.g. myEntity.DoStuff() or myService.DoStuffOn(myEntity)?

Does it depend on whether other entities are involved? If it involves other entities, implement as service operation? But entities can have associations and can traverse it from there too right?

Does it depend on stateless or not? But service can also access entities' variable, right? Like in do stuff myService.DoStuffOn, it can have code like

```<code>if(myEntity.IsX) doSomething();
</code>```

Which means that it will depend on the state?

Or does it depend on complexity? How do you define complex operations?

Body:
Just pick the most intuitive/simple one for the corresponding situation.

To illustrate this more clearly, let me pick more specific names than "myEntity" and "DoStuff"

   myService.process(myData) // fits perfectly.

   myStatefulThingy.reset() // fits perfectly.

In the first case, myData/myEntity is merely some data passed to a service. In the second one, it's a self contained operation.

I recommend that in the first case, myData/myEntity is not altered while in the second case myStatefulThingy/myEntity is the only thing which gets modified.


问:
Command-Query-Separation and multithreading safe interfaces
I like the command query separation pattern (from OOSC / Eiffel - basically you either return a value or you change the state of the class - but not both). This makes reasoning about the class easier and it is easier to write exception safe classes.

Now, with multi threading, I run into a major problem: the separation of the query and the command basically invalidates the result from the query as anything can happen between those 2.

So my question is: how do you handle command query separation in an multi-threaded environment?

Clarification example:

A stack with command query separation would have the following methods:

push (command)

pop (command - but does not return a value)

top (query - returns the value)

empty (query)

The problem here is - I can get empty as status, but then I can not rely on top really retrieving an element since between the call of empty and the call of top, the stack might have been emptied. Same goes for pop & top. If I get an item using top, I can not be sure that the item that I pop is the same.

This can be solved using external locks - but that's not exactly what I call threadsafe design.

答:
there are 2 main approaches

external read/write locks as I said in the comments

"failable" commands like the classic CompareAndSwap

```<code>bool CaS(from,to){
    if(from==state){
        state=to;
        return true;
    }
    return false;
}
</code>```

however this can result very large functions for non-trivial problem flow

Body:
there are 2 main approaches

external read/write locks as I said in the comments

"failable" commands like the classic CompareAndSwap

bool CaS(from,to){
    if(from==state){
        state=to;
        return true;
    }
    return false;
}

however this can result very large functions for non-trivial problem flow


问:
Is mentioning my blog on my resume helpful or hurtful to a job search?
I have a blog that I use mostly to record solutions to problems I have had, that I had some trouble finding an answer to. Mostly problems where the online doc I googled provided too much info, and I found the answer to my question on the fifth page of my third google hit.

(Or if I asked the question here, I either didn't get an answer or I got slammed for asking a question that "the answer could be easily googled.")

I frequently look up stuff on this blog to remind myself of how I solved a problem, and it gets a decent amount of hits from others as well.

Anyway, I was wondering if mentioning this blog on my resume would help or hurt me in a job search? The topics are all over the map.

What I would hope it shows is that

I am a person who finds solutions to problems

I have used many different technologies in my work

I am not afraid to tackle a challenge

What I am concerned it shows is that

This person had trouble with something that simple?

Why is this person bothering to blog this stuff?

答:
You can use your blog as an example of your personal knowledge management if this turns up in the interviewer's question. Otherwise, there is no need to mention in interview.

Never include your blog URL in a resume. When a personal URL appears in a resume, the reviewer will naturally expect that the site is as professionally managed as a corporate website (due to the reviewer's own expectation bias). Any sign of non-professionalism will hurt your chances, compared to candidates who do not provide any URL.

Most modern companies use some knowledge-sharing technologies such as internal wiki, internal blog, informal documentation, white board, prototyping, etc. This is in addition to any personal notetaking.

The key differences are:

Knowledge generated inside a company usually must be kept internal. Therefore, one needs to strike a balance in terms of asking questions without revealing sensitive intellectual/business information.

Modern companies are interested in improving overall (team) productivity through knowledge sharing. Personal notetaking only contributes to personal productivity. Therefore, it is important that your coworkers can understand your information and find it useful. This may require good technical writing skill.


答:
If I understand correctly your position (from the question and the comments under VJovic's answer), you'd have preferred instead of a mostly compatible C++11, a new language based (I'll call it NC++) on C++03 but source incompatible with it but linkable with it.

Here are some points to consider:

it isn't possible to implement C++11 using existing C++03 ABI (compilers providers don't guarantee that linking code compiled in C++03 mode and in C++11 will works), and it is a safe guess that it would be the same for NC++. So you'd have to have new C++03 compilers targeting the NC++ ABI as well as NC++ compiler to have your idea implemented.

you have the same problem with the standard library. You'd need a new implementation of the C++03 library able to be interoperable with your NC++ library.

the transition from C to C++ can be smooth as C is mostly a C++ subset. When the C code takes advantage of C99 features not present in C++, the transition is less smooth. Notably shared headers have to be coded in the common subset of C++ and C which isn't natural if you want to take advantage of C99.  In your case, shared headers will have to be coded in the common subset of C++03 and NC++, which I fear will be impractical if your goal in NC++ is to take advantage of the possibility to break source code compatibility to have a "cleaner" language.


答:
Following this very good article by Martin Fowler you should tend to keep your Business Logic in your Entities and your Service Layer thin. I don't think it's a question of complexity. If other entities (not "owned" entities) are involved, I would recommend to use the Service Layer for delegating to Business Logic in other entities.

You should read this article! Martin Fowler refers to the book you're currently reading in regard to your issue.


问:
Why aren't young programmers interested in mainframes?
A key issue with mainframes is that the cohort of supporting programmers is dwindling. While normally this wouldn't be a problem in that a falling supply of programmers would be offset by an increasing amount of salary those causing a rising supply of programmers via the law of supply and demand, I'm not sure this is really happening for mainframes.

While they still form critical infrastructure for many businesses, the simple fact is there isn't an adequate number of young programmers coming up along to keep the support population populated.

Why is this? What makes mainframes unattractive to young programmers?

答:
Lets start with some facts about IBM mainframes and specifically zSeries.

The hardware is brand spanking shiny and new. It contains some of the most advanced electronics and chip designs available and they are fast.

While z/OS has its roots in the 1960s it has undergone continual development and at least two complete re-writes so apart from the quirks resulting from IBM's fetish for backward compatibility its probably one of the newer OSes in general use.

The key selling points are:-

The aforementioned backward compatibility if it a program ran in 1976 on an MVS/MVT machine the chances are it will run on the latest zSeries without being re-compiled and produce exactly the same results.

Bandwidth it can move access and store massive amounts of data, at massive speed and at a very fine grained level.

Availability. SYSPLEX which has been available for the last 15 years or so provides seamless clustering over multiple sites, complete with load balancing, automatic fail over etc. much of which is implemented in hardware. It makes most *nix clustering look primitive.

Convergence. This one sounds a bit weird but with full POSIX support and a superfast JVM a modern mainframe is practically indistinguishable from any other *NIX box if that's how you want to use it.

So far the mainframe has outlived nearly everything that the pundits said were going to replace it.

There are a number of downsides:-

Backward compatibility means that many shops are running twenty, thirty and in some cases forty year old systems. While they work well and perform their business functions well (or they wouldn't still be running!) they reflect the coding styles and obsessions of a bygone age.

backward culture. Programmers working in a ghetto of ancient COBOL systems don't seem to have realized the world has moved on, or if they do a fossilized management won't let them.

Lack of availability. Unless you are actually being paid to work on one of these monsters you will not get access to one. There may even be one where you work but if your immediate job description does not include working on it you will not get a login. Much has been said in other postings about the "herecules" emulation software and it is indeed excellent but its very much for experts only, it runs an ancient version of the operating system, it lacks most of the standard components such as CICS,COBOL and DB2 which form the framework of most running mainframe applications.


答:
Yangchenyun, whenever I hear remember or memorize in a programming context, my alarm bells start ringing.

You need to understand what a certain part of the API is doing and what concepts the API is based on. Then the fact that the API is able to do a certain thing will stay in your head automatically, even if you don't have all the details present in your head at any time.

After that Mad Keith's and Geerten's answers will kick in.

Just keep programming in your language of choice and your API knowledge will increase automatically.


答: Most important is to learn the idioms and conventions of a particular framework / API. I'm a .NET developer and because of the consistency across the .NET Framework class libraries, I can pick up entirely different parts of the framework in very little time, because I understand the idiosyncrasies which permeate the entire .NET ecosystem. I would imagine the same is true for the Java universe, although perhaps not for more fragmented environments such as PHP.</p>


问:
Do I have to deliver my utility and helper code to clients?
Over the years I've created a bunch of Java utility and helper libraries which I just attach to new projects. Then, when I deliver code to my clients, I send all the code except for the libraries themselves (not JARs but source code files).

A client complained that he could not compile the project as some libraries were missing. I tried explaining him about my own libraries, but he was not satisfied.

How do you handle such situations? I am still apporting changes to these libraries often and I cannot compile JARs each time I start working on some new project. How to overcome this issue - not to share private libraries (personal intellectual property) and have happy clients?

答:
You probably have to version your proprietary library and make (your own internal) releases. Then when you start a new project, you just use your latest released library in that project, and upgrade to a new version whenever needed.

Then you can send the source to your client, including the jar of your library in the version that you have tested the project with.


答:
To add to what bjarkef wrote, you should have an automated build process, so that your libraries are built automatically.

You should label the stable releases of your libraries source code and binaries (jars).

When you distribute a product based on your libraries or on 3rd party libraries you should include the binaries (jars) of all the libraries you tested it against within your release.

There are certain open source projects that do not distribute their 3rd party dependencies along with their distribution, however, this is a very bad practice.

Your client is correct to insist on receiving products that are complete and not to start looking for the correct version of all your dependencies.

Title: Do I have to deliver my utility and helper code to clients?

Body:
Over the years I've created a bunch of Java utility and helper libraries which I just attach to new projects. Then, when I deliver code to my clients, I send all the code except for the libraries themselves (not JARs but source code files).

A client complained that he could not compile the project as some libraries were missing. I tried explaining him about my own libraries, but he was not satisfied.

How do you handle such situations? I am still apporting changes to these libraries often and I cannot compile JARs each time I start working on some new project. How to overcome this issue - not to share private libraries (personal intellectual property) and have happy clients?


问:
Drawback of implementing DDD service as static class?
Can Services in a domain-driven design be implemented as C# static class? What are the drawbacks of this choice? Can it be implemented as a non-singleton non-static class?</p>

答:
As far as I can see, making a service class static does not affect its DDD'ness.

There are however other issues with static classes, primarily testability. It becomes difficult to unit test the class, and even more difficult to test classes that have dependencies to your static class.

Therefore I would always create the class as an instance class, and define an interface for it. This allows me to replace the class by test doubles when testing other classes that have a dependency to this class.

But it doesn't make it more DDD, it just makes it more TDD :)


答:
If the contract expects source code to be delivered, then the source code you give them should compile.

Not giving them the libraries to do this is ridiculous.

If the code in your libraries is generic helper type code, then there is nothing wrong with giving them the binaries and some license agreement with them.

If the libraries contain something specific to how the system is built then the customer will be within their right to expect to receive that code as well. They may need to modify it at some point for example.


答:
First, this is mainly about the contract you have with the client. If you have a contract which includes delivering of the source code, your client can expect source code they can compile by himself. If you refuse to do this, you break the contract - and it does not matter if the missing source in lib A or lib B or lib "Utility". From the client's point of view, there is no difference between those parts.

If you have specificially excluded some libs in your contract (and your client inattentively signed that), then you may rightfully refuse to deliver your source for that libs, but don't expect to keep the client in the future.

If you want to avoid that situation in the future, separate your utility library clearly in your contract and try to sell / license it to your customers as a closed-source-product, together with the sources of the main product your are creating for them. That will imply proper versioning and configuration management of your utitlity lib, of course.

ContentLicense: CC BY-SA 4.0


问:
Bug once in a while, but high priority
I am working on a CNC (computer numerical control) project which cuts shapes into metal with help of laser.

Now my problem is once in a while (1-2 times in 20 odd days) the cutting goes wrong or not according to what is set.

But this causes loss so the client is not very happy about it.

I tried to find out the the cause of it by

Including log files

Debugging

Repeating the same environment.

But it wont repeat.

A pause and continue operation will again make it to run smoothly without the bug reappearing.

How do I tackle this issue? Should I state it as a Hardware Problem?

答:
The problem is a real one with real consequences for the user - i.e. ruined work etc. so it needs fixing. However, it doesn't have to be fixed "properly". You state:

A pause and continue operation will again make it to run smoothly with the bug reappearing.

In that case just do this. The customer will be happy that they are not wasting material on defective runs even if normal runs take a couple of seconds longer.

Obviously in the long term you might need to fix this "properly" but for the time being cut your losses, go with the workaround and get onto something else.

Title: Bug once in a while, but high priority


答:
Words in CSS class names should be separated with dashes (class-name), as that's how words in CSS properties and pseudo-classes are separated and their syntax is defined by the CSS specs.

Words in ID names also should be separated with dashes, to match the syntactic style of class names and becaus ID names are often used in URLs and the dash is the original and most common word separator in URLs.

Title: Practical considerations for HTML / CSS naming conventions (syntax)

Body:
Question: what are the practical considerations for the syntax in class and id values?

Note that I'm not asking about the semantics, i.e. the actual words that are being used, as for example described in this blogpost. There are a lot of resources on that side of naming conventions already, in fact obscuring my search for practical information on the various syntactical bits: casing, use of interpunction (specifically the - dash), specific characters to use or avoid, etc.

To sum up the reasons I'm asking this question:

The naming restrictions on id and class don't naturally lead to any conventions

The abundance of resources on the semantic side of naming conventions obscure searches on the syntactic considerations

I couldn't find any authorative source on this

There wasn't any question on SE Programmers yet on this topic :)

Some of the conventions I've considered using:

UpperCamelCase, mainly as a cross-over habit from server side coding

lowerCamelCase, for consistency with JavaScript naming conventions

css-style-classes, which is consistent with naming of css properties (but can be annoying when Ctrl+Shift+ArrowKey selection of text)

with_under_scores, which I personally haven't seen used much

alllowercase, simple to remember but can be hard to read for longer names

UPPERCASEFTW, as a great way to annoy your fellow programmers (perhaps combined with option 4 for readability)

And probably I've left out some important options or combinations as well.  So: what considerations are there for naming conventions, and to which convention do they lead?


问:
Alternatives to using  cookies?
Whate are alternatives to using cookies/client-side storage for a PHP/MySQL based site on Apache.

Scenario/Requirements:

I want to try using some anti-bot code to prevent specific scrapers etc. from accessing the site.

I would like to run this code before launching the rest of the site (before DB access etc.).

I don't want to constantly run the same code on every page-load after a visitor has passed the initial check.

I'd like to avoid the use of Cookies/Client side storage if at all possible.

The only solution I can currently think of is to write files to the server based on the visitors IP/UA, or to write a list of them to a single file.

Yet this has the limitation of multiple users through a proxy/same connection, etc ...

So, any ideas/suggestions?

Or am I simply over working the issue?

答: It sounds like you want to be using Sessions. Try this tutorial for more information if you are not already familiar with sessions: http://www.tizag.com/phpT/phpsessions.php</p>

Title: Alternatives to using  cookies?


问:
what is Docking Framework
I searching for undestanding Docking Framework concept in web, but I don't understand its concept and benefit. I see exist several 'Docking Framework' in java such as Netbeans Platform or MyDoggy or Sanaware and etc but I don't understand its benefit.

Do you can explain it?

Thanks.

答:
A docking window is one that, as well as being able to be displayed as a normal window, can be snapped into the sides of another window, and then unsnapped and dragged somewhere else.

I think describing them as frameworks is pushing it slightly, they are just GUI widget libraries for creating docking windows. The benefit is that you don't have to write the code yourself.

most of these libraries will have some sort of example/demo which may help you understand better.

Title: what is Docking Framework


答:
Work arounds

As ChrisF suggests, the pragmatic short term solution may be to use the pause and resume trick, but you have to talk to your customers to know what your priorities should be. For example:

If the fault trashes a £1000 part or causes 4 hours of downtime once a week, while the pause-resume fix reduces production by 1%, they will probably prefer the fix right now.

If the fault trashes a £1 part or causes 4 minutes of downtime once a week, but the pause-resume fix reduces production by 1%, they will probably prefer to wait for a fix which doesn't affect production rate.

Having worked in the laser micro-machining industry for many years, I know just how much pressure you can be under to optimise the process and make your machine produce as many parts per hour as is possible, so either way you are going to be under pressure to fix the problem properly.

Logging

In my experience, the only way to effectively track down a Heisenbug is copious logging. Log everything in and around the part of the code which could be responsible for the error. Learn how to read your log files effectively, make sure you are monitoring following error on your motors (are your stages moving where they should when they should?). Look at the memory usage on the machine, is a memory leak causing a critical process to be starved?

Make sure you are logging user actions too, are you sure that the operator isn't hitting the emergency stop so they can pop out for a shifty cigarette break while it's being fixed? I've seen this happen!

Static analysis

Also, look for correlations between scribing certain patterns and the bug being triggered more or less often. If you can find patterns that trigger the problem more frequently (or never trigger it) these may point to your problem.

Try to make patterns that trigger the problem even more frequently. If you can find a way to trigger the problem reliably then you are half the way to a solution.

Other options

Finally, don't be quick to blame the hardware, but never assume that it's perfect. Many times I've been blamed for problems which turned out to be electrical or mechanical in nature, so you always have to have that at the back of your mind.

Even though you may not normally have access to the machine, remember that some problems can only be efficiently solved on the machine. Sometimes a few days on-site can be worth weeks via remote desktop and months off-line completely. If you run out of off-line options, don't be afraid to propose a site visit, they can only say no.

You might also want to look at the questions and answers to What do you do with a heisenbug? and What to do with bugs that do not repro? but these might not be so useful for your situation.

Title: Bug once in a while, but high priority

Body:
I am working on a CNC (computer numerical control) project which cuts shapes into metal with help of laser.

Now my problem is once in a while (1-2 times in 20 odd days) the cutting goes wrong or not according to what is set.

But this causes loss so the client is not very happy about it.

I tried to find out the the cause of it by

Including log files

Debugging

Repeating the same environment.

But it wont repeat.

A pause and continue operation will again make it to run smoothly without the bug reappearing.

How do I tackle this issue? Should I state it as a Hardware Problem?


答:
Rule 1 number one in debugging: you need a reproducible scenario.

If you don't have one, you should work on that first. Can you reproduce that bug in some kind of "simulation mode" of the machine, where no metal is actually cut? This seem to make sense here. Can you run several different cutting programs quickly and automatically, simulating the process of 20 days in a few minutes? That may increase the probability of the issue showing up.

Then, when you have such a scenario, the next step is to gather as much information as possible and actually start debugging.

Title: Bug once in a while, but high priority


问:
Must developers understand the business domain or should the specification be sufficient?
I work for a company for which the domain is really difficult to understand because it is high technology in electronics, but this is applicable to any software development in a complex domain.

The application that I work on displays a lot of information, charts, and metrics which are difficult to understand without experience in the domain. The developer uses a specification to describe what the software must do, such as specifying that a particular chart must display this kind of metrics and this metric is the following arithmetic formula.

This way, the developer doesn't really understand the business and what/why he is doing this task. This can be OK if specification is really detailed but when it isn't or when the author has forgotten a use case, this is quite hard for the developer to find a solution.

At the other hand, training every developer to all the business aspects can be very long and difficult.

Should we give more importance to detailed specification (but as we know, perfect specification does not exist) or should we train all the developers to understand the business domain?

EDIT: keep in mind in your answer that the company could used external developers and that a formation to all the domain can be about 2 weeks

答: I'd like to answer as someone coming from the business side, who works with developers who show little interest in learning the basics of the trade, sometimes even seem to be proud of not having to know about those basics: The problem is that the developers will not be able to see mistakes in the result at first glance (unplausible results, wrong signs and so on), which requires either detailed test cases (which we didn't develop until recently), or constant supervision of the results. Insofar, as much as I am willing to learn the basics of software development to ease the communication, I'd like to urge developers to do the same. </p>

OwnerDisplayName: Jerome C.


答:
With multithreading, you just can't separate queries and commands, unless you have an external lock which serializes calls.

The usual approach looks like this:

```<code>// query + command
// moves value at top into external thread-local storage `value`
// may fail and return `false`
bool ThreadSafeStack::try_pop(Value& value)
{
    lock_guard guard(m_lock); // or `using(m_lock)`, `with m_lock:`

    if (m_stack.empty())
       return false;

    value = m_stack.top();
    m_stack.pop();
    return true;
}
</code>```

But, you can use a hack: you can turn value into a member of the class.

Assume you have a data structure like this:

```<code>struct StackAndLock {
   Stack stack;
   Mutex lock;
};
</code>```

Then you can create a ThreadSafeStack class:

```<code>class ThreadSafeStack
{
    Stack& m_stack;
    Mutex& m_lock;

    Value m_value;
public:
    ThreadSafeStack(StackAndLock& stackAndLock);

    void push(Value value); // command
    bool try_pop() // command, may fail
    {
        ...
        m_value = m_stack.top();
    }
    Value get_last() { return m_value; } // query
    bool empty(); // query
};
</code>```

So you have one shared StackAndLock object, and multiple ThreadSafeStack objects, one per thread:

```<code>void thread_proc(StackAndLock& bundle)
{
     ThreadSafeStack stack(bundle);

     ...
     if (stack.try_pop())
     {
         ... stack.get_last() ...
     }
}
</code>```

I can't say that it's such a great idea, but definitely it is Command-Query separation.

Title: Command-Query-Separation and multithreading safe interfaces

Body:
I like the command query separation pattern (from OOSC / Eiffel - basically you either return a value or you change the state of the class - but not both). This makes reasoning about the class easier and it is easier to write exception safe classes.

Now, with multi threading, I run into a major problem: the separation of the query and the command basically invalidates the result from the query as anything can happen between those 2.

So my question is: how do you handle command query separation in an multi-threaded environment?

Clarification example:

A stack with command query separation would have the following methods:

push (command)

pop (command - but does not return a value)

top (query - returns the value)

empty (query)

The problem here is - I can get empty as status, but then I can not rely on top really retrieving an element since between the call of empty and the call of top, the stack might have been emptied. Same goes for pop & top. If I get an item using top, I can not be sure that the item that I pop is the same.

This can be solved using external locks - but that's not exactly what I call threadsafe design.

Body:
With multithreading, you just can't separate queries and commands, unless you have an external lock which serializes calls.

The usual approach looks like this:

// query + command
// moves value at top into external thread-local storage `value`
// may fail and return `false`
bool ThreadSafeStack::try_pop(Value& value)
{
    lock_guard guard(m_lock); // or `using(m_lock)`, `with m_lock:`

    if (m_stack.empty())
       return false;

    value = m_stack.top();
    m_stack.pop();
    return true;
}

But, you can use a hack: you can turn value into a member of the class.

Assume you have a data structure like this:

struct StackAndLock {
   Stack stack;
   Mutex lock;
};

Then you can create a ThreadSafeStack class:

class ThreadSafeStack
{
    Stack& m_stack;
    Mutex& m_lock;

    Value m_value;
public:
    ThreadSafeStack(StackAndLock& stackAndLock);

    void push(Value value); // command
    bool try_pop() // command, may fail
    {
        ...
        m_value = m_stack.top();
    }
    Value get_last() { return m_value; } // query
    bool empty(); // query
};

So you have one shared StackAndLock object, and multiple ThreadSafeStack objects, one per thread:

void thread_proc(StackAndLock& bundle)
{
     ThreadSafeStack stack(bundle);

     ...
     if (stack.try_pop())
     {
         ... stack.get_last() ...
     }
}

I can't say that it's such a great idea, but definitely it is Command-Query separation.


答:
If client is indeed concerned only about code being compilable, consider making and passing them "stubs" that don't do work but implement interfaces needed for code to compile:

```<code>public class MyClass {
    public void myMethod() {
        throw unsupported();
    }
    private UnsupportedOperationException unsupported() {
        return new UnsupportedOperationException(
                "stub code intended to use only in compilation");
    }
}
</code>```

Body:
If client is indeed concerned only about code being compilable, consider making and passing them "stubs" that don't do work but implement interfaces needed for code to compile:

public class MyClass {
    public void myMethod() {
        throw unsupported();
    }
    private UnsupportedOperationException unsupported() {
        return new UnsupportedOperationException(
                "stub code intended to use only in compilation");
    }
}


答:
In general case, in order to keep track of users and for example to know which one is logged on, sessions are used. But sessions mean session IDs stored in cookies¹; it's just that if you need to remember N entries for a user, there is only one cookie involved, not N.

In your particular case, on the other hand, you care about protecting your website against illegitimate use (and avoid repetitive checks). It means that sessions are not appropriate: why a scrapper would ever send session cookie to you?² Instead:

Detect the IP address of the request before starting processing it,

If you have no information about the IP address:

Detect if it is a scrapper (like you currently do),

Store the result in cache (or in database, or both),

Load the result from cache.

Respond according to the result. If it's a scrapper, send a "please stop scrapping" page; if it is a legitimate user, process the page and send the ordinary response.

¹ PHP is also able to pass session ID in URIs. It's ugly and must be used only when you can't do anything else.

² Remember, legitimate users may have their cookies disabled for some reason. The fact that a client doesn't send the cookies to you doesn't automatically mean it's an automated process.

Title: Alternatives to using  cookies?

Body:
Whate are alternatives to using cookies/client-side storage for a PHP/MySQL based site on Apache.

Scenario/Requirements:

I want to try using some anti-bot code to prevent specific scrapers etc. from accessing the site.

I would like to run this code before launching the rest of the site (before DB access etc.).

I don't want to constantly run the same code on every page-load after a visitor has passed the initial check.

I'd like to avoid the use of Cookies/Client side storage if at all possible.

The only solution I can currently think of is to write files to the server based on the visitors IP/UA, or to write a list of them to a single file.

Yet this has the limitation of multiple users through a proxy/same connection, etc ...

So, any ideas/suggestions?

Or am I simply over working the issue?


问:
How to represent a Rubik's Cube in a data structure
If I am attempting to simulate a Rubik's Cube, how would you create a data structure to store the cube's state in memory, with X number of tiles per side?

Things to consider:

the cube can be of any size

it is a Rubik's cube, so layers can be rotated

答:
you can use a simple array (each element having a 1 to 1 mapping to a square on a face) and simulate each rotation with a certain permutation

you can get away with only 3 essential permutations: rotate a slice with the axis though the front face, rotate the cube around the vertical axis and rotate the cube over the horizontal axis through the left and right faces. all the other moves can be expressed by some concatenation of these three.

the most straightforward way of know whether a cube is solvable is to solve it (find a series of permutations that will solve the cube), if you end up with 2 edges that have swapped place, a single flipped edge, a single flipped corner or 2 swapped corners you have a unxolvable cube


答: What's wrong with a plain old array of size [6X][X]? You do not need to know about inner mini-cubes, because you do not see them; they are not part of the cube's state. Hide two ugly methods behind a nice-looking and simple to use interface, unit test it to death, and voila, you're done!

Title: How to represent a Rubik's Cube in a data structure

Body:
If I am attempting to simulate a Rubik's Cube, how would you create a data structure to store the cube's state in memory, with X number of tiles per side?

Things to consider:

the cube can be of any size

it is a Rubik's cube, so layers can be rotated


答:
You don't have to, but why wouldn't you want to?

I would be concerned about any programmer who was reluctant and especially unable to learn the domain to some degree. It's important to get out of the "ivory code tower" once in awhile.

Writing code without having any idea how it is used and for what purpose just sounds like a terrible job. Who wants to just break bricks when you could be building cathedrals?

Title: Must developers understand the business domain or should the specification be sufficient?

Body:
I work for a company for which the domain is really difficult to understand because it is high technology in electronics, but this is applicable to any software development in a complex domain.

The application that I work on displays a lot of information, charts, and metrics which are difficult to understand without experience in the domain. The developer uses a specification to describe what the software must do, such as specifying that a particular chart must display this kind of metrics and this metric is the following arithmetic formula.

This way, the developer doesn't really understand the business and what/why he is doing this task. This can be OK if specification is really detailed but when it isn't or when the author has forgotten a use case, this is quite hard for the developer to find a solution.

At the other hand, training every developer to all the business aspects can be very long and difficult.

Should we give more importance to detailed specification (but as we know, perfect specification does not exist) or should we train all the developers to understand the business domain?

EDIT: keep in mind in your answer that the company could used external developers and that a formation to all the domain can be about 2 weeks


答:
You seem to be asking two separate questions.

How to represent a cube with X number of sides?

If you are going to simulate a real-world Rubic's cube, then all Rubik's cubes have 6 sides. I think what you mean is "X number of tiles per dimension per side". Each side of the original Rubic's cube is 3x3. Other sizes include 4x4 (Professor's Cube), 5x5, and 6x6.

I would represent the data with 6 sides, using the "standard" cube solving notation:

FRONT: the face facing the solver

BACK

RIGHT

LEFT

UP

DOWN

Each side is a 2-D array of X by X.


问:
How do I showcase my work experience in programming?
I'm a student of web development languages like PHP, Ruby, and Python. Currently I'm working on some school projects but I'm trying to work on some weekend projects which I can use to showcase for potential employers, what's the best way to set this up? Specifically, are there any tips you have for a new programmer because I don't want opinions on how this or that should or shouldn't be set up. If possible please give real examples.

Edit: what about Git? Is this a good place to show my projects?

答:
I honestly think you can do no better then shelling out a few bucks to buy a domain name that has your name and a monthly server. It's not expensive.

This way, you can do anything you want on it, show case your projects and let them be viewed and downloadable by employers or the friends your trying to impress =)   The way you want people to see them. Small portions or full downloads, your in control of the name and the content.


问:
Finding right bug tracker web application
I'm looking for a bug tracking system (similiar as http://www.mantisbt.org) with these following requirements:

Requirement specifications are:

Upload picture and different files without any limitaton of the file's space.

If user belong to a specific group or businesss group, the GUI:s logotype should be changed into group's logotype after the user has entered user name and password. All user use the same database with different GUI.

Right information of unassigned, modified and resolved bug case will be displayed based on what group or business group that the user is assigned to.

All information will display after the user has logged in.

Enable to create 1 or more super user (administrator) and regular user.

Right user with right group or business group will retrieve right information.

Non functional requirement:

The bugging tracker take place in a webbapplication.

All information must use web browser to view all information.

答: You don't mention your infrastructure but where I work we use BugNET for one of our projects. If you're running on IIS then it's worth a look. From your list of requirements it'll satisfy most of them. Each defined project within BugNET can have its own logo, I don't think it's possible to alter the logo on a per-user or per-user group basis. It is open-source however so you could, in theory, add that feature yourself.</p>


问:
Should injecting dependencies be done in the ctor or per method?
Consider:

```<code>public class CtorInjectionExample
{
    public CtorInjectionExample(ISomeRepository SomeRepositoryIn, IOtherRepository OtherRepositoryIn)
    {
        this._someRepository = SomeRepositoryIn;
        this._otherRepository = OtherRepositoryIn;
    }

    public void SomeMethod()
    {
        //use this._someRepository
    }

    public void OtherMethod()
    {
        //use this._otherRepository
    }
}
</code>```

against:

```<code>public class MethodInjectionExample
{
    public MethodInjectionExample()
    {
    }

    public void SomeMethod(ISomeRepository SomeRepositoryIn)
    {
        //use SomeRepositoryIn
    }

    public void OtherMethod(IOtherRepository OtherRepositoryIn)
    {
        //use OtherRepositoryIn
    }
}
</code>```

While Ctor injection makes extension difficult (any code calling the ctor will need updating when new dependencies are added), and method level injection seems to remain more encapsulated from the class level dependency and I can't find any other arguments for/against these approaches.

Is there a definitive approach to take for injection?

(N.B. I have searched for information on this and tried to make this question objective.)

答:
There are various kinds of inversion of control, and your question proposes only two (you can also use factory to inject dependency).

The answer is : it depends on the need. Sometimes it is better to use one kind, and another different kind.

I personally like constructor injectors, since the constructor is there to fully initialize the object. Having to call a setter later on makes the object not fully constructed.


答:
Right, first off, let's deal with "Any code calling the ctor will need updating when new dependencies are added"; To be clear, if you're doing dependency injection and you have any code calling new() on an object with dependencies, you're doing it wrong.

Your DI container should be able to inject all the relevant dependencies, so you don't need to worry about changing the constructor signature, so that argument doesn't really hold.

As for the per-method vs. per-class injection idea, there are two major issues with per-method injection.

One issue is that your class's methods should share dependencies, it's one way to help make sure your classes are separated effectively, if you see a class with a large number of dependencies (probably more than 4-5) then that class is a prime candidate for refactoring into two classes.

The next issue is that in order to "inject" the dependencies, per-method, you'd have to pass them into the method call. This means that you'll have to resolve the dependencies before the method call, so you'll likely end up with a bunch of code like this:

```<code>var someDependency = ServiceLocator.Resolve<ISomeDependency>();
var something = classBeingInjected.DoStuff(someDependency);
</code>```

Now, say you're going to call this method in 10 places around your application: you'll have 10 of these snippets. Next, say you need to add another dependency to DoStuff(): you're going to have to change that snippet 10 times (or wrap it in a method, in which case you're just replicating DI behaviour manually, which is a waste of time).

So, what you've basically done there is made your DI-utilising classes aware of their own DI container, which is a fundamentally bad idea, as it very quickly leads to a clunky design that's difficult to maintain.

Compare that to constructor injection; In constructor injection you're not tied to a particular DI container, and you're never directly responsible for fulfilling the dependencies of your classes, so maintenance is fairly headache-free.

It sounds to me like you're trying to apply IoC to a class containing a bunch of unrelated helper methods, whereas you might be better off splitting the helper class into a number of service classes based on usage, then using the helper to delegate the calls. This still isn't a great approach (helper classed with methods that do anything more complex than just deal with the arguments that are passed to them are generally just badly-written service classes), but it will at least keep your design a little cleaner.

(N.B. I've done the approach you're suggesting before, and it was a very bad idea that I have not repeated since. Turned out I was trying to separate out classes that really didn't need to be separated, and ended up with a set of interfaces where each method call required a near-fixed selection of other interfaces. It was a nightmare to maintain.)

Title: Should injecting dependencies be done in the ctor or per method?

Body:
Consider:

```<code>public class CtorInjectionExample
{
    public CtorInjectionExample(ISomeRepository SomeRepositoryIn, IOtherRepository OtherRepositoryIn)
    {
        this._someRepository = SomeRepositoryIn;
        this._otherRepository = OtherRepositoryIn;
    }

    public void SomeMethod()
    {
        //use this._someRepository
    }

    public void OtherMethod()
    {
        //use this._otherRepository
    }
}
</code>```

against:

```<code>public class MethodInjectionExample
{
    public MethodInjectionExample()
    {
    }

    public void SomeMethod(ISomeRepository SomeRepositoryIn)
    {
        //use SomeRepositoryIn
    }

    public void OtherMethod(IOtherRepository OtherRepositoryIn)
    {
        //use OtherRepositoryIn
    }
}
</code>```

While Ctor injection makes extension difficult (any code calling the ctor will need updating when new dependencies are added), and method level injection seems to remain more encapsulated from the class level dependency and I can't find any other arguments for/against these approaches.

Is there a definitive approach to take for injection?

(N.B. I have searched for information on this and tried to make this question objective.)

Body:
Right, first off, let's deal with "Any code calling the ctor will need updating when new dependencies are added"; To be clear, if you're doing dependency injection and you have any code calling new() on an object with dependencies, you're doing it wrong.

Your DI container should be able to inject all the relevant dependencies, so you don't need to worry about changing the constructor signature, so that argument doesn't really hold.

As for the per-method vs. per-class injection idea, there are two major issues with per-method injection.

One issue is that your class's methods should share dependencies, it's one way to help make sure your classes are separated effectively, if you see a class with a large number of dependencies (probably more than 4-5) then that class is a prime candidate for refactoring into two classes.

The next issue is that in order to "inject" the dependencies, per-method, you'd have to pass them into the method call. This means that you'll have to resolve the dependencies before the method call, so you'll likely end up with a bunch of code like this:

var someDependency = ServiceLocator.Resolve<ISomeDependency>();
var something = classBeingInjected.DoStuff(someDependency);

Now, say you're going to call this method in 10 places around your application: you'll have 10 of these snippets. Next, say you need to add another dependency to DoStuff(): you're going to have to change that snippet 10 times (or wrap it in a method, in which case you're just replicating DI behaviour manually, which is a waste of time).

So, what you've basically done there is made your DI-utilising classes aware of their own DI container, which is a fundamentally bad idea, as it very quickly leads to a clunky design that's difficult to maintain.

Compare that to constructor injection; In constructor injection you're not tied to a particular DI container, and you're never directly responsible for fulfilling the dependencies of your classes, so maintenance is fairly headache-free.

It sounds to me like you're trying to apply IoC to a class containing a bunch of unrelated helper methods, whereas you might be better off splitting the helper class into a number of service classes based on usage, then using the helper to delegate the calls. This still isn't a great approach (helper classed with methods that do anything more complex than just deal with the arguments that are passed to them are generally just badly-written service classes), but it will at least keep your design a little cleaner.

(N.B. I've done the approach you're suggesting before, and it was a very bad idea that I have not repeated since. Turned out I was trying to separate out classes that really didn't need to be separated, and ended up with a set of interfaces where each method call required a near-fixed selection of other interfaces. It was a nightmare to maintain.)


答: You missed the one that at least for me is the most flexible - property injection. I use Castle/Windsor and all I need to do is add a new auto property to my class and I get the injected object without any problems and without breaking any interfaces.</p>


问:
Do you have to be good at math to be a good programmer?
It seems that conventional wisdom suggests that good programmers are also good at math. Or that the two are somehow intrinsically linked. Many programming books I have read provide many examples that are solutions to math problems, or are somehow related to math as if these examples are what make sense to most people.

So the question I would like to float is: do you have to be good at math to be a good programmer?

答:
Mathematics is an abstract notation for modeling real world situations, and this is exactly what programming is.

If you can't visualize and figure out how to build an accurate working model of the world then you won't be a good programmer (or mathematician), and there's no getting around that. That said you could probably pound out some JavaScript and Bash and make a fine living at it without knowledge of advanced mathematics, but I assure you knowing math will only add to your ability to think abstractly and create better models.

Learning to be a good programmer is a ton of work, and I suggest that you simply consider learning mathematics to be a part of that workload because it can be the difference between being a fantastic programmer and merely being a competent one.

OwnerDisplayName: Charles Roper