问:
Ways for beginner programmer to practice with C++
So i just finished my first semester of college. In my intro to programming class we made a bunch of super interesting (sarcasm) console applications. Any suggestions on ways other than just messing around with console applications for a beginner C++ student to improve?

答:
Depends on what you mean by console apps, but there is nothing wrong with console applications to learn C++. It all depends on how complex they are.

You could try writing a gui app with something like QT, but then you'll spend most of the time learning the framework.

You could write a game in something like OpenGL, SDL etc.

The problem with C++ is that it is a huge step from simple stuff to something useful.


问:
Why was the Itanium processor difficult to write a compiler for?
It's commonly stated that Intel's Itanium 64-bit processor architecture failed because the revolutionary EPIC instruction set was very difficult to write a good compiler for, which meant a lack of good developer tools for IA64, which meant a lack of developers creating programs for the architecture, and so no one wanted to use hardware without much software for it, and so the platform failed, and all for the want of a horseshoe nail good compilers.

But why was the compiler stuff such a difficult technical problem?  It seems to me that if the explicit parallelism in EPIC was difficult for compiler vendors to implement... why put that burden on them in the first place?  It's not like a good, well-understood solution to this problem didn't already exist: put that burden on Intel instead and give the compiler-writers a simpler target.

Itanium came out in 1997.  By this point, the UCSD P-Code bytecode system was nearly 20 years old, the Z-machine just slightly younger, and the JVM was the hot new rising star in the world of programming languages.  Is there any reason why Intel didn't specify a "simple Itanium bytecode" language, and provide a tool that converts this bytecode into optimized EPIC code, leveraging their expertise as the folks who designed the system in the first place?

答:
As Robert Munn pointed out -- it was the lack of backward compatibility that killed the Itanium ( and many other "new" technologies).

While writing a new compiler might have been hard you only need a few of them. A C compiler which produces optimized code is a must -- otherwise you will not have a useable Operating System. You need a C++ compiler, Java and given that the main user base would be Windows some sort of Visual Basic. So this was not really a problem. There was a decent operating system (NT) and a good C compiler available.

What would seem like a trivial effort for a company offering a software product -- recompile and retest your C code base (and at that time most would have been written in pure C!) was not that simple; converting a large set of C programs which assumed a 32 bit integer and assumed 32 bit addressing to a native 64 bit architecture was full of pitfalls. Had IA64 become a dominant chip (or even a popular one!) most software companies would have bitten the bullet and made the effort.

So fast chip with a reasonable OS but a very limited set of software available, therefore not many people bought it, therefore not many software companies provided products for it.

ContentLicense: CC BY-SA 3.0


问:
What are the best resources for learning about concurrency and multi-threaded applications?
I realised I have a massive knowledge gap when it comes to multi-threaded applications and concurrent programming. I've covered some basics in the past, but most of it seems to be gone from my mind, and it is definitely a field that I want, and need, to be more knowledgeable about.

What are the best resources for learning about building concurrent applications? I'm a very practical oriented person, so if said book contains concrete examples the better, but I'm open to suggestions. I personally prefer to work in pseudocode or C++, and a slant toward game development would be best, but not required.

答: There are many concurrency models so you'd better have a good idea about all before you decide which one to pick. For that, I recommend the book Seven Concurrency Models in Seven Weeks: When Threads Unravel. Check the reviews and the TOC and you can see why this is a good book. And it is also recent (2014).</p>


答:
But why was the compiler stuff such a difficult technical problem? It seems to me that if the explicit parallelism in EPIC was difficult for compiler vendors to implement... why put that burden on them in the first place? It's not like a good, well-understood solution to this problem didn't already exist: put that burden on Intel instead and give the compiler-writers a simpler target.

What you describes is a bit what Transmeta tried to do with their code morphing software (which was dynamically translating x86 "bytecode" into Transmeta internal machine code).

As to why did Intel failed to make a good enough compiler for IA64... I guess is that they did not have enough compiler expertise in house (even if of course they did have some very good compiler experts inside, but probably not enough to make a critical mass). I guess that their management underestimated the efforts needed to make a compiler.

AFAIK, Intel EPIC failed because compilation for EPIC is really hard, and also because when compiler technology slowly and gradually improved, other competitors where also able to improve their compiler (e.g. for AMD64), sharing some compiler know-how.

