问:
Iteratively building a Test Framework
(Upfront, I'm not a test or agile expert, just trying to push us to be better. If I'm wrong on anything I'd love your guy's opinions).

So I've been pushing for us to become a real agile shop and less of a "calling ad-hoc agile" shop. So I'm iteratively trying to improve our process. I've found that its been good to slowly build towards "doing it right": I can get buy in for small changes, or large changes on their own. So we've got slow iterations (about a month) that I've been using to slowly fold more and more in. My personal goal is to get us to a process that support continuous integration: at that point I think we can do things like speed up our iterations at much lower cost.

The next bit that I've sold management on that we need to improve is our testing. We've never had a real solid test strategy, so I'd like to start to build up our capabilities there. We've already introduced "Test Driven Development", using Google Test (unit test) framework, which has brought us very far. But these unit tests are not enough to test the system as a whole. We're supplementing this with our old way of testing, ad-hoc system and functional tests that are really specific to the project, that are rewritten every time, and that are not automated. To make matters worse, our functional and system tests are often more similar to characterization tasks than pass-fail tasks: our system/functional test tools need to be able to support advanced plotting and number crunching, which mean a lot of them are in Matlab shudder.

From what I can tell, a good automated test system has two parts: the Test Framework (something akin to the roboframework, ect) that figures out what tests to run, calls those tests, orgamizes the results, ect...the thing that actually does the automation. That uses the Test Tool(s), the fixture that actually performs your test. I may be viewing this wrong, but the Test Framework is like a huge batch file, and the Test Tools are the tests.

So I see two possible ways to go with "what to do next".

Implement (could be writing our own, though I'd prefer to acquire/modify) a Test Framework. Leave our ad-hoc system tests, but let the framework take over automation. The goal would to have a way to hit "Test" and have all the tests run.

Figure out a way that we can use to make Test Tools more efficiently and effectively.

I'm not sure what the best way to go is here, or if any of the following matter:

We do both windows and linux development, though usually not at the same time

While I want to focus on C++, C with CMake, we also do C# and Matlab development. The ideal framework would support all of these, even if it is different tools.

The "testers", "test automators", and "developers" are all going to be pulled from the same group of highly-competent developers (for now.)

I need to support command-line executable and libraries now, but would like to support GUIs (QT and .NET) in the future.

The scope of 2 seems HUGE, though doing 1 first seems like putting the cart before the horse. Do I have a semi-accurate picture of whats going on? I've read a few things that use Google Test as their test framework, but doesn't better fit the definition of test tool? Am I biting off more than I can chew?

答:
In my experience, the biggest hurdle to writing tests is in answering the question "how do I write a test?". If it is difficult or unclear, people won't do it. So, if you make it clear, and make it not-difficult, people will start doing it.

So, how do you do that? You pick an existing framework, install it such that anyone can use it, and start using it. Don't get bogged down in picking the best framework, and certainly don't go down the path of building your own since you don't really know what you want.

You are correct that there are two parts to the system -- the testing framework itself, and a scheduler for running the tests. What you want is to get to the point where someone can write a test, check it in, and it automatically builds (if necessary) and runs.

No matter what platform you're on, and no matter what language you're writing  your code in, you can probably use the combination of jenkins plus robotframework to test your software. Are they perfect? Definitely not. But they are easy to install, flexible, actively developed, and most likely can let you start writing tests in only a day. Plus, they work very well together since there's a robotframework plugin for jenkins.

Once you have jenkins and robotframework installed, and you start writing a few tests using those tools, you'll begin to get a more clear picture of what you actually need. You'll see places where these tools solve existing problems today, and you'll find deficiencies that you may want to rectify.

The important thing is, start now with something concrete. Get the ball rolling. Learn from the experience, and then you'll have more information to improve your testing solution in the future.

Title: Iteratively building a Test Framework


问:
Java's Boolean class - why not an enum?
It seems to me that the Boolean class is an ideal candidate to be implemented as an enum.

Looking at the source code, most of the class is static methods which could be moved unchanged to an enum, the rest become much simpler as an enum.  Compare original (comments and static methods removed):

```<code>public final class Boolean implements java.io.Serializable,
                                      Comparable<Boolean>
{
   public static final Boolean TRUE = new Boolean(true);
  public static final Boolean FALSE = new Boolean(false);
   private final boolean value;
   public Boolean(boolean value) {
       this.value = value;
   }
   public Boolean(String s) {
       this(toBoolean(s));
   }
   public boolean booleanValue() {
       return value;
   }
   public String toString() {
       return value ? "true" : "false";
   }
   public int hashCode() {
       return value ? 1231 : 1237;
   }
   public boolean equals(Object obj) {
       if (obj instanceof Boolean) {
           return value == ((Boolean)obj).booleanValue();
       }
       return false;
   }
   public int compareTo(Boolean b) {
       return compare(this.value, b.value);
   }
}
</code>```

with an enum version:

```<code>public enum Boolean implements Comparable<Boolean>
{
   FALSE(false), TRUE(true);
   private Boolean(boolean value) {
       this.value = value;
   }
   private final boolean value;
   public boolean booleanValue() {
       return value;
   }

   public String toString() {
       return value ? "true" : "false";
   }
}
</code>```

Is there any reason why Boolean couldn't become an enum?

If this is the Sun code to override the equals() method, it is missing a very fundamental check of comparing the references of the two objects before comparing their values. This is how I think the equals() method should be:

```<code>   public boolean equals(Object obj) {

       if (this == obj) {
          return true;
       }

       if (obj instanceof Boolean) {
           return value == ((Boolean)obj).booleanValue();
       }
       return false;
   }
</code>```

答:
Well, I guess I could start by arguing that Java enumerations were not added to the Java programming language until the JDK 1.5. and therefore this solution was not even an alternative in the early days when the Boolean class was defined.

That being said, Java has the reputation of keeping backwards compatibility between releases and so, even if we, today, may consider your solution as a good alternative, we cannot do it without breaking thousands of lines of code out there already using the old Boolean class.

ContentLicense: CC BY-SA 3.0

Title: Java's Boolean class - why not an enum?


问:
What can slow a developer down?
What things tend to slow a developer down?

Please try to refrain from posting answers that:

are slow now but useful in the feature. (TDD, Refactoring, ...)

list a distraction.

答: A slow computer </p>

ContentLicense: CC BY-SA 2.5

Title: What can slow a developer down?

Body: A slow computer


问:
How to get money from reluctant client?
I completed this website 4 months ago. (I would like to keep the website anonymous - if this post comes up on google search by customers, it will have a negative impact on their business). We did several iterations, the client was very demanding (and nosy), I complied with every single thing that was wanted, including the font-size of the footer which destroyed the aesthetic looks by quite a bit; (and they messed with the colours too, making it look dangerously childish and unprofessional).

Anyway, the client was very friendly during the whole process. After getting all the requirements I accepted to build the website for £950 and I charged him £150 in advance so he wouldn't want to bail out after I started the work. The requirements kept changing quite a lot, I made adjustments as and completed the website just 5 days late, w.r.t. the agreed date, in-spite all the changes in requirements.

That was four months ago. They have never returned my calls nor replied to my emails since then. How do I get the money back from them? I really need some advice on this, this is the second time someone has not paid me.

Points to be noted:

We did not sign any contract - the client was a friend of a friend.

I still hold the passwords for ftp, cpanel and everything. I don't want to bring the site down; somehow it doesn't seem ethical to me.

I posted this on Stack Overflow and it was closed, I was redirected here.

EDIT

Thank you everyone, for your enormous support. I thought I should include some more details: The client is hosting the site; as in, I made them register and use their own debit card to buy the domain name, webspace and everything, I just have the passwords for his cpanel, and ftp (well, I have access to cpanel that pretty much gives me access to many things).

Now, if I give them a warning, he might change the password to cpanel, but I am fairly sure they doesn't know about ftp's.

UPDATE

I followed Anna Lear's advice and sent the final invoice, on Saturday, with a warning that I will take the site down if he doesn't respond to my email before this Tuesday. They havn't replied to my emails yet, but I will let you know how this goes. Thanks much for your support. I plan to put up a holding page as Darknight suggested after Tuesday.

Points

I don't have a server space of my own, however I have few web spaces of my clients but I don't want to use them for this kind of purpose.

RESULTS

After my follow up of final invoice and warning, the client refused to anything. workman's advice seemed to be the most sensible to me. I mirrored the site to my own webspace, logged into his CPanel and forwarded the website to my site. Once that was done, I put up a holding page on my site so anyone going to the website would see a holdup page (nothing fishy, just an Under Construction page). Of course, this was all very weak in the sense that if my client knew about CPanel he could just remove the redirection. But, I had this second chance to get back to him and I was relying on him not knowing anything.

Two hours later, I got a call from the said client, (and  acting as if they did not get any of my voice mails or emails) and asked me to get the site back up. I, of-course, said I had to be paid and two days after that I received a bank transfer. The site's back up and running now.

Just wanted to say thank you all very much, I was very desperate when I had started this question. You are the best, not only you told me to learn the lesson (which I did) you also gave me a very very good solution that seemed to be very ethical (almost) to me.

A BIG thank you to workman!

If I could choose more than once answer, I would have chosen Anna Lear  too, but since I followed workman's advice I had to pick that up. People who made a point about not taking the site down without consulting a lawyer, thanks a lot.

答:
Send him a final invoice with a note that you will be shutting down the site on such and such date/time until payment is made. That should get his attention.

I agree that shutting it down out of the blue would be a bit unethical (no matter how obvious it may be to us that he should pay up), but with a clear warning, all bets are off.

Beyond that... I don't think there's much you can do without a contract.

As for advice on preventing this kind of thing in the future, always sign a contract. It's not optional. Sign a contract and take them to court for non-payment if that's what it takes.

Title: How to get money from reluctant client?


答:
Most likely because the primitive boolean type isn't an Enum, and the boxed versions of primitive types behave almost identically to their unboxed version. E.g.

```<code>Integer x = 5;
Integer y = 7;
Integer z = x + y;
</code>```

(The performance may not be the same, but that's a different subject.)

It'd be kind of strange if you could write:

```<code>Boolean b = Boolean.TRUE;
switch (b) {
case Boolean.TRUE:
    // do things
    break;
case Boolean.FALSE:
    // do things
    break;
}
</code>```

but not:

```<code>boolean b = true;
switch(b) {
case true:
    // do things
    break;
case false:
    // do things
    break;
}
</code>```

Title: Java's Boolean class - why not an enum?

Body:
It seems to me that the Boolean class is an ideal candidate to be implemented as an enum.

Looking at the source code, most of the class is static methods which could be moved unchanged to an enum, the rest become much simpler as an enum.  Compare original (comments and static methods removed):

```<code>public final class Boolean implements java.io.Serializable,
                                      Comparable<Boolean>
{
   public static final Boolean TRUE = new Boolean(true);
  public static final Boolean FALSE = new Boolean(false);
   private final boolean value;
   public Boolean(boolean value) {
       this.value = value;
   }
   public Boolean(String s) {
       this(toBoolean(s));
   }
   public boolean booleanValue() {
       return value;
   }
   public String toString() {
       return value ? "true" : "false";
   }
   public int hashCode() {
       return value ? 1231 : 1237;
   }
   public boolean equals(Object obj) {
       if (obj instanceof Boolean) {
           return value == ((Boolean)obj).booleanValue();
       }
       return false;
   }
   public int compareTo(Boolean b) {
       return compare(this.value, b.value);
   }
}
</code>```

with an enum version:

```<code>public enum Boolean implements Comparable<Boolean>
{
   FALSE(false), TRUE(true);
   private Boolean(boolean value) {
       this.value = value;
   }
   private final boolean value;
   public boolean booleanValue() {
       return value;
   }

   public String toString() {
       return value ? "true" : "false";
   }
}
</code>```

Is there any reason why Boolean couldn't become an enum?

If this is the Sun code to override the equals() method, it is missing a very fundamental check of comparing the references of the two objects before comparing their values. This is how I think the equals() method should be:

```<code>   public boolean equals(Object obj) {

       if (this == obj) {
          return true;
       }

       if (obj instanceof Boolean) {
           return value == ((Boolean)obj).booleanValue();
       }
       return false;
   }
</code>```

Body:
Most likely because the primitive boolean type isn't an Enum, and the boxed versions of primitive types behave almost identically to their unboxed version. E.g.

Integer x = 5;
Integer y = 7;
Integer z = x + y;

(The performance may not be the same, but that's a different subject.)

It'd be kind of strange if you could write:

Boolean b = Boolean.TRUE;
switch (b) {
case Boolean.TRUE:
    // do things
    break;
case Boolean.FALSE:
    // do things
    break;
}

but not:

boolean b = true;
switch(b) {
case true:
    // do things
    break;
case false:
    // do things
    break;
}


问:
Passing data between classes
A question similar to this has been asked before, and will be asked again I am sure.
I have spent some time googling and trying to work this out for myself, but I am at an impasse.

What I am trying to achieve is to implement a database search screen for an application I have been tasked with creating.

What I am doing is loading a JFrame with JPanels through a cardlayout. On a few of these JPanels I will have a button that calls another JFrame that will search a DB and load the result set into a table displayed on the frame. The search is only conducted after the user has typed in the search data and pressed search. The screen is to be disposed of, and return the values once the user has selected a row in the table and pressed another button.

I have all the GUI components created, and the DB search functionality working. The problem I have is returning the value.

At the moment I have the Search JFrame object created by the JPanel that has the button, but any attempts I ave made to get the data from the search frame have resulted in null results.

Is there a way to return a value through this way and if so how?

I have tried getter/setter methods, but obviously since the initial results of the variables are null it returns as null.
I tried linking the result to the table with the same result. (Actually it returned -1, but that's just splitting hairs).
I tried changing the search screen to a JDialog as I read that that can halt the running code while waiting for a response.
I tried various methods to check if the search screen was enabled/visible and to hold on those.

All to no avail.

Any help is appreciated.

答:
Without going deep into details...

An alternative is to have a common model that both frames share. When you pop up the frame for the user to run the search, you pass the model object which should be shared between the two UI components. When you populate this model and come back to the main frame, you can use the shared model to update any views.

A second alternative is use callbacks with an observer pattern. In this way, the main frame registers with a listener to receive events, and when you pop up the search frame, you pass the listener to it so that when user does a search, you can notify all listening objects about the results.

Title: Passing data between classes


问:
Can I use machine learning for screening experimental data?
I am a experimental physicist. In our research, we have our experimental data in a 400*400*400 matrix(x, y, z axis of a 3d space), each entry is associated with a value("brightness"). We expect the brightest entries will form a closed path in the 3d space. But some portion of the path is always too dark to identify, also there are some noise in the space(random bright lines).

Our current algorithm generates random seed points into the space, they are attracted by the brightness of the data. After certain amount of time, they will be trapped in the path. If we record the seed points position we can get the path. Our current algorithm does a fairly good job while I still need to manually add those relatively dark points to the path.

I am not familiar with machine learning, but I am wondering if it can be used on this case? For example, is it possible that I tell the program which data points are on the path, the program will know how to choose the data points for the path in the future. Or if there is some other method we can use? Thanks!

答:
Isn't this just a regression on (x, y, z)? But it sounds like a regression rather than a classification because you're trying to determine a path -- in other words, (continuous) values of x, y, z close to the measured path, based on initial measurements of the brightness.

Alternately, you could train a neural network to identify the path, and produce a "fitness" estimate based on (x, y, z) inputs. You might have to have a different neural network for each data set, though, if the shape of the path is different each time. (I think this would just be a more generalized version of doing a mathematical regression, though.)

If you could express the path as a parameterized formula that scores an (x, y, z) tuple based on closeness to the path, you could do a Genetic Algorithm to search the space and guess and select good values for the parameters. In other words, the Genetic Algorithm could search for parameters that optimize the formula for the path.

From your description, it sounds like you're almost doing a Genetic Algorithm already -- selecting a random point and then doing incremental optimization. That's the basic idea, the difference would be in the optimization method.

Each of these techniques optimizes the answer to minimize the effect of noise.

...

Saying "regression" is still pretty broad, because there are lots of variations on regression (linear regression, logistic regression, etc.). Here's a roadmap from Python's scikit-learn site that might give you roadmap of techniques that might work for you:

http://scikit-learn.org/stable/tutorial/machine_learning_map/index.html

(Note that something happened a while back, and the whole field of statistical analysis kind of crashed into the Arificial Intelligence realm and created the Machine Learning buzzword. So a lot of things that just would have been "statistics" or "analysis" are now "machine learning" because they meet the criteria of "improving the quality of the answer given more time and data")


问:
Should I pass array or pointer?
I am writing a C++ library (but prefer C style interface functions) and one of the function returns array of floats. I am not sure if I should pass pointer or fixed array to get this data?

```<code>// in the library header file
#define MAX_ITEMS_SIZE   1000

int getData(float * data, int &size );
</code>```

or

```<code>int getData(float (&data)[MAX_ITEMS_SIZE], int & size )
</code>```

If I am passing the pointer, the client should allocate MAX_ITEMS_SIZE for it. Is that a reasonable and fair expectations? Passing it as array forces the client to pass the max memory required. Which one is better?

Some more background, the MAX_ITEMS_SIZE is the maximum number of floats that can be returned. In reality the array will contain less items which is filled in the size parameter. The function returns int which is error code where zero means no error.

My overall goal is how to return the data which is array of floats in easy to understand and reliable way. Even though I am using C++, I would like to stick with C interface functions so the library can be used more widely.

答:
My few cents... Since you want to maintain compatibility with C, I would say - neither. C does not have a "reference" concept and it also does not allow for passing array by reference. Furthermore, C++ has name mangling so unless the function is declared with C-linkage, it would not be possible to call it from a C code in a straightforward way.

Therefore, I'd say that for the purpose of compatibility with C, the signature should look like this:

```<code>#ifdef __cplusplus
extern "C" {
#endif

int getData(float *data, int* size)

#ifdef __cplusplus
}
#endif
</code>```

Title: Should I pass array or pointer?

Body:
My few cents... Since you want to maintain compatibility with C, I would say - neither. C does not have a "reference" concept and it also does not allow for passing array by reference. Furthermore, C++ has name mangling so unless the function is declared with C-linkage, it would not be possible to call it from a C code in a straightforward way.

Therefore, I'd say that for the purpose of compatibility with C, the signature should look like this:

#ifdef __cplusplus
extern "C" {
#endif

int getData(float *data, int* size)

#ifdef __cplusplus
}
#endif


问:
Algorithm for Learning development
This is a fairly general question. I know a bit of Perl and Python and I am looking to learn programming in more depth so that once I get the hang of it I can start developing applications and then websites.

I would like to know of an algorithm (sequence of steps :)) that could describe my approach towards learning programming in general. I have posted small questions on Perl/Python and I have recieved great help from everyone.

Note:- I am not in a hurry to learn. I know it takes time and that's fine.

Please give any suggestions you think are valid. Also, please don't push me to learn Lisp, Haskell etc - I am a beginner.

答:
The 11 step algorithm for learning a new programming language

I'm currently in the process of learning Lisp, and I'd recommend the following algorithm:

Ask around if the language is worth learning and where good resources can be found. If positive responses to the language are given by experts then proceed to step 2.

Create an initial programming environment. Keep it simple: text editor and compiler/interpreter. The bare minimum. Consider a specific user account on your machine with a special colour scheme to cue the change of mindset.

Create the "Hello, World!" application.

Learn general syntax and control statements (if-then-else, repeat-until etc). Create sandbox to verify simple control cases (true/false evaluations etc). Try out every primitive type (int, double, string etc). Perform currency calculations. The number guessing game (as suggested by @Jeremy) is good for this.

Create class (if applicable) with several methods/functions. Make calls between functions. Apply control statements.

Learn arrays and collections. Create suitably complex examples that create arrays and collections of each of the classes/functions/primitives that are available to you

Learn file IO. Create examples of reading, manipulating and writing binary and character based files.

Ask more questions about idiomatic programming within the language (pointers, macros, monads, closures, support frameworks, build environments etc).

Choose (or adapt your existing) IDE to work in the recomended idiom.

Write a variety of applications that please you (or your boss).

After 1 year return to step 1 for another language while maintaining your interest in the one you've just been learning.

Title: Algorithm for Learning development


问:
Is it fine to skip MVC?
I am building a pair of components that communicates in a one-way fashion:

```<code>[ JButton ] --> data...process...process...out --> [ JTextField ]
</code>```

The JButton allows the user to select a file and the JButton's ActionListener picks up the click and pulls out the file name and directory.  I then need that information to be displayed by the JTextField.  Such functionality is so basic, it need not ever change.  Someone suggested a way to relay the message here, but I am asking another question: should I skip the MVC?

```<code>[ JButton ]  --> [ JTextField ]
</code>```

Simple is best, right? That's the simplest and clearest way I can think of of relaying the message.  I mean, just modify the the JTextField by JButton's ActionListener.  So should I go with this simpler approach or try to apply MVC anyway?

答:
It's ok to drop MVC if you're looking to write the fewest lines of code possible.

If that's your goal, you may also be interested in minimizing the number of objects you have instantiated at any one time.

You could achieve this by getting rid of your JTextField.  Simply customize your JButton to also display a text field and voila!  One object does two things.

Feels like a victory right?  No?

But it technically works, and it's pretty simple.  So it must be the best, no?

Probably not.

OK, so my example was a bit extreme, but I was simply trying to challenge your notion of "Simple is best".

The whole point of using a pattern like MVC isn't to produce simple code in terms of fewest classes, fewest objects, or fewest lines of code.  It's about producing code that is simple to maintain.

Eventually, ease of maintainability will become a big concern in your project.  Even if you don't think it will and even if you think your code will never change.

So, my suggestion:  Take the initial hit of writing more code.  Apply MVC.  You'll get more loosely coupled code which will make debugging and maintaining so much easier.

In Summary

Simple may be best, but it really depends on which definition of simple you're striving for.

Title: Is it fine to skip MVC?


问:
Is it okay to user other open source libraries when building your own or should that be avoided?
Seems like an odd question, but I've been questioning this myself for some time now.
 I've been told that, if you're working on a open source library/project, you should avoid adding dependencies for other external, open sourced, libraries because that'll make the software, that uses your libraries, become heavier with all the dependencies, inside dependencies, etc... But sometimes I'm a little on the fence about that. Do I really need to reinvent the wheel just to keep my library away from external dependencies?
For example, I'm currently building an Objective-C project that will be open sourced on Github and I need to use a XML parser to get data from — you guessed it — XML files. Apple's OS X already has a built-in API for XML parsing, but I'm not very fond of the way it works, it needs a lot of background processing and workarounds to get the data I really need, so I was thinking about using another XML parser to do a much cleaner job in terms of making my life easier, as the developer, but also by making the code a lot more legible for other developers.

What are your thoughts on this? Thank you.

答:
Xml Parsers are not something you should be building yourself, unless you want to for learning purposes or to make something specific for your needs.  XML parsers are complicated enough that other folks already know how to write one better than you or I could (within a reasonable time frame).

One of the reasons for using XML is that libraries to read and write it are readily available.  So, in the case of XML, I'd say go ahead and take the dependency.  The library writer has already done the hard work for you, and it doesn't make sense to spend weeks or months writing something that's already readily available.


问:
Do the Project managers build a structure of an app (with empty methods) then give it to the others for completing the app in real world Project?
I have very little experience working in a big project. But I did work about 3 months in a small outsourcer (a company that do the coding for a bigger foreigner web development company).

This is what I saw. The foreigner company did all the user analysis & all database designs. Then a group of the Project managers in that foreigner company start to build a structure of the Application.

That means they build all the basic classes that are the framework of the app. For example, in the framework they got many undone (empty) methods like:

```<code>int calNoOfCustomer(...){
   // do the calculation here
}
</code>```

My small company then starts to fill in the details of empty methods but it did not build the whole structure.

I think it likes an assignment in IT school. The teacher build a structure & empty methods & ask students to complete them.

So, I want to ask you that "is that the way how web development company does in real world big project?"

Do the Project managers build a structure of an application (with empty methods)  then give it to the other programmers for completing the app  in real world Big Project?

答:
Writing an "empty shell" is certainly one way of creating a design.  But it's more common for the architect or project designer to write Software Requirements and a Software Design Specification.

At its most basic form, software is about writing methods or functions, little bits of code that take an input, manipulate it in some way, and produce an output (the output can be in the form of side-effects and state changes).  In order to write those methods, a programmer needs to know:

The method name and signature,

The formal parameters and types,

The expected behavior of the method, and

Test cases.

You can get 1 and 2 with a program skeleton.  To get 3 and 4 you need requirements and a software design specification.


答:
The whole point of open source is that you don't have to reinvent the wheel.

But you do need to understand the licenses of the libraries you use. Just including a library doesn't mean you have to use the same license for your project. But if you change the code in a library you would have to use a compatible license.

For example, I can use a LGPL library in a commercial product, provided I supply the LGPL and make the library source available. I don't need to supply my source. But if I change that library, I would have to release my code under LGPL and supply my code.

Title: Is it okay to user other open source libraries when building your own or should that be avoided?

Body:
Seems like an odd question, but I've been questioning this myself for some time now.
 I've been told that, if you're working on a open source library/project, you should avoid adding dependencies for other external, open sourced, libraries because that'll make the software, that uses your libraries, become heavier with all the dependencies, inside dependencies, etc... But sometimes I'm a little on the fence about that. Do I really need to reinvent the wheel just to keep my library away from external dependencies?
For example, I'm currently building an Objective-C project that will be open sourced on Github and I need to use a XML parser to get data from — you guessed it — XML files. Apple's OS X already has a built-in API for XML parsing, but I'm not very fond of the way it works, it needs a lot of background processing and workarounds to get the data I really need, so I was thinking about using another XML parser to do a much cleaner job in terms of making my life easier, as the developer, but also by making the code a lot more legible for other developers.

What are your thoughts on this? Thank you.


问:
Model-View-Controller: Does the user interact with the View or with the Controller?
I have recently learned about the MVC design pattern. I'm learning from the Head First Design Pattern book.

According to this book (if I understand correctly):

The Model is most of the application logic and data.

The View is basically the GUI that represents the Model visually to the user.

The Controller is responsible to 'mediate', and act as a 'middleman' between the View and the Model. The View reports to the Controller that the user made an action, and the Controller translates it to method calls on the Model. The following figure shows what is described above:

However, a lot of places on the web contradict what I understand from that book. They claim that generally the user interacts with the Controller, not the View. The following figure illustrates the contradiction

Which one is true or more common? Does the user interact with the Controller directly, or with the View directly? Are both approaches acceptable? Which is more common?

答:
The user interacts with the View, but the View must communicate the actions to the Controller. The Controller may update the Model, but it isn't required with every/any change.

The description I am providing is based on my personal experience with the .NET implementation of MVC. Your implementation can be different.

The Controller is where actions are processed, basically a business layer. A simple controller will do nothing more than get the data from the Model to feed to the View. A complicated Controller will perform all sorts of actions, up to security management, authentication, authorization, registration, and possibly many other things.

The View should only be responsible for displaying the information in a fashion that the user can understand. There can be some cross over here with both the Controller and the Model as things like Single Page Applications (SPAs) will have data validation feedback for the user. Any other cross overs are heavily frowned upon.

The Model deals with data. This includes validation of data (where applicable). Data storage and retrieval is also handled in this layer.

UPDATE

There seems to be some confusion surrounding who does what when. I included two different overviews of the MVC architectures because they are similar, but not the same. There is room for either interpretation. Possibly, many more. The descriptions above are my interpretation of MVC from multiple sources, including my own experience building applications using this methodology. Hopefully, this update will help to clear up some of this confusion.

MVC is an attempt to build a Separation of Concerns design pattern for software development. It has primarily been implemented in web based applications (to my knowledge).

The View handles all of the user interaction. If your user clicks on a button, the View determines if the click is a user interface interaction or something that is beyond its concern (a Controller interaction). If the button does something like copy values from one field to another, your implementation will determine if that is a View concern or a Controller concern. You will most likely only have this blurring of concerns when dealing with a Single Page Application (SPA).

The Controller is where your actions are processed. The View has communicated the user decided to change values for some fields. The Controller may perform validation on that data or it may be handled by the Model. Again this is implementation dependent. If the Controller has security features, it may determine that the user doesn't have sufficient privileges to perform the action. It would reject the changes and update the View accordingly. The Controller also determines what data to retrieve from the Model, how to package it, and update the View with that data.

The Model determines how and where to store data. It may also perform validation of that data before storing it (it should do this because people will bypass the View on occasion).

Wikipedia has an article on MVC.

A model notifies its associated view/views and controllers when there has been a change in its state. This notification allows views to update their presentation, and the controllers to change the available set of commands. In some cases an MVC implementation might instead be "passive," so that other components must poll the model for updates rather than being notified.

A view is told by the controller all the information it needs for generating an output representation to the user. It can also provide generic mechanisms to inform the controller of user input.

A controller can send commands to the model to update the model's state (e.g., editing a document). It can also send commands to its associated view to change the view's presentation of the model (e.g., by scrolling through a document).

From Microsoft's Overview of MVC.

Models. Model objects are the parts of the application that implement the logic for the application's data domain. Often, model objects retrieve and store model state in a database. For example, a Product object might retrieve information from a database, operate on it, and then write updated information back to a Products table in a SQL Server database.

In small applications, the model is often a conceptual separation instead of a physical one. For example, if the application only reads a dataset and sends it to the view, the application does not have a physical model layer and associated classes. In that case, the dataset takes on the role of a model object.

Views. Views are the components that display the application's user interface (UI). Typically, this UI is created from the model data. An example would be an edit view of a Products table that displays text boxes, drop-down lists, and check boxes based on the current state of a Product object.

Controllers. Controllers are the components that handle user interaction, work with the model, and ultimately select a view to render that displays UI. In an MVC application, the view only displays information; the controller handles and responds to user input and interaction. For example, the controller handles query-string values, and passes these values to the model, which in turn might use these values to query the database.

ContentLicense: CC BY-SA 4.0


问:
DB Design: How to link a single column to a collection of entities
I have a db design question that I am sure has been quite extensively covered but I cannot find a good answer already.

The problem is how to efficiently link a single school course to a collection of textbooks, a course may have 0 books and it may have 10. The problem here is that multiple courses can use the same textbook as well.

My first thought was to include the textbook tables PK as a FK in the courses table. Then the courses table has a composite PK of course id and textbook id. The problem with this approach is that the courses table could potentially have a lot of columns, and then I am repeating the entire course row for every textbook addition, in addition to having to set a fake textbook_id for courses that do not have a textbook.

courses

course_id

course_name

FK textbook_id

PK(course_id, textbook_id)

textbook

textbook_id

textbook_name

My next thought was to have a table that has 10 columns for textbooks, that I use for linking a course to all the textbooks. But, I'm not sure if there is a better approach (this will end up using less space), when I think about this I think why not have textbook1, textbook2 columns in the courses table in the first place.

courses

PK course_id

course_name

FK textbooks_ids

course_textbook

FK course_id

FK textbook_1

FK textbook_2

FK textbook_3

FK textbook_4

textbook

isbn

textbook_name

A bit of background as well, using MySql, Hibernate ORM, and writing a separate search indexer.

Anyone have any suggestions on a better approach or thoughts on which of these two approaches is better?

Thanks in advance for the help

答: You are certainly getting close with your last thought. When you start to think about "a class could have at most ten textbooks," you're complicating the problem more than you need to.  Instead of having multiple columns for the course_textbook table, stick with one for textbook and one for course. This is a many-to-many mapping, and that's exactly what you want: the ability to pick any course, and find every book it uses, or pick and book, and find every course it uses. Typically, in database design, we care about only three conditions: 0, 1, and many. Your SELECT statement would then join on the table, returning multiple rows if there are multiple books.


问:
Who has right over the code that comes from contributions in an open source project?
If somebody starts an open source project (for example with a GPL license) where people will make contributions, than who will own these contributions in the level of the whole project? Will the new code become the property of the original author or the contributors will be authors too?

Who has the right over the ongoing project? For example who has the power to release the code in a second license? The original author only? Can the contributors separately do that as well, or do they have to make a joint decision with the original author and all of the contributors?

答: The copyright holder.  By default, that's the author of the code in question (each individual author if there are many).  Copyright can be assigned to someone else, and some open source projects do require copyright assignment as a condition of contributing.  </p>


答:
Each author retains copyright to their code.  If the project is under the GPL, contributing the code requires that the code is licensed under the GPL.  If you want to do something else with the code like releasing it in a different license, you'd need the permission of the original author.

For many projects, the project owner requires contributors to assign copyright to contributed code to the project owner.  This makes it possible to, for example, release GPL projects under new versions of the GPL license as those are released since it quickly becomes impractical to chase down hundreds of individual contributors in these cases.

Title: Who has right over the code that comes from contributions in an open source project?

Body:
If somebody starts an open source project (for example with a GPL license) where people will make contributions, than who will own these contributions in the level of the whole project? Will the new code become the property of the original author or the contributors will be authors too?

Who has the right over the ongoing project? For example who has the power to release the code in a second license? The original author only? Can the contributors separately do that as well, or do they have to make a joint decision with the original author and all of the contributors?


答:
There are a couple of non-legal paths you can take.

You mentioned that your client is a friend of a friend.  You could start there.  Tell your mutual friend about the situation.  Perhaps they can get in contact with your client and apply some pressure.

And excluding some sort of legal action your last resort is taking down the site.  Send your client another email asking for a response and that if you don't hear from him by X date that the site will be taken down.  My guess is that you will hear from him after that.

Title: How to get money from reluctant client?

Body:
I completed this website 4 months ago. (I would like to keep the website anonymous - if this post comes up on google search by customers, it will have a negative impact on their business). We did several iterations, the client was very demanding (and nosy), I complied with every single thing that was wanted, including the font-size of the footer which destroyed the aesthetic looks by quite a bit; (and they messed with the colours too, making it look dangerously childish and unprofessional).

Anyway, the client was very friendly during the whole process. After getting all the requirements I accepted to build the website for £950 and I charged him £150 in advance so he wouldn't want to bail out after I started the work. The requirements kept changing quite a lot, I made adjustments as and completed the website just 5 days late, w.r.t. the agreed date, in-spite all the changes in requirements.

That was four months ago. They have never returned my calls nor replied to my emails since then. How do I get the money back from them? I really need some advice on this, this is the second time someone has not paid me.

Points to be noted:

We did not sign any contract - the client was a friend of a friend.

I still hold the passwords for ftp, cpanel and everything. I don't want to bring the site down; somehow it doesn't seem ethical to me.

I posted this on Stack Overflow and it was closed, I was redirected here.

EDIT

Thank you everyone, for your enormous support. I thought I should include some more details: The client is hosting the site; as in, I made them register and use their own debit card to buy the domain name, webspace and everything, I just have the passwords for his cpanel, and ftp (well, I have access to cpanel that pretty much gives me access to many things).

Now, if I give them a warning, he might change the password to cpanel, but I am fairly sure they doesn't know about ftp's.

UPDATE

I followed Anna Lear's advice and sent the final invoice, on Saturday, with a warning that I will take the site down if he doesn't respond to my email before this Tuesday. They havn't replied to my emails yet, but I will let you know how this goes. Thanks much for your support. I plan to put up a holding page as Darknight suggested after Tuesday.

Points

I don't have a server space of my own, however I have few web spaces of my clients but I don't want to use them for this kind of purpose.

RESULTS

After my follow up of final invoice and warning, the client refused to anything. workman's advice seemed to be the most sensible to me. I mirrored the site to my own webspace, logged into his CPanel and forwarded the website to my site. Once that was done, I put up a holding page on my site so anyone going to the website would see a holdup page (nothing fishy, just an Under Construction page). Of course, this was all very weak in the sense that if my client knew about CPanel he could just remove the redirection. But, I had this second chance to get back to him and I was relying on him not knowing anything.

Two hours later, I got a call from the said client, (and  acting as if they did not get any of my voice mails or emails) and asked me to get the site back up. I, of-course, said I had to be paid and two days after that I received a bank transfer. The site's back up and running now.

Just wanted to say thank you all very much, I was very desperate when I had started this question. You are the best, not only you told me to learn the lesson (which I did) you also gave me a very very good solution that seemed to be very ethical (almost) to me.

A BIG thank you to workman!

If I could choose more than once answer, I would have chosen Anna Lear  too, but since I followed workman's advice I had to pick that up. People who made a point about not taking the site down without consulting a lawyer, thanks a lot.


问:
Scheduling between child and parent process
When child processes are created using the fork system call what is there scheduling priorities..are they same? if so will always a child process run first and then parent...or is there a manipulation to this pattern.

I have a implementation which apparently is running the parent process first.
Is this expected?

答:
Please be careful to understand that priority is not the same as order of running. As a rule, when you fork a process it runs at the same priority, unless you ask for it to be lower. The order in which parent and child run is separate.

The answer is that you cannot and should not depend on the order. In many cases after forking (or using any comparable mechanism in any other operating system), the parent will continue to run before the child starts. Or not. It all depends.

If it is important, you will have to include synchronising mechanisms to control which process runs and which waits.


问:
"Sensitive Data" clause in Bitbucket's Customer Agreement
I'm using Bitbucket for a few projects, but as of April 28, 2014 they will replace their End User Agreement with a new Customer Agreement. The new agreement mentions in 7.7.2: "You will not submit to the Hosted Services ... any personally identifiable information" One of my projects clearly contains such information, and I'm now trying to figure out what to do. These are the three possible options I could come up with:

I may keep all existing projects and continue to work with them, as long as no new patch involves sensitive data. This is under the assumption that what I have done so far has been in accordance with the current agreement, and that the new agreement only concerns information submitted after April 28.

I have to remove that particular project, but may keep the others. This seems likely if 7.4 in the new agreement means that any data that have been submitted to the "Hosted Services" will be treated equally, regardless of under which agreement it was submitted: "Your Data" means any data, content, code, video, images or other materials of any type that you upload, submit or otherwise transmit to or through Hosted Services.

I have to terminate the agreement, and thus remove my account and all of my projects. This is a possible interpretation if the continuation of 7.4, about the company's right to "collect, use, copy, store, transmit, modify and create derivative works of Your Data", means that they can still do whatever they want, even with data that were submitted under the terms of an older agreement and have since then been removed.

答:
The answer is that you should comply with your understanding of the agreement, which means you have to choose one of those options. You seem to have a good understanding, and if you go ahead and comply you most likely don't need a lawyer to tell you so.

If you plan to keep using the service, and if you get paid for doing it and/or you may cause harm to anyone, then you must get competent legal advice. That won't protect you, but it will tell you how bad the risks are.

To add one option: you could encrypt the data. If it uses strong encryption and you absolutely do not part with the keys (you keep them personally and in a safe place) then you should be safe. You might still want to get legal advice.

Bear in mind that this change in the agreement is probably a coded signal that the company is being required to hand over its data to a government body (the NSA for example). If you keep using the service, and particularly if you encrypt the data, you may yourself get a visit from someone in a suit and tie. If that happens, it will probably be too late to ask for advice.


问:
Authentication with If/Else
For keeping the "Administration Panel" secure to those who are logged in, for my web application, is the best practice to use an If/Else Statement?

```<code>if($_SESSION['logged_in'] == true) {
   include '../styles/templates/admincp/header.php';
   include '../styles/templates/admincp/content.php';
   include '../styles/templates/admincp/footer.php';
}
else {
   include '../styles/templates/login.php';
}
</code>```

Is this how the "professionals' (such as CMS creators, etc) do this authentication style? OR is there a completely better route and method to the If/Else statement to authenticate pages for logged in users to access?

答:
At some point, all authentication comes down to an if statement.

If this user is logged in...

If this user has manager privileges...

If this user has admin privileges...

If this user has connected from an OAuth provider...

There are many methods for including (or excluding) the privileged features:

Hide the things the user isn't allowed to see

Don't include a module or control

Redirect the user to a page that they do have access to

The example code you have posted will work just fine.

Title: Authentication with If/Else


答:
I think it means that you need to remove the project and or the personally identifiable information from the project.

On option 1 what is the point of having source code hosted somewhere if you can't update it? I don't think number 3 (terminating your account) is necessary, though as there is a reason this a change to the terms of use. The new terms of use were not in effect and you had not agreed to them when you checked in personally identifiable information.

I have to ask though, who do you dislike so much as to store their personal information unencrypted on a third party server that you have no control over?

On a side note chances are that atlassian's lawyers looked at their legal risk if their servers were compromised and realized that being responsible for personal information in source code repositories was a relatively large risk and not part of their core business model. So it makes sense for them to not want to be in the business of storing that type of information.

Frankly I can't think of a good reason to store personal info in source control outside of perhaps an error report email or similar.

Title: "Sensitive Data" clause in Bitbucket's Customer Agreement

Body:
I'm using Bitbucket for a few projects, but as of April 28, 2014 they will replace their End User Agreement with a new Customer Agreement. The new agreement mentions in 7.7.2: "You will not submit to the Hosted Services ... any personally identifiable information" One of my projects clearly contains such information, and I'm now trying to figure out what to do. These are the three possible options I could come up with:

I may keep all existing projects and continue to work with them, as long as no new patch involves sensitive data. This is under the assumption that what I have done so far has been in accordance with the current agreement, and that the new agreement only concerns information submitted after April 28.

I have to remove that particular project, but may keep the others. This seems likely if 7.4 in the new agreement means that any data that have been submitted to the "Hosted Services" will be treated equally, regardless of under which agreement it was submitted: "Your Data" means any data, content, code, video, images or other materials of any type that you upload, submit or otherwise transmit to or through Hosted Services.

I have to terminate the agreement, and thus remove my account and all of my projects. This is a possible interpretation if the continuation of 7.4, about the company's right to "collect, use, copy, store, transmit, modify and create derivative works of Your Data", means that they can still do whatever they want, even with data that were submitted under the terms of an older agreement and have since then been removed.


问:
Is it legal to reflector some .NET code and use it in a commercial application?
I'm working on a commercial application that requires .NET 4.0 Client Profile, but I need to make a call to HttpUtility.ParseQueryString, which is not included in the Client Profile but it is in the normal one.

So I just figured out that I can use Reflector to get the whole method and all the other required methods for it to work and add it to my app. This way I won't need to change the requirement from Client Profile to the normal one which is a lot heavier just to call a single method. Would this be illegal? Do I have to change the applications target framework just for a single method?

答:
We had a similar situation and we asked Microsoft's lawyers. They (eventually) responded that they regarded it as falling within the "fair use" provisions of copyright law. We used their source code on that basis.

As any competent lawyer will tell you, fair use:

allows you to copy and use small parts of a copyright work without seeking permission, depending on the purpose and other factors

usually allows commercial use regardless of any other terms in any licence

varies from country to country (the term is specific to the USA, the concept applies elsewhere).

This article is pretty good: http://en.wikipedia.org/wiki/Fair_use.

Note: reverse engineering of small parts is not a problem. It's what you do with the source code that matters.

Note: using Mono source code does not solve the problem. It just binds you to the Mono licence instead, unless you (again) rely on fair use.

If you plan commercial use or may cause damage to anyone, you really do need competent legal advice. It won't protect you, but it will tell you the risks and how to mitigate them.


答:
somehow it doesnt seem ethical to me

Neither is not paying you, or answering your calls.

I'm amazed you have waited this long. I kick up a fuss if my client doesn't pay me within one month - and I'm on a long term contract.

Title: How to get money from reluctant client?


答:
The user interacts with the Controller. From the technical point-of-view you're not interacting with the View, you're just using it to interact with the Controller.

On the surface it seems that the user is interacting with the GUI -- also to a non-programmer this makes more sense, however by clicking on a button you're basically talking to the Controller not the View.

Also not all the applications -- even MVC web-applications, does have a GUI. You might interact with the Controller via an API -- just simple url-routes for example, placed in the Controller itself.

The Controller should be the place that Receives and Handles the user requests. So if you're somehow accessing the Model directly from View -- doesn't matter how, then it's not MVC anymore.

Title: Model-View-Controller: Does the user interact with the View or with the Controller?

Body:
I have recently learned about the MVC design pattern. I'm learning from the Head First Design Pattern book.

According to this book (if I understand correctly):

The Model is most of the application logic and data.

The View is basically the GUI that represents the Model visually to the user.

The Controller is responsible to 'mediate', and act as a 'middleman' between the View and the Model. The View reports to the Controller that the user made an action, and the Controller translates it to method calls on the Model. The following figure shows what is described above:

However, a lot of places on the web contradict what I understand from that book. They claim that generally the user interacts with the Controller, not the View. The following figure illustrates the contradiction

Which one is true or more common? Does the user interact with the Controller directly, or with the View directly? Are both approaches acceptable? Which is more common?


答:
It comes down to an if statement finally somewhere in your code. Personally I've something more similar to this:

```<code>if ( true === (bool) $_SESSION['user']['login'] &&
     0 < (int) $_SESSION['user']['id'] &&
     time() <= ((int) $_SESSION['user']['last-activity'] + 20 * 60) &&
     $_SERVER['REMOTE_ADDR'] === (string) $_SESSION['user']['ip']
     ) {

    /* Update the last user activity time */
    $_SESSION['user']['last-activity'] = time();

    /* Check the permissions, etc. */

    /* Render dashboard */

} else {

    /* Redirect to Login */
    header( 'Location: ' + $cfg->url + '/login/' );
}
</code>```

Title: Authentication with If/Else

Body:
For keeping the "Administration Panel" secure to those who are logged in, for my web application, is the best practice to use an If/Else Statement?

```<code>if($_SESSION['logged_in'] == true) {
   include '../styles/templates/admincp/header.php';
   include '../styles/templates/admincp/content.php';
   include '../styles/templates/admincp/footer.php';
}
else {
   include '../styles/templates/login.php';
}
</code>```

Is this how the "professionals' (such as CMS creators, etc) do this authentication style? OR is there a completely better route and method to the If/Else statement to authenticate pages for logged in users to access?

Body:
It comes down to an if statement finally somewhere in your code. Personally I've something more similar to this:

if ( true === (bool) $_SESSION['user']['login'] &&
     0 < (int) $_SESSION['user']['id'] &&
     time() <= ((int) $_SESSION['user']['last-activity'] + 20 * 60) &&
     $_SERVER['REMOTE_ADDR'] === (string) $_SESSION['user']['ip']
     ) {

    /* Update the last user activity time */
    $_SESSION['user']['last-activity'] = time();

    /* Check the permissions, etc. */

    /* Render dashboard */

} else {

    /* Redirect to Login */
    header( 'Location: ' + $cfg->url + '/login/' );
}


问:
Need advice on design in Ruby On Rails
For personal educational purposes I am making a site for a conference. One of the object that exist in a conference is a session, which has different states and in each state it has slightly different attributes:

When submitted it has a speaker (User in the system), Title and abstract.

When under review it has reviews and comments (in addition to the basic data)

When accepted it has a defined time-slot but no reviewers anymore.

I feel that it is not the best thing to add a "status" attributes and start adding many if statements...

So I thought it would be better to have different classes for each state each with it's own validations and behaviors.

What do you think about this design? Do you have a better idea?

答:
I would say that this is one of those situations that could justify the use of Single Table Inheritance (STI). For the rails implementations see the API. The nice thing about using STI in this case would be that you store all the data in a single table, but are able to provide different 'windows' on it through the various child models. This way you keep the data of previous states readily available and also cover any data shared between states (you might need to know who reviewed an accepted submission, but that wouldn't matter anymore once it was scheduled).

Hope this helps,

Niels

PS if a few more pointers would be of use, just let me know! (Although that is probably more on-topic on Stack Overflow. If you repost your question there, let me know and I'll answer it there)

PPS concerning the option of adding bunches of if-statements: that is generally considered to be a 'code smell' and thus best avoided. See this answer on SO.

Title: Need advice on design in Ruby On Rails


问:
Designing software functions which are both pausable and restartable
Consider the following situation:

One hardware device, two applications (1 C# application, 1 Firmware).
The C# application sends frames to the firmware and the firmware executes scripts.

C# -> transmit frame[x]

FW -> receive frame[x]

FW -> execute script relating to frame[x]

FW   -> before finished, a FW event is triggered
forcing moving parts to stop (safety precaution).

C# requirement after such events are raised:

Poll FW for status, if status == stopped, send a resume fame.

Caveat: the C# logic therefore needs to adjust itself to being "restarted".

So this is the situation I have; but what I'm seeking advice with is how I should design a class which can handle the pausing and restarting of tasks an unlimited number of times.

While I can write convoluted methods which are hard to maintain through a chain of logical statements, I'm struggling with finding a design which is reusable and clean.

Such scenarios are true for ~50 unique tasks,  so finding a solution I can apply everytime would save a lot of headache. Anytime a script is restarted or resumed, a physical user can easily cause a safety trigger stop, therefore a solution needs to be robust.

While I'm sure recursion would be a first good step, I'm worried that the stack limits has the potential to introduce errors.

Clarification:

In my bid to simplify things, I seem to have omitted too much. Apologies.

Firmware:
Software running on a physical device which controls the hardware. I have no control over this code-base and it was designed independently while allowing USB communication.

Synchronization:
There is very little or no synchronization between the C# application and the firmware. My C# code will send a frame of bytes which match up to a specification document for the firmware, and if the frame is valid, the firmware will reply saying it received the frame and will begin the work. After that, there is no direct synchronization. A task described by a frame typically has two attributes: the time it takes to execute (need to manually observe) and an end target status (complete with status identifiers). Currently I poll the firmware for the status until the target status is reached or until time-out.

Recursion:
What I meant by that was (if not complete -> callSelfAgain())

Pause: User has done something to the device, wait here until they fix (can happen at ANY time during the time the firmware is running its jobs).

Restart: The user has amended the state, now start the job from the beginning (or where we left off [task dependent]).

答:
I think your best bet is to design the system as a state machine. The idea is that you have objects symbolizing each discrete step of the process, including any state data that has accumulated so far, and by pointing to the subtask currently being executed you can reconstruct the execution from that point.

However, I've just remembered that there is a C# mechanism that actually works in this exact manner and also fulfills all of your requirements. Although they weren't made for this purpose, you can implement the design using iterators.

They already support pausing execution at arbitrary points, and also support restarting it any number of items as the need arises. They don't actually have to return a value, but they can, and that's a bonus.

```<code>public class Unit {
    private Unit() {

    }
}
public class StateMachine {

    public IEnumerable<Unit> Run(int input) {

        int working = input + 1;
        yield return null; //stop execution
        //restarting... we still have all the working state data!
        working *= input;
        //more work...
        yield return null; //stop work
        //restart...
        if (IsError()) {
            throw new Exception();
        }
        if (IsOverPrematurely()) {
            yield break;
        }
    }
}
</code>```

(I might be misunderstanding whether or not your question requires a return value, though.)

Body:
I think your best bet is to design the system as a state machine. The idea is that you have objects symbolizing each discrete step of the process, including any state data that has accumulated so far, and by pointing to the subtask currently being executed you can reconstruct the execution from that point.

However, I've just remembered that there is a C# mechanism that actually works in this exact manner and also fulfills all of your requirements. Although they weren't made for this purpose, you can implement the design using iterators.

They already support pausing execution at arbitrary points, and also support restarting it any number of items as the need arises. They don't actually have to return a value, but they can, and that's a bonus.

public class Unit {
    private Unit() {

    }
}
public class StateMachine {

    public IEnumerable<Unit> Run(int input) {

        int working = input + 1;
        yield return null; //stop execution
        //restarting... we still have all the working state data!
        working *= input;
        //more work...
        yield return null; //stop work
        //restart...
        if (IsError()) {
            throw new Exception();
        }
        if (IsOverPrematurely()) {
            yield break;
        }
    }
}

(I might be misunderstanding whether or not your question requires a return value, though.)


问:
How to get money from reluctant client?
I completed this website 4 months ago. (I would like to keep the website anonymous - if this post comes up on google search by customers, it will have a negative impact on their business). We did several iterations, the client was very demanding (and nosy), I complied with every single thing that was wanted, including the font-size of the footer which destroyed the aesthetic looks by quite a bit; (and they messed with the colours too, making it look dangerously childish and unprofessional).

Anyway, the client was very friendly during the whole process. After getting all the requirements I accepted to build the website for £950 and I charged him £150 in advance so he wouldn't want to bail out after I started the work. The requirements kept changing quite a lot, I made adjustments as and completed the website just 5 days late, w.r.t. the agreed date, in-spite all the changes in requirements.

That was four months ago. They have never returned my calls nor replied to my emails since then. How do I get the money back from them? I really need some advice on this, this is the second time someone has not paid me.

Points to be noted:

We did not sign any contract - the client was a friend of a friend.

I still hold the passwords for ftp, cpanel and everything. I don't want to bring the site down; somehow it doesn't seem ethical to me.

I posted this on Stack Overflow and it was closed, I was redirected here.

EDIT

Thank you everyone, for your enormous support. I thought I should include some more details: The client is hosting the site; as in, I made them register and use their own debit card to buy the domain name, webspace and everything, I just have the passwords for his cpanel, and ftp (well, I have access to cpanel that pretty much gives me access to many things).

Now, if I give them a warning, he might change the password to cpanel, but I am fairly sure they doesn't know about ftp's.

UPDATE

I followed Anna Lear's advice and sent the final invoice, on Saturday, with a warning that I will take the site down if he doesn't respond to my email before this Tuesday. They havn't replied to my emails yet, but I will let you know how this goes. Thanks much for your support. I plan to put up a holding page as Darknight suggested after Tuesday.

Points

I don't have a server space of my own, however I have few web spaces of my clients but I don't want to use them for this kind of purpose.

RESULTS

After my follow up of final invoice and warning, the client refused to anything. workman's advice seemed to be the most sensible to me. I mirrored the site to my own webspace, logged into his CPanel and forwarded the website to my site. Once that was done, I put up a holding page on my site so anyone going to the website would see a holdup page (nothing fishy, just an Under Construction page). Of course, this was all very weak in the sense that if my client knew about CPanel he could just remove the redirection. But, I had this second chance to get back to him and I was relying on him not knowing anything.

Two hours later, I got a call from the said client, (and  acting as if they did not get any of my voice mails or emails) and asked me to get the site back up. I, of-course, said I had to be paid and two days after that I received a bank transfer. The site's back up and running now.

Just wanted to say thank you all very much, I was very desperate when I had started this question. You are the best, not only you told me to learn the lesson (which I did) you also gave me a very very good solution that seemed to be very ethical (almost) to me.

A BIG thank you to workman!

If I could choose more than once answer, I would have chosen Anna Lear  too, but since I followed workman's advice I had to pick that up. People who made a point about not taking the site down without consulting a lawyer, thanks a lot.

答:
Put up a holding page.

and remove the content, until he pays you.

And I would do this fast, because if he is smart, he may simply move the hosting else were.

Title: How to get money from reluctant client?


问:
What is the order analysis of the following (using a list of primes)
I have the following program:

Iterate x from 1 to N.  Check to see if x is prime.  If it is, add it to a list of primes.

The way I check to see if it is prime is iterating through the current list of primes, and seeing if they can divide x evenly.

What is the order analysis of this program?  I don't think it is O(n^2), because the growing list of primes certainly doesn't increase at the rate of n.  I don't it is O(nlog(n)), either.

How would I perform order analysis of the function?

答:
You are using the naive methods of Primality testing. For a given n the number of primes < n is given by the
prime counting function, which is approximately n/log(n). I'm not 100% sure of the complexity of this method as you generally will not need to divide by all primes < sqrt(n).

The slightly more sophisticated Sieve_of_Eratosthenes has complexity O(n log log n).


答:
Everybody holds the copyright to the code they write. Which means by default the original author is the only person who can grant a license for that code.

As open source project typically have many authors it is not feasible to track down all authors and get them to agree every time a licensing change needs to be made. To avoid this problem some open source projects are licensed under a license which allows the use of the code under any later version of that license. This way you get the authors to agree to future versions of the license which are not yet available. Usually the license authors promise to make those later versions similar in spirit to the original license, e.g. in the GNU General Public License:

The Free Software Foundation may publish revised and/or new versions
  of the GNU General Public License from time to time. Such new versions
  will be similar in spirit to the present version, but may differ in
  detail to address new problems or concerns.

The other way to tackle this problem is to have authors agree to transfer their copyright to somebody else, e.g. the project owner. This person is then entitled to decide whether to license the project und a new license. The downside of this approach is that project owners are people and might not act in the spirit of the original author. This also makes it harder for forks to switch to a newer license as the original project owner is likely not part of the fork and the fork owner will not have the copyright of the original code authors.

Lastly, when you are a really big entity you might petition the license authors into making changes to the license. This is how Wikimedia managed to switch from a GFDL-only licensing to dual licensing with CC-by-sa: They petitioned the FSF to publish a newer version of the GFDL which included a section to enable projects to switch their content to CC-by-sa for a limited time.

As you can see, licensing is always a hassle and it's not clear what the best course of action is. Usually you should invest a bit of time into finding the right license for the project before you have other people contribute as changing the license later on is usually quite hard.


问:
Unit testing behaviours without coupling to implementation details
In his talk TDD, where did it all go wrong, Ian Cooper pushes Kent Beck's original intention behind unit testing in TDD (to test behaviours, not methods of classes specifically) and argues for avoiding coupling the tests to the implementation.

In the case of behaviour like save X to some data source in a system with a typical set of services and repositories, how can we unit test the saving of some data at the service level, through the repository, without coupling the test to implementation details (like calling a specific method)? Is avoiding this kind of coupling actually not worth the effort/bad in some way?

答:
Your specific example is a case that you usually have to test by checking if a certain method was called, because saving X to data source means communicating with an external dependency, so the behavior you have to test is that the communication is occurring as expected.

However, this isn't a bad thing. The boundary interfaces between your application and its external dependencies are not implementation details, in fact, they are defined in the architecture of your system; which means that such a boundary is not likely to change (or if it must, it would be the least frequent kind of change). Thus, coupling your tests to a repository interface should not cause you too much trouble (if it does, consider if the interface is not stealing responsibilities from the application).

Now, consider only the business rules of an application, decoupled from UI, databases and other external services. This is were you must be free to change both structure and behavior of the code. This is where coupling tests and implementation details will force you to change more test code than production code, even when there is no change in the overall behavior of the application. This is where testing State instead of Interaction help us go faster.

PS: It's not my intention to say if testing by State or Interactions is the only true way of TDD - I believe it to be a matter of using the right tool for the right job.


答:
Note that the answer depends in large part on the terms under which the open-source project accepts your code.

Most will, at the very least, have a statement saying that by contributing it you have granted the project rights to use, distribute, etc. your contribution, and granted all the project's users rights to look at and execute your code. That doesn't negate your copyright, but it means you have irrevocably agreed to license it for use in that project.

Depending on the terms under which the project is then distributed and the details of the license you have agreed to, that may or may not give everyone else with access to the project rights to use your code in other contexts.

It's your responsibility to read and understand these details before you contribute code. If in doubt, you can ask the folks running the project to explain what they intended their licenses to say, but remember that free legal advice -- including everything you're seeing in response to your question -- is worth exactly what you paid for it.

If this really matters to you, get the exact language and hire your own lawyer to examine it for pitfalls. Or don't contribute code you aren't willing to see escape into general use. Or get someone else to do that research for you -- my employer has fairly specific rules about what kinds of open source I am and am not allowed to get involved with.


答:
Let's use a concrete example of why users interact directly with views and not controllers.

In the music app on the iPhone, a high level feature is to play a playlist. "Play a playlist" is a function of a controller to the app.

There is more than one way to activate that function. I can click on the playlist inside of the app, or I can ask Siri (voice interface) to perform the same function. Those are two different gestures that are recognized by the various views.

The feedback in each view is also different. Siri will tell you that it is playing the music you requested. The music app will show you a visual feedback that it is playing the playlist.


问:
Is it advisable to create an ad-hoc open source software license?
I have several private projects that I might be needed to show to my prospective employers. I haven't uploaded them to any online version control system because not only do I not have the patience to filter the many many licenses available and choose the most appropriate one (as I am not yet sure how I would want my open source code to be used), I also feel the projects aren't fit enough for upload in public domain as they are not tested rigorously enough for me. I could create a private repository somewhere and allow access to the prospective employers, or I could simply take a USB stick with me, but the question still remains about licensing.

So, I thought of creating an ad-hoc license to the effect of saying "this code is made available to you and no part of it shall be reproduced from memory...", which is almost like signing a NDA. I know it might sound silly, or inane, but I want to protect my IP in someway (you never know what your code could become!).

What is the best way of going about this? If indeed license creation is an option, how would the creation work? Would merely writing a prologue at the beginning of every source file suffice, or is there some long winding legality involved?

答:
You don't have to license your code at all in order to publicise it – with no license stating otherwise, other people can't do anything with your code except reading it. There are some exceptions:

Copyright law may grant limited use of your work. One important example is the fair use clause in U.S. copyright law, another common exemption would be citations in an academic work – but all of these vary from country to country.

If you distribute your code via some service, you grant this service the right to do so which essentially is a kind of license. Depending on the service, you may also be granting further rights. For example, GitHub has the following paragraph in its TOS:

We claim no intellectual property rights over the material you provide to the Service. Your profile and materials uploaded remain yours. However, by setting your pages to be viewed publicly, you agree to allow others to view your Content. By setting your repositories to be viewed publicly, you agree to allow others to view and fork your repositories.

Your works are protected by copyright even without any markings or boilerplate clauses.
But while you don't need any license, you should make sure that it's perfectly clear who owns the copyright: you. A simple comment “Copyright 2014 by My Name” is sufficient for that. To emphasize that you aren't granting any rights to the reader, you can also use the phrase “all rights reserved”, although it has no legal significance.

Note: IANAL either.


问:
Programmers forgetting syntax
Do good programmers need to have syntax at the tip of their tongue when writing code? What do you make of them if they google for simple stuff online?  Are they good or bad(maybe they know where to look for)? Should programmers have a good memory? Is this a trait for a good programmer?</p>

答:
I'm curious about Googling "syntax" here.

My suspicion (and fear) is that we're not talking about what parameters a call takes (because most IDEs will prompt you there so you wouldn't Google them) but actual "how to do X" type things.

IDEs have made it unnecessary to memorise precise names and parameter lists in the way that used to be required and that's made many people a bit lazy about it but that's fine.

But something you need to Google?  To me that's usually not syntax, that's just something you either don't really know or are only passingly familiar with.

Of course that's not to say it's wrong to have to Google stuff - languages can be pretty broad these days and few people know everything but I would say that if you claim to be competent with a language then Google should be the exception rather than the rule.

For me unless you're doing something relatively unusual, or perhaps you're rusty with the language after a period of doing something different, if you claim to "know" a language, you shouldn't be Googling more than 10% of stuff at most, and that should be really quite specific stuff.

In reference to the idea that this is about having a good memory, it's not really.  It's about the sort of instinctive feel you get for something you really (rather than superficially) know.  I don't consider the fact I know how to cook a Melanzane Parmigiana without a recipe a sign that I have a good memory, it's a sign that I understand how to cook that dish - they're subtly different things.

Besides, ask yourself this, would you expect to go into a restaurant kitchen and find the chef constantly looking at a cookbook?  Or to see the mechanic working on your car flicking through the Hayes manual for that model?  If I saw either of those things I'd be pretty uneasy about how good that person was.

Title: Programmers forgetting syntax


问:
Java's Boolean class - why not an enum?
It seems to me that the Boolean class is an ideal candidate to be implemented as an enum.

Looking at the source code, most of the class is static methods which could be moved unchanged to an enum, the rest become much simpler as an enum.  Compare original (comments and static methods removed):

```<code>public final class Boolean implements java.io.Serializable,
                                      Comparable<Boolean>
{
   public static final Boolean TRUE = new Boolean(true);
  public static final Boolean FALSE = new Boolean(false);
   private final boolean value;
   public Boolean(boolean value) {
       this.value = value;
   }
   public Boolean(String s) {
       this(toBoolean(s));
   }
   public boolean booleanValue() {
       return value;
   }
   public String toString() {
       return value ? "true" : "false";
   }
   public int hashCode() {
       return value ? 1231 : 1237;
   }
   public boolean equals(Object obj) {
       if (obj instanceof Boolean) {
           return value == ((Boolean)obj).booleanValue();
       }
       return false;
   }
   public int compareTo(Boolean b) {
       return compare(this.value, b.value);
   }
}
</code>```

with an enum version:

```<code>public enum Boolean implements Comparable<Boolean>
{
   FALSE(false), TRUE(true);
   private Boolean(boolean value) {
       this.value = value;
   }
   private final boolean value;
   public boolean booleanValue() {
       return value;
   }

   public String toString() {
       return value ? "true" : "false";
   }
}
</code>```

Is there any reason why Boolean couldn't become an enum?

If this is the Sun code to override the equals() method, it is missing a very fundamental check of comparing the references of the two objects before comparing their values. This is how I think the equals() method should be:

```<code>   public boolean equals(Object obj) {

       if (this == obj) {
          return true;
       }

       if (obj instanceof Boolean) {
           return value == ((Boolean)obj).booleanValue();
       }
       return false;
   }
</code>```

答:
There are some things that don't work, and don't work in rather surprising ways when you compare them to previous functionality of Java's boolean.

We're going to ignore boxing as that was something added with 1.5.  Hypothetically, if Sun wanted to they could have made the enum Boolean to behave just like the boxing performed on the class Boolean.

Yet, there are other surprising (to the coder) ways that this would suddenly break compared to the functionality of the earlier class.

The valueOf(String) problem

A simple example of this is:

```<code>public class BooleanStuff {
    public static void main(String args[]) {
        Boolean foo = Boolean.valueOf("TRUE");
        System.out.println(foo);
        foo = Boolean.valueOf("TrUe");
        System.out.println(foo);
        foo = Boolean.valueOf("yes");  // this is actually false
        System.out.println(foo);

        // Above this line is perfectly acceptable Java 1.3
        // Below this line takes Java 1.5 or later

        MyBoolean bar;
        bar = MyBoolean.valueOf("FALSE");
        System.out.println(bar);
        bar = MyBoolean.valueOf("FaLsE");
        System.out.println(bar);
    }

    enum MyBoolean implements Comparable<MyBoolean> {
        FALSE(false), TRUE(true);
        private MyBoolean(boolean value) { this.value = value; }
        private final boolean value;
        public boolean booleanValue() { return value; }
        public String toString() { return value ? "true" : "false"; }
    }
}
</code>```

The run of this code gives:

```
true
true
false
false
Exception in thread "main" java.lang.IllegalArgumentException: No enum constant BooleanStuff.MyBoolean.FaLsE
    at java.lang.Enum.valueOf(Enum.java:236)
    at BooleanStuff$MyBoolean.valueOf(BooleanStuff.java:17)
    at BooleanStuff.main(BooleanStuff.java:13)
```

The problem here is that I can't pass through anything that isn't TRUE or FALSE to valueOf(String).

That's ok... we'll just override it with our own method...

```<code>    public static MyBoolean valueOf(String arg) {
        return arg.equalsIgnoreCase("true") ? TRUE : FALSE;
    }
</code>```

But... there's a problem here.  You can't override a static method.

And so, all the code that is passing around true or True or some other case mixed will error out - and quite spectacularly with a runtime exception.

Some more fun with valueOf

There are some other bits that don't work too well:

```<code>public static void main(String args[]) {
    Boolean foo = Boolean.valueOf(Boolean.valueOf("TRUE"));
    System.out.println(foo);

    MyBoolean bar = MyBoolean.valueOf(MyBoolean.valueOf("FALSE"));
    System.out.println(bar);
}
</code>```

For foo, I just get a warning about boxing an already boxed value.  However, the code for bar is a syntax error:

```
Error:(7, 24) java: no suitable method found for valueOf(BooleanStuff.MyBoolean)
    method BooleanStuff.MyBoolean.valueOf(java.lang.String) is not applicable
      (actual argument BooleanStuff.MyBoolean cannot be converted to java.lang.String by method invocation conversion)
    method java.lang.Enum.valueOf(java.lang.Class,java.lang.String) is not applicable
      (cannot instantiate from arguments because actual and formal argument lists differ in length)
```

If we coerce that syntax error back into a String type:

```<code>public static void main(String args[]) {
    Boolean foo = Boolean.valueOf(Boolean.valueOf("TRUE"));
    System.out.println(foo);

    MyBoolean bar = MyBoolean.valueOf(MyBoolean.valueOf("FALSE").toString());
    System.out.println(bar);
}
</code>```

We get our runtime error back:

```
true
Exception in thread "main" java.lang.IllegalArgumentException: No enum constant BooleanStuff.MyBoolean.false
    at java.lang.Enum.valueOf(Enum.java:236)
    at BooleanStuff$MyBoolean.valueOf(BooleanStuff.java:11)
    at BooleanStuff.main(BooleanStuff.java:7)
```

Why anyone would write that? Dunno... but its code that used to work and would no longer work.

Don't get me wrong, I really do like the idea of only one copy of a given immutable object ever.  The enum does solve this problem.  I've personally encountered vendor code that had bugs in it from vendor code that looked something like this:

```<code>if(boolValue == new Boolean("true")) { ... }
</code>```

that never worked (No, I didn't fix it because the incorrect state was fixed somewhere else, and fixing this broke that in strange ways that I really didn't have the time to debug).  If this was an enum, that code would have worked instead.

However, the necessities of the syntax around the enum (case sensitive - dig into the enumConstantDirectory behind valueOf, runtime errors that need to work that way for the other enums) and the way static methods work causes a number of things to break that prevents it from being a drop in replacement for a Boolean.

Title: Java's Boolean class - why not an enum?

Body:
There are some things that don't work, and don't work in rather surprising ways when you compare them to previous functionality of Java's boolean.

We're going to ignore boxing as that was something added with 1.5.  Hypothetically, if Sun wanted to they could have made the enum Boolean to behave just like the boxing performed on the class Boolean.

Yet, there are other surprising (to the coder) ways that this would suddenly break compared to the functionality of the earlier class.

The valueOf(String) problem

A simple example of this is:

public class BooleanStuff {
    public static void main(String args[]) {
        Boolean foo = Boolean.valueOf("TRUE");
        System.out.println(foo);
        foo = Boolean.valueOf("TrUe");
        System.out.println(foo);
        foo = Boolean.valueOf("yes");  // this is actually false
        System.out.println(foo);

        // Above this line is perfectly acceptable Java 1.3
        // Below this line takes Java 1.5 or later

        MyBoolean bar;
        bar = MyBoolean.valueOf("FALSE");
        System.out.println(bar);
        bar = MyBoolean.valueOf("FaLsE");
        System.out.println(bar);
    }

    enum MyBoolean implements Comparable<MyBoolean> {
        FALSE(false), TRUE(true);
        private MyBoolean(boolean value) { this.value = value; }
        private final boolean value;
        public boolean booleanValue() { return value; }
        public String toString() { return value ? "true" : "false"; }
    }
}

The run of this code gives:

true
true
false
false
Exception in thread "main" java.lang.IllegalArgumentException: No enum constant BooleanStuff.MyBoolean.FaLsE
    at java.lang.Enum.valueOf(Enum.java:236)
    at BooleanStuff$MyBoolean.valueOf(BooleanStuff.java:17)
    at BooleanStuff.main(BooleanStuff.java:13)

The problem here is that I can't pass through anything that isn't TRUE or FALSE to valueOf(String).

That's ok... we'll just override it with our own method...

    public static MyBoolean valueOf(String arg) {
        return arg.equalsIgnoreCase("true") ? TRUE : FALSE;
    }

But... there's a problem here.  You can't override a static method.

And so, all the code that is passing around true or True or some other case mixed will error out - and quite spectacularly with a runtime exception.

Some more fun with valueOf

There are some other bits that don't work too well:

public static void main(String args[]) {
    Boolean foo = Boolean.valueOf(Boolean.valueOf("TRUE"));
    System.out.println(foo);

    MyBoolean bar = MyBoolean.valueOf(MyBoolean.valueOf("FALSE"));
    System.out.println(bar);
}

For foo, I just get a warning about boxing an already boxed value.  However, the code for bar is a syntax error:

Error:(7, 24) java: no suitable method found for valueOf(BooleanStuff.MyBoolean)
    method BooleanStuff.MyBoolean.valueOf(java.lang.String) is not applicable
      (actual argument BooleanStuff.MyBoolean cannot be converted to java.lang.String by method invocation conversion)
    method java.lang.Enum.valueOf(java.lang.Class,java.lang.String) is not applicable
      (cannot instantiate from arguments because actual and formal argument lists differ in length)

If we coerce that syntax error back into a String type:

public static void main(String args[]) {
    Boolean foo = Boolean.valueOf(Boolean.valueOf("TRUE"));
    System.out.println(foo);

    MyBoolean bar = MyBoolean.valueOf(MyBoolean.valueOf("FALSE").toString());
    System.out.println(bar);
}

We get our runtime error back:

true
Exception in thread "main" java.lang.IllegalArgumentException: No enum constant BooleanStuff.MyBoolean.false
    at java.lang.Enum.valueOf(Enum.java:236)
    at BooleanStuff$MyBoolean.valueOf(BooleanStuff.java:11)
    at BooleanStuff.main(BooleanStuff.java:7)

Why anyone would write that? Dunno... but its code that used to work and would no longer work.

Don't get me wrong, I really do like the idea of only one copy of a given immutable object ever.  The enum does solve this problem.  I've personally encountered vendor code that had bugs in it from vendor code that looked something like this:

if(boolValue == new Boolean("true")) { ... }

that never worked (No, I didn't fix it because the incorrect state was fixed somewhere else, and fixing this broke that in strange ways that I really didn't have the time to debug).  If this was an enum, that code would have worked instead.

However, the necessities of the syntax around the enum (case sensitive - dig into the enumConstantDirectory behind valueOf, runtime errors that need to work that way for the other enums) and the way static methods work causes a number of things to break that prevents it from being a drop in replacement for a Boolean.


问:
How do statically typed languages handle test discovery?
I come from a Python background, so I'm used to pretty automatic test discovery. For example, the py.test library automatically locates any files which begin with test, finds classes whose names start with Test inside of the those files, and then calls all the functions whose names start with test_ in those classes.

This type of test discovery is enabled by Python's deep support for reflection and dynamism.

These features are often absent in statically typed languages, because they're difficult to make integrate with the type system.

Therefore, I'm interested in hearing about what approaches statically typed languages use to make test discovery simpler?

答:
Many statically-typed languages still use reflection for this purpose - for example, JUnit3 calls all methods named testWhatever, and go test looks for methods named TestWhatever() inside any _test.go files.

JUnit4 appears to rely on Java's "annotations" system -- it supports a @Test annotation which is available at runtime and is used for test discovery (https://github.com/junit-team/junit/wiki/Getting-started).

I've personally done some awful, awful things in C using GCC's __attribute__((section)) and the preprocessor to implement a DSL for tests -- see the implementation details. I don't really recommend it.