答:
Well, the motivation (backwards compatibility) is both an advantage and a disadvantage. It is disadvantage because we all would prefer to have reifiable types, but the price to pay was high. Consider the design choices in C#. They have reifiable types, but now they have duplicate APIs. So, imagine a Java API where we also had duplicate APIs for every parameterized class. Now, picture yourself porting thousands of lines of code from legacy classes to the new generic classes. Now, who would not consider duplicate APIs a disadvantage? But hey, they have reifiable types!

So, the major motivation was "evolution, not revolution". And logically, every decision has tradeoffs.

Besides the other disadvantages mentioned, we could also add the fact that type erasure can be difficult to reason about at compile time, since it is not evident that certain types will be removed, and this leads to very weird and hard to find errors.

The existence of bridge methods (this compiler syntactically-generated methods to keep binary compatibility) can also be seen as disadvantage. And these can be precisely one of the reasons of errors I mentioned in the previous paragraph.

Major disadvantages derive from the already obvious fact that there is a single class and not multiple classes for generic types. As another example consider that overloading a method with same generic class fails in Java:

```<code>public void doSomething(List<One>);
public void doSomething(List<Two>);
</code>```

Something that could be seen as a disadvantage of reifiable types (at least in C#) is the fact that they cause code explosion. For instance List<int> is one class, and a List<double> is another totally different, as it is a List<string> and a List<MyType>. So classes have to be defined at runtime, causing an explosion of classes and consuming valuable resources while they are being generated.

Regarding the fact that it is not possible to define a new T() in Java, mentioned in another answer, it is also interesting to consider that this is not only a matter of type erasure. It also requires the existence of a default constructor, that is why C# requires a "new constraint" for this. (See Why new T() is not possible in Java, by Alex Buckley).

Title: Generics and Type-erasure

Body:
Generics in Java are implemented using type erasure. The JLS  says that the inspiration was backward compatibility. Where as on the other hand C# generics are reifiable.

Theoretically what are the advantages and disadvantages by having Generics as "erasure" or "reifiable"?

Is Java missing onto something?

Body:
Well, the motivation (backwards compatibility) is both an advantage and a disadvantage. It is disadvantage because we all would prefer to have reifiable types, but the price to pay was high. Consider the design choices in C#. They have reifiable types, but now they have duplicate APIs. So, imagine a Java API where we also had duplicate APIs for every parameterized class. Now, picture yourself porting thousands of lines of code from legacy classes to the new generic classes. Now, who would not consider duplicate APIs a disadvantage? But hey, they have reifiable types!

So, the major motivation was "evolution, not revolution". And logically, every decision has tradeoffs.

Besides the other disadvantages mentioned, we could also add the fact that type erasure can be difficult to reason about at compile time, since it is not evident that certain types will be removed, and this leads to very weird and hard to find errors.

The existence of bridge methods (this compiler syntactically-generated methods to keep binary compatibility) can also be seen as disadvantage. And these can be precisely one of the reasons of errors I mentioned in the previous paragraph.

Major disadvantages derive from the already obvious fact that there is a single class and not multiple classes for generic types. As another example consider that overloading a method with same generic class fails in Java:

public void doSomething(List<One>);
public void doSomething(List<Two>);

Something that could be seen as a disadvantage of reifiable types (at least in C#) is the fact that they cause code explosion. For instance List<int> is one class, and a List<double> is another totally different, as it is a List<string> and a List<MyType>. So classes have to be defined at runtime, causing an explosion of classes and consuming valuable resources while they are being generated.

Regarding the fact that it is not possible to define a new T() in Java, mentioned in another answer, it is also interesting to consider that this is not only a matter of type erasure. It also requires the existence of a default constructor, that is why C# requires a "new constraint" for this. (See Why new T() is not possible in Java, by Alex Buckley).


问:
If you should only have one assertion per test; how to test multiple inputs?
I'm trying to build up some test cases, and have read that you should try and limit the number of assertions per test case.

So my question is, what is the best way to go about testing a function w/ multiple inputs.  For example, I have a function that parses a string from the user and returns the number of minutes.  The string can be in the form "5w6h2d1m", where w, h, d, m correspond to the number of weeks, hours, days, and minutes.

If I wanted to follow the '1 assertion per test rule' I'd have to make multiple tests for each variation of input?  That seems silly so instead I just have something like:

```<code>self.assertEqual(parse_date('5m'), 5)
self.assertEqual(parse_date('5h'), 300)
self.assertEqual(parse_date('5d') ,7200)
self.assertEqual(parse_date('1d4h20m'), 1700)
</code>```

In the one test case.  Is there a better way?

答:
Purists would say that assertions for different values of input should be put in separate test methods within the test class. One reason for this is that, depending on your testing UI, it's often easier to distinguish between individual test failures than between individual assertions, which might lead you to identify the source of failure more quickly.

When testing with JUnit we can get around this by using the version of assert* methods with an initial String argument to differentiate one assertion from another within the same test method.

```<code>self.assertEqual("just minutes", parse_date('5m'), 5)
self.assertEqual("just hours", parse_date('5h'), 300)
self.assertEqual("just days", ('5d') ,7200)
self.assertEqual("days, hours, minutes", parse_date('1d4h20m'), 1700)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Purists would say that assertions for different values of input should be put in separate test methods within the test class. One reason for this is that, depending on your testing UI, it's often easier to distinguish between individual test failures than between individual assertions, which might lead you to identify the source of failure more quickly.

When testing with JUnit we can get around this by using the version of assert* methods with an initial String argument to differentiate one assertion from another within the same test method.

self.assertEqual("just minutes", parse_date('5m'), 5)
self.assertEqual("just hours", parse_date('5h'), 300)
self.assertEqual("just days", ('5d') ,7200)
self.assertEqual("days, hours, minutes", parse_date('1d4h20m'), 1700)


答:
Yeah, make multiple tests for each variation of input.

The main goal of the one assertion per test guideline is to have it (ideally) that one error leads to one test failure and vice versa so that you know exactly what failed. Then you can work with one very precise test to debug the root cause and verify. You can break this with one assert, and you can be okay with multiple asserts. In this particular scenario, I would have a test for each suffix and a few combinations of ordering.

Hopefully it is clear why isolating tests is a benefit: you waste less time debugging when something does go wrong. Now, if you're really sure that the test is unlikely to fail, and that overhead of hunting through the test is small, then maybe it makes sense to just test them all at once to save implementation time.

But history has shown that saving a little time writing code at the expense of reading/using code is never worth it. Hence the guideline.

Title: If you should only have one assertion per test; how to test multiple inputs?

Body:
I'm trying to build up some test cases, and have read that you should try and limit the number of assertions per test case.

So my question is, what is the best way to go about testing a function w/ multiple inputs.  For example, I have a function that parses a string from the user and returns the number of minutes.  The string can be in the form "5w6h2d1m", where w, h, d, m correspond to the number of weeks, hours, days, and minutes.

If I wanted to follow the '1 assertion per test rule' I'd have to make multiple tests for each variation of input?  That seems silly so instead I just have something like:

```<code>self.assertEqual(parse_date('5m'), 5)
self.assertEqual(parse_date('5h'), 300)
self.assertEqual(parse_date('5d') ,7200)
self.assertEqual(parse_date('1d4h20m'), 1700)
</code>```

In the one test case.  Is there a better way?


答:
A more pragmatic way to view the one assert per test "rule", is to have your asserts in a single test cover a single concept.

This way you are still testing a single concept in a single test. In your case, whether your input string is correctly parsed in a single date.

You should exercise your judgement on a case by case basis to check if you are better off testing a single concept with multiple asserts or having a single assert in a many tests.

Go for the option that makes for clearer tests, less repetition while still having your tests be able to highlight different points of failures in your method. You want it to be clear when a test fails exactly what happened rather than have to debug your test to find out what went wrong.


问:
Quality Assurance=inspections, reviews..?
Studying this subject extensively, the most books state the following:

Quality Assurance: prevention activity. Act of inspection, reviewing..

Quality Control: testing

While there are some exceptions that mention that QA deals with just processes (planning, strategy, standard application etc.) which is IMHO much closer to real QA, yet I cannot find any good reference in Google Books.

I believe that inspections, reviews, testing is all quality control as it is about checking products, no matter if it is the final one or work products. The problem is that so many authors do not agree.

I would be grateful for detailed explanation, ideally with a reference.

答:
I think this is an artificial distinction.  Inspection, reviewing, and testing are all activities designed to ensure quality of the product.

On the other hand, it may be meaningful to categorize these activities based on who performs them. In software development unit tests and code reviews are typically done by developers, while manual testing and possibly integration testing are typically done by QA people (aka Quality Engineers, aka testers, etc.). However, there are always exceptions: you may have QA people who help write unit tests, or you may have developers running manual tests.  Also, if you have an extensive test infrastructure (e. g. dedicated machines, a complex build system, etc.) you might have people whose job is to maintain it. Also, companies who can afford it often have usability specialists who help design and test user interfaces.

So, IMHO, QA, QC, and even "quality engineering" refer to the same thing, and trying to split hairs and come up with fine distinctions here is a waste of time.


答:
It depends very much on your testing library.  In the C# library NUnit you can doing something like:</p>

```<code>[TestCase('5m', 5)]
[TestCase('5h', 300)]
[TestCase('5d', 7200)]
[TestCase('1d4h20m', 1700)]
public void ParseDateTest(inputString, expectedMinutes)
{
    Assert.That(parse_date(inputString), Is.EqualTo(expectedMinutes));
}
</code>```

Body:
It depends very much on your testing library.  In the C# library NUnit you can doing something like:

[TestCase('5m', 5)]
[TestCase('5h', 300)]
[TestCase('5d', 7200)]
[TestCase('1d4h20m', 1700)]
public void ParseDateTest(inputString, expectedMinutes)
{
    Assert.That(parse_date(inputString), Is.EqualTo(expectedMinutes));
}


问:
Keeping a domain model consistent with actual data
Recently domain driven design got my attention, and while thinking about how this approach could help us I came across the following problem.

In DDD the common approach is to retrieve entities (or better, aggregate roots) from a repository which acts as a in-memory collection of these entities. After these entities have been retrieved, they can be updated or deleted by the user, however after retrieval they are essentially disconnected from the data source and one must actively inform the repository to update the data source and make is consistent again with our in-memory representation.

What is the DDD approach to retrieving entities that should remain connected to the data source? For example, in our situation we retrieve a series of sensors that have a specific measurement during retrieval. Over time, these measurement values may change and our business logic in the domain model should respond to these changes properly. E.g., domain events may be raised if a sensor value exceeds a predefined threshold.

However, using the repository approach, these sensor values are just snapshots, and are disconnected from the data source. Does any of you have an idea on how to solve this following the DDD approach?

答:
I think you need to separate out your areas of concern as they really are separate.  Considering them together just muddies the picture.

First, you have the representation of your SCADA / monitoring data and the periodic refreshes that will be required for it.

Second, you have the generation of events based upon sensor readings.

Most SCADA systems that I've worked with have some mechanism to periodically poll the data source in order to refresh the display.  You'll need a similar mechanism for your application.  This doesn't violate DDD, as DDD's focus is how the data is mapped to the domain not in how often it is retrieved.

Generally, sensor reads are a read-only type thing but overwrites may be necessary.  To allow for the overwrite, you'll need to keep track of the timestamp(s) associated with the changed value(s).  You'll need some function to then overwrite within the data store, or alternatively write to another table that has preferential retrieve access to the original values.  Again, this doesn't violate DDD.

For the second aspect, you'll need some sort of event monitoring agent.  Following a DDD approach should help you here.  Having the data schema align with the application structures as well as the business logic will make it easier to update rules as necessary.  I suspect your business object environment will be reasonably static so you won't have to worry about accommodating structural change all that often.  I imagine you'll have tweaks to alarm thresholds and / or new combinations of data streams for analysis.

Long answer short - DDD doesn't preclude any of the concerns you bring up.  It's more about how you structure your data.


问:
Why didn't "cloud computing" offer appear earlier?
Cloud computing is a model of renting resources - servers and data storage. Both servers and data storage have been around for much more than a decade so far. Yet cloud computing offers only appeared several years ago.

What's the deal here? What was the critical change that triggered massive adoption and massive marketing of cloud computing offers?

答:
Cloud computing is really time-sharing computing/shared hosting (very old models!) on modern hardware with virtualization to make things appear nicer (but again, that's pretty old; IBM has been doing virtualization on their hardware for decades). It's also what we do with that technology when we have the beginnings of ubiquitous networking. And it is the business model that goes with it; the ability to hire computing power or storage for very short amounts of time at minimal cost[*] greatly changes how you go about planning and using those resources.

So… the major technological change was network ubiquity, but that's not such a big thing really; the edges of that have been around for the whole of my professional career. No, it's the business model innovation that was the real difference. A sane way of making it work financially for all concerned without complex multi-year account management was the missing piece. I'm not quite sure who invented it first either: the earliest I know of is Amazon AWS (who have been thoroughly copied) but I really don't know if they were borrowing off of others.

So don't knock the business-heads who are raving about this like it's the greatest thing since sliced bread: I suspect they're actually right and most of us techies are just too focused on the implementation aspects to see it (and those have huge precedents in this case). Innovations that enable new major classes of use are important, even if they're not in areas that we know a vast amount about.

[* Not just monetary cost either, but also opportunity costs too. Being able to quicky respond to incidents is very valuable.]


问:
Views : ViewControllers, many to one, or one to one?
I have developed an Android application where, typically, each view (layout.xml) displayed on the screen has it's own corresponding fragment (for the purpose of this question I may refer to this as a ViewController).

These views and Fragments/ViewControllers are appropriately named to reflect what they display. So this has the effect of allowing the programmer to easily pinpoint the files associated with what they see on any given screen.

The above refers to the one to one part of my question.

Please note that with the above there are a few exceptions where very similar is displayed on two views so the ViewController is used for two views. (Using a simple switch (type) to determine what layout.xml file to load)

On the flip side. I am currently working on the iOS version of the same app, which I didn't develop. It seems that they are adopting more of a one-to-many (ViewController:View) approach.

There appears to be one ViewController that handles the display logic for many different types of views. In the ViewController are an assortment of boolean flags and arrays of data (to be displayed) that are used to determine what view to load and how to display it.

This seems very cumbersome to me and coupled with no comments/ambiguous variable names I am finding it very difficult to implement changes into the project.

What do you guys think of the two approaches? Which one would you prefer? I'm really considering putting in some extra time at work to refactor the iOS into a more 1:1 oriented approach.

My reasoning for 1:1 over M:1 is that of modularity and legibility. After all, don't some people measure the quality of code based on how easy it is for another developer to pick up the reigns or how easy it is to pull a piece of code and use it somewhere else?

答:
Disclosure - my approach may or may not align with strict interpretations of MVC, MVP, or MVVM.  But it is based upon my experience in working with those approaches.

In general, a VC should only have one View, but that's primarily driven by the fact that you won't have much overlap between Views.  I think the more important aspect is an indifference upon the VC's part about what the View actually is.  So if you need if and switch statements to couple your VC to your View then I think something is wrong.

The VC is there to drive data to the View but it doesn't care how the View presents the data as that's the View's job.  Likewise, the View doesn't care how the VC gets the data, it just knows that it will.  It's really the separation of responsibilities that's important.

"Well that's great" (~Denis Leary) but it doesn't address issues where you have duplication across the Views.  This is where I would take a slightly bastardized approach and allow a VC to be composed of other VCs but maintain a relationship of 1 View to 1 VC.  The "containing" VCs will bind to a View but the "contained" (child, members of containing VC, whatever you want to call it) won't necessarily have a View that they are bound to.  This provides a degree of re-use within your code without overly cluttering things.  It does fly in the face of some of the paradigms, so I would comment what you're doing.

Ultimately, you'll have one VC that handles retrieving | manipulating the data that is displayed on multiple Views.  But you'll need an additional "layer" of VCs to keep the code structure clean.

Alternatively, just duplicate the code at the VC layer and re-use calls to the Model instead.  I'm not a big fan of this as I like to think in terms of re-usable widgets when putting together my Views and ViewControllers.


问:
Did C++11 address concerns passing std lib objects between dynamic/shared library boundaries? (ie dlls and so)?
One of my major complaints about C++ is how hard in practice it is to pass std library objects outside of dynamic library (ie dll/so) boundaries.

The std library is often header-only. Which is great for doing some awesome optimizations. However, for dll's, they are often built with different compiler settings that may impact the internal structure/code of a std library containers. For example, in MSVC one dll may build with iterator debugging on while another builds with it off. These two dlls may run into issues passing std containers around. If I expose std::string in my interface, I can't guarantee the code the client is using for std::string is an exact match of my library's std::string.

This leads to hard to debug problems, headaches, etc. You either rigidly control the compiler settings in your organization to prevent these issues or you use a simpler C interface that won't have these problems. Or specify to your clients the expected compiler settings they should use (which sucks if another library specifies other compiler settings).

My question is whether or not C++11 tried to do anything to solve these issues?

答:
The specification never ever had this issue. That's because it has concept called "one definition rule", which mandates that each symbol has exactly one definition in the running process.

Windows DLLs violate this requirement. That's why there are all these problems. So it's up to Microsoft to fix it, not C++ standardization committee. Unix never had this problem, because shared libraries work differently there and by default conform to one definition rule (you can explicitly break it, but you obviously only do if you know you can afford it and need to squeeze out the few extra cycles).

Windows DLLs violate one definition rule because:

They hardcode from which dynamic library a symbol will be used during static link time and resolve symbols statically within the library that defines them. So if the same weak symbol gets generated in multiple shared libraries and those libraries than get used in single process, the dynamic linker has no chance to merge those symbols. Usually such symbols are static members or class impedimenta of template instances and it than causes problems when passing instances between code in different DLLs.

They hardcode whether symbol will be imported from dynamic library already during compilation. Thus code linked with some library statically is incompatible with code linked with the same library dynamically.

Unix using ELF format exports implicitly imports all exported symbols to avoid the first problem and does not distinguish between statically and dynamically resolved symbols until static link time to avoid the second.

The other issue is of compiler flags. That issue exists for any program composed from multiple compilation units, dynamic libraries don't have to be involved. However it's much worse on Windows. On Unix it does not really matter whether you link statically or dynamically, nobody links standard runtime statically anyway (in Linux it might even be illegal) and there is no special debug runtime, so one build is good enough. But the way Microsoft implemented static and dynamic linking, debug and release runtime and some other options means they caused combinatorial explosion of needed library variants. Again platform issue rather than C++ language issue.


问:
Is there an excuse for short variable names?
This has become a large frustration with the codebase I'm currently working in; many of our variable names are short and undescriptive. I'm the only developer left on the project, and there isn't documentation as to what most of them do, so I have to spend extra time tracking down what they represent.

For example, I was reading over some code that updates the definition of an optical surface. The variables set at the start were as follows:

```<code>double dR, dCV, dK, dDin, dDout, dRin, dRout
dR = Convert.ToDouble(_tblAsphere.Rows[0].ItemArray.GetValue(1));
dCV = convert.ToDouble(_tblAsphere.Rows[1].ItemArray.GetValue(1));
... and so on
</code>```

Maybe it's just me, but it told me essentially nothing about what they represented, which made understanding the code further down difficult. All I knew was that it was a variable parsed out specific row from a specific table, somewhere. After some searching, I found out what they meant:

```<code>dR = radius
dCV = curvature
dK = conic constant
dDin = inner aperture
dDout = outer aperture
dRin = inner radius
dRout = outer radius
</code>```

I renamed them to essentially what I have up there. It lengthens some lines, but I feel like that's a fair trade off. This kind of naming scheme is used throughout a lot of the code however. I'm not sure if it's an artifact from developers who learned by working with older systems, or if there's a deeper reason behind it. Is there a good reason to name variables this way, or am I justified in updating them to more descriptive names as I come across them?

答:
Surely this is what // comments are for?

If the assignments have comments which are descriptive you get the best of both worlds:  a description of the variable and any equations are easily comparable with their text book counterpart.


问:
Why should a class be anything other than "abstract" or "final/sealed"?
After 10+ years of java/c# programming, I find myself creating either:

abstract classes: contract not meant to be instantiated as-is.

final/sealed classes: implementation not meant to serve as base class to something else.

I can't think of any situation where a simple "class" (i.e. neither abstract nor final/sealed) would be "wise programming".

Why should a class be anything other than "abstract" or "final/sealed" ?

EDIT

This great article explains my concerns far better than I can.

答:
A class should neither be final/sealed nor abstract if:

It's useful on its own, i.e. it's beneficial to have instances of that class.

It's beneficial for that class to be the subclass/base class of other classes.

For example, take the ObservableCollection<T> class in C#. It only needs to add the raising of events to the normal operations of a Collection<T>, which is why it subclasses Collection<T>. Collection<T> is a viable class on its own, and so it ObservableCollection<T>.

ContentLicense: CC BY-SA 4.0


答:
No.

There is a lot of work going on to replace the header system, feature which is called Modules and which could have an impact on this, but certainly not a big one.

Title: Did C++11 address concerns passing std lib objects between dynamic/shared library boundaries? (ie dlls and so)?

Body:
One of my major complaints about C++ is how hard in practice it is to pass std library objects outside of dynamic library (ie dll/so) boundaries.

The std library is often header-only. Which is great for doing some awesome optimizations. However, for dll's, they are often built with different compiler settings that may impact the internal structure/code of a std library containers. For example, in MSVC one dll may build with iterator debugging on while another builds with it off. These two dlls may run into issues passing std containers around. If I expose std::string in my interface, I can't guarantee the code the client is using for std::string is an exact match of my library's std::string.

This leads to hard to debug problems, headaches, etc. You either rigidly control the compiler settings in your organization to prevent these issues or you use a simpler C interface that won't have these problems. Or specify to your clients the expected compiler settings they should use (which sucks if another library specifies other compiler settings).

My question is whether or not C++11 tried to do anything to solve these issues?


答: Test classes seem to come to mind. These are classes that are called in an automated fashion or "at will" based on what the programmer/tester is trying to accomplish. I'm not sure I've ever seen or heard of a finished class of tests that's private. </p>

Title: Why should a class be anything other than "abstract" or "final/sealed"?

Body:
After 10+ years of java/c# programming, I find myself creating either:

abstract classes: contract not meant to be instantiated as-is.

final/sealed classes: implementation not meant to serve as base class to something else.

I can't think of any situation where a simple "class" (i.e. neither abstract nor final/sealed) would be "wise programming".

Why should a class be anything other than "abstract" or "final/sealed" ?

EDIT

This great article explains my concerns far better than I can.


答:
Ironically, I find the opposite: the use of abstract classes is the exception rather than the rule and I tend to frown on final/sealed classes.

Interfaces are a more typical design-by-contract mechanism because you do not specify any internals--you are not worried about them. It allows every implementation of that contract to be independent. This is key in many domains. For example, if you were building an ORM it would be very important that you can pass a query to the database in a uniform way, but the implementations can be quite different. If you use abstract classes for this purpose, you end up hard-wiring in components that may or may not apply to all implementations.

For final/sealed classes, the only excuse I can ever see for using them is when it is actually dangerous to allow overriding--maybe an encryption algorithm or something. Other than that, you never know when you may wish to extend the functionality for local reasons. Sealing a class restricts your options for gains that are non-existent in most scenarios. It is far more flexible to write your classes in a way that they can be extended later down the line.

This latter view has been cemented for me by working with 3rd party components that sealed classes thereby preventing some integration that would have made life a lot easier.


答:
Generally, I believe that the rule for this, should be that you can use extremely short variable names where you know that people who are "skilled in the art" of your particular code will immediately understand the reference of that variable name. (You always have comments for the exception of this case anyway), and that the localized usage of the variables can easily be discerned based on the context of how they are used.

To expand on this, it means that you shouldn't go out of your way to obfuscate your variable names, but, you can use abbreviations for your variables names, where you know that only people who understand the underlying concept of your code are likely to read it anyway.

To use a real world example, recently, I was creating a Javascript class that would take a latitude, and tell you the amount of sunlight that you would expect on a given date.

To create this Sundial class, I referred to perhaps half a dozen resources, the Astronomy Almanac, and snippets from other languages, (PHP, Java, C etc).

In almost all of these, they used similar identical abbreviations, which upon the face of it mean absolute nothing.

K, T, EPS, deltaPsi, eot, LM, RA

However, if you have knowledge of physics you can understand what they were. I wouldn't expect anyone else to be touching this code, so why use verbose variable names?

julianTime, nutationOfEclipticalLongitudeExpressedInDegrees, equationOfTime, longitudeMean, rightAscension.

Additionally, a lot of the time, when variable names are transitory, that is to say, they are only used to temporarily allocate some value, then it frequently doesn't make sense to use a verbose version, especially when the context of the variable explains it's purpose.

Title: Is there an excuse for short variable names?

Body:
This has become a large frustration with the codebase I'm currently working in; many of our variable names are short and undescriptive. I'm the only developer left on the project, and there isn't documentation as to what most of them do, so I have to spend extra time tracking down what they represent.

For example, I was reading over some code that updates the definition of an optical surface. The variables set at the start were as follows:

```<code>double dR, dCV, dK, dDin, dDout, dRin, dRout
dR = Convert.ToDouble(_tblAsphere.Rows[0].ItemArray.GetValue(1));
dCV = convert.ToDouble(_tblAsphere.Rows[1].ItemArray.GetValue(1));
... and so on
</code>```

Maybe it's just me, but it told me essentially nothing about what they represented, which made understanding the code further down difficult. All I knew was that it was a variable parsed out specific row from a specific table, somewhere. After some searching, I found out what they meant:

```<code>dR = radius
dCV = curvature
dK = conic constant
dDin = inner aperture
dDout = outer aperture
dRin = inner radius
dRout = outer radius
</code>```

I renamed them to essentially what I have up there. It lengthens some lines, but I feel like that's a fair trade off. This kind of naming scheme is used throughout a lot of the code however. I'm not sure if it's an artifact from developers who learned by working with older systems, or if there's a deeper reason behind it. Is there a good reason to name variables this way, or am I justified in updating them to more descriptive names as I come across them?


问:
Requiring multithreading/concurrency for implementation of scripting language
Here's the deal: I'm looking at designing my own scripting/interpreted language for fun. I'm only in the planning stages right now; I want to make sure I have a very strong hold on exactly how I will implement everything before I start coding.

What I'm currently struggling with is concurrency. It seems to me like an easy way to avoid the unpredictable performance that comes with garbage collection would be to put the garbage collector in its own thread, and have it run concurrently with the interpreter itself. (To be clear, I don't plan to allow the scripts to be multithreaded themselves; I would simply put a garbage collector to work in a different thread than the interpreter.) This doesn't seem to be a common strategy for many popular scripting languages, probably for portability reasons; I would probably write the interpreter in the UNIX/POSIX threading framework initially and then port it to other platforms (Windows, etc.) if need be.

Does anyone have any thoughts in this issue? Would whatever gains I receive by exploiting concurrency be nullified by the portability issues that will inevitably arise? (On that note, am I really correct in my assumption that I would experience great performance gains with a concurrent garbage collector?) Should I move forward with this strategy or step away from it?

答:
am I really correct in my assumption that I would experience great
  performance gains with a concurrent garbage collector?

I don't think so.

First of all, even if you manage to build a totally cost-free GC, you'd only get "great performance gains" if current in-thread GC's were great performance sinks.  Experience in modern GC implementations point otherwise.  Some of them are quite light.

Second, by nature, a GC touches lots of memory while other thread(s) are working on it, so you have to be really careful to avoid quite nasty race conditions.  Any lock you put there will be significantly contented, making them expensive operations.  Even if you manage to use lock-free structures (not for the faint of heart!), tight coupling between the GC thread and the interpreter would make each CAS operation a cache-trashing point.

In my opinion, the extra complexity required for an out-of-thread GC makes them impractical unless you want to go for full multi-threading.  In that case, you've already paid most of the contention costs, so dedicating a thread to GC makes sense.

Note that most heavily multithreaded JVM implementations (like Azul's one) do have an out-of-thread GC, but still try to do most management in-thread to avoid the fail-and-retry pattern that lock-free structures are prone to in heavy load.


答:
From a java perspective I think that final classes are not as smart as it seems.

Many tools (especially AOP, JPA etc) work with load time waeving so they have to extend your clases. The other way would be to create delegates (not the .NET ones) ad delegate everything to the original class which would be much more messy than extending the users classes.


问:
How to specify WIP limits in Kanban?
Consider a typical Kanban board:

Input, Analysis, Dev Ready, Development, Build Ready, Test, Release Ready

How to specify WIP limits for each column? any formula?

答:
While I agree there is no formula as such - at the same time there is the real possibility of modelling your Kanban process. This will help you simulate likely outcomes for things such as Cycle Time, Wait Time, Efficiency, etc.

I have implemented such a simulator which models our Kanban process. It simulates the flow of stories across the board under our Kanban constraints around WIP limits and team resources.
We have a state requiring external customer review. We all suspected that this stage was something killing our Cycle Time by backing up our stories.

The gut feel was to time box this stage but we didn't know if this would simply push the problem elsewhere. Nor did we know how far to go with the time boxing nor how big an improvement it would make.

It's all very well saying just carry on tweaking but it can be very disruptive. People will get used to a process and get frustrated with someone constantly trying to tweak on a hunch. So you often have to make a very good case before implementing change.

When you model you can tweak without disruption and have a far greater confidence that your tweaks are going to deliver the outcome you want. Plus it will go someway to getting you your magic formula.

OwnerDisplayName: The Legend of 1982

Title: How to specify WIP limits in Kanban?


答:
That is a great article by Eric Lippert, but I don't think it supports your viewpoint.

He argues that all classes exposed for use by others should be sealed, or otherwise made non-extensible.

Your premise is that all classes should be abstract or sealed.

Big difference.

EL's article says nothing about the (presumably many) classes produced by his team that you and I know nothing about.  In general the publicly-exposed classes in a framework are only a subset of all the classes involved in implementing that framework.


问:
How do .so files avoid problems associated with passing header-only templates like MS dll files have?
Based on the discussion around this question. I'd like to know how .so files/the ELF format/the gcc toolchain avoid problems passing classes defined purely in header files (like the std library). According to Jan in that answer, the dynamic linker/loader only picks one version of such a class to load if its defined in two .so files. So if two .so files have two definitions, perhaps with different compiler options/etc, the dynamic linker can pick one to use.

Is this correct? How does this work with inlining? For example, MSVC inlines templates aggressively. This makes the solution I describe above untenable for dlls. Does Gcc never inline header-only templates like the std library as MSVC does? If so wouldn't that make the functionality of ELF described above ineffective in these cases?

答:
I'm not sure I understand. If you build parts of your program with different incompatible flags, it's not a .so or .dll problems, the same problems will appear with static libraries as well.

First note that I stopped programming for Windows in 94. So nearly all my understanding about Windows behavior comes from the net and discussions with colleagues working on Windows and may be outdated, misremembered badly understood facts.

It is customary on Windows to include the standard library in .DLL. That's not the case on Unix (and I get it isn't mandatory on Windows).

Default symbol resolution on Windows prefer the DLL, on Unix it will be the normal search (in both, you may changing it).

It's considered bad practice on Unix to make debug libraries which aren't substitutable for the optimized one.  Yes this limit the instrumentation which can be done, but it make a lot of thing easier.  We may do special instrumented libraries which need a total recompilation when they are worthwhile, but it's not the case for routine debug builds. My understanding is that MSC++ compiler ships with some libraries which aren't substitutable if you compile user code in debug or optimized (I've heard horror stories with #defining new for instance, which seems to me a very bad idea even for special instrumented builds). Nothing of Windows forces you to do that bad practice (but if the standard C++ library is in that case, you probably have to use a saner standard library).


问:
Graduated transition from Green - Yellow - Red
I am having algorithm mental block in designing a way to transition from Green to Red, as smoothly as possible with a, potentially, unknown length of time to transition.

For testing purposes, I will be using 300 as my model timespan but the methodology algorithm design needs to be flexible enough to account for larger or even smaller timespans.

Figured using RGB would probably be the best to transition with, but open to other color creation types, assuming its native to.Net (VB/C#).

Currently I have:

```<code>t = 300
x = t/2
z = 0
low = Green (0, 255, 0)
mid = Yellow (255, 255, 0)
high = Red (255, 0, 0)
</code>```

Lastly, sort of an optional piece, is to account for the possibility of the low, mid, and high color's to be flexible as well.  I assume that there would need to be a check to make sure that someone isn't putting in low = (255,0,0), mid=(254,0,0), and high=(253,0,0). Outside of this anomaly, which I will handle myself based on the best approach to evaluate a color.

Question:

What would be the best approach to do the transition from low to mid and then from mid to high?

What would be some potential pitfalls of implementing this type of design, if any?

答:
You can't really do it smoothly using the RGB color space, but it's easier when done with HSV.

See HSL and HSV

Using HSV space you can transition from Green to Yellow to Red along a single float value for Hue while keeping the saturation/value constant.


答:
While you can do the transition in RGB space (using component-wise linear interpolation), this might cause unnaturally-looking transitions; most noticably, the brightness and saturation may bump between control points. If it this is acceptable, just do it this way. Mapping the values through some sort of gamma function before interpolating and then reverting the gamma on the interpolated values may alleviate the bumps a bit.

If that's not good enough, convert your colors into a color space closer to how the human perception works, such as HSI (hue - saturation - intensity). Then apply the same interpolation, but do keep in mind that the hue component is circular, that is, if you have hues ranging from 0 to 100, and your input colors are at 95 and 5, you want to move forward and then wrap around (thus 95 up to 100 and then "jump" to 0, continuing up to 5) instead of going down from 95 to 5 - think of the hue axis as a circle along which you travel; your interpolation should take the shorter route along the circle's edge.

The HSI calculation is more expensive, because you have to convert the interpolated HSI value back to RGB for display on each frame, but it yields much better results, because the hue, brightness and saturation transition independently without causing perceived artifacts.

Title: Graduated transition from Green - Yellow - Red

Body:
I am having algorithm mental block in designing a way to transition from Green to Red, as smoothly as possible with a, potentially, unknown length of time to transition.

For testing purposes, I will be using 300 as my model timespan but the methodology algorithm design needs to be flexible enough to account for larger or even smaller timespans.

Figured using RGB would probably be the best to transition with, but open to other color creation types, assuming its native to.Net (VB/C#).

Currently I have:

```<code>t = 300
x = t/2
z = 0
low = Green (0, 255, 0)
mid = Yellow (255, 255, 0)
high = Red (255, 0, 0)
</code>```

Lastly, sort of an optional piece, is to account for the possibility of the low, mid, and high color's to be flexible as well.  I assume that there would need to be a check to make sure that someone isn't putting in low = (255,0,0), mid=(254,0,0), and high=(253,0,0). Outside of this anomaly, which I will handle myself based on the best approach to evaluate a color.

Question:

What would be the best approach to do the transition from low to mid and then from mid to high?

What would be some potential pitfalls of implementing this type of design, if any?


问:
Using Visual Studio as a Task-Focused IDE
Are there patterns or libraries or any official Microsoft SDK for using Visual Studio as a specifically Task-Focused UI?

For example, both Revolution R (IDE for the R language) and SQL 2012 (and I think SQL 2008 and possibly 2005) use Visual Studio as the underlying IDE framework.

Is there an officially supported SDK and/or examples/samples for doing this type of thing?

I am building a language Parser for an existing language - whose only available IDE is INSANELY expensive - using Irony (and eventually will generate a Language Service as well).

Any direct or indirect suggestions/answers are appreciated.

答:
You might want to have a look at Visual Studio Shell.  The Visual Studio 2012 Shell (Isolated) provides a foundation on which you can build your own custom-branded tools environment.

Visual Studio Shell is part of the Visual Studio SDK.  A redistributable runtime is provided.

See also http://studioshell.codeplex.com/


答:
The problem with final/sealed classes is that they are trying to solve a problem that hasn't happen yet. It's useful only when the problem exists, but it's frustrating because a third-party has imposed a restriction. Rarely does sealing class solve a current problem, which makes it difficult to argue it's usefulness.

There are cases where a class should be sealed. As example; The class manages allocated resources/memory in a way that it can not predict how future changes might alter that management.

Over the years I've found encapsulation, callbacks and events to be far more flexible/useful then abstracted classes. I see far to much code with a large hierarchy of classes where encapsulation and events would have made life simpler for the developer.


答:
Two common cases where you will need vanilla, non-sealed classes:

Technical: If you have a hierarchy that is more than two levels deep, and you want to be able to instantiate something in the middle.

Principle: It is sometimes desirable to write classes that are explicity designed to be safely extended. (This happens a lot when you are writing an API like Eric Lippert, or when you're working in a team on a large project). Sometimes you want to write a class that works fine on its own, but it is designed with extensibility in mind.

Eric Lippert's thoughts on sealing makes sense, but he also admits that they do design for extensibility by leaving the class "open".

Yes, many classes are sealed in the BCL, but a huge number of classes are not, and can be extended in all sorts of wonderful ways. One example that comes to mind is in Windows Forms, where you can add data or behavior to almost any Control via inheritance. Sure, this could have been done in other ways (decorator pattern, various types of composition, etc.), but inheritance works very well, too.

Two .NET specific notes:

In most circumstances, sealing classes often not critical for safety, because inheritors cannot mess with your non-virtual functionality, with the exception of explicit interface implementations.

Sometimes a suitable alternative is to make the Constructor internal instead of sealing the class, which allows it to be inherited inside your codebase, but not outside of it.


答:
For interfaces (e.g., method signatures, function signatures) I tend to solve this by annotating the parameter declarations.  For C/C++ this decorates the .h file as well as the code of the implementation.

I do the same for variable declarations where knowing the usage of the variable is not obvious in context and in the naming.  (This applies in languages that don't have strong typing also.)

There are many things that we don't want to clog the variable name.  Is the angle in radians or degrees, is there some tolerance on precision or range, etc.  The information can provide valuable assertions about characteristics that must be dealt with correctly.

I am not religious about it.  I am simply interested in clarity and in making sure that I now what it is the next time my forgetful self visits the code.  And anyone looking over my shoulder has what they need to know to see where something is off, what is essential (the last critical for proper maintenance).


问:
Dynamic Fields/Columns
What is the best way to allow for dynamic fields/database columns? For example, let's say we have a payroll system that allows a user to create unique salary structures for each employee. How could/should one handle this scenario? I thought of using a "salary" table that hold the salary component fields and joining these columns to a "salary_values" table that hold the actual values. Does this make sense?

Example Salary Structures:

Notice how the components of the salary can be shared or unique.

-- Jon's Salary --

```<code>Basic           100
Annual Bonus    25
Tel. Allowances 15
</code>```

-- Jane's Salary --

```<code>Basic             100
Travel Allowances 10
Bi-annual Bonus   30
</code>```

答: I am not sure which data base you are referring to, however if you use the PIVOT concept, you can easily achieve the nth level of your dynamic columns requirement.

Title: Dynamic Fields/Columns


问:
How do you get your product owner more engaged on agile projects?
During iteration retrospectives on agile projects, one of the topics that comes up most often for us is that the product owner is (or product owners are) not available or engaged in the project at a day to day level.

It seems to be a common theme that customers are unwilling to "give up" the necessary amount of their product owner's time to the project, but instead have them answer questions via email, or during product demos only. This has the effect of increasing the length of the feedback cycle and making the project less effective.

Have you had to overcome this hurdle? How did you do it?

答:
Daily seems like a lot for a product owner. Regardless of how often they are required, they need to know there are consequences for their lack or delayed input. If they want the project sooner/on-time, they may sacrifice and make the time commitment.

If you are 100% sold on an agile approach and your client is at 0%, you have a deadlock. Someone who is in charge needs to face the fact that business will run out the door requardless if you're agile, not agile, Windows only, Linux only, web only, embedded only, etc.

I'm trying to implement at way to get a commitment from project owners at our firm. There was a time when every single project I was working on, was waiting on a review, test, approval, etc. from someone else. Thank goodness for SO/SE.

ContentLicense: CC BY-SA 2.5


问:
Quality Assurance activities

Possible Duplicate:

  Verification of requirements question

Having asked but deleted the question as it was a bit misunderstood. If Quality Control is the actual testing, what are the commonest true quality assurance activities? I have read that verification (reviews, inspections..) but it does not make much sense to me as it looks more like quality control as mentioned here:

DEPARTMENT OF HEALTH AND HUMAN SERVICES
ENTERPRISE PERFORMANCE LIFE CYCLE FRAMEWORK
Practices guide

Verification - “Are we building the product right?” Verification is a
  quality control technique that is used to evaluate the system or its
  components to determine whether or not the project’s products satisfy
  defined requirements. During verification, the project’s processes are
  reviewed and examined by members of the IV&V team with the goal of
  preventing omissions, spotting problems, and ensuring the product is
  being developed correctly.

  Some Verification activities may include
  items such as: • Verification of requirement against defined
  specifications • Verification of design against defined specifications
  • Verification of product code against defined standards •
  Verification of terms, conditions, payment, etc., against contracts

And the opposite (project management knowledge scope - google result)
Verification is a quality assurance process or technique applied by ...

答:
A quality assurance department helps a development organization to release their software in a timely manner with as few defects as possible. Developing and releasing software is a series of trade-offs. QA can help a company decide which defects or user experience problems are acceptable at a certain time.

Some common QA goals are:

ensure that the software continues to work as it should (minimize regressions)

new features are usable and work correctly

help identify problem areas and make recommendations on how to fix them

use the system

As much as we hate to admit it, a QA department is often the first real users of a system. Because of this, they can help identify "customer" pain points that developers and even designers fail to see so they can be fixed.

Title: Quality Assurance activities


问:
Suggestions for connecting .NET WPF GUI with Java SE Server
BACKGROUND

We are building a Java (SE) trading application which will be monitoring market data and sending trade messages based on the market data, and also on user defined configuration parameters.

We are planning to provide the user with a thin client, built in .NET (WPF) for managing the parameters, controlling the server behavior, and viewing the current state of the trading. The client doesn't need real-time updates; it will instead update the view once every few seconds (or whatever interval is configured by the user).

The client has about 6 different operations it needs to perform with the server, for example:

CRUD with configuration parameters

query subset of the data

receive updates of current positions from server

It is possible that most of the different operations (except for receiving data) are just different flavors of managing the configuration parameters, but it's too early in our analysis for us to be sure.

To connect the client with the server, we have been considering using:

SOAP Web Service

RESTful service

building a custom TCP/IP based API (text or xml) (least preferred - but we use this approach with other applications we have)

As best as I understand, pros and cons of the different web service flavors are:

SOAP

pro: totally automated in .NET (and Java), modifying server side interface require no code changes in communication layer, just running refresh on Web Service reference to regenerate the classes.

con: more overhead in the communication layer sending more text, etc. We're not using J2EE container so maybe doesn't work so well with J2SE

REST

pro: lighter weight, less data. Has good .NET and Java support. (I don't have any real experience with this, so don't know what other benefits it has.)

con: client will not be automatically aware if there are any new operations or properties added (?), so communication layer needs to be updated by developer if server interface changes.

con: (both approaches) Server cannot really push updates to the client at regular intervals (?)  (However, we won't mind if client polls the server to get updates.)

QUESTION

What are your opinions on the above options or suggestions for other ways to connect the 2 parts?  (Ideally, we don't want to put much work into the communication layer, because it's not the significant part of the application so the more off-the-shelf and automated the better.)

答:
To give a different choice, try a non-connected but bi-directional protocol such as a message queue (of which my preference would be ZeroMQ) where you can push changes to the client, and if the client happens to be disconnected, it'll get them when it next connects, and you can push updates to all connected clients very easily. (there are plenty of topology scenarios you can support with a message-passing architecture).

You will care if you have a lot of clients all polling the server for updates, so if you're looking to have several clients, its best to think of this from the start.


答:
"Sealing" or "finalizing" in object systems allows for certain optimizations, because the complete dispatch graph is known.

That is to say, we make it difficult for the system to be changed into something else, as a trade-off for performance. (That is the essence of most optimization.)

In all other respects, it's a loss. Systems should be open and extensible by default. It should be easy to add new methods to all classes, and extend arbitrarily.

We don't gain any new functionality today by taking steps to prevent future extension.

So if we do it for the sake of prevention itself, then what we are doing is trying to control the lives of future maintainers. It is about ego. "Even when I no longer work here, this code will be maintained my way, damn it!"


答:
Is there a good reason to name variables this way, or am I justified in updating them to more descriptive names as I come across them?

Usually, complex algorithms are implemented in matlab (or similar language). What I have seen is people just taking over the variables name. That way, it is simple to compare implementations.

All other answer are almost correct. These abbreviations can be found in math and physics, except they do not begin with d (as in your example). Variables beginning with d are usually named to represent differentiation.

All normal coding guides are telling not to name variables with the first letter representing type (as in your case), because it is so easy to browse the code in all modern IDEs.


问:
Learning by doing (and programming by trial and error)
How do you learn a new platform/toolkit while producing working code and keeping your codebase clean?

When I know what I can do with the underlying platform and toolkit, I usually do this:

I create a new branch (with GIT, in my case)

I write a few unit tests (with JUnit, for example)

I write my code until it passes my tests

So far, so good. The problem is that very often I do not know what I can do with the toolkit because it is brand new to me. I work as a consulant so I cannot have my preferred language/platform/toolkit. I have to cope with whatever the customer uses for the task at hand.

Most often, I have to deal (often in a hurry) with a large toolkit that I know very little so I'm forced to "learn by doing" (actually, programming by "trial and error") and this makes me anxious.

Please note that, at some point in the learning process, usually I already have:

read one or more five-stars books

followed one or more web tutorials (writing working code a line at a
time)

created a couple of small experimental projects with my IDE
(IntelliJ IDEA, at the moment. I use Eclipse, Netbeans and others,
as well.)

Despite all my efforts, at this point usually I can just have a coarse understanding of the platform/toolkit I have to use. I cannot yet grasp each and every detail. This means that each and every new feature that involves some data preparation and some non-trivial algorithm is a pain to implement and requires a lot of trial-and-error.

Unfortunately, working by trial-and-error is neither safe nor easy. Actually, this is the phase that makes me most anxious: experimenting with a new toolkit while producing working code and keeping my codebase clean.

Usually, at this stage I cannot use the Eclipse Scrapbook because the code I have to write is already too large and complex for this small tool. In the same way, I cannot use any more an indipendent small project for my experiments because I need to try the new code in place. I can just write my code in place and rely on GIT for a safe bail-out. This makes me anxious because this kind of intertwined, half-ripe code can rapidly become incredibly hard to manage.

How do you face this phase of the development process?

How do you learn-by-doing without making a mess of your codebase?

Any tips&tricks, best practice or something like that?

答:
I find the best solution is to not learn by doing in that way.

Rather than immediately trying to solve your problem, isolate what you don't understand and figure that out first.

Take a trivial example, you don't know how Nullable works in the .NET framework. Rather than attempting to write code using it, create a sample application and play around with it.

For example:

```<code>public static void Main(string[] args)
{
    var test = new int?();
    Console.WriteLine("new int? - {0}", test);
    test = 0;
    Console.WriteLine("0 - {0}", test);
    test = 1;
    Console.WriteLine("1 - {0}", test);
    test = null;
    Console.WriteLine("null - {0}", test);

    Console.WriteLine("test == null - {0}", test == null);
    Console.WriteLine("test.HasValue - {0}", test.HasValue);
    Console.WriteLine("test.GetValueOrDefault() - {0}", test.GetValueOrDefault());
    Console.WriteLine("test.GetValueOrDefault(2) - {0}", test.GetValueOrDefault(2));
}
</code>```

Throwing in any examples you find and seeing what happens. This allows you to perform the unit testing style of exploration you are used to without having to run a complex code base through your tools.

Note that this can sometimes work with existing code bases. Be careful of assumptions about the running environment however. If you call a DLL that expects to be running in an IIS environment from an EXE you may run into some odd errors.

Body:
I find the best solution is to not learn by doing in that way.

Rather than immediately trying to solve your problem, isolate what you don't understand and figure that out first.

Take a trivial example, you don't know how Nullable works in the .NET framework. Rather than attempting to write code using it, create a sample application and play around with it.

For example:

public static void Main(string[] args)
{
    var test = new int?();
    Console.WriteLine("new int? - {0}", test);
    test = 0;
    Console.WriteLine("0 - {0}", test);
    test = 1;
    Console.WriteLine("1 - {0}", test);
    test = null;
    Console.WriteLine("null - {0}", test);

    Console.WriteLine("test == null - {0}", test == null);
    Console.WriteLine("test.HasValue - {0}", test.HasValue);
    Console.WriteLine("test.GetValueOrDefault() - {0}", test.GetValueOrDefault());
    Console.WriteLine("test.GetValueOrDefault(2) - {0}", test.GetValueOrDefault(2));
}

Throwing in any examples you find and seeing what happens. This allows you to perform the unit testing style of exploration you are used to without having to run a complex code base through your tools.

Note that this can sometimes work with existing code bases. Be careful of assumptions about the running environment however. If you call a DLL that expects to be running in an IIS environment from an EXE you may run into some odd errors.


答:
Assuming you have read some books and documentation, the only way to go forward from there is to practice. You are lucky in that when you are a consultant that you already have a
project that needs doing, so you can just start doing it.

In general, I think your current approach is correct.

You

a) Learn the background and the theory.

b) Create tests fot TDD.

c) Start working.

The only thing I would add is

d) Refactor when you learn/discover a better way of doing something that you've already done.

The above is IMHO always the right approach to new frameworks. You can't expect to read books and docs until you know EVERYTHING and only then start coding. The human mind doesn't work like that, and even if it did that would probably be sub-optimal.

Title: Learning by doing (and programming by trial and error)

Body:
How do you learn a new platform/toolkit while producing working code and keeping your codebase clean?

When I know what I can do with the underlying platform and toolkit, I usually do this:

I create a new branch (with GIT, in my case)

I write a few unit tests (with JUnit, for example)

I write my code until it passes my tests

So far, so good. The problem is that very often I do not know what I can do with the toolkit because it is brand new to me. I work as a consulant so I cannot have my preferred language/platform/toolkit. I have to cope with whatever the customer uses for the task at hand.

Most often, I have to deal (often in a hurry) with a large toolkit that I know very little so I'm forced to "learn by doing" (actually, programming by "trial and error") and this makes me anxious.

Please note that, at some point in the learning process, usually I already have:

read one or more five-stars books

followed one or more web tutorials (writing working code a line at a
time)

created a couple of small experimental projects with my IDE
(IntelliJ IDEA, at the moment. I use Eclipse, Netbeans and others,
as well.)

Despite all my efforts, at this point usually I can just have a coarse understanding of the platform/toolkit I have to use. I cannot yet grasp each and every detail. This means that each and every new feature that involves some data preparation and some non-trivial algorithm is a pain to implement and requires a lot of trial-and-error.

Unfortunately, working by trial-and-error is neither safe nor easy. Actually, this is the phase that makes me most anxious: experimenting with a new toolkit while producing working code and keeping my codebase clean.

Usually, at this stage I cannot use the Eclipse Scrapbook because the code I have to write is already too large and complex for this small tool. In the same way, I cannot use any more an indipendent small project for my experiments because I need to try the new code in place. I can just write my code in place and rely on GIT for a safe bail-out. This makes me anxious because this kind of intertwined, half-ripe code can rapidly become incredibly hard to manage.

How do you face this phase of the development process?

How do you learn-by-doing without making a mess of your codebase?

Any tips&tricks, best practice or something like that?


答:
Well I'm by no means a pro, but I learn as the process goes on, learning and implementing new features as they're needed, however I have the luxuries of time and being a student.

As far as I can tell, you're doing a pretty good job of keeping up with all the changes.

The only tip I can give as a beginner is to break it down into consumable bits, and learn the features you need side by side with the basics of the toolkit/platform so that you can code the trivial code faster and be satisfied with your overall code.


答:
I was going to suggest that you make a throwaway project to familiarize yourself with the tool
but you've already got that covered. There will always be more the to tool than books, tutorials, and sample projects can show
you. All the nuances come out only with experience. But if you don't feel you have a sufficient grasp on a tool, I'd simply
spend more time on those three steps.

You plan seems solid to me.

I work as a consulant

Oh. Well, in that case, FAKE IT. Deliver whatever you can slap together in a roughshod manner that appears to work, bill
the customer for meeting your contractual obligation, and leave. If it's not the prettiest, that's someone else's problem. Or it's seeding for future employment. Thus is the life of a contractor. If you have specific domain knowledge about whatever, be sure
to fork that over in a handy document or tool or example code, as that's what they're really paying you for. But if they just need a code-monkey for a weekend, and
they don't let you use the tools you know, then this is the sort of results they should expect. Sorry, but that's how piece-meal work
turns out. If you put in that extra effort, another consultant will undercut you. If your client was hiring for quality,
they'd have actually HIRED someone.

Don't get me wrong, consultants can be a god-send when you need a superman of SQL or a gnu guru to banish the bugs that plague you.
But hiring a consultant who has to learn the tools? naw.


问:
Quality Assurance=inspections, reviews..?
Studying this subject extensively, the most books state the following:

Quality Assurance: prevention activity. Act of inspection, reviewing..

Quality Control: testing

While there are some exceptions that mention that QA deals with just processes (planning, strategy, standard application etc.) which is IMHO much closer to real QA, yet I cannot find any good reference in Google Books.

I believe that inspections, reviews, testing is all quality control as it is about checking products, no matter if it is the final one or work products. The problem is that so many authors do not agree.

I would be grateful for detailed explanation, ideally with a reference.

答:
Quality Assurance is process compliance. It has nothing to do with testing, except for its planning. QA personnel will decide what test methodology to use, how to test, who will test, how to report. It checks that processes being used on the project are appropriate, correctly implemented (standards, procedures, conventions). It says what we should do in order to make a quality product.

Quality Control is about checking the output, which is any work product produced by any process. This means that QC checks for conformance with specifications, standards...

Saying that QA tools are reviews and inspections is misguided. These activities need an output that has been done as a result of a process: so it is just a quality control (static, dynamic or both).

Quality Control also belongs within the Quality Assurance domain (it is driven by it and provides a feedback), hence testing is sometimes said to be QA (actually it can be thought as of one indirect QA activity).

EDIT: I would add that both are part of Quality Management. I would not agree that Quality Assurance overisghts verification as QA defines and measureses only processes. Verification is checking product by static methods, hence it is Quality Control. But I concur that the gray area is really confusing and enables a lot of possible intepretations.


问:
Keeping a domain model consistent with actual data
Recently domain driven design got my attention, and while thinking about how this approach could help us I came across the following problem.

In DDD the common approach is to retrieve entities (or better, aggregate roots) from a repository which acts as a in-memory collection of these entities. After these entities have been retrieved, they can be updated or deleted by the user, however after retrieval they are essentially disconnected from the data source and one must actively inform the repository to update the data source and make is consistent again with our in-memory representation.

What is the DDD approach to retrieving entities that should remain connected to the data source? For example, in our situation we retrieve a series of sensors that have a specific measurement during retrieval. Over time, these measurement values may change and our business logic in the domain model should respond to these changes properly. E.g., domain events may be raised if a sensor value exceeds a predefined threshold.

However, using the repository approach, these sensor values are just snapshots, and are disconnected from the data source. Does any of you have an idea on how to solve this following the DDD approach?

答:
To answer the question it would be helpful to know the consistency model appropriate for the application. Would eventual consistency suffice? In other words, how "connected" does the data need to be? Also, what type of storage technology is used? A relational database? A NoSQL database with weakened ACID constraints?

One of the issues is that as soon as data is read from the database into memory, there is already potential for inconsistency, unless a write-lock is issued. However, in your case, a write lock cannot be issued because the data needs to be updated from another source. Therefore, you have to embrace eventual consistency because there will be a delay between when sensor data is updated and when that information reaches the domain code.

If eventual consistency is acceptable, then you can implement a message handler which listens for sensor data and invokes the appropriate domain layer code, which may in turn raise domain events. This message handler is in a sense outside of your domain layer - it is an infrastructural/application layer concern. It is very much like a message handler in something like NServiceBus or MassTransit, the only difference being that the underlying storage mechanism is different. (Although if MSMQ or ZeroMQ is suitable for the application you can just use those).


答:
In light of your progression of questions, I guess the TL;DR; answer is:

Quality Assurance == Oversight of the Verification activity

Quality Control == Oversight of the Validation activity

And yes, that is deliberately embracing the ambiguity and grey area between Ver and Val

:-)

Title: Quality Assurance=inspections, reviews..?

Body:
Studying this subject extensively, the most books state the following:

Quality Assurance: prevention activity. Act of inspection, reviewing..

Quality Control: testing

While there are some exceptions that mention that QA deals with just processes (planning, strategy, standard application etc.) which is IMHO much closer to real QA, yet I cannot find any good reference in Google Books.

I believe that inspections, reviews, testing is all quality control as it is about checking products, no matter if it is the final one or work products. The problem is that so many authors do not agree.

I would be grateful for detailed explanation, ideally with a reference.


问:
Why not Green Threads?
Whilst I know questions on this have been covered already (e.g. https://stackoverflow.com/questions/5713142/green-threads-vs-non-green-threads), I don't feel like I've got a satisfactory answer.

The question is: why don't JVM's support green threads anymore?

It says this on the code-style Java FAQ:

A green thread refers to a mode of operation for the Java Virtual
  Machine (JVM) in which all code is executed in a single operating
  system thread.

And this over on java.sun.com:

The downside is that using green threads means system threads on Linux
  are not taken advantage of and so the Java virtual machine is not
  scalable when additional CPUs are added.

It seems to me that the JVM could have a pool of system processes equal to the number of cores, and then run green threads on top of that.  This could offer some big advantages when you have a very large number of threads which block often (mostly because current JVM's cap the number of threads).

Thoughts?

答:
I remember the JVM abandoning green threads and moving to native threads. This was for two simple reasons: the green threads were frankly rubbish, and there was a need to support multi-core processors with the limited developer effort available at Sun.

This was a shame - green threads provide a far better abstraction, allowing concurrency to be a useful tool not a stumbling block. But green threads are no use if several hurdles can't be overcome:

they must use all the cpu cores available to them

context switching must be cheap

I/O may block any thread engaged in it, but not any other thread and certainly not all other threads, which was the case in some early implementations.

I've often wondered why multi-threading is so hard in Java but it's now becoming clearer - it was ultimately to do with the switch to native threads, which are:

good at using all the cpu cores

good at being truly concurrent, providing independent I/O etc

slow at context switching (compared with the best green thread implementations)

horribly greedy with memory, hence limiting the maximum usable number of them

a poor abstraction for any basis for expressing the real world, which is highly concurrent of course.

Nowadays, a lot of programmer time now goes into coding up non-blocking I/O, futures etc. It's a big shame we don't have a better level of abstraction.

For comparison, besides Erlang the new Go language does a good job of huge concurrency. The grand-daddy of them all remains Occam, still an ongoing research project.

Title: Why not Green Threads?


问:
Can I distribute a software with the following permission notice
I've recently written a piece of software (without any other contributors) for a company which I part own. I was wondering if I could distribute it with the following permission notice, which is a modified version of the MIT License. Are there any obvious risks if I do distribute with this licence and does it give me the right to reuse the code in other projects?

Permission is hereby granted, to any person within CompanyName (the
  "Company") obtaining a copy of this software and associated
  documentation files, excluding any third party libraries (the
  "Software"), to deal with the Software, with limitations restricted to
  use, copy, modify and merge, the Software may not be published,
  distributed, sublicensed and/or sold without the explicit permission
  from AuthorName (the "Author"). This notice doesn't apply to
  sections of the Software where copyright is held by any persons other
  than the Author.

The Author remains the owner of the Software and may deal in the
  Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or
  sell copies of the Software.

The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

答:
Presuming your company is based in the United States or another country with similar laws, you can release the software however you want.  How effective that license will be in protecting you from liability is something that only an attorney can handle.  You can't just pervert a license for your purposes and hope that it will hold up in a court of law.

Honestly, I don't know why you're trying to re-use the MIT license in this fashion.  MIT license is intentionally a permissive license and you're attempting to create a number of restrictions.

Take a look at the various Creative Commons licenses or perhaps the Wikipedia comparison of free software licenses.

OTOH, if you're charging for the product then you probably don't want to start with a license that is based upon a "free" model.  Selling a product will create warranty obligations whether you want them or not.  An IP attorney should be able to help you work through those questions.


答:
does it give me the right to reuse the code in other projects?

Fun fact about copyright and licenses: As the (sole) owner of some code, you can do anything you want with it and no one can cite you for copyright violation. Because only you own the copyright on it.

Once people start making contributions to this project, then there's the question of what the license allows you to do with what is now THEIR code. At first glance, sure, it's a sticky license that explicitly give you specifically control and rights to it. But I wouldn't vouch for that in court. If you want to make your own license, yeah, you should probably pass it by a lawyer first.

And by and far the most important advice I can give is that NONE of this is iron-clad, and ANYONE and EVERYONE could argue the case that the exact opposite is true. And you'd have to get a lawyer to sort that out in court. Even if you DO get a lawyer's stamp of approval on it first.

If you're making software for a company however, there's a question over who actually owns it. I can slap any license I want onto our next release, but since I made it on company computers, on company time, (and my contract states that anything I write under such circumstances is owned by the company) then the license is null and void because I didn't own the copyright to have the right to do so. There's also weird state laws about who owns what by default when there's no contract stating as such. And of course all of this gets even wonkier when you step over international lines.

Welcome to the eternal gray of IP law.

Title: Can I distribute a software with the following permission notice

Body:
I've recently written a piece of software (without any other contributors) for a company which I part own. I was wondering if I could distribute it with the following permission notice, which is a modified version of the MIT License. Are there any obvious risks if I do distribute with this licence and does it give me the right to reuse the code in other projects?

Permission is hereby granted, to any person within CompanyName (the
  "Company") obtaining a copy of this software and associated
  documentation files, excluding any third party libraries (the
  "Software"), to deal with the Software, with limitations restricted to
  use, copy, modify and merge, the Software may not be published,
  distributed, sublicensed and/or sold without the explicit permission
  from AuthorName (the "Author"). This notice doesn't apply to
  sections of the Software where copyright is held by any persons other
  than the Author.

The Author remains the owner of the Software and may deal in the
  Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or
  sell copies of the Software.

The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


答:
Do not include any license at all in the software, but add the following:

Copyright 2012 {Your name} All rights reserved.

Then create a separate document that says something like this:

{Company} has a non-exclusive royalty free license to use {Software} forever.

Sign it and give it to the company.

As the owner of the Copyright you do not need any license information in the file at all to use it any way you want.

Note:
It is very likely you own the copyright unless the software is considered a Work for hire in which case the person or company that paid for the work is the copyright owner.


答:
The time when you need to consider a class that is intended to be extended is when you are doing some real planning for the future. Let me give you a real life example from my work.

I spend a good deal of my time writing interface tools between our main product and external systems. When we make a new sale, one big component is a set of exporters that are designed to be run at regular intervals which generate data files detailing the events that have happened that day. These data files are then consumed by the customer's system.

This is an excellent opportunity for extending classes.

I have an Export class which is the base class of every exporter. It knows how to connect to the database, find out where it had got to last time it ran and create archives of the data files it generates. It also provides property file management, logging and some simple exception handling.

On top of this I have a different exporter to work with each type of data, perhaps there is user activity, transactional data, cash management data etc.

On top of this stack I place a customer-specific layer which implements the data file structure the customer needs.

In this way, the base exporter very rarely changes. The core data-type exporters sometimes change but rarely, and usually only to handle database schema changes which should be propagated to all customers anyway. The only work I ever have to do for each customer is that part of the code that is specific to that customer. A perfect world!

So the structure looks like:

```<code>Base
 Function1
  Customer1
  Customer2
 Function2
 ...
</code>```

My primary point is that by architecting the code this way I can make use of inheritance primarily for code re-use.

I have to say I cannot think of any reason to go past three layers.

I have used two layers many times, for example to have a common Table class which implements database table queries while sub-classes of Table implement the specific details of each table by using an enum to define the fields. Letting the enum implement an interface defined in the Table class makes all sorts of sense.

Body:
The time when you need to consider a class that is intended to be extended is when you are doing some real planning for the future. Let me give you a real life example from my work.

I spend a good deal of my time writing interface tools between our main product and external systems. When we make a new sale, one big component is a set of exporters that are designed to be run at regular intervals which generate data files detailing the events that have happened that day. These data files are then consumed by the customer's system.

This is an excellent opportunity for extending classes.

I have an Export class which is the base class of every exporter. It knows how to connect to the database, find out where it had got to last time it ran and create archives of the data files it generates. It also provides property file management, logging and some simple exception handling.

On top of this I have a different exporter to work with each type of data, perhaps there is user activity, transactional data, cash management data etc.

On top of this stack I place a customer-specific layer which implements the data file structure the customer needs.

In this way, the base exporter very rarely changes. The core data-type exporters sometimes change but rarely, and usually only to handle database schema changes which should be propagated to all customers anyway. The only work I ever have to do for each customer is that part of the code that is specific to that customer. A perfect world!

So the structure looks like:

Base
 Function1
  Customer1
  Customer2
 Function2
 ...

My primary point is that by architecting the code this way I can make use of inheritance primarily for code re-use.

I have to say I cannot think of any reason to go past three layers.

I have used two layers many times, for example to have a common Table class which implements database table queries while sub-classes of Table implement the specific details of each table by using an enum to define the fields. Letting the enum implement an interface defined in the Table class makes all sorts of sense.


问:
If I implement a web-service, how do I respond to POST requests with JSON?
I have to make a rather complex system for my diploma work. Logically it will consist of the following components:

Database

Web-service

Management with web interface

Client iOS application that will consume web-service

I decided to implement all the first three components under .NET.
Firstly I will create a database depending on the information load - this is clear.
But then I need a web-service that will return data in JSON format for iOS clients to consume - that's obvious and not that hard to implement. For this I will use WCF technology.

Now I have a question, if I implement the web-service, how will I be able to respond to POST requests with JSON? It probably involves WCF JSON or something related? But I also need some web pages as admin part, so will this web-application be able to consume my centralized web-services as well or I should develop it separately? I just want my web service to act like a set of controllers.

There is a related question here but this doesn't quite reflect my question.

答: I think .NET MVC with some controller actions returning JSON might be your best bet, as could deliver web app and the web service component with some nice RESTfull urls</p>


答:
You can use ASP.NET MVC with an Json serializer library such as JSON.NET.

However, I would recommend to use ASP.NET Web API as it is specialized for these kinds of operations. ASP.NET Web API is a very simply and easy to use and learn framework for such purposes.

Of course, WCF is also an option though it is more complex and the learning curve is a bit higher.

Title: If I implement a web-service, how do I respond to POST requests with JSON?

Body:
I have to make a rather complex system for my diploma work. Logically it will consist of the following components:

Database

Web-service

Management with web interface

Client iOS application that will consume web-service

I decided to implement all the first three components under .NET.
Firstly I will create a database depending on the information load - this is clear.
But then I need a web-service that will return data in JSON format for iOS clients to consume - that's obvious and not that hard to implement. For this I will use WCF technology.

Now I have a question, if I implement the web-service, how will I be able to respond to POST requests with JSON? It probably involves WCF JSON or something related? But I also need some web pages as admin part, so will this web-application be able to consume my centralized web-services as well or I should develop it separately? I just want my web service to act like a set of controllers.

There is a related question here but this doesn't quite reflect my question.


问:
Is there a way communicate or measure levels of abstraction?
I'll be the first to say that this question is a bit... out there.  But here are a couple questions I bear in mind :

Is abstraction continuous or discrete?

Is there a single unit of abstraction?

But I'm not sure those questions are truly answerable or even really makes sence.  My naive answer would be something along the lines of abitrarily discrete but not necescarily having a single unit measure.  Here's what I mean...

Take a Black Labrador; an abstraction that could be made is that a Black Lab is a type of animal.

[Animal]<--[Black Lab]

A Black Lab is also a type of Dog.

[Dog]<--[Black Lab]

One way to establish a degree of abstraction is by comparing the two the abstractions.  We could say that [Animal] is more abstract than [Dog] in respect to a Black Lab.  It just so happens [Animal] can also be used as an abstraction of [Dog]  So, we might end up with something like

[Animal]<--[Dog]<--[Black Lab]

With the model above, one might be inclined to say that there's two hops of abstraction to get from [Black Lab] to [Animal].  But you can't exactly tell somebody they need one level abstraction and reasonalby expect they will come up with [Dog] given they aren't explicity given the options above.

If I needed to tell someobody in a single email that they needed an abstract class with out knowing what that abstract class is, is there a way to communaticate a degree of abstraction such that they might end up on Dog instead of Animal? As a side note, what area of study might this type of analysis fall under?

答:
Is abstraction continuous or discrete?
  Is there a single unit of abstraction?

I look at abstraction as a discrete thing, measured in "layers" that can only be counted based on your current point of view.

For the sake of example, let's say an Animal is at the top of a class hierarchy.

If I call some method that expects an Animal, you're looking down at the top and have absolutely no clue if what you've been handed is actually a Dog or an Aardvark.  You shouldn't care, either, because those details are hidden behind the abstraction.  That barrier prevents you from measuring any deeper than Animal.  The abstraction does allow you to know that every Animal has a sleep() method but not that it's implemented as layDown(); closeEyes() (Aardvark) or turnAround(3); layDown(); closeEyes() (Dog).  As long as the end result is a sleeping Animal, that shouldn't be an impediment.

If I call a method expecting a BlackLab, you're in a different position.  By virtue of the fact that you know this class inherits Dog and Animal, you can measure that there are two layers of abstraction above you, but you're still blind to anything below such as subclasses MaleBlackLab and FemaleBlackLab.

If I needed to tell someobody in a single email that they needed an
  abstract class with out knowing what that abstract class is, is there
  a way to communaticate a degree of abstraction such that they might
  end up on Dog instead of Animal?

No, because your scenario is dropping not-so-subtle hints that implementation has started without having completed a design which would tell you how the class hierarchy will look

Without that context, the directions you'd give ("write a BlackLab class with two layers of abstraction above it") would be ambiguous.  The first several implementation possibilities that come to mind are these:

Animal / Dog / BlackLab

Dog / HuntingDog / BlackLab

HuntingDog / Retriever / BlackLab

Canine / Dog / BlackLab

Dog / BlackDog / BlackLab

Without an understanding of what kind of software you're writing, any of those might be appropriate.  Once you start to zero in on solving a specific problem, only one becomes the right thing:

If your project is for the local animal shelter, which deals with many kinds of animals (dogs, cats, etc.), the first hierarchy makes a lot of sense.

For the American Kennel Club (dogs only), it the second one might work better.

For the North American Gun Dog Association (hunting dogs only), the third works.

You get the picture.  Context is king.

As a side note, what area of study might this type of analysis fall under?

This is really basic software engineering, specifically the chapter on fully understanding the problem before you start work on it.  :-)


问:
doing a full permutation search and replace on a string
I'm writing an app that does something like a custom number (license) plate generator tool where if I ask for the plate "robin" it will suggest I try:

r0bin

rob1n

r0b1n

Are there any published algorithms which can do this? It has to be able to handle replacing single letters with multiples, e.g. m with rn and vise-versa and not fall over if it replaces an i with an l then comes to check the l and replaces it back to an i.

The list of what gets swapped with what is going to be user input but I'm not expecting a huge list, possibly 10 pairs at most.

I'll be implementing this in Ruby or Python but I should be able to convert code from any other language.

答:
First, you get a list of replacements that it would make:

I --> 1

A --> 4

m --> rn

etc...

You will have some finite set of these changes.

For that set, generate the set of combinations. If you have 10 changes, there are possibly 1024 changes total.  This list is all the changes from 0 .. 1023.  Take the bit representation of each of these values.  The 953rd (1110111001) change would have the first, second, third, fifth, sixth, seventh, and tenth change applied.

This could be reduced by only having changes that have a candidate letter in them (it would not make sense to try to apply the change 'm' --> 'rn' when there is not an 'm' in 'robin').