BTW, I wished that AMD64 would have been some more RISCy instruction set. It could have been some POWERPC64 (but it probably wasn't because of patent issues, because of Microsoft demands at that time, etc...). The x86-64 instruction set architecture is really not a "very good" architecture for compiler writer (but it is somehow "good enough").

Also the IA64 architecture has builtin some strong limitations, e.g. the 3 instructions/word have been good as long as the processor had 3 functional units to process them, but once Intel went to newer IA64 chips they added more functional units, and the instruction-level parallelism was once again hard to achieve.

Perhaps RISC-V (which is an open source ISA) will gradually succeed enough to make it competitive to other processors.

Title: Why was the Itanium processor difficult to write a compiler for?

Body:
It's commonly stated that Intel's Itanium 64-bit processor architecture failed because the revolutionary EPIC instruction set was very difficult to write a good compiler for, which meant a lack of good developer tools for IA64, which meant a lack of developers creating programs for the architecture, and so no one wanted to use hardware without much software for it, and so the platform failed, and all for the want of a horseshoe nail good compilers.

But why was the compiler stuff such a difficult technical problem?  It seems to me that if the explicit parallelism in EPIC was difficult for compiler vendors to implement... why put that burden on them in the first place?  It's not like a good, well-understood solution to this problem didn't already exist: put that burden on Intel instead and give the compiler-writers a simpler target.

Itanium came out in 1997.  By this point, the UCSD P-Code bytecode system was nearly 20 years old, the Z-machine just slightly younger, and the JVM was the hot new rising star in the world of programming languages.  Is there any reason why Intel didn't specify a "simple Itanium bytecode" language, and provide a tool that converts this bytecode into optimized EPIC code, leveraging their expertise as the folks who designed the system in the first place?


答:
The Wikipedia article on EPIC has already outlined the many perils common to VLIW and EPIC.

If anyone does not catch the sense of fatalism from that article, let me highlight this:

Load responses from a memory hierarchy which includes CPU caches and DRAM do not have a deterministic delay.

In other words, any hardware design that fails to cope with (*) the non-deterministic latency from memory access will just become a spectacular failure.

(*) By "cope with", it is necessary to achieve reasonably good execution performance (in other words, "cost-competitive"), which necessitates not letting the CPU fall idle for tens to hundreds of cycles ever so often.

Note that the coping strategy employed by EPIC (mentioned in the Wikipedia article linked above) does not actually solve the issue. It merely says that the burden of indicating data dependency now falls on the compiler. That's fine; the compiler already has that information, so it is straightforward for the compiler to comply. The problem is that the CPU is still going to idle for tens to hundreds of cycles over a memory access. In other words, it externalizes a secondary responsibility, while still failing to cope with the primary responsibility.

The question can be rephrased as: "Given a hardware platform that is destined to be a failure, why (1) didn't (2) couldn't the compiler writers make a heroic effort to redeem it?"

I hope my rephrasing will make the answer to that question obvious.

There is a second aspect of the failure which is also fatal.

The coping strategies (mentioned in the same article) assumes that software-based prefetching can be used to recover at least part of the performance loss due to non-deterministic latency from memory access.

In reality, prefetching is only profitable if you are performing streaming operations (reading memory in a sequential, or highly predictable manner).

(That said, if your code makes frequent access to some localized memory areas, caching will help.)

However, most general-purpose software must make plenty of random memory accesses. If we consider the following steps:

Calculate the address, and then

Read the value, and then

Use it in some calculations

For most general-purpose software, these three must be executed in quick succession. In other words, it is not always possible (within the confines of software logic) to calculate the address up front, or to find enough work to do to fill up the stalls between these three steps.

To help explain why it is not always possible to find enough work to fill up the stalls, here is how one could visualize it.

Let's say, to effectively hide the stalls, we need to fill up 100 instructions which do not depend on memory (so will not suffer from additional latency).

Now, as a programmer, please load up any software of your choice into a disassembler. Choose a random function for analysis.

Can you identify anywhere a sequence of 100 instructions (*) which are exclusively free of memory accesses?

(*) If we could ever make NOP do useful work ...

Modern CPUs try to cope with the same using dynamic information - by concurrently tracking the progress of each instruction as they circulate through the pipelines. As I mentioned above, part of that dynamic information is due to non-deterministic memory latency, therefore it cannot be predicted to any degree of accuracy by compilers. In general, there is simply not enough information available at the compile-time to make decisions that could possibly fill up those stalls.

In response to the answer by AProgrammer

It is not that "compiler ... extracting parallelism is hard".

Reordering of memory and arithmetic instructions by modern compilers is the evidence that it has no problem identifying operations that are independently and thus concurrently executable.

The main problem is that non-deterministic memory latency means that whatever "instruction pairing" one has encoded for the VLIW/EPIC processor will end up being stalled by memory access.

Optimizing instructions that do not stall (register-only, arithmetic) will not help with the performance issues caused by instructions that are very likely to stall (memory access).

It is an example of failure to apply the 80-20 rule of optimization: Optimizing things that are already fast will not meaningfully improve overall performance, unless the slower things are also being optimized.

In response to answer by Basile Starynkevitch

It is not "... (whatever) is hard", it is that EPIC is unsuitable for any platform that has to cope with high dynamism in latency.

For example, if a processor has all of the following:

No direct memory access;

Any memory access (read or write) has to be scheduled by DMA transfer;

Every instruction has the same execution latency;

In-order execution;

Wide / vectorized execution units;

Then VLIW/EPIC will be a good fit.

Where does one find such processors? DSP. And this is where VLIW has flourished.

In hindsight, the failure of Itanium (and the continued pouring of R&D effort into a failure, despite obvious evidence) is an example of organizational failure, and deserves to be studied in depth.

Granted, the vendor's other ventures, such as hyperthreading, SIMD, etc., appears to be highly successful. It is possible that the investment in Itanium may have had an enriching effect on the skills of its engineers, which may have enabled them to create the next generation of successful technology.


问:
Job Interview Challenges
The other day, in our PHP class, our teacher gave us a challenge used by a friend of his in job interviews. It works in every programming language, so it's not limited to PHP. He said that his friend uses this 'riddle' to weed out the people who can't think of a fast answer when it comes to logical challenges. The people that don't solve it won't get a job, of course.

The riddle is as follows:

```<code>    $a = 3;
    $b = 7;

    echo "a = $a";        // has to become 7
    echo "<br />";
    echo "b = $b";        // has to become 3
</code>```

You basically have to switch the contents of both variables without doing lame things like $b = $a + 4. You cannot use a temporary variable either! I struggled with this, I have to admit that; I was like 'oooh yeah' when we finally got the answer.

I don't want to spoil this for anyone, so instead of posting the solution I'll just put a link.

Now, as for my question. I was wondering if there are more riddles like these out there, that people (that's you, SO) use in job interviews, etc. Perhaps even a bit harder than this one. My goal is to train my logical thinking a bit and get better in solving issues like this. Perhaps there are any books or websites out there devoted to stuff like this?

答:
I wonder what Joris' teacher's response was.

The biggest problem with this is that the trick is obscure and anyone who used it in a professional programming environment is really adding difficult to maintain code. This is a huge problem for a professional place, anywhere that has very large codebases needs easy-to-understand code so future workers can see what its doing without spending large amounts of time grokking code, or worse - not understanding it and making a mistake.

If you need an example, look at the Story of Mel. Very fancy code, neat trick, useless professional programmer. You might say the only reason this is acceptable is that it was a very tight environment where such tricks made a difference. In 99.999% of modern environments this would be marked as requiring rework.

OwnerDisplayName: Joris Ooms

Title: Job Interview Challenges


答:
TL;DR: 1/ there are other aspects in the failure of Itanium than the compiler issues and they may very well be enough to explain it; 2/ a byte code would not have solved the compiler issues.

It's commonly stated that Intel's Itanium 64-bit processor architecture failed because the revolutionary EPIC instruction set was very difficult to write a good compiler for

Well, they were also late (planned for 98, first shipment in 2001) and when they finally delivered the hardware, I'm not even sure that it delivered what was promised for the earlier date (IIRC, they at least dropped part of the x86 emulation which was initially planned), so I'm not sure that even if the compilation problems has been solved (and AFAIK, it has not yet), they would have succeeded.  The compiler aspect was not the only aspect which was overly ambitious.

Is there any reason why Intel didn't specify a "simple Itanium bytecode" language, and provide a tool that converts this bytecode into optimized EPIC code, leveraging their expertise as the folks who designed the system in the first place?

I'm not sure where you place the tool.

If it is in the processor, you have just another micro-architecture and there is no reason not to use x86 as public ISA (at least for Intel, the incompatibility has an higher cost than whatever could bring a cleaner public ISA).

If it is externally, starting from a byte-code make it even harder than starting from an higher level language. The issue with EPIC is that it can use only the parallelism that a compiler can find, and extracting that parallelism is hard.  Knowing the language rules give you more possibilities than if you are constrained by something already scheduled. My (admitted unreliable and from someone who followed that from far) recollection is that what HP(*) and Intel failed to achieve on the compiler front is the language level extraction of parallelism, not the low level which would have been present in a byte code.

You are perhaps underestimating the cost at which current processor achieve their performance. OOO is more effective than the other possibilities, but it is surely not efficient.  EPIC wanted to use the area budget used by the implementation of OOO to provide more raw computing, hoping that compilers would be able to make use of it.  As written above, not only we are still unable -- as AFAIK, even in theory -- to write compilers which have that ability, but the Itanium got enough other hard-to-implement features that it was late and its raw power was not even competitive (excepted perhaps in some niche markets with lots of FP computation) with the other high end processor when it got out of fab.

(*) You also seem to underestimate HP role in EPIC.


问:
Should i avoid FaultException for Custom Validation Error messages to client
We are as a team working on a project which currently using WCF as in between client and server.

All business rules are written on managers classes which are used by service so its means no validation rule will be on client side (for example duplicate user name )

so far in case of duplicate user name validation fails we throw faultException from service and use those fault Exceptions can be used by client to check why that operation is failed.

Now my manager wants that we should not use faultException. he has following points

Exception throwing for validation messages is not a good approach.

EXception throw and catch take more time .

Everytime client must have to check faultException catch block before any other catch block

so he gave us idea to implement the methods of service with an extra parameter which will be ref type of error class object . any validation rule will be added to that ref type and client will check that ref first and if any error client can show validation message.

so my questions are

really using faultException for business rules validation is bad practice ?

what are cons of using ref varibales as parameter in service operation contracts ?

What will be better approach if any other normally uses in programming world ?

答:
what are cons of using ref varibales as parameter in service operation contracts ?

I first wrote: "The major con is that this does not work. Period. You need another approach." It seems that that's not correct, as long as you don't leave the .NET environment, it seems to work. However, ref parameters are considered bad practice even in normal code by Microsoft. Lengthy explanation here. There simply is no need to have ref or out parameters.

I would expect a validation to return it's result. As a return value or if more information is required as a class encapsulating return values and error messages.

If the validation itself could not be processed (like you check against a database but the database was not available) then I would indeed expect an exception.


问:
How to mark next version in the source code?
We are developing a software that gets released every few months, and it is either a major version (1.0.x -> 2.0.0) or a minor version (-> 1.1.x). This version is visible in the software, say that we have a variable for it like this:

```<code>var version = '1.0.0';
</code>```

and then it's displayed somehow:

```<code>print(version);
</code>```

When we release 1.0.0 and start working on "vNext", it just feels wrong to leave 1.0.0 there because all the developers and testers will see a "wrong" version in the app. However, at that point we are not sure what the next version will be called - it might be 1.1 or 2.0. I've thought about possibly just marking the next version as "DEV" so that there is no expectation of a certain version number but am not sure this is a good idea (and it's certainly not in semver format so some other code may be broken if it works with the version number in any way). Another idea was to just call it "post-1.0" but that's not a proper version format, too.

Have you ever run into this situation, and how did you deal with it?

答: One standard answer to this is in the Maven world. Development versions use the next version number with the suffix "-SNAPSHOT". After a release of 1.0.2, for example, Maven automatically increments the version to 1.0.3-SNAPSHOT.</p>


问:
How do you decide your side projects
At any given time, I usually have a bunch of ideas for weekend/side projects that I can work on. The ideas can be generally be categorized into these:

Self Learning: Learning a new language/ technology/ framework

Work related: Learning/Doing something that would help you at work

Money: Projects that (you think) can make some money

Fun/Utility projects

These are just the rough categories that I can think of and there can be more/other ways of classification.

My question is based on your experience what should drive the decision of what kind of project to work on. What parameters apart from the type of project should impact this decision (time, effort, money...)

答:
Scratch an itch.

The side projects that I do are usually things I need myself. If they fit into your four categories then thats even better.

Title: How do you decide your side projects

ContentLicense: CC BY-SA 2.5


问:
What exactly makes the Haskell type system so revered (vs say, Java)?
I'm starting to learn Haskell. I'm very new to it, and I am just reading through a couple of the online books to get my head around its basic constructs.

One of the 'memes' that people familiar with it have often talked about, is the whole "if it compiles, it will work*" thing - which I think is related to the strength of the type system.

I'm trying to understand why exactly Haskell is better than other statically typed languages in this regard.

Put another way, I assume in Java, you could do something heinous like bury
ArrayList<String>() to contain something that really should be ArrayList<Animal>(). The heinous thing here is is that your string contains elephant, giraffe, etc, and if someone puts in Mercedes - your compiler won't help you.

If I did do ArrayList<Animal>() then, at some later point in time, if I decide my program isn't really about animals, it's about vehicles, then I can change, say, a function that produces ArrayList<Animal> to produce ArrayList<Vehicle> and my IDE should tell me everywhere there is a compilation break.

My assumption is that this is what people mean by a strong type system, but it's not obvious to me why Haskell's is better. Put another way, you can write good or bad Java, I assume you can do the same in Haskell (i.e stuff things into strings/ints that should really be first-class data types).

I suspect I'm missing something important/basic.

I would very happy to be shown the error of my ways!

答:
Lots of people have listed good things about Haskell. But in answer to your specific question "why does the type system make programs more correct?", I suspect the answer is "parametric polymorphism".

Consider the following Haskell function:

```<code>foobar :: x -> y -> y
</code>```

There is literally only one possible way to implement this function. Just by the type signature, I can tell precisely what this function does, because there is only one possible thing it can do. [OK, not quite, but almost!]

Stop and think about that for a moment. That's actually a really big deal! It means if I write a function with this signature, it's actually impossible for the function to do anything other than what I intended. (The type signature itself can still be wrong, of course. No programming language will ever prevent all bugs.)

Consider this function:

```<code>fubar :: Int -> (x -> y) -> y
</code>```

This function is impossible. You literally cannot implement this function. I can tell that just from the type signature.

As you can see, a Haskell type signature tells you a hell of a lot!

Compare to C#. (Sorry, my Java is a little rusty.)

```<code>public static TY foobar<TX, TY>(TX in1, TY in2)
</code>```

There are a couple of things this method could do:

Return in2 as the result.

Loop forever, and never return anything.

Throw an exception, and never return anything.

Actually, Haskell has these three options too. But C# also gives you the additional options:

Return null. (Haskell does not have null.)

Modify in2 before returning it. (Haskell does not have in-place modification.)

Use reflection. (Haskell does not have reflection.)

Perform multiple I/O actions before returning a result. (Haskell won't let you perform I/O unless you declare that you perform I/O here.)

Reflection is a particularly big hammer; using reflection, I can construct a new TY object out of thin air, and return that! I can inspect both of the objects, and do different actions depending on what I find. I can make arbitrary modifications to both of the objects passed in.

I/O is a similarly big hammer. The code could be displaying messages to the user, or opening database connections, or reformatting your harddisk, or anything, really.

The Haskell foobar function, by contrast, can only take some data and return that data, unchanged. It cannot "look at" the data, because its type is unknown at compile-time. It cannot create new data, because... well, how do you construct data of any possible type? You'd need reflection for that. It can't perform any I/O, because the type signature doesn't declare that I/O is being performed. So it can't interact with the filesystem or the network, or even running threads in the same program! (I.e., it is 100% guaranteed thread-safe.)

As you can see, by not letting you do a whole bunch of stuff, Haskell is allowing you to make very strong guarantees about what your code actually does. So tight, in fact, that (for really polymorphic code) there's usually only one possible way that the pieces can fit together.

(To be clear: It's still possible to write Haskell functions where the type signature doesn't tell you much. Int -> Int could be just about anything. But even then, we know that the same input will always produce the same output with 100% certainty. Java doesn't even guarantee that!)

Body:
Lots of people have listed good things about Haskell. But in answer to your specific question "why does the type system make programs more correct?", I suspect the answer is "parametric polymorphism".

Consider the following Haskell function:

foobar :: x -> y -> y

There is literally only one possible way to implement this function. Just by the type signature, I can tell precisely what this function does, because there is only one possible thing it can do. [OK, not quite, but almost!]

Stop and think about that for a moment. That's actually a really big deal! It means if I write a function with this signature, it's actually impossible for the function to do anything other than what I intended. (The type signature itself can still be wrong, of course. No programming language will ever prevent all bugs.)

Consider this function:

fubar :: Int -> (x -> y) -> y

This function is impossible. You literally cannot implement this function. I can tell that just from the type signature.

As you can see, a Haskell type signature tells you a hell of a lot!

Compare to C#. (Sorry, my Java is a little rusty.)

public static TY foobar<TX, TY>(TX in1, TY in2)

There are a couple of things this method could do:

Return in2 as the result.

Loop forever, and never return anything.

Throw an exception, and never return anything.

Actually, Haskell has these three options too. But C# also gives you the additional options:

Return null. (Haskell does not have null.)

Modify in2 before returning it. (Haskell does not have in-place modification.)

Use reflection. (Haskell does not have reflection.)

Perform multiple I/O actions before returning a result. (Haskell won't let you perform I/O unless you declare that you perform I/O here.)

Reflection is a particularly big hammer; using reflection, I can construct a new TY object out of thin air, and return that! I can inspect both of the objects, and do different actions depending on what I find. I can make arbitrary modifications to both of the objects passed in.

I/O is a similarly big hammer. The code could be displaying messages to the user, or opening database connections, or reformatting your harddisk, or anything, really.

The Haskell foobar function, by contrast, can only take some data and return that data, unchanged. It cannot "look at" the data, because its type is unknown at compile-time. It cannot create new data, because... well, how do you construct data of any possible type? You'd need reflection for that. It can't perform any I/O, because the type signature doesn't declare that I/O is being performed. So it can't interact with the filesystem or the network, or even running threads in the same program! (I.e., it is 100% guaranteed thread-safe.)

As you can see, by not letting you do a whole bunch of stuff, Haskell is allowing you to make very strong guarantees about what your code actually does. So tight, in fact, that (for really polymorphic code) there's usually only one possible way that the pieces can fit together.

(To be clear: It's still possible to write Haskell functions where the type signature doesn't tell you much. Int -> Int could be just about anything. But even then, we know that the same input will always produce the same output with 100% certainty. Java doesn't even guarantee that!)


问:
What is the difference of smoke testing and black-box testing?
Main theme of my question is about the differences of Smoke Testing and other types of software testing specially Black-box testing but also I'm very curoius to know what is the purpose of this naming? how smoke testing is related to Smoke (or perhaps smoking)?

P.S:
my question is a bit more specific than  this question

答:
Basically, in smoke testing you turn on the system, especially for the first time ever, and see whether it starts to emit smoke... which would be a sign that something is very wrong with it. It doesn't tell you anything beyond that, but it can still be valuable to avoid further effort on something that is obviously not going to work at all.

According to Wikipedia, the words "smoke test" originated from plumbing, where smoke was forced through pipes to find leaks.  Electronics engineers began using the term to identify a basic power-on test; if the equipment didn't smoke, it passed the test.  Software engineers use the term to identify tests that confirm basic functions of the software.  The term is meant to be somewhat humorous.

Black-box testing is simply testing something from the outside, via its API, with no information (or while pretending not to have any information) about the implementation. The two terms are not related in any way; "black box testing" refers only to software.  Compare White Box testing, which tests internal structures or workings of an application, as opposed to its functionality.


问:
Leaving intentional bugs in code for testers to find
We don't do this at our firm, but one of my friends says that his project manager asked every developer to add intentional bugs just before the product goes to QA. This is how it works:

Just before the product goes to QA, the development team adds some intentional bugs at random places in the code. They properly back up the original, working code to make sure that those bugs aren't shipped with the end product.

Testers are also informed about this. So they will test hard,
because they know there are bugs present and that not finding them might
be considered as a sign of incompetence.

If a bug (intentional or otherwise) has been found, they will be reported for the development team to fix. The development team then adds another intentional bug in a related section of the code just before the product goes to the second-level QA. The project manager says a tester should think like a developer and he/she should expect new bugs in sections where changes were made.

Well, this is how it goes. They say that this approach has following advantages.

Testers will be always on their toes and they will test like crazy.
That helps them to also find hidden (unintentional) bugs so developers
can fix them.

Testers feed on bugs. Not finding any bugs will affect their morale.
So giving them an easy one to find will help their morale.

If you ignore the scenario where one of these intentional bugs gets shipped with the final product, what are the other drawbacks we should consider before even thinking of adopting this approach?

Some clarifications:

They properly backup the original code in source control.

When a tester finds the intentional bug, the development team just ignores it. If tester finds out an unintentional (original) bug, the development team first checks whether it is caused by any of the intentional bugs. That is, the development team first tries to reproduce that on the original working code and tries to fix it if they can.

Just ignore the relationship issues between QA and development team. I specifically asked this question on Programmers, not on The Workplace. Consider that there is good rapport between QA and the development team, and they party together after working hours. The project manager is a nice, old gentleman who is always ready to support both teams (Godsend).

答:
One thing nobody else has mentioned yet: mutation testing.

This is where an automated tool takes your source code and deliberately inserts bugs into it. (E.g., delete a randomly-chosen statement, change an AND to an OR, or whatever.) It then runs your full test suite, and checks whether the tests pass.

If all tests pass, then there are two possibilities:

The thing that was changed doesn't do anything. In other words, you have dead code.

The change introduced a bug which your test suite isn't catching. You need more tests.

Note that, unlike your proposal, everything I've described above is automated. You're not wasting developers' time inserting pointless bugs by hand. And you're not wasting testers' time finding known bugs. The only thing you're using up is machine time, which is much cheaper. (Machines don't get bored of doing the same test 20,000 times. Humans stop caring after a while!)

I would suggest that automated mutation testing is a far, far better approach than the manual scenario you're talking about.

Note that if you ask a developer to manually insert bugs, the kind of bug you get is probably not representative of the kind of accidental mistakes humans might make. (E.g., if you haven't realised there's a possible race condition, you're unlikely to insert a deliberate one either.) Whether an automated tool manages to be more objective remains to be seen, of course…


问:
What are the real benefits of static code analysis?
Tools like pc-lint or QAC can be used to perform static code analysis on a code base.

In my experience the static analysis often yields a huge amount of noise, i.e. warnings on things that are not real bugs but somehow violate one of the rules in a given rule set. Turning off certain rules (either for good in the rule set or via special comments in the code) can be a real cumbersome process.

What are the real benefits of static code analysis?

答:
Static analysis can also be performed without tools, by performing manual reviews on the software code. This is often the most cost-effective way to improve code quality.

The second best option is to invest for one or more high-end static analysis tools (like earlier mentioned Coverity, or KLOCwork). Since these tools perform much deeper analyses than lint, for example, the signal-to-noise ratio is much better.

I consider using lint as the third option, because of the high noise level. Applying lint to an existing project can be a daunting task.

In general static program analysis has progressed a lot over the recent years. Current static analysis tools are capable of performing deep interprocedural analyses, an can automatically identify for example procedure pre- and post-conditions. This can be a great help for later code reviews as well.


问:
What's the best way to store class/type info in a plugin system in your software?
There are lots of applications like 3ds Max, Maya, etc that allows you to use plugins, where even the default nodes are created as plugins.

This is all good but if the developer changes the class/type name of any node, then all the files using the previous version breaks.

It's like you commit to a name and that name cannot be changed. I am not an expert in designing these systems but wouldn't it be better to use some other info like a GUID for every plugin to create this link between which plugins are being used in a file?

So if you have a node like "deform", and later you realize "bend" is better, and you rename it, then everything still works fine. Note that in these systems, there are class/type names and Labels, I am talking about the former, as changing Label names doesn't break anything.

But the node class/type is still used everywhere in the app visually so seeing "deform" in those places but "bend" in a few other UI elements would be confusing.

I just thought GUIDs would allow you to basically bind the type/class of a specific plugin to its instances used in files without the issue of collision with other plugins.

答:
While this is a bit subjective, there are good reasons for using a GUID or other value that is not coupled to the name of a plugin.

You allude to the fact that there are several global properties to a plugin:

A label, which is user presentation. This does not change the identity of the plugin and may change, for example, due to internationalization.

Plugins must also have a class or function that loads it and makes it "go." This is a source code identifier.

Plugins should have a static ID such as a name or GUID. This is what you are asking about.

Clearly, the first two identifiers are not optimal. One is user-facing and mutable, the second has specific implementation problems (e.g. C++ name mangling). However, in languages such as Java and C# with pervasive namespacing through packages that is mitigated somewhat, but still less than ideal.

The third option is clearly superior. If a plugin or class name changes, the plugin is still identified as installed and needing to load. Preferences are still linked.

Why go with a GUID over an arbitrary name? A name may have trademark or copyright implications that force the author to change it. Perhaps a plugin's scope changes, making the name inaccurate. Maybe the name translates to something taboo in a foreign language. There are plenty of reasons.

GUIDs get around these issues. Practical limitations aside, they are pretty much guaranteed to be unique, are not real words in any human language, and should never need to change.

As to why any particular software program uses whatever method they use to identify plugins, you need to contact the program's authors. If I were writing a software that implements a plugin framework today, I would use GUIDs.


答:
The term "smoke testing" can be thought of as a sanity check. These are quick tests to get a quick, overall view of whether or not the system seems to be working. It isn't careful, methodical testing. For example, smoke testing might catch things like obvious freezes or obvious integration problems.

Black box testing is a completely different category. Black box testing means that the testers should have no idea of the implementation of the application, and should be using it from the point of view of an end-user. Now, that could encompass smoke testing -- it would be like an end-user's sanity check of the system. Or, black box testing could be a software testing methodically trying to stress the system through use to find where its operation may break down.

What would be an example of something you would not do with black box testing? You would not, for example, manually enter bad data in a back end database to see how the system handles such data. That is not testing from the point of view of an end-user: meaning, via the application's interface. If you could somehow get bad data into the database by entering it via the interface, that would be black box testing.

Title: What is the difference of smoke testing and black-box testing?

Body:
Main theme of my question is about the differences of Smoke Testing and other types of software testing specially Black-box testing but also I'm very curoius to know what is the purpose of this naming? how smoke testing is related to Smoke (or perhaps smoking)?

P.S:
my question is a bit more specific than  this question


答:
These two types of testing are not directly related.

A smoke test is a quick system test with the purpose of finding major flaws in a software artifact. For example, a test might deploy a web app to a test server, validate that it deploys and starts up, and the server can service simple requests. This would validate that the application file (e.g. WAR file in Java) was built correctly and is not missing anything important.

The expectation here is that QA will need to perform much more in-depth testing to validate the system. But if a build process breaks and the delivery artifact is unusable, why waste anyone's time testing if the application will not even start?

Black box testing is really a category of testing, not a specific type of test. It is any test that assumes no knowledge about the inner workings of a module of code.

One good real-world example of black box testing was many years ago when IBM dominated the PC market. Other manufacturers wanted to break into the (then) lucrative hardware market. The issue was IBM's BIOS was locked down and they would not license their chips to competitors. Several competitors performed black box testing to figure out the inner workings of the BIOS, and made their own clones.

Unit tests are also ideally a form of black box testing. A good unit test is written to the interface of a class or method, not the implementation. This helps developers avoid "coddling" their code, i.e. avoiding input values that might break it. Good unit tests are black box tests because they are impartial and try to break the code in any way possible.


问:
How to test Windows .NET TCP program handling of connection failure
I've written my own C# TCP communications module (using SocketAsyncEventArgs, although that's presumably irrelevant). My module runs at both ends of the connection, client and server. As part of the programming it is supposed to detect when the connection fails, and then automatically try to reestablish the connection.

I'd like to hear idea about how to test this. One solution is to run it on two physical machines and unplug the network cable for a while and then reconnect. This isn't very automated.

I'm wondering if there is some kind of WinSock hook program that can be used to simulate connection failures? Or any other suggestions?

答:
First, I think this is a perfectly good question. It's an interesting area and i don't get why was this downvoted.

You don't need winsock you can disable the network a adapter and change it's settings programmatically... but network issues could be very tricky to simulate this way...
https://code.msdn.microsoft.com/windowsapps/Disableenable-network-8112f642

I'm assuming this is an integration test of some sort....

What I would do is make a small component to function as a proxy \ bridge. So that the tested app will talk to the bridge, and the "bridge" would transfer it's traffic to wherever it was intended. Then you can use the "bridge" app to simulate any kind of network issue you may need i.e. latency, jitter, lost packets, disconnects...

There are tools for this you should look up before writing your own...

http://jagt.github.io/clumsy/

https://github.com/tylertreat/Comcast


问:
How does Polyglot Persistence handle relational data?
I have recently been studying up on microservices, and an associated idea that I've seen is that of polyglot persistence and microservices working with their own databases, or whatever storage they may be using. My question is how does this model handle relational data that may span more than one service?

For example, say you have a microservice for dealing with Customer information, and one dealing with Orders. I would assume an Order would need a way to reference a given Customer in its storage model, which I believe a relational database handles well, but if these microservices truly have independent databases, how is this handled?

As a side note, I've worked with one large relational database in my organization for the last three years, so I could understand if my thinking has been clouded by repetition, but I am very eager to understand this concept. Thanks!

答:
"Polyglot persistence" is just a fancy name for "heterogenous data stores" (which I suppose is also a fancy name).  You can solve the problem in a number of ways:

Have "One Table to Rule Them All:" a specific Primary Key in a specific database is the master identifier for a particular entity,

Have mapping tables that map the keys of one data store to the keys of another,

Use keys that are globally-unique, like GUIDs.


问:
How can I argue convincingly against duplicating database columns?
I've started working at a new organization and one of the patterns I've been seeing in the database is duplicating fields to make writing queries easier for the business analysts. We're using Django and its ORM.

In one case, we keep a MedicalRecordNumber object with a unique string identifying a patient in a certain context. We have Registration objects which track patients and have associated MedicalRecordNumbers, but rather than using a foreign key relationship, they duplicate the string so they can avoid writing a join (not for performance reasons). This pattern is common throughout the database.

For me the importance of a data model being clean is just so I can think about it well. Needless complexity is a waste of my limited cognitive processing time. It's a systematic problem. Not being comfortable writing joins is a rectifiable skills issue. I don't necessarily want to advocate going back and changing the schema, but I'd love to be able to convincingly articulate the problems with this type of duplication.

答:
Quit.

Honestly, you can spend months arguing about normalization, consistency, and fighting crazy bugs caused by sheer laziness, and then quit.

Or you can just save time, and frustration and quit now.

Good programmers are very lazy people. They understand customer and management needs. But most importantly they understand that solving problems well, using well designed, and well implemented solutions saves them personally HUGE amounts of work, effort, and most importantly agony and stress.

So you would be much better working at a place that understands and values good engineering.

Good Luck.

Afterthought :
Maybe what they need are BI / OLAP tools...
http://en.wikipedia.org/wiki/Online_analytical_processing


问:
Why do I need to map arguments to instance variables?
```<code>Class BankAccount:

    def __init__(self, accID, name, balance):
        self.accID = accID
        self.name = name
        self.balance = balance
</code>```

In the code above, why is it that I'm required to map all of my arguments to instance variables? This just seems like a waste of time. I'm using the exact same names, and the only difference is that I prepend them with the 'self' keyword. Why can't I just use the argument names? In python, things seem to get rather unwieldy when an object's constructor takes in many arguments.

I understand the obvious -- that it is a requirement of the langugage -- but I was wondering why virtually all OO languages are implemented this way.

答:
The purpose of a constructor method is to construct an object.  Your constructor parameters are scoped to the constructor method, so unless you save them in instance variables, they are lost once your constructor method goes out of scope.  This is how parameters work in any method; they are local to the method, not global to the class.

Your constructor method might simply map the parameter values to member variables, but it might do something completely different.  Your programming paradigm needs the flexibility to allow you to do both.

Constructor methods typically don't return anything.  An ordinary method can perform useful work with parameters without involving instance variables, since you can actually return something from the method.


问:
Architecture: Are form default values considered business logic and where should the logic to calculate them be placed?
An example of default form values on a search form might be:

Start Date - Today

End Date   - The last day of the next month

Obviously, these are fairly simple examples, but default values can get a lot more complex and potentially rely on "real business logic" (from an entity).

A search form is a good example because it does not have a corresponding entity.

So what is a good way to encapsulate complex default value logic? Perhaps the view model? Maybe create a new business object? Or should it just go in the view/controller responsible for rendering the form?

This is an ASP.NET Webforms application and my particular problem is where to put the logic to decide how the feed back regarding an event is categorized.

答: I asserted that default values are business logic and should be tested as such in a recent code review. It's not hard to pull the initialization logic out into whatever component owns "presenting" your view. In essence, ask yourself why a default value should be treated any different from a.. I don't know.. "normal" value. If you concede default values are special, you are willfully ignoring logic just because it seems to be trivial.


答:
In a MVC type web application, default values being submitted with a form request should generally be placed in the view directly.  This is to say that the controller shouldn't care what arrives, so long as the parameters are valid (and as these things go, it is always a good idea to check user input).

However, it is also true that default values can get complicated as you mentioned.  Say that you want the default starting date to be when an order was placed.  If this were a web application, of course you don't have this information readily.  You'd have to pass it to the page so that the page could use it as a default value.

In this case, I would argue that you should allow the possibility of not submitting a starting date.  The server, upon seeing that a starting date isn't provided, would provide the default.  These types of parameters, unlike those which are constant or don't depend on the state of your model, should be considered business logic and should have their defaults taken from the model portion of the application.  If done right, the user will not have many parameters with defaults, but rather only a few mandatory parameters with the possibility to add additional parameters.  This makes your request much more organic and you have less validation to worry about, thus also making it more robust.  In addition, your view will become more intuitive to use.

Title: Architecture: Are form default values considered business logic and where should the logic to calculate them be placed?

Body:
An example of default form values on a search form might be:

Start Date - Today

End Date   - The last day of the next month

Obviously, these are fairly simple examples, but default values can get a lot more complex and potentially rely on "real business logic" (from an entity).

A search form is a good example because it does not have a corresponding entity.

So what is a good way to encapsulate complex default value logic? Perhaps the view model? Maybe create a new business object? Or should it just go in the view/controller responsible for rendering the form?

This is an ASP.NET Webforms application and my particular problem is where to put the logic to decide how the feed back regarding an event is categorized.


答:
There are cases where a simple one-to-one mapping is not appropriate. Automatically assigning parameters to instance variables only works sometimes, not all of the time. Perhaps validation is needed, or an exception might be thrown. Maybe a parameter must be scaled, or another object created.

Consider a Java BigDecimal. Internally it has a BigInteger and an integer scale. I see exactly one constructor out of many that accepts those two parameter types. Why go through the effort of having an automatic mapping that is of niche use a lot of the time? Most of those constructors likely have to perform additional processing to convert the parameters into its internal state. Those are a type of convenience constructor.

Furthermore, such a feature might encourage leaky abstractions. While that feature alone is not leaky, it could encourage lazy programmers to make all of the constructors they write to accept precisely the object's internal state as parameters.

Title: Why do I need to map arguments to instance variables?

Body:
```<code>Class BankAccount:

    def __init__(self, accID, name, balance):
        self.accID = accID
        self.name = name
        self.balance = balance
</code>```

In the code above, why is it that I'm required to map all of my arguments to instance variables? This just seems like a waste of time. I'm using the exact same names, and the only difference is that I prepend them with the 'self' keyword. Why can't I just use the argument names? In python, things seem to get rather unwieldy when an object's constructor takes in many arguments.

I understand the obvious -- that it is a requirement of the langugage -- but I was wondering why virtually all OO languages are implemented this way.


问:
Testing code in Java that is only loosely defined
My question is about testing in general. At school, professors say that testing has to be written before we begin to write some code.
I guess we need to use EasyMock to represent the classes not written yet.
But I think something is wrong in my understanding of that concept.

How can you write testing code when nothing has been defined except interfaces?

And if you do it, when do you run the tests? Once you've defined the classes and you've written the code, EasyMock has no place; you can use JUnit for testing.

答:
This is the driving motivation behind Test-driven development, with the principles being thus:

You do not write code without tests.

You write just enough code for the test to pass.

You refactor the code that you have written and ensure that tests pass.

I think I understand what you're getting at - you don't know if you can/should write tests for objects you haven't defined yet.  If you're following TDD, you should at least define the class, and once you've done that, you can start writing tests.

Interfaces are nicer since you don't have to care about what concrete object is implementing it, so long as the tests pass.  Then you'd declare the interface and a class that implements it, but nothing more.

The main guiding principle is that you are always running tests.  Every time you change that single unit of code you run the test against it to ensure that breakage hasn't occurred.  When you're done, you run the suite.

To that point, EasyMock is only a mocking framework - it's meant to pretend that an instance of a defined class exists.  There's a time and place for mocks, and this is not one of them; you're not going to gain anything by mocking out a class that has no definitions.

OwnerDisplayName: Makoto


答:
The idea behind test-driven development is that your tests are written in the form of scripts, running through the flow that a user or client package would take if they made use of the software you are about to write.

Obviously at first your test classes will be full of errors which complain that the classes and methods don't exist (or they do exist but simply throw an exception which says that the method has not yet been implemented). But, once your test script outlines the scope and expected behaviour of these embryonic methods, the next step is to write code for all of those classes and methods, and keep running your test scripts until every test passes.

Alongside these flow scripts, you need to have unit tests which attack every method with every type of valid and illegal parameter. Tests should exist to make sure that null parameters, empty/zero parameters, and parameters of the wrong form are handled appropriately, either by throwing an exception in the case of invalid data or returning the result expected in the case of valid data.

Even if you set out to write all tests before writing any actual application code, you'll probably find that you end up writing new application code before writing tests for it, at least some of the time.

Title: Testing code in Java that is only loosely defined

Body:
My question is about testing in general. At school, professors say that testing has to be written before we begin to write some code.
I guess we need to use EasyMock to represent the classes not written yet.
But I think something is wrong in my understanding of that concept.

How can you write testing code when nothing has been defined except interfaces?

And if you do it, when do you run the tests? Once you've defined the classes and you've written the code, EasyMock has no place; you can use JUnit for testing.

OwnerDisplayName: Arkanon


答:
I understand the obvious -- that it is a requirement of the language -- but I was wondering why virtually all OO languages are implemented this way.

Because there is a difference between the type (or type constructor) and the constructor (or data constructor). By mixing these concepts, you're making assumptions about what the programmer wants - preventing them from having multiple constructors for the same type.

That said, C# 6 is introducing primary constructors to do this sort of stuff:

https://msdn.microsoft.com/en-us/magazine/dn802602.aspx

I also did this in an iteration of Tangent because I explicitly wanted to unify type constructors and data constructors, because by tying a single data constructor to a type made it much easier (read: possible) to mix the types together and still get a constructable type.


答:
This is a very very broad question... Too broad to really answer well...

Are we talking about things like days of the week? are we talking about things that matter only to the UI, and the Business Logic doesn't care about? are we talking about values that arise from real Business Logic?

Some default values come directly from Business Logic. Eg. employ rank, is a product a fruit or a vegetable, preferred payment method. usually these values come from a predefined set, and can change with time and requirements. These values and their deaf ult should probably come from data i.e. a Data Base. which will leave them free to easily change, and the UI won't care. Sometimes these values have more clever logic behind them, for example the "Waze" app offering you to drive home, or to work depending on where you are.

Sometimes default values are only relevant to the UI and user usability. If I have a method like SearchSomething(Time start, Time end) in the BL (business layer). I couldn't care less about the values i get, and maybe different clients would like to have different defaults? So it's something that should be determined in the UI, but I wouldn't want to soil an MVC view with this. I think it's more appropriate as a part of a model.

Some default values are so common and trivial it doesn't matter where you put them. you could naively put them in the UI, in the view itself, or in some Constants class in the BL. Depending on what you actually need...


答:
I used to work on a project where the version was incremented after every added feature. We used semantic versioning so after each change we could increment the version according to whether it was a bugfix, a compatible or an incompatible change. The release version was the version we arrived at after all changes that got into this release.

This meant that releases were not "continuous": the release after 4.5.2 might be 6.3.1, not neccessarily 4.6.0 or 5.0.0. This was OK in that particular project. Of course if your version is used for marketing to end users, you probably won't be allowed to use this scheme.

Personally, I found this way of versioning very convenient. It removes the issue altogether - each version displays its very own version number, there are no "versions in between" about which you would need to worry.

Title: How to mark next version in the source code?

Body:
We are developing a software that gets released every few months, and it is either a major version (1.0.x -> 2.0.0) or a minor version (-> 1.1.x). This version is visible in the software, say that we have a variable for it like this:

```<code>var version = '1.0.0';
</code>```

and then it's displayed somehow:

```<code>print(version);
</code>```

When we release 1.0.0 and start working on "vNext", it just feels wrong to leave 1.0.0 there because all the developers and testers will see a "wrong" version in the app. However, at that point we are not sure what the next version will be called - it might be 1.1 or 2.0. I've thought about possibly just marking the next version as "DEV" so that there is no expectation of a certain version number but am not sure this is a good idea (and it's certainly not in semver format so some other code may be broken if it works with the version number in any way). Another idea was to just call it "post-1.0" but that's not a proper version format, too.

Have you ever run into this situation, and how did you deal with it?


答:
Because of inheritance.

In a language without inheritance, the constructor could simply map its arguments to the object's fields in a one-to-one manner. If the mapping isn't one-to-one, you can always hide the constructor and provide a static method to do the work and pass the final values to the constructor. Case in point, this is how many functional languages handle it.

However, with inheritance, you run into a problem - you need to initialize the parent class's fields. The language could force you to declare the subclass constructor such that it includes all of the parent class's fields, but which values do you pass? The logic for initializing them is locked away in the parent class's static factory method. You'd need to reimplement that logic, and that could be impossible if you don't have the source code and the logic is undocumented.

That said, there's no reason why the language can't provide syntactic sugar for it.


答:
From a language structure point of view: Because of scope. Parameters passed in to a function are only valid and accessible within that function. Instance variables are valid and accessible in every function.

Furthermore, by definition function parameters are passed in to the function from a caller. So they do not reside within the object: they reside in the caller. They must, of necessity, represent two different physical areas in memory.

I suppose that in principle you could have a language where any parameters in a function that have the same name as object variables are automatically copied before the first line of the function is executed. My first thought is that that could cause trouble, because there are surely times when you would not want such an automatic copy. There might well be validity tests that should be done before saving any data. We might want to test if a new value equals the old value and so some logging. Etc. I suppose someone could reply that in that case you could just give the parameter a different name.

For two or three variables, I generally see it as no big deal. Yes, when there are 15 variables passed in and all have to be assigned to the correct object variable, it's a pain. I'd be interested in seeing a language that had a feature to do this cleanly.

Frankly, what I usually do is create the object and then have a bunch of assignment statements. Like

```<code>myfoo=new Foo();
myfoo.bar=42;
myfoo.plugh="fwacbar";
... etc ...
</code>```

This can be more clear than having a long string of values in the constructor, where it may not be obvious which variable each value goes to. (Especially small integers and Booleans.) It's only slightly more typing to write the assignment statements rather than a long parameter list. In the not-uncommon case where the constructor is only called once or twice, it might be less typing, as it eliminates the parameter list and simply moves the assignments from the constructor to the caller.

Of course it has the drawback that it only works if all the values are straight assignments with no validation or manipulation. And in some cases we can say that a constructor with all the values produces a valid, usable object; while this technique means it almost certainly does not, which some consider a violation of the constructor contract.

Body:
From a language structure point of view: Because of scope. Parameters passed in to a function are only valid and accessible within that function. Instance variables are valid and accessible in every function.

Furthermore, by definition function parameters are passed in to the function from a caller. So they do not reside within the object: they reside in the caller. They must, of necessity, represent two different physical areas in memory.

I suppose that in principle you could have a language where any parameters in a function that have the same name as object variables are automatically copied before the first line of the function is executed. My first thought is that that could cause trouble, because there are surely times when you would not want such an automatic copy. There might well be validity tests that should be done before saving any data. We might want to test if a new value equals the old value and so some logging. Etc. I suppose someone could reply that in that case you could just give the parameter a different name.

For two or three variables, I generally see it as no big deal. Yes, when there are 15 variables passed in and all have to be assigned to the correct object variable, it's a pain. I'd be interested in seeing a language that had a feature to do this cleanly.

Frankly, what I usually do is create the object and then have a bunch of assignment statements. Like

myfoo=new Foo();
myfoo.bar=42;
myfoo.plugh="fwacbar";
... etc ...

This can be more clear than having a long string of values in the constructor, where it may not be obvious which variable each value goes to. (Especially small integers and Booleans.) It's only slightly more typing to write the assignment statements rather than a long parameter list. In the not-uncommon case where the constructor is only called once or twice, it might be less typing, as it eliminates the parameter list and simply moves the assignments from the constructor to the caller.

Of course it has the drawback that it only works if all the values are straight assignments with no validation or manipulation. And in some cases we can say that a constructor with all the values produces a valid, usable object; while this technique means it almost certainly does not, which some consider a violation of the constructor contract.


问:
Verifying absence of an event in multithreaded unit test
I've got a legacy application that had a fragile unit test (which is really more of an integration test) that used a lot of Thread.Sleep calls to wait for events to happen.

While trying to introduce some determinism into the tests with some configurable callbacks I came across a test that is attempting to validate that given a certain input, another event doesn't occur.

It is also using Thread.Sleep to wait for 100ms before checking to see if the callback was called, but I'm thinking that a delay in execution could result in a false positive.

I'm trying to keep the test suite snappy without introducing longer delays by increasing the value of the wait.

For the positive tests I've created some code barriers that get resolved through the course of the test, but I don't see a pattern to deterministically determine that an event is not going to occur.

答: Set some variable (accessible to your unit test) when the event occurs.  If the event doesn't occur, the variable doesn't get set; you can check for that in your unit test.</p>


答:
You usually don't need to.  Scala, for example, just keeps the arguments to the primary constructor in scope throughout the object's lifetime.  It turns out, the vast majority of the time that's all you need, especially if you support default values.

However, you still have to support those other cases that the other answers enumerated.  Most languages optimized their design to cover the largest number of cases consistently, rather than optimizing for brevity in the most frequent case at the expense of more complexity and less consistency in handling the less frequent cases.

Partially, this is because as a language designer, it's difficult to tell what will actually be the most frequent case in the wild, or what the real-world consequences would be of sometimes holding onto a reference to a constructor argument that you no longer need.


答:
Here is a simple way to do it. Since it must be a higher version then the current, the minimal required increment is a minor version. Use that to start with.

If later the decision is made to change it to a new major version change it again.

Why make it more complex?


答:
I develop in a heavily embedded environment, so I'll add in another option:

Our devices have a query command to grab the firmware version, and will return the result with a 2-byte number on success. The problem with the above responses is that it may be impractical to add tags like "pre" when you're limited on your data output format.

What we've decided to do is add a binary mask to our version number that would not normally be there. For example, a timeline of our development might be:

0x0048 (previous stable version)

0x8049 (first stage beta, working version 0, bit15 is the prerelease flag, bit14 - bit12 used as beta dev stages )

0x8149 (first stage beta, working version 1)

0x9049 (second stage beta, working version 0)

0x0049 (final public release)


答:
Multiple approaches are available for this, mostly convention and politics than technical actually.

If you can take research what is done for large open source projects you may find lots of good inspiration.

An example of what I 've done for a project I worked for.

Versions marked Major.Minor.Patch.Build.  build was generated by the build system so development versions would only have three numbers whereas "official" (aka automatically created from the build system) versions would have all 4.

The version on the head would always be the next version, so if the last release was 1.3.5, the version committed was 1.3.6.

If we needed to release a minor or major release we would first commit the new version numbers then do the build, then commit the next version.

However, things rarely go perfect first time around so what actually got done was :

1 - Branch to a release branch and bump version if needed (if releasing major or minor)
2 - Bump the version on the main branch so it represents the next version that would be released.  (always assumed to be a patch on the last release)
Stabilize the version to be released and merge fix on main branch.
Work normally on the main branch.

In our situation the version was marked in a file (per-product) containing the first 3 digits, build ID was managed entirely by the build system.

This is just an example.  there are many others and variations that you can use.  It depends a lot on the work habits of your teams (branch etc) the capabilities of your build system, the marketing of your products etc so no single solution fits all.

Hope this helps.


答:
Instead of using a magic number (variable) that is not "present" while viewing code I suggest another approach:

Do the versioning with directories, e.g.

```<code>/the_project/1.0/src/files
/the_project/1.1/src/files
/the_project/2.0/src/files
/the_project/2.1/src/files
</code>```

This way when people are navigating the code they should have little doubt about which version they are in because it's part of the directory path that they are browsing.

Body:
Instead of using a magic number (variable) that is not "present" while viewing code I suggest another approach:

Do the versioning with directories, e.g.

/the_project/1.0/src/files
/the_project/1.1/src/files
/the_project/2.0/src/files
/the_project/2.1/src/files

This way when people are navigating the code they should have little doubt about which version they are in because it's part of the directory path that they are browsing.


问:
Global / Application settings and testing
We have a global dictionary of application settings (read from a DB on start-up and refreshed when required) and a static class with a bunch of methods to get these settings. This is historic, but I see no reason why it would be done differently today unless it adds value in testing...

The options for swapping out values for testing different scenarios I think include:

Updating the database values before the test

Mock the static methods and intercept the ones you need and allow defaults for the ones that don't impact the test

Refactor code to take in a settings instance (e.g. IDepartmentApiSettings) at construction time (constructor injection) and use this instead of the static methods

The first two work without code change, so are preferred on the legacy code. The third therefore would only be viable for new code (or code that can be easily refactored).

Now here's my question, is there any real advantage to injecting the settings in this way? Or would you live with static methods and use option 1 or 2 to keep consistency across the code base?

Note: Code is C# but that shouldn't make any difference, would be the same question for Java, so I won't tag it.

答:
Personally, I would not like to live with static methods to keep consistency across a code base.

The advantages, whether you consider them "real" or not, of injecting the settings lie, as always in the freedom gained and the disadvantages avoided.

I'd always prefer to inject a settings instance as it ties you down the least and doesn't force you to use a mocking framework.

Mocking the static methods is the next best, I guess. As you are in C# and static and virtual don't mix there, I can't think of a convenient way - like using a test descendant and overriding the methods - to mock the methods without using a mocking framework.

Updating the database values before the test is horrible. As your tests then have an external dependency, they automatically become integration tests. It can work, but either you have to make your tests all use the same values or update the values every test method execution. The first is horribly restrictive. The latter will slow down your tests extremely and make everybody turn them off... No use having them in that case.

In short: injection prefered, use mocking the static methods as a crutch if you can't afford to update all uses of your static settings class to an injection pattern all in one go.

If I understand your setup with the settings class correctly, another option might be to keep your static class, make reading the values from the database happen as part of an initialization call on that class. Give the initialization method two parameters: one name/value pairs or whatever you like that you can pass in from your tests to populate your settings dictionary, the other to indicate whether values should be read from the database. Make the defaults to be an empty list of name/value pairs and "yes" read from db. (You may need to use overloads in C# to allow for default parameter values).

Now you also have your hands free for testing without affecting production use of the static class.

Production code would simply call Initialize without using any parameters at some point in the startup of your application.

Test code can call with an empty list and "no" to clear the settings.

Test code can call with a list of name/value pairs and "no" to provide a limited set of specific values (clearing out what was there before if you so desire).

Test code can call with a list of name/value pairs and "yes" to provide overrides to whatever will be read from the database.


答:
You test these by mocking the client and server and using IP Address 127.0.0.1

Depending on the test you are performing, it could be a simple matter of having the mock-server simply closing its end of the connection after some predefined time and then verifying that the client reconnected within the specified time-frame.

It may be difficult to test some of the possible error conditions that could occur at the TCP and IP layers but most of those errors you don't care about anyways, as your main concern is handling errors that are reported by the higher level socket interface. So being able to automatically create any one of similar low level errors will be an adequate test for your application level unit test.

Title: How to test Windows .NET TCP program handling of connection failure

Body:
I've written my own C# TCP communications module (using SocketAsyncEventArgs, although that's presumably irrelevant). My module runs at both ends of the connection, client and server. As part of the programming it is supposed to detect when the connection fails, and then automatically try to reestablish the connection.

I'd like to hear idea about how to test this. One solution is to run it on two physical machines and unplug the network cable for a while and then reconnect. This isn't very automated.

I'm wondering if there is some kind of WinSock hook program that can be used to simulate connection failures? Or any other suggestions?


答:
What you describe is a thinly-veiled coating over Singleton. Essentially, you have global state and are trying to funnel access through that one class. The fact that the interface is static instead of object-owned is the "coating" I referred to.

This is one of the few acceptable uses for Singleton. While that pattern is often misapplied, providing a single point of access to what is a single configuration is one okay use.

What I would do is go one step further and decouple the implementation of "get these global settings" from "by calling this static method." This is your option three.

Code example:

public class Settings {
  private static final Settings instance;
  static {
    // Insert code to create a Settings and populate instance dynamically here.
    // By default create a Settings, but allow tests to override with a subclass.
  }

  // Example of how to delegate:
  public static int getMaxWidgets() {
    return instance.getMaxWidgetsImpl();
  }

  protected int getMaxWidgetsImpl() {
    // Call the DB here, but allow subclasses to override.
    return ...;
  }
}
```

What this does is allow you to swap out (inject) a different implementation of the code that looks up settings using some mechanism. Maybe call a method to change it. In Java, I might use a system property with the class name. The point is, it is very easy to change the implementation and none of the application code is any wiser.

Title: Global / Application settings and testing

Body:
We have a global dictionary of application settings (read from a DB on start-up and refreshed when required) and a static class with a bunch of methods to get these settings. This is historic, but I see no reason why it would be done differently today unless it adds value in testing...

The options for swapping out values for testing different scenarios I think include:

Updating the database values before the test

Mock the static methods and intercept the ones you need and allow defaults for the ones that don't impact the test

Refactor code to take in a settings instance (e.g. IDepartmentApiSettings) at construction time (constructor injection) and use this instead of the static methods

The first two work without code change, so are preferred on the legacy code. The third therefore would only be viable for new code (or code that can be easily refactored).

Now here's my question, is there any real advantage to injecting the settings in this way? Or would you live with static methods and use option 1 or 2 to keep consistency across the code base?

Note: Code is C# but that shouldn't make any difference, would be the same question for Java, so I won't tag it.

Body:
What you describe is a thinly-veiled coating over Singleton. Essentially, you have global state and are trying to funnel access through that one class. The fact that the interface is static instead of object-owned is the "coating" I referred to.

This is one of the few acceptable uses for Singleton. While that pattern is often misapplied, providing a single point of access to what is a single configuration is one okay use.

What I would do is go one step further and decouple the implementation of "get these global settings" from "by calling this static method." This is your option three.

Code example:

public class Settings {
  private static final Settings instance;
  static {
    // Insert code to create a Settings and populate instance dynamically here.
    // By default create a Settings, but allow tests to override with a subclass.
  }

  // Example of how to delegate:
  public static int getMaxWidgets() {
    return instance.getMaxWidgetsImpl();
  }

  protected int getMaxWidgetsImpl() {
    // Call the DB here, but allow subclasses to override.
    return ...;
  }
}

What this does is allow you to swap out (inject) a different implementation of the code that looks up settings using some mechanism. Maybe call a method to change it. In Java, I might use a system property with the class name. The point is, it is very easy to change the implementation and none of the application code is any wiser.


问:
How do you build the confidence to work on large projects?
So I'm a programmer who works in telecom. I'm currently in school as well and I'm also an avid gamer (shocker). I said this to form my question: Take a big game title such as DotA 2 - how do you know when you're ready to work on a system that complicated?

I work on web applications at work, but they aren't all that complicated. From my perspective, the little errors I make in web dev would never fly in a company like Valve when their game reaches 11 million people monthly. This could apply to any large company with products whose code must hold up at all times. After all, big errors in the code could mean a loss of big dollars.

What I'm asking is, how does one get confident enough to know that code I'm writing is robust enough to not have an insane error show up, while working on a huge system like an online game? How does one approach coding in the midst of incredibly complex systems while producing minimal to no errors?

答:
Two things:

Split software into manageable pieces, each of which is simple and intuitive on its own. Most software that actually works is already like this to some degree, and usually you only need to work in one part at a time, so it's a lot more doable than it might seem at first. When something really is too hard to understand, that doesn't mean you suck, it means the code needs refactoring.

Get in all the cliche good software development habits. Write automated tests. Use a bug/issue tracker. Automate build/deployment stuff as much as possible. Document your public interfaces. Design things before hacking away at the code. Follow YAGNI and SOLID to the degree that they make sense. Even if you're the only one working on a project, all these things help you in the long run, and when you start seeing those long-term benefits kick in, that's a massive confidence boost.


问:
How can I transition to a job using the Microsoft stack?
I graduated from university with a computer science degree (BSc), having done some C, C++, Java, Python, and Oracle along the way. I did some freelancing while I was at university and carried this into a full time job when I graduated, and I've been working full time for a year now.

PHP isn't really what I want to do, and I think it's limiting my opportunities the longer I stay along this path. It's not a language I like to use on a daily basis, and I would like to work in a larger organization, where it doesn't seem PHP has much use.

I want to stay in web development, and there seems to be plenty of jobs for the Microsoft stack: C#, SQL Server, and ASP.NET MVC. But beyond a half semester writing common-line C++ in Visual Studio, I have no experience with Microsoft technology.

Where do I start to make the transition to landing a job in a Microsoft shop? Are there any specific certifications I should be focusing on, or university courses I should be taking? What are employers or recruiters looking for?

What can I do besides creating a pet project in my spare time?

答: Certification is unlikely to get you any notice. Actually, your best bet may simply be to build something cool using the MS stack and throwing it up on the web, sort of like a portfolio project. Another thing would be to start answering Stack Overflow questions in C# and ASP and then apply through SO Careers (I notice that you've mostly answered PHP and JS questions).</p>


问:
Why is there no default constructor generated if you define an explicit constructor?
```<code>class Employee{

    String name;
    int id;

   //No explicit constructors
}
</code>```

Now I can invoke the following statement:

```<code>Employee e1 = new Employee();
</code>```

With the above code, the compiler will provide the definition for the constructor Employee().

If I define a single explicit constructor as follows:

```<code> class Employee{

    String name;
    int id;

    Employee(String aName){
        this.name=aName;
    }
}
</code>```

Now, why can't I invoke the following statement:

```<code>Employee e2 = new Employee();
</code>```

Even though the compiler knows how to provide definition of Employee().

Now, just because I have defined an explicit constructor Employee(String aName), why can't I use a default constructor?

Also, if the compiler had allowed the use of the default constructor even after defining an explicit one, it would have helped us to reuse the code for default constructor.

答:
If you define a constructor with a parameter, then there must be a valid reason in doing so. Maybe this parameter is so important to your class that without it the object state is invalid. That is why the Java does not make a no-argument constructor for you when you already define one.

If you decide that it would be handy to have no-arg constructor, then you can still define it:

```<code>Employee(){
  // good practice to call existing constructor with your favorite value
  this("");
}
</code>```

Body:
If you define a constructor with a parameter, then there must be a valid reason in doing so. Maybe this parameter is so important to your class that without it the object state is invalid. That is why the Java does not make a no-argument constructor for you when you already define one.

If you decide that it would be handy to have no-arg constructor, then you can still define it:

Employee(){
  // good practice to call existing constructor with your favorite value
  this("");
}


答:
Beyond mocking the network interface, you don't need two physical machines for a system test:

Disable/reenable the network card using scripts that do ifconfig/ipconfig.

use a virtual machine for one end of the system and script it up/down or enable/disable the networking.

Hooking into WinSock is way more work than you need to do here.


问:
How do I actually use Selenium to automate UI testing?
We have a large inventory system where we work and making changes has the possibility to break things in other areas. This happens a lot, and it is hard to manually test for everything every time because something even as simple as a Javascript action applied to a text field can stop working.

Most of the manual tests would consist of entering data in certain fields and submitting that and ensuring no errors are given. How would I use Selenium to automate this kind of regression testing?

We have used Unit testing programs such as PHPUnit for other applications which were more standard, however these kinds of tests need to test a whole system, not just isolated parts, so PHPUnit is not as ideal.

答:
Yes selenium can be used to automate the manual interaction steps.

It's intended to be used against web browsers and it's widely used and implemented.

However this is only half of the puzzle.  Selenium is the core technology in  browser automation tools, APIs and frameworks.  To actually USE selenium you are going to need to pick an actual implementation.

You can start of with the IDE plug-in for Firefox.  This is nearly always referred to as a quick and dirty, temporary solution.  It does not need to be.  If you use it to record existing interactions and try and play them back, or do selections based on text, then yes, the test suites you create will be brittle.  If you use good practices such as css ID's and HTML data-attributes you can create robust and complex automation this way.

It also has the benefit of actually letting you, or even your product team, see the automation for themselves.
It has the downside of only running in the browser IDE that it is implemented which I believe is still just Firefox so starting it is still a manual step.

The other, more extensive and maintainable options is to use Selenium from within test framework such as Ruby On Rails with Rspec and Capybara which enable you to write scripts which can be run headless and against different browsers.  This approach has the downside of not showing you the actual screens which might have visual layout issues.

Programming Languages & Frameworks

Languages are supported through drivers with commands from the Selenium API as methods/functions.

Testing frameworks that can be used with Selenium:

C#  - Frameworks: NUnit Haskell

Java - Frameworks: JUnit, TestNG

JavaScript

Objective-C

Perl

PHP - Frameworks: Behat + Mink, Yii

Python - Frameworks: unittest, pyunit, py.test, robot framework

R

Ruby - Frameworks: RSpec, Test::Unit

See also:

How can you write tests for Selenium (or similar) which don't fail because of minor or cosmetic changes?

and

Selenium and non technical team members

and in convincing the business to support:

What problem does automated user interface testing solve?


问:
In C is it possible to change http requests to https
Long story short I've got this package that currently has a security risk where credentials are sent over http and I need to convert them to https but I currently lack the knowledge to do so. Could anyone point me in the right direction on how to go about this?

Just for the record I did not create this program but became its proxy maintainer for Gentoo as to keep it available for the community and since its kinda my first package I don't want to lose it.

答:
It sounds like you're asking how to take "http data" and convert it to "https data" so that it's automatically more secure when you send it into the internet. That's not how it works.

HTTPS is a different protocol, in which SSL is used to establish a secure connection with the other endpoint before sending regular HTTP packets. Whether you want to set this up directly with OpenSSL or a higher-level library depends on what your program is trying to accomplish and what library/ies it's currently using for networking.


问:
Move Files Using Git mv Or Use File System Instead
I am wondering what the difference in Git would be if I used the mv command versus moving it in Windows explorer. From Perforce I know it's important because the version system keep track of the file origin. I am wondering if this is just as important in Git or is it just the same as moving files in the file system?

The reason I am asking is because we are moving a lot of files around, and using the command line is pretty tedious.

答:
If you move the file in Windows Explorer, you still have to git add the new file location and git rm (or git add --all) the old file location. Once those two things are done, git will work out on its own that the new file is mostly identical to the old file, and will automatically display it as a move in commands like git status.

The benefit of git mv is that it combines the "Explorer move", git add and git rm all into one operation. When you're moving a single file, I see no reason not to use mv.

When I need to move or rename entire folders, I use Windows Explorer because that sort of thing is much easier in a GUI. When I'm done shuffling things around, I can tell git to process all the changes I made with a single git add --all . command from the top directory.


问:
Ways for beginner programmer to practice with C++
So i just finished my first semester of college. In my intro to programming class we made a bunch of super interesting (sarcasm) console applications. Any suggestions on ways other than just messing around with console applications for a beginner C++ student to improve?

答: Console applications are the best ways to learn C++. And rather than learning advanced C++, better learn the data structures first. Once you learn list, tress, graph etc. then you will have much more option in console applications. </p>


答:
Whether its window or unix, git mv basically combines three actions:

a file system move

a git delete of the original file

a git add of the new file.

So, without git rm, one might do (this is Unix/OSX but the steps are similar in windows unless using cygwin terminal emulator and then u probably can):

```<code>$ mv newfile movedfile
$ git status
On branch master
Changes not staged for commit:
  (use "git add/rm <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

        deleted:    newfile

Untracked files:
  (use "git add <file>..." to include in what will be committed)

        movedfile

no changes added to commit (use "git add" and/or "git commit -a")
$ git rm newfile
rm 'newfile'
$ git add movedfile
$ git status
On branch master
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

        renamed:    newfile -> movedfile

$ git commit -m"renamed"
[master 46332e4] renamed
 1 file changed, 0 insertions(+), 0 deletions(-)
 rename newfile => movedfile (100%)
$ git status
On branch master
nothing to commit, working directory clean
</code>```

whereas with git rm one can just do:

```<code>$ git mv newfile2 renamed_newfile2
$ git status
On branch master
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

        renamed:    newfile2 -> renamed_newfile2

$ git commit -m"renamed"
[master 8d1e296] renamed
 1 file changed, 0 insertions(+), 0 deletions(-)
 rename newfile2 => renamed_newfile2 (100%)
$ git status
On branch master
nothing to commit, working directory clean
</code>```

Title: Move Files Using Git mv Or Use File System Instead

Body:
I am wondering what the difference in Git would be if I used the mv command versus moving it in Windows explorer. From Perforce I know it's important because the version system keep track of the file origin. I am wondering if this is just as important in Git or is it just the same as moving files in the file system?

The reason I am asking is because we are moving a lot of files around, and using the command line is pretty tedious.

Body:
Whether its window or unix, git mv basically combines three actions:

a file system move

a git delete of the original file

a git add of the new file.

So, without git rm, one might do (this is Unix/OSX but the steps are similar in windows unless using cygwin terminal emulator and then u probably can):

$ mv newfile movedfile
$ git status
On branch master
Changes not staged for commit:
  (use "git add/rm <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

        deleted:    newfile

Untracked files:
  (use "git add <file>..." to include in what will be committed)

        movedfile

no changes added to commit (use "git add" and/or "git commit -a")
$ git rm newfile
rm 'newfile'
$ git add movedfile
$ git status
On branch master
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

        renamed:    newfile -> movedfile

$ git commit -m"renamed"
[master 46332e4] renamed
 1 file changed, 0 insertions(+), 0 deletions(-)
 rename newfile => movedfile (100%)
$ git status
On branch master
nothing to commit, working directory clean

whereas with git rm one can just do:

$ git mv newfile2 renamed_newfile2
$ git status
On branch master
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

        renamed:    newfile2 -> renamed_newfile2

$ git commit -m"renamed"
[master 8d1e296] renamed
 1 file changed, 0 insertions(+), 0 deletions(-)
 rename newfile2 => renamed_newfile2 (100%)
$ git status
On branch master
nothing to commit, working directory clean


问:
How to upload a C# project to Github without visual studio
I would like to know  How to upload a C# project  to Github without visual studio?
What do i need and how would I do it?</p>

答:
You can follow Github's guide to getting your project on Github.

Generically, there are several options, assuming you've installed git and possibly a git-related utility:

via commandline

via a UI

See this Stackoverflow post for more info.