问:
How do you detect lying Stubs/Mocks?
Consider this piece of code from the PHPUnit manual(I'm using PHP only as an example):

```<code>class StubTest extends PHPUnit_Framework_TestCase
{
    public function testStub()
    {
        // Create a stub for the SomeClass class that could be later injected into another class, but removed here for simplicity.
        $stub = $this->getMock('SomeClass');

        // Configure the stub.
        $stub->expects($this->any())
             ->method('doSomething')
             ->will($this->returnValue('foo'));

        // Calling $stub->doSomething() will now return 'foo'.
        $this->assertEquals('foo', $stub->doSomething());
    }
}
</code>```

Now I just stubbed the method doSomething() to return foo.

What if some time later in the future I decide to implement SomeClass like this:

```<code>class SomeClass{

    function doSomething(){
        return 'bar';
    }
}
</code>```

Of course i have tests for SomeClass that test for bar, but I totally forgot to test for foo.

Now I have a lying test. How does TDD handle this situation?

答:
```<code>// Calling $stub->doSomething() will now return 'foo'.
$this->assertEquals('foo', $stub->doSomething());
</code>```

This right here is actually the key part of the code that represents the following two problems:

The way you are implementing your tests, you are testing your tests, not testing your code,

If you need that level of specificity, you are testing implementation, not interface.

Asserting that the output of a stub is what you said it should be exercises the functionality of the testing framework's stubbing functionality rather than anything in your code. I doubt you have any actual lines like the above in your tests, but, subtly, you probably have tests that amount to the same if you are asking the question you are asking.

Let's say we have an example test, which I will use to explain:

```<code>// A Doubler takes the result of SomeClass#doSomething and doubles it.
class DoublerTest extends PHPUnit_Framework_TestCase
{
    public function testToString()
    {

        // Create a stub for the SomeClass
        $stub = $this->getMock('SomeClass');

        // Configure the stub.
        $stub->expects($this->any())
             ->method('doSomething')
             ->will($this->returnValue('foo'));

        $doubler = new Doubler($stub);

        // Calling $doubler->toString() will now return 'foofoo'.
        $this->assertEquals('foofoo', $doubler->toString());
    }
}
</code>```

A Doubler has a simple functionality: double the return value of the doSomething method of the injected SomeClass. What's important to note there is that I did not specify what SomeClass#doSomething needed to returns, as it is irrelevant to the algorithm. Whether it returns "foo" or "bar", the method works the same. The test still gives useful and valid information.

Now, you may contend that, in your case, the return value does change the outcome of the algorithm:

```<code>// Doubler also doubles 'r's in the output string
// ... setup the stub, return "bar" ...
$this->assertEquals('barrbarr', $doubler->toString());

// If Doubler sees a 'q', party time! (return "PartyParty")
// ... setup the stub, return "qux" ...
$this->assertEquals('PartyParty', $doubler->toString());
</code>```

This should be apparent in the specification of the Doubler class (which you use to guide building your tests in TDD), and should already be tested for, since it represents a code path in that class. A code coverage tool will make spotting code paths easy if you miss any (and there's one built into PHPUnit). Therefore, changing the implementation of SomeClass#doSomething is still irrelevant to the test.

If you change the interface of SomeClass in a way that doesn't follow a pre-existing code path, you will find you need to write new code in the dependent classes anyway, which is the point where you will alter the tests (including stubs) for that code, bringing it back in alignment with your interface.

Unit tests are meant to test interfaces rather than implementations. If your code depends on subtle implementation details like the exact return value of a method beyond just its type (or beyond other general factors), writing and running integration tests will most likely find those types of problems. Ideally, your code won't depend on implementation details and you could use OO design patterns and principles to isolate those details, but we don't live in an ideal world.

Title: How do you detect lying Stubs/Mocks?

Body:
// Calling $stub->doSomething() will now return 'foo'.
$this->assertEquals('foo', $stub->doSomething());

This right here is actually the key part of the code that represents the following two problems:

The way you are implementing your tests, you are testing your tests, not testing your code,

If you need that level of specificity, you are testing implementation, not interface.

Asserting that the output of a stub is what you said it should be exercises the functionality of the testing framework's stubbing functionality rather than anything in your code. I doubt you have any actual lines like the above in your tests, but, subtly, you probably have tests that amount to the same if you are asking the question you are asking.

Let's say we have an example test, which I will use to explain:

// A Doubler takes the result of SomeClass#doSomething and doubles it.
class DoublerTest extends PHPUnit_Framework_TestCase
{
    public function testToString()
    {

        // Create a stub for the SomeClass
        $stub = $this->getMock('SomeClass');

        // Configure the stub.
        $stub->expects($this->any())
             ->method('doSomething')
             ->will($this->returnValue('foo'));

        $doubler = new Doubler($stub);

        // Calling $doubler->toString() will now return 'foofoo'.
        $this->assertEquals('foofoo', $doubler->toString());
    }
}

A Doubler has a simple functionality: double the return value of the doSomething method of the injected SomeClass. What's important to note there is that I did not specify what SomeClass#doSomething needed to returns, as it is irrelevant to the algorithm. Whether it returns "foo" or "bar", the method works the same. The test still gives useful and valid information.

Now, you may contend that, in your case, the return value does change the outcome of the algorithm:

// Doubler also doubles 'r's in the output string
// ... setup the stub, return "bar" ...
$this->assertEquals('barrbarr', $doubler->toString());

// If Doubler sees a 'q', party time! (return "PartyParty")
// ... setup the stub, return "qux" ...
$this->assertEquals('PartyParty', $doubler->toString());

This should be apparent in the specification of the Doubler class (which you use to guide building your tests in TDD), and should already be tested for, since it represents a code path in that class. A code coverage tool will make spotting code paths easy if you miss any (and there's one built into PHPUnit). Therefore, changing the implementation of SomeClass#doSomething is still irrelevant to the test.

If you change the interface of SomeClass in a way that doesn't follow a pre-existing code path, you will find you need to write new code in the dependent classes anyway, which is the point where you will alter the tests (including stubs) for that code, bringing it back in alignment with your interface.

Unit tests are meant to test interfaces rather than implementations. If your code depends on subtle implementation details like the exact return value of a method beyond just its type (or beyond other general factors), writing and running integration tests will most likely find those types of problems. Ideally, your code won't depend on implementation details and you could use OO design patterns and principles to isolate those details, but we don't live in an ideal world.


问:
Java serialization - advantages and disadvantages, use or avoid?
Serialization is used for persistence in Java. It may be okay to persist a few objects using serialization. But, for a large number of objects, ORM, Database etc might be better. It seems that serialization is useful only for small jobs. May be I am wrong. So please tell me
what are the advantages of serialization over non-serialization methods ? When should it be used and when should it be avoided ?

This question came to my mind after seeing DZone article Is Object Serialization Evil?

And these are the lines that gave rise to my question:

If you look at Java and its session objects, pure object serialization is used. Assuming that an application session is fairly short-lived, meaning at most a few hours, object serialization is simple, well supported and built into the Java concept of a session. However, when the data persistence is over a longer period of time, possibly days or weeks, and you have to worry about new releases of the application, serialization quickly becomes evil. As any good Java developer knows, if you plan to serialize an object, even in a session, you need a real serialization ID (serialVersionUID), not just a 1L, and you need to implement the Serializable interface. However, most developers do not know the real rules behind the Java deserialization process. If your object has changed, more than just adding simple fields to the object, it is possible that Java cannot deserialize the object correctly even if the serialization ID has not changed. Suddenly, you cannot retrieve your data any longer, which is inherently bad.

Now, may developers reading this may say that they would never write code that would have this problem. That may be true, but what about a library that you use or some other developer no longer employed by your company? Can you guarantee that this problem will never happen? The only way to guarantee that is to use a different serialization method.

答:
What are the advantages of serialization over non-serialization methods ?

Java serialization has some advantages:

Built into the system: You don't need to rely on third-party tools, libraries, or configuration.

Relatively simple to understand, at least in the beginning.

Every developer knows it (or should).  Regardless of whether Java devs approve or disapprove, they are likely to be familiar with serialising Java objects.

And, of course, there are disadvantages:

Circumvents standard Java flow.  Allocates memory but does not call a constructor, so transient fields are not initialised.  Fields are initialised in alphabetical order, not source order.

Not so efficient in terms of space, but not horrible either.  You may want to compress the result.

Brittle unless you take precautions when your objects change.  And even then.

When should it be used and when should it be avoided ?

Use when:

Deployment size matters.  Built into the system, so 0 extra bytes.

All actors will use compatible versions.

Long-term storage is not an issue.

Avoid when:

Any of the above do not apply.

ContentLicense: CC BY-SA 3.0


问:
How can I apply machine learning to automated melody generation?
I've been working for a while on an app that makes up melodies. Each melody is composed of several phrases (musical sentences, or 'sub-melodies').

Now, I want to improve on this:

The user can press a button to 'like' a melody.

The app saves the phrases (sequence of notes)  composing the melody to storage.

These stored phrases will be integrated into future melodies.

In particular, the app should not only use the verbatim phrases but apply attributes like the rhythm, pitch etc. to generate new melodies.

My question is: Which machine learning techniques can I apply to infer new melodies using the stored phrases?

答: Sure it is. It's supervised machine learning, in that you use preexisting external expert judgments to try to deduce the essence of a pattern (in this case, "pretty melodies") and ultimately allow you to generate more of them autonomously. The fact that the metric you are optimizing (aesthetic judgment on music) is somewhat  unusual doesn't change that.</p>


问:
What is the proper way to extract and pass parameters to call javascript functionality from my PHP page?
This is my situation: I have a search results page in PHP where most of the logic resides in a javascript file in order to avoid refreshing the page every time an action is performed. The first thing I do using PHP is filter out and save valid query string values to PHP variables and I make use of the htmlspecialchars function to prevent injection. Now, I'd like to call my javascript function using those variables, so I created a script tag at the bottom of the page in order to pass the PHP variables to it (see my example).

When I put all of my javascript code inside of its own scope (as I read this was a good security practice), I realized that I could no longer call my function from outside of it. I also realize that the javascript method can still be called with anything a hacker wants, so does that mean I can't really make use of htmlspecialchars in my situation?

Here's a stripped-down version of my code:

```<code><?php
try {
  if (isset($_GET["id"])) {
    if (!is_numeric($_GET["id"]))
      throw new Exception("URL is not in a correct format");
    $id= $_GET["id"];
  }
  elseif (isset($_GET["keyword"])) {
    $keyword = htmlspecialchars($_GET["keyword"]);
  }
}
catch (Exception $e) {
  // handle error
}
?>
<html>
<head></head>
<body>
  <div class="searchResults"><!-- placeholder --></div>
  <?php
  if (isset($id)) {
    echo '<script type="text/javascript">ShowSearchResults("id",'.$id.');</script>';
  }
  elseif (isset($keyword)) {
    echo '<script type="text/javascript">ShowSearchResults("keyword","'.$keyword.'");</script>';
  }
  ?>
</body>
</html>
</code>```

This is basically the js:

```<code>function ShowSearchResults(key,value)
{
    $.getJSON("includes/search_results.php?"+key+"="+value,
    function(data) {
      // populate search results
      $(".searchResults").html( "search results" );
    })
    .error(function() {
       $(".searchResults").html( "no results" );
    });
}
</code>```

My questions are (while keeping security and best practices in mind):

Is it bad practice to pass the query string values to my javascript function from within the body? I initially did this because I had the impression that it was not a good idea to extract query string values using javascript. Maybe I'm wrong there.

Should I be extracting the query string values from the $(document).ready function, and then calling the appropriate javascript functions from there? What is the appropriate way to do that (htmlspecialchars equivalent)?

Keep in mind that within my javascript code, I use $.getJSON to call another server side function (in PHP) that can reject anything insecure.

Any insight would be greatly appreciated.

答:
Just copy one of the functions from this Stack Overflow post on retrieving values from a query string, and reuse it in your JavaScript code, such as this function:

```<code>function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
</code>```

There's nothing wrong with pulling parameters from the query string in your JavaScript code as long as you are not executing anything you get from the query string. The JavaScript equivalent of htmlspecialchars is here.

However, if the $id was not coming from the query string, lets say it was coming directly from your server, it would be fine to echo it into your HTML and access it from JavaScript. (Try pressing ctrl-u now and see this page's HTML).

Body:
Just copy one of the functions from this Stack Overflow post on retrieving values from a query string, and reuse it in your JavaScript code, such as this function:

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

There's nothing wrong with pulling parameters from the query string in your JavaScript code as long as you are not executing anything you get from the query string. The JavaScript equivalent of htmlspecialchars is here.

However, if the $id was not coming from the query string, lets say it was coming directly from your server, it would be fine to echo it into your HTML and access it from JavaScript. (Try pressing ctrl-u now and see this page's HTML).


问:
Coding: conciseness/efficiency vs readability
I am fairly new to c# and trying to learn best practices. I've been faced with many situations over the last week in which I need to make a choice between longer+simpler code, or shorter code that combines several actions into a single statement. What are some standards you veteran coders use when trying to write clear, concise code? Here is an example of code I'm writing with two options. Which is preferable?

A)

```<code>    if (ncPointType.StartsWith("A"))//analog points
    {
        string[] precisionString = Regex.Split(unitsParam.Last(), ", ");
        precision = int.Parse(precisionString[1]);
    }
    else
    {
        precision = null;
    }
</code>```

B)

```<code>    if (ncPointType.StartsWith("A"))//analog points
        precision = int.Parse(Regex.Split(unitsParam.Last(), ", ")[1]);
    else
        precision = null;
</code>```

C)

```<code>    precision = ncPointType.StartsWith("A") == true ?
            int.Parse(Regex.Split(unitsParam.Last(), ", ")[1]) :
            null;
</code>```

答:
Not being in your aware of the rest of your code, I clearly prefer option A.

A) In case you want to debug, you'll have an easy access to precisionString

B) Not so good, the return value of the regexp parsing will not be easily accessed in debugging. Also the absence of the {} is dangerous: adding one statement (eg: a debug line) will break the logic

C) Is actually too verbose it would also be accessible to have:

```<code>precision = ncPointType.StartsWith("A") /* Analog unit */ ?
        int.Parse(Regex.Split(unitsParam.Last(), ", ")[1]) :
        null;
</code>```

(without the easy access on the regexp split return value)

Body:
Not being in your aware of the rest of your code, I clearly prefer option A.

A) In case you want to debug, you'll have an easy access to precisionString

B) Not so good, the return value of the regexp parsing will not be easily accessed in debugging. Also the absence of the {} is dangerous: adding one statement (eg: a debug line) will break the logic

C) Is actually too verbose it would also be accessible to have:

precision = ncPointType.StartsWith("A") /* Analog unit */ ?
        int.Parse(Regex.Split(unitsParam.Last(), ", ")[1]) :
        null;

(without the easy access on the regexp split return value)


问:
Is adding support for another operation system a minor version or a patch?
Let's say I use Semantic Versioning for a my project. I'm developing it under FooOS, but the language uses virtual machine(either interpreted language or bytecode based) so any operation system can run it. The thing is, the project interacts heavily with OS-managed things(e.g. pipes, processes, the file system) so if you try running it under a different operation system - BarOS - it gets so buggy and so many things don't work that the project is practically useless.

Now, at some point I want to make my project work for BarOS, and I want to release a version just to add that support. The question is - does that count as a minor version or as a patch?

It seems like it's a patch:

All I do is fixing all the bugs that appear when running the project under BarOS.

Users of my project shouldn't notice any change in functionality, since they are using FooOS in the first place.

For BarOS users my whole project is new - but getting new users is not something that should result in a version increment.

But even with all that reasoning, it just doesn't seem right to label a release as big as new OS support as a patch...

答:
If you already officially supported BarOS, but there were so many issues with it that nobody would use it, then providing proper support for BarOS would be a set of bug fixes and thus a patch release.

On the other hand, if you never officially supported BarOS, then adding official support for BarOS (regardless of how well it worked previously) is a new (backwards compatible) feature and therefor a minor release.

So, the answer to your question is that it depends on the official status of BarOS within your project so far.


问:
Can I use a part of another program without having to give away my rights on my own code?
I'm currently making a game and want to use some textfiles (lists of names) that are covered under the GNU General Public License (or the Attribution-ShareAlike 3.0 Unported License). Do I have to release my whole game under one of these licenses if I only used these (relatively small) files in my game or is it just these files I have to keep licensed like that?

If this is not permitted am I allowed to do this anyway if I choose not to actually release my code and only "hosted" this game, since it's a web game.

答:
Do I have to release my whole game under one of these licenses if I only used these (relatively small) files in my game

Yes, you do.

If this is not permitted am I allowed to do this anyway if I choose not to actually release my code and only "hosted" this game, since it's a web game.

For the regular GPL, this is indeed allowed, see this answer.


答:
In general, you MAY NOT use anyone else's copyright protected work without their permission, usually given in the form of a license.  If you could not use that list of names in lieu of the GPL or the Creative Commons license, you may not use them without following all of the terms of the specific license.

The question of how little a usage you can use and not have penalties imposed by court is a tricky one, that may wind up getting a lawyers involved.  If someone else wrote X, and you use part of X, the only way to absolutely avoid getting dragged into court is to follow exactly what their terms are.

That said, in many examples a mere mere list of names isn't a work protected by copyright.  If there is something special about the list, such as a list of twenty-six names each starting with a different letter, it's probably protected.  But if it's just a list, such as a random list of 5,000 common English first names, it may be no more protected than the names and numbers of an old phone book.

Title: Can I use a part of another program without having to give away my rights on my own code?

Body:
I'm currently making a game and want to use some textfiles (lists of names) that are covered under the GNU General Public License (or the Attribution-ShareAlike 3.0 Unported License). Do I have to release my whole game under one of these licenses if I only used these (relatively small) files in my game or is it just these files I have to keep licensed like that?

If this is not permitted am I allowed to do this anyway if I choose not to actually release my code and only "hosted" this game, since it's a web game.


问:
How should templates be named?
In D I can create templates like this:

```<code>template Foo(A) {
    A add(A a, A b) { ... }
    A multiply(A a, A b) { ... }
    A concatenate(A a, A b) { ... }
}
</code>```

What should a template be named ideally? What conventions exist out there? I'm looking to something similar like 'function names must always start with a verb'.

答:
In your case, I would use a name that refers to the collection of functions that you have. For example:

```<code>template Operations(A) { ...
</code>```

If you hadn't mentioned concatenate, then I would have suggested ArithmeticOperations for example.

Title: How should templates be named?

Body:
In your case, I would use a name that refers to the collection of functions that you have. For example:

template Operations(A) { ...

If you hadn't mentioned concatenate, then I would have suggested ArithmeticOperations for example.


问:
How important is XML for a developer?
Is it must that every developer should know XML? How important is XML for a developer? Any suggestion...</p>

答:
You should at least know the concept behind XML. Knowing the specifics isn't worth a damn if you don't understand why it's used in the first place. XML's approach to transporting data is by encasing it in tags like so: <greeting>hi</greeting> but you're probably saying, what? Why's he all inventing HTML on me?

You know, some may not agree with me here, but I don't think it's a good idea to be calling yourself a developer and not knowing what XML is. It's just too common, too simple, and too easy to pickup any second now.

For example, you may spend 3 minutes reading these responses. But BAM, in those three minutes, I just read the introduction to XML at w3schools: http://www.w3schools.com/xml/xml_whatis.asp

Now I can let my bosses know that, hey, if you ever need some data transported... I'm the right guy to ask (sorta).

ContentLicense: CC BY-SA 2.5

Title: How important is XML for a developer?


问:
Dividing responsibilities between client and server
I'm working on a Web app that uses node.js on the server and AngularJS on the client. I'm new to Angular, but enables writing client-side applications that can be more self-contained than some other approaches.

Here is the scenario. On the server, I query a DB and then transform the results into a list of nodes and edge objects. These objects are sent to the client (browser), and the client displays them as a graph.

The code to parse the query results and build the graph is pretty generic and I expect to use it again subsequent apps. It can stay on the server. However, a lot of the code could be moved to the client because it is specific the sigma.js package that displays the graph.

Part of me wants to offload the processing the client. There is also talk of ditching sigma.js for the next application we build, so shoving it into the client sounds pretty appealing.

However, the client is already feels bloated and complicated. I could use something like the decorator pattern to keep the sigma.js specific code encapsulated while leaving room for more representations.

Which direction should I go? What should I taking into consideration?

答:
There's one thing you mention in the last paragraph that stands out to me:

the client is already feels bloated and complicated.

The modern approach to client/server relationship is a parallel of the relationship between human and machine.

Client Akin to iOS programming, we ought to perceive the Angular front-end as a View-Controller.  Don't use models in the frontend, use services.  Those services connect to your models which live entirely on the server.  The View-Controller is a direct instrument of the User.  Your User uses the client to understand wtf is going on in their data within your application, and to express their wishes ("actions") within the system.

Server Here we use the Express framework (or whatever) to implement MVC architecture.  I recommend pointing all of your angular services to /api/XXX routes that serve a proper hypermedia API.  (My personal favorite MEAN implementation is https://github.com/DaftMonk/generator-angular-fullstack )

The next step here is to re-factor to create room for innovation.  Create a Top-Level diagram of your whole application.  Draw a vertical line down the middle of it, and write "Backend" on the left and "Frontend" on the right.

Where your application feels bloated, DRY it out.  Where your application feels complicated, try an exercise where you re-imagine that part of it from zero.  Amputate a giant bloated, complicated bad practice, especially if it's wasting your own development time.

Re-draw your Top-Level diagram three times from scratch, and just keep your mind limber and open to throwing out bad code if it saves your time in the future.


问:
Should a user story be shared between developers?
I commonly see stories that have back-end and front-end development.  For example, consider a large dialog with a few tables and some dynamic controls.  We'll make several stories (maybe one for each table and another for the dynamic control system).

The dev team will then split with one person on the back-end and another on the front-end.  This makes it easy for the back-end person to just worry about the structure of the SQL layer while the front-end person focuses on stuff like layout.  After the initial interface between back- and front-end is agreed, the two developers can focus their attention to get their part done by the end of the sprint.

Then comes the chaos.  Who "owns" which story?  What does "in progress" mean or "done"?  Should we make two separate stories for back-end and front-end?  If so, doesn't that break the idea of user stories based on feature?  Our system has a notion of "sub-tasks", which eases some of these problems.  But sub-tasks add an extra complexity.  Is there a better way?  Is this a "bad" way to use Scrum?

I have been using some form of Agile over the past few years at a couple places.  I have no official training yet, so please forgive any wrong terminology or ideology.  I'm just trying to learn practical ways to improve our process.

答:
Who "owns" which story?

Whomever grabs the story. They key from an organizational point of view is one person is responsible for the work. Once you get two people, it's too easy to pass the buck.

Should we make two separate stories for back-end and front-end? If so, doesn't that break the idea of user stories based on feature?

It depends. I've seen both ways work. If the story is large enough to have two developers work full time on it, then maybe it should be split. If the two developers are part of two different teams, then maybe it should be split. If the two developers will work on it during different sprints, then maybe it should be split.

Is this a "bad" way to use Scrum?

The key to remember is that process is there to serve you, not vice versa. User stories are a way for technical folks and non-technical folks to facilitate communication. They spell out what they'd like, everyone negotiates, and then you provide feedback in the story about its progress.

As long as the process is working for you, it can't be that bad.


问:
Should I feel "uncomfortable" using auto in C++?
C++11 features the new auto type declaration, allowing you to work with an object without ever knowing its actual type.

I use only strongly typed languages - C++, Delphi (Object Pascal), Go, etc and I feel uncomfortable (guilty?) using auto, (or for example the short variable declaration - x:=1- in Go.) It feels like a hack to me - I use strongly typed languages because they ensure that you know what type you're using. (With the exception of the abuse of untyped pointers.) Although certainly I appreciate the benefits:  Proper type names involving iterators, templates, smart pointers etc can get very lengthy and a bit difficult to determine and declare explicitly, or to parse when reading. Granted, once you know the proper type name, you can "typedef it", but sometimes getting it right the first time is time consuming and not always so easy.

Or, imagine you that inherit a large, complex project that you need to modify, and every variable possible in that project is declared using auto- you're going to have to do a lot more work to understand that code-base than if everything was declared using explicit types.

So, what are some guidelines on when to use auto and when to sweat it out with full and proper type names? I am currently reading Stroustrup's A Tour of C++ and he himself there in Chapter 1 advocates using auto in situations when you know auto will "get it right":

We use auto where we don’t have a specific reason to mention the type
  explicitly. “Specific reasons” include:

• The definition is in a large scope where we want to make the type
  clearly visible to readers of our code.

• We want to be explicit about a variable’s range or precision (e.g.,
  double rather than float).

In the Advice section of Chapter 1 there he also warns:

-Prefer the {}-initializer syntax for declarations with a named type;

-Prefer the = syntax for the initialization in declarations using
  auto;

This, because default initialization {} could result in an incorrect type initialization.

Still, I feel a bit uncomfortable using auto.

Can anyone perhaps give me some additional guidelines about the use of auto, and/or debunk my impression that auto is a hack of sorts and really should be avoided in favor of determining the proper type and then using atypedef?

答:
No, you should not feel uncomfortable using auto.

Just use it in situations where the type is obvious, or where no one is going to care about it

A classic example (IMO) of where auto is handy:

```<code>std::vector<sometype> vec
...
...
//some code
...
...
for(auto iter = vec.begin(); iter != vec.end(); ++iter)
{
   //something here
}
</code>```

Nobody really cares about the details of the iterator variable (std::vector<sometype>::iterator iter), only that it is an iterator. Explicitly specifying the type just adds visual noise. Often, without auto, people will create typedefs for commonly used iterators, which can obscure issues and lead to some bizzare error messages if you use the wrong typedef.

Body:
No, you should not feel uncomfortable using auto.

Just use it in situations where the type is obvious, or where no one is going to care about it

A classic example (IMO) of where auto is handy:

std::vector<sometype> vec
...
...
//some code
...
...
for(auto iter = vec.begin(); iter != vec.end(); ++iter)
{
   //something here
}

Nobody really cares about the details of the iterator variable (std::vector<sometype>::iterator iter), only that it is an iterator. Explicitly specifying the type just adds visual noise. Often, without auto, people will create typedefs for commonly used iterators, which can obscure issues and lead to some bizzare error messages if you use the wrong typedef.


问:
How to control work of programmers (outsourcers)
Some time ago I decided to outsource web development projects (php coding & design). I've opened small office abroad with manager and couple of programmers and designer. I just started but already have a problem controlling their work.

Some programmers are fast, others work much slower. I pay them fixed salary, so it matters for me if they do their job on time.

When they work from office, I at least have a person responsible for the project to tell if they really worked. But sometimes they work from home and in that case I have no way to know if they really spent that time working on some issue.

Some of my ideas were: controlling amount of code done with svn, strict deadlines, everyday reporting.. But nothing seems perfect to me. It creates even more work from my side.

Can anyone suggest a way of fair judgement on how much really time was spent on actual work? How to stimulate people to work? Maybe create some bonus system if work is done fast? Any idea/experience on this topic would be highly appreciated.

答:
Make It Mandatory. At the end of each day, require the teams to send you a daily scrum in the form of an email or other, answering the following questions:
1.  What did I do today?
2.  What am I going to do tomorrow?
3.  What do I need from Team Leader, so I can do my job tomorrow?</p>


问:
Automated Testing Using Virtual Machines
I am working on making a system for the automated testing of student assignments. The biggest hurdle I am facing right now is figuring out how to sandbox the testing of the code yet still get and process the results of the test. I need to run it on a VM as there is no guarantee the code will not be malicious.

I would like to have a process similar to the following:

Student submits assignment

VM is created and is given the source code submitted by the student

VM runs the tests on the source code

VM returns results of the test back to the host operating system

Results are processed

Steps 2 and 4 are the ones I am looking for a good solution for. I am not sure what would be a good way automate the passing of files to the VM and the passing of results back from the VM. It seems like this is a problem that might have a solution already and I would rather not reinvent the wheel.

答:
Here are a few options, in order of ascending preference:

Option 1)
For 2), you can copy the file to some shared location defined on the VM. An artifact of 3) is that it can produce some output file. For 4), the host OS can poll the expected output file on the VM to know when the tests are done.

Option 2)
Create some trivial web service (i.e. SOAP or HTTP API) on the VM which the host OS can call, the VM then executes, and returns response back to the web service client on the host OS. If the execution can take a long time, you have to consider setting a sufficiently high timeout on the web service client.

Option 3)
If possible (not sure because I dont know what VM software you are using) use some API provided by the VM server to execute a command and get its response.


问:
Improving performance for grepping over a huge file
I have FILE_A which has over 300,000 lines and FILE_B which has over 30 million lines. I created a Bash script that greps each line in FILE_A over in FILE_B and writes the result of the grep to a new file.

This whole process is taking over 5 hours.

How can I improve the performance of my script?

I'm using grep -F -m 1 as the grep command. FILE_A looks like this:

```<code>123456789
123455321
</code>```

and FILE_B is like this:

```<code>123456789,123456789,730025400149993,
123455321,123455321,730025400126097,
</code>```

So with Bash I have a while loop that picks the next line in FILE_A and greps it over in FILE_B. When the pattern is found in FILE_B, I write it to file result.txt.

```<code>while read -r line; do
   grep -F -m1 $line 30MFile
done < 300KFile
</code>```

答:
why don't you put that file in a database
 databases are really good at doing an efficient merge,hash,nested loop join like this
. And they are really good at utilizing virtual memory</p>


答:
You are still getting strong types even if they aren't explicitly specified.  You're going to eventually hit a static type mismatch in most circumstances.  The main concern with type inference is accidentally inferring a type too concrete or abstract.  In other words, inferring a derived type when you really needed the base type, or vice versa.  If it matters what exact type you get, don't use auto.

Another concern about type inference is if it might change the public interface of your code.  In general, you should make the types of your public interface explicit.

Aside from those circumstances, there's little reason not to use auto when it simplifies your code.

Title: Should I feel "uncomfortable" using auto in C++?

Body:
C++11 features the new auto type declaration, allowing you to work with an object without ever knowing its actual type.

I use only strongly typed languages - C++, Delphi (Object Pascal), Go, etc and I feel uncomfortable (guilty?) using auto, (or for example the short variable declaration - x:=1- in Go.) It feels like a hack to me - I use strongly typed languages because they ensure that you know what type you're using. (With the exception of the abuse of untyped pointers.) Although certainly I appreciate the benefits:  Proper type names involving iterators, templates, smart pointers etc can get very lengthy and a bit difficult to determine and declare explicitly, or to parse when reading. Granted, once you know the proper type name, you can "typedef it", but sometimes getting it right the first time is time consuming and not always so easy.

Or, imagine you that inherit a large, complex project that you need to modify, and every variable possible in that project is declared using auto- you're going to have to do a lot more work to understand that code-base than if everything was declared using explicit types.

So, what are some guidelines on when to use auto and when to sweat it out with full and proper type names? I am currently reading Stroustrup's A Tour of C++ and he himself there in Chapter 1 advocates using auto in situations when you know auto will "get it right":

We use auto where we don’t have a specific reason to mention the type
  explicitly. “Specific reasons” include:

• The definition is in a large scope where we want to make the type
  clearly visible to readers of our code.

• We want to be explicit about a variable’s range or precision (e.g.,
  double rather than float).

In the Advice section of Chapter 1 there he also warns:

-Prefer the {}-initializer syntax for declarations with a named type;

-Prefer the = syntax for the initialization in declarations using
  auto;

This, because default initialization {} could result in an incorrect type initialization.

Still, I feel a bit uncomfortable using auto.

Can anyone perhaps give me some additional guidelines about the use of auto, and/or debunk my impression that auto is a hack of sorts and really should be avoided in favor of determining the proper type and then using atypedef?


问:
What language is better for working with databases?
I am going to develop a software that works with different databases and I'm considering whether to use .NET languages or C++. I've known that .NET features LINQ and ADO.NET but are there features like that in the native C++? Which one works better, faster with databases?</p>

答:
There's no clear-cut answer to your question - it depends on what sort of work you plan to do and the requirements of any particular project - you need "the right tool for the right job". Also, your question as stated isn't entirely valid, because C++ is clearly designated as a systems language - not really designed for developing forward facing applications - but the .NET languages are part of a framework that spans pretty much every aspect of modern software development and focuses on the development of  applications for "consumers". (LINQ is a language feature of C# and isn't part of C++, although using the STL you can do some similar things, with work...) Having said that, here's an overview of how things break down:

When you use .NET languages with VStudio, the database stuff is pretty much there "right out of the box" - it's all set up for you - you can do it all with very little code using wizards and template projects, etc, if that's what you want. Or you can code by hand using the framework's classes for database handling, or combine the approaches, depending on your ability, taste and requirements. And of course it's integrated with ADO, ADO.Net (part of the framework itself), etc - so you can connect quite easily to just about any DBMS out there. (Sometimes you'll have to pay some good money for top quality ADO/ADO.net provider packages from third parties.)

But there is a price to pay with .NET, in terms of performance (your mileage may vary, depending on what you're doing with it), in terms of your wallet, and in terms of being locked into a proprietary framework, which MS has a nasty habit of breaking and complicating from time to time... etc - essentially part of their business model... You're also pretty much locked into the Windows platform with .NET. Although Mono and MonoDevelop (as well as some other IDE's) are open source and are available for Linux, IMO they are not really on a par with the MS tool-chain, and it can get a bit nasty keeping track of .NET versions and compatibility, and staying in sync, etc.

In native C++ it's a very different story. "Out of the box" C++ has no database support - since it's a systems language, it's not part of the standard. Doing it all by hand is generally not an option - you could spend the rest of your career just developing a solid framework for accessing various databases. Even if you only need one database, it is still challenging.

So, when working with databases in C++, you generally need to work with frameworks that have been designed for/with database support. QtSql for example, is quite popular  as is libdbi (google will lead you to others) or at least download or buy drivers for various databases and learn how to wire them up. Again, not always so easy, but quite doable if you're comfortable with C++.

The upside of using C++ is that's free, there are great tools for developing with it that are also free, performance will, as a rule, be superior to .NET, your code will be more or less cross platform, and you'll be working with what is arguably the most important language in modern computing. (Not trying to start any language wars here - I know there are other candidates...)

Another important consideration is your frontEnd: Again, with .NET, it can all be done "out of the box" - you've got all sorts of controls that are easy to wire up to your database input and output. In C++, frontEnds are also not part of the standard, since it's a systems language, as explained. So you'll have to use another framework for your frontEnd and "hand wire" things. The QT platform does provide an "end to end" solution in native C++, but it's still a lot more work than using the MS tools, and it does have its down-sides, although it is very popular and is widely used on Linux. For example, KDE a very important and popular GUI toolkit for Linux, is QT based.

So - it's your call: If you need quick and easy solutions for Windows only, IMO go for .NET. If you need open source/cross platform, super high performance solutions and are ready to roll up your sleeves, C++ is what you want. But in that case, other languages, such as Java and Python, might also be candidates for you to investigate, depending on your needs and taste. They are easier to work with than C++ if you're new to this sort of thing.


问:
Website as an API client vs using the API only when needed?
I'm developing a website (using Django) which will depend on an API for it's main functionality which is create/update/delete objects.

But the API also provides:

User sign up and login

User relations to their objects

User groups and permissions

This is great but I'm conserned about fully depending on the API for everything even user sign up and login, so I have 2 choices:

Using the API for everything:

Advantages:

User authentication, objects, relations, permissions are already managed

My job is only to query the API and display the results

Disadvantages:

Lots of HTTP requests to the API

The website will break if the API goes down

The website rendering time will be slower (will use ajax)

Using the API when needed:

Advantages:

Fewer HTTP requests

The website will be a little faster

If the API goes down, not all the functions of the website will stop

Disadvantages:

I'll have to manage user authentication, permissions and relations to his objects in the API

Duplicate user data in my database and the API (I'll have a copy of the user objects)

Worried about the data sync (I'll update the database only on create/update/delete requests to the API)

Which one is a better choice and why ? what design is usually used for such cases ?

答:
This is an interesting question, and not very easy to answer. It depends on what website you are developing, in order to justify the effort in any direction. Here is my opinion for some of your points:

Using the API for everything: Disadvantages

Lots of HTTP requests to the API

This depends on whether you are developing a standard website or one that should be accessible extensively via mobile devices. It makes sense to use smaller in portions, but more frequent communication in case when the client is a mobile device. Mobile devices have limited capabilities in terms of hardware and could also have slower internet connection. A large server response may take significant time to be processed on the device itself.

The website will break if the API goes down

Well, that is a problem of the website, not the API. The website must be developed with caution to the case when the API is not available. This could be a real-life scenario, as if the API is being updated and redeployed, the site would experience a downtime and not work. Regardless of whether entirely depending on the API or not, you must provide means for graceful error handling - show a suitable error page, or limit the functionality accordingly.

The website rendering time will be slower (will use ajax)

I disagree. AJAX actually causes the site to load faster. Each AJAX request, if made asynchronous, would render a separate portion of the site. If you were to wait for all portions to load at once, the cumulative loading time would hardly differ. Besides, almost everyone uses AJAX today, and this has proven to not be an issue, if properly done. Additionally, AJAX is extensively used to bring some processing to the client, not the server - this is usually employed as a technique to reduce server load.

Using the API when needed: Disadvantages

I'll have to manage user authentication, permissions and relations to his objects in the API

If that is a concern to you, I mean if you need to do the user authentication and security by youtself, then you should not rely on the API entirely. It is often the case that people develop their own system and maintain both the local and the remote (the API's) accounts at once - the concept of linked accounts. It is popular approach for system with already existing users to provide means for linking the user account with, for instance, the user's facebook account.
If you want have your own user account information, but are reluctant to manage the authentication and authorization yourself, consider using OpenID if the API supports it, or consider implementing one, if you are developing the API too.

Duplicate user data in my database and the API (I'll have a copy of the user objects)

As per the above point, it is inevitable to have some data repeated. If the user object to your project means something different to you than the user from the API, then you must manage this information yourself.

Worried about the data sync (I'll update the database only on create/update/delete requests to the API)

Maintaining two distinct systems in sync is something that has always been a serious development effort. If you can avoid this, and rely entirely on the API, you'd probably prefer the API approach. If the API does not provide you with all the capabilities for your own project, then you could still have to face this maintenance task.

In addition to your concerns, you need to consider some additional ones:

Does the API guarantee backwards compatibility if they introduce changes?

Is the API documented well enough so you can cover the aspects of your project with it entirely?

How does one introduce fixes/improvements to the API? There are serious differences between maintaining and improving OpenSource projects/APIs and commercial ones. Also, any project usually has its own policy to when is appropriate to apply certain fixes and changes (most open source projects will do this faster than a commercial product, that is not to say fast enough for you). This is something to consider if you discover a problem with the API that breaks your code. If this is not seen to be fixed by the API's team, you would be on your own for working this around.

It is sometimes acceptable to not directly use the external API, but create a wrapping API that is what you would directly use for your project. Then delegate the API availability and compatibility problems to your API wrapper. That way, changes will not directly affect the website, or any other application that consumes it. You will also have the freedom to expose the external API in a form that is more suitable. For example, you may expose a single method that results in multiple calls to the external API - so you will reduce the number of requests the website does.

As a bottom line, the real concerns you may have is the data duplication and the site availability in case of API crash or incompatible changes. I would decide based on the estimated development effort with either approach, and the likeability of problems with that approach.


答:
Your job as a manager is not to control programmers, it is to give them all they need to get the work done.

If a task doesn't progress as fast as you want, don't blame the task owner, but analyze what is blocking. It is not always the programmer's fault. It may be a lack of correct tools, a late delivery in input documentation, a broken air conditionner...

As a general rule when facing a problem, find the root cause and solve it, don't find a responsible.

Sure it will cost time and money. Software is not free, even Linux. Indeed, you'll only get what you pay for.

Title: How to control work of programmers (outsourcers)

Body:
Some time ago I decided to outsource web development projects (php coding & design). I've opened small office abroad with manager and couple of programmers and designer. I just started but already have a problem controlling their work.

Some programmers are fast, others work much slower. I pay them fixed salary, so it matters for me if they do their job on time.

When they work from office, I at least have a person responsible for the project to tell if they really worked. But sometimes they work from home and in that case I have no way to know if they really spent that time working on some issue.

Some of my ideas were: controlling amount of code done with svn, strict deadlines, everyday reporting.. But nothing seems perfect to me. It creates even more work from my side.

Can anyone suggest a way of fair judgement on how much really time was spent on actual work? How to stimulate people to work? Maybe create some bonus system if work is done fast? Any idea/experience on this topic would be highly appreciated.


问:
How to choose parameter for Golomb coding?
I am trying to implement Golomb coding, but I don't understand how it's tuned to obtain optimal code.

It is said that

Golomb coding uses a tunable parameter M to divide an input value into two parts: q, the result of a division by M, and r, the remainder. The quotient is sent in unary coding, followed by the remainder in truncated binary encoding.

I don't understand how should I choose the parameter M - I can't see how the explanation in Wikipedia relates to actual data. I believe it should be related to statistical moments, is that true?

For example, if I have this example set:

{3,4,4,4,3,1,2,2,3,1,2,1,4,1,2,2,2,2,1,1,2,2,1}

I believe M should be very small for this kind of data. I bet it's either 1 or 2. It's mean is ~2.2 and standard deviation is ~1.1. My intuition would tell me to choose 2.

Another dataset here:

{2,7,11,19,6,2,6,13,11,1,5,2,19,7,6,9,6,7,2,4,5,12,3}

This time the mean is ~7.2 and standard deviation is ~5.0.

Is 7 the right value in this case? And should I prefer Rice code (use 8 as it is a power of 2) if I get a value like 7?

I understand that division will be easier if I use Rice coding, but are there any benefits in NOT using it? I mean - 3 bits will be used for remainder in either case, how could pure Golomb code be more optimal then?

One more nuance - Golomb code is for nonnegative integers. If I have positive integers instead, should I save x-1 instead? It would change a lot for the first of the mentioned datasets.

答:
The Golomb-Rice algorithm doesn't specify how to find the optimal parameters, and in the general case you will have to try to infer the posterior probability of symbol occurrences in the dataset to estimate the optimal value of M. Note that it is a common choice to have M = 2 k, a power of 2, as coding in this case is simple, and then discuss k instead. The search for the optimal k is usually done exhaustively over the dataset.

Following the above you can now understand why the wikipedia article you link to doesn't refer to any actual data, but says the follows as a way of an example,

Given an alphabet of two symbols, or a set of two events, P and Q, with probabilities p and (1 − p) respectively, where p ≥ 1/2, Golomb coding
  can be used to encode runs of zero or more P's separated by single Q's. In this application, the best setting of the parameter M is the
  nearest integer to  \frac{-1}{\log_{2}p}.

In the case where the probability p is known, where we have the prior equivalent to the posterior distribution, it can be shown that there is a best known value for M, but not otherwise.

Practically what this means is that you have to have a fairly good idea of how your eventual dataset will look like, possibly further increasing confidence with re-sampling methods (e.g., bootstrapping), and then searching exhaustively1 for the optimal parameter value in the sample datasets - the k that minimises the expected code length. Then you use an average value of the k you've decided on for the future datasets. Some implementations store a table of input dataset characteristics and adaptively select (i.e. change) the code parameters when they detect that the input pattern shifts. For example it is common to evaluating the running characteristics of the input sequence, mean, variance, etc, and select accordingly when thresholds are breached.

1 There are precise bounds that could be established for the value of k for input integers that follow certain distributions, saving on the fullness of the exhaustive search. However, for many integers in real datasets you have to deal with, the distribution cannot be easily bundled into a convenient approximation of a uniform random variable - for example, have you heard of Benford's law? Notwithstanding, note that close to optimal selection of parameters for the encoding would rarely significantly differ in outcome from optimal selection, in practical implementations.


问:
How can I promote clean coding at my workplace?
I work with a lot of legacy Java and RPG code on an internal company application. As you might expect, a lot of the code is written in many different styles, and often is difficult to read because of poorly named variables, inconsistent formatting, and contradictory comments (if they're there at all).

Also, a good amount of code is not robust. Many times code is pushed to production quickly by the more experienced programmers, while code by newer programmers is held back by "code reviews" that IMO are unsatisfactory. (They usually take the form of, "It works, must be ok," than a serious critique of the code.) We have a fair number of production issues, which I feel could be lessened by giving more thought to the original design and testing.

I have been working for this company for about 4 months, and have been complimented on my coding style a couple of times. My manager is also a fan of cleaner coding than is the norm. Is it my place to try to push for better style and better defensive coding, or should I simply code in the best way I can, and hope that my example will help others see how cleaner, more robust code (as well as aggressive refactoring) will result in less debugging and change time?

答:
There are two things which can do wonders for ensuring a a consistent and high-bar for code quality.

Do Code Reviews

You should strive for every checkin -- no matter how trivial -- getting reviewed by another person on the team. No exceptions. This seems like it will get in the way at first, especially for senior developers who think they don't have anything to gain by having less experienced people review their code. However, having regular code reviews will have an immeasurable impact for every developer on the team.

Define a Standard and Stick With it

At Google we have a coding style guide for every language we use: C++, Java, Python, etc. While engineers are free to disagree with the style guide, it is not optional. (And is rigorously enforced in code reviews.) As a result, the entire codebase -- hundreds of thousands of lines of code -- is very consistent.

ContentLicense: CC BY-SA 4.0


问:
How to design the relation between a Game and a Player in a game?
I am currently attempting to make a Trading Card Game and I have got a whole array of features working already, yet I am stuck now at the portion where one player can attacker another player (more strictly: the monster cards of another player on the field). The game is designed primarely to be played with two players in mind, though having it open for future extensions is never a bad idea.

This is the design I have so far, shown as a minimalistic example in pseudo-code:

```<code>class Game
    private final Player self
    private final Player opponent

class Player
    private final String name
    ...
</code>```

The game loops over all players and lets them do their turn, which may involve attacking another player. That method has the following structure:

```<code>class AttackMonsterAction
    private final int monsterIndex
    private final int targetMonsterIndex
    private final Player targetPlayer

    public void performAction(final Player player)
</code>```

If it is of any relevance, I am coding this in Java.

My concrete question is the following: How do I create my class design such that AttackMonsterAction called from a certain Player object, can reference "the other player"?

答:
A couple of options come to mind:

Pass a GameState object to performAction, the GameState represents the current environment including the other palyer(s) and game board.  This would allow you to move  performAction into an interface and use it for your other actions such as move and hide

Use a Mediator Object 2 to manage the interaction between the two players.

Regarding adding more players in the future; sounds like a big redesign so apply the XP principal of "You aren't gonna need it " and dont add it yet.  Write tests to prove that the game works and then when you want to add more players use you tests to make sure that the two player game still works.


答:
Assuming that the contents of the file are the result of a sufficient creative process that they fall under copyright protection1, there are two possibilities.

The files are made a physical part of your program. For example, they are processed during compilation. In that case, your program is a derived work of those files and you are bound to the restrictions that the respective licenses impose on derived works. Often (and especially in the case of GPL) that is that your code must use the same license.

Your program reads those files at runtime and takes some action based on what it read (possibly combined with actions taken by the user). For example, it shows the list of names to the user to select one. In this case, the license on the text file does not affect the licenses you can distribute your program under. The text files are 'mere data' and they are considered completely separate from the program processing them. (This would be similar to the relation between source code and a compiler/editor.)

You can still distribute the file together with your program, as long as you observe the relevant conditions in the file's license and you state that different licenses apply to different parts of the distribution.

1: Where that bar exactly lies is fodder for lawyers, but it isn't that high. So, the assumption is on the safe side but probably not that far off

If you don't distribute your code, you generally don't have to bother with copyrights. The main catch here is that it can differ from license to license what the term 'distribute' means.

For example, with the Affero GPL, distribution also includes running the software on a publicly accessible server, but that is the odd one out among software licenses. Non-software licenses, such as creative commons, might have a different view on distribution.


问:
Applying DDD to a simple app with a configuration twist
I’m using the light-weight PHP Fat-Free Framework as a base to form a simple MVC based app with DDD philosophy for the Model layer. I’m aware that DDD is most suitable or enterprise solutions and that applying DDD to simple, mostly data-driven apps is kind of an overkill, but there are some concepts in DDD that I find appealing (like the Repository pattern, business logic in Entities, etc.) which I’d like to apply to my app.

Fat-Free Faramework has a Base class that represents the application (a Singleton) and the instance of Base holds a lot of useful tool methods and a registry of global framework variables (the hive) which is used, among other things, for configuration data.

As I’m writing my app, I find myself using a lot of Base class tools inside classes in the Model layer, and I’m a bit confused by how to reference the Base instance in those classes. Do I simply call Base:instance() inside model classes or do I inject it through the constructor as a dependency? Dependency injection seems like the proper way to do it, but since most of the app will depend on it, the whole reference passing through the constructor seems unnecessary. Also, how to pass for an example database config data to data persistance classes which is stored in the hive? Should it be passed by the Controllers when instantiating Repositories or called directly from the Repository (or Data Mapper)?  I’m looking for a way which won’t fire back on me, so I’m looking for any insight or advice on this.

The second part of my problem is that I’m trying to write my app so that each Entity and business logic related to it is configurable from the Entity class. This is an idea inspired by Sails.js I’m still testing out, but for an example, I have a method getProperties() which returns an array of user-defined configuration data for each Entity property, e.g.:

```<code>'title' => array(
    'type' => 'text',
    'minLength' => 30,
    ...
)
</code>```

or for associations:

```<code>'children' => array(
    'entity' => 'ChildClass',
    'relation' => 'oneToMany'
)
</code>```

It might look a bit controversial, but I’ve tested business logic functionality and so far it works OK for me, and client code communicates with entities via usual get/set/other methods. The idea behind such configuration is to be able to automatically generate scaffolding/administration interface for each Entity, and configure Data Mappers and Repositories based on the related Entity’s getProperties() method.

What’s bugging me now is that if I want to have one place where this configuration data exists, I’d have to place some non-business-domain logic into the Entity, such as an exceptional database table name, whether a field requires a rich-text editor or not, whether a checkbox is checked by default, a certain field used as an Entity’s print identity in the admin web interface, etc.

I realise that the problem I have is a tradeoff between a clean model and the single-place configuration idea and that I’ll probably have to pollute the Entities by storing such non-business-domain data into the Entites, but I thought perhaps someone here might have an idea about how to approach this in a different, or better way?

Thanks for reading.

答:
I feel you are mixing concerns here. Your entities should be exclusively about business logic; I can almost guarantee you that the minimum length of a title is not business logic (barring some very special business domains). Stuff about (initial) validation or how to render a field belongs in UI view models.

If you are unsure, find a business process that will behave differently when the minimum length of a title is not met.

I also find it odd that you would need to reference global configuration variables inside your business logic related entities. If that is indeed the case, then you are either missing concepts in your business model, or you are mixing infrastructural concerns with your model.

As for your dependency injection question: if you have e.g. repositories that need connection strings, then use constructor injection and use you IoC container to wire everything together. Don't take on static dependencies all over your code; it will seriously hamper any unit testing you may wish to undertake, it will couple a large portion of your codebase to an implementation detail and it will make baby Jezus cry.

As an aside: you've touched on this, but I want to stress this again: what you are describing is not DDD.

DDD is about making the discrepancy between how your code runs and how actual business processes run as small as possible. It is about modeling the domain of a company inside your code, using the same language that the business uses. And it is about recognizing that you'll need different models for different parts of the business, thus partitioning your application.

The patterns you describe are a means to an end; applying them without the core aspects of DDD is what is commonly referrer to as "DDD lite". Don't take this as me saying that you need to pursue DDD, but it's important to know the difference.


问:
Is it good style to store view data inside the model?
I'm using a variant of the MVC pattern. In my GUI code, often the need arises to synchronize "view data" (e.g., selected item) between different views.

For example, let's imagine a vector drawing program. We have two views: the image, and a listview of all objects (rectangles, squares, ...). The currently selected item should remain in sync - if you click on "Rectangle A" in the listview, the same rectangle should be highlighted in the image view.

The way I usually do it is to have a ViewState class contained in my model.
Is that a good idea? If not, what would be a better solution?

```<code>class VectorDrawing
{
  List<Object> Items;
  DrawingViewstate Viewstate;
}
class DrawingViewstate
{
  Object SelectedItem;
  event SelectedItemChanged;
}
class ListviewController
{
  ListviewController(VectorDrawing model)
  {
    model.Viewstate.SelectedItemChanged += ... // Subscribe to event
    ...
  }
}
class ImageViewController
{
  ... // similar to the ListviewController
}
</code>```

答:
I think you are on the right track.

Consider using events to notify the views that a selection has been made/changed.  Each view can register a selection listener with the model and then when the selection changes the model  can notify the views that the selection has changed.

Decouple a view requesting that an object is selected from the notification that is has been selected.


答:
The reason this apparent violation of the MVC separation of concerns isn't really that, is that in your case, this ViewState object isn't, in fact, a part of the View data. It's a part of the model. Just like "the list of objects" is part of your data, so is "the currently selected object".

The View part of this selected-object data might be a highlighted line in a listbox, or a change of color for the selected shape on the canvas, but the fact that the identity of the currently selected item is used in multiple places, and is not just an artifact of the UI process (for instance, selection in a listbox as a way to enable the "delete object" command, for instance) is a good hint that it is, indeed, a part of your model.

Title: Is it good style to store view data inside the model?

Body:
I'm using a variant of the MVC pattern. In my GUI code, often the need arises to synchronize "view data" (e.g., selected item) between different views.

For example, let's imagine a vector drawing program. We have two views: the image, and a listview of all objects (rectangles, squares, ...). The currently selected item should remain in sync - if you click on "Rectangle A" in the listview, the same rectangle should be highlighted in the image view.

The way I usually do it is to have a ViewState class contained in my model.
Is that a good idea? If not, what would be a better solution?

```<code>class VectorDrawing
{
  List<Object> Items;
  DrawingViewstate Viewstate;
}
class DrawingViewstate
{
  Object SelectedItem;
  event SelectedItemChanged;
}
class ListviewController
{
  ListviewController(VectorDrawing model)
  {
    model.Viewstate.SelectedItemChanged += ... // Subscribe to event
    ...
  }
}
class ImageViewController
{
  ... // similar to the ListviewController
}
</code>```


答:
Is there a reason you need to spin up and spin down the VM between tests?

Personally, I would have a single VM that is capable of performing the tests and has access to a shared drive on the host machine where the tests reside. You can then iterate over the tests within a single VM by accessing the shared space.

I am only verse in VirtualBox, but you can create shared folders with relative ease, and export your VM when you have it all set up nicely so that if you come across something malicious, you just blast the broken VM and take another export (copy) of the backed up version.

The downside of this is that you don't have the results automatically given to the host from the guest, but I don't know any method of doing this on a program level anyway. Of course, the guest can write the results to the same (or different) shared folder it has access to on the host machine.

Title: Automated Testing Using Virtual Machines

Body:
I am working on making a system for the automated testing of student assignments. The biggest hurdle I am facing right now is figuring out how to sandbox the testing of the code yet still get and process the results of the test. I need to run it on a VM as there is no guarantee the code will not be malicious.

I would like to have a process similar to the following:

Student submits assignment

VM is created and is given the source code submitted by the student

VM runs the tests on the source code

VM returns results of the test back to the host operating system

Results are processed

Steps 2 and 4 are the ones I am looking for a good solution for. I am not sure what would be a good way automate the passing of files to the VM and the passing of results back from the VM. It seems like this is a problem that might have a solution already and I would rather not reinvent the wheel.


答:
I would probably just use ssh to the VM. First copy the executable into the VM using ssh (scp or sftp), then execute it again using ssh and read it's output, possibly use ssh again to pull output files (scp/sftp again, though it's easiest to stick with standard output whenever sufficient) and shut down the VM.

The VM needs to have networking enabled for this, but you can easily prevent it from reaching outside world by configuring firewall on the host.

The VM should have it's disk image mounted in copy-on-write mode and the writable part discarded after the shutdown, so all tests run with the same initial state. You can optionally check that the copy-on-write file does not contain changes to any files it is not supposed to contain.


问:
Type Safety of Spray.io
Yesterday I read a tweet disparaging Jersey with JAX-RS due to run-time errors. Spray.io was mentioned in the tweet:

Not even 5 minutes using Jersey / JAX-RS and already a runtime error
  due to a missing annotation. That's why I like @sprayio: type safety.

https://twitter.com/gbelrose/status/467295643053338626

How does spray.io provide  type safety?

Could you please give an example?

答:
There are several components to the type-safety of spray. Here's a selection

more-or-less complete model for HTTP data structures including many headers

type-class-based (un)marshalling infrastructure

type-safe data extraction in the routes, type-safe combination of route parts

To explain a bit more

A complete model for HTTP means that after parsing (or constructing) an HTTP message follows a certain fixed structure and certain invariants are met. E.g. this means user-level parsing of headers is usually not needed and runtime errors in code dealing with those headers can be ruled out to some degree.

The (un)marshalling infrastructure ensures statically that values of domain types can only then be converted into HTTP data structures if a marshaller for that type is statically available (through implicits). That means that in a route you can usually work on the level of your domain types with all the logic bridging the types being tucked away in Marshaller definitions.

In spray's route structure you can extract values from a request. E.g. you can use parameters('name.as[String], 'age.as[Int]) to access the name and age query parameter of a request. Using as[T] means that the extracted value will be converted into the type T at runtime. Inside the parameters route you know that name and age will be of the right types (otherwise spray will generate an appropriate error message for the client).

spray's routes are composed of "directives". Each directive has a type Directive[T1 :: T2 :: ... :: HNil] where the T1... are types of values that are extracted by a directive. Directives can be freely composed, that means that instead of parameters('name.as[String], 'age.as[Int]) (which is of type Directive[String :: Int :: HNil]) you could also write parameters('name.as[String]) & parameters('age.as[Int]). This allows you to extract common patterns in your route into your own custom directives that you can re-use anywhere.

See the spray documentation on directives for more information about this topic.

It would also make sense to talk about points where spray isn't type-safe (some of those points may be addressed in the future, others are inherent in the architecture). E.g.

You can miss the ~ operator while building a route.

It can be hard to see if a content-type is allowed/generated for a route or not.

It is currently possible not to handle a request in the route.

A service you "ask" for an answer to a request (see the Akka ask pattern) may answer with an unexpected kind of message.

You can violate the message protocol to spray actors (which is common to all message flow with Akka actors which is untyped).

...

Title: Type Safety of Spray.io


问:
Exercise 3.6: Skiena Algorithm Design Manual
I am preparing for interview and try to solve the exercise problems of the book.

3-6. [5] Describe how to modify any balanced tree data structure such that search,
  insert, delete, minimum, and maximum still take O(log n) time each, but successor
  and predecessor now take O(1) time each. Which operations have to be modified
  to support this?

Solution: Maintain extra pointers to the successor and predecessor. Update the pointers on
insert and delete.

Nothing else right? Or is there some other trick involved.

Thanks

答:
The typical operations on a tree are insertion, deletion and traversal - including successor and predecessor. When a tree is balanced there would be an internal rebalancing operation, so the answer on what operations need to be modified depends on whether you want to interpret "operation" with respect to the external or the internal interface.

The answer, generally is affirmative - you'd need to keep a pointer to the successor (the next element greater than the current one) and the predecessor.

What the question is really about though, is how do you keep these newly proposed pointers up to date given insertions, deletions and rebalance. You can reason about this by induction - given a balanced tree T such that the conditions given in the question apply with respect to T, how inserting a new node V will affect all the other nodes of the tree, and especially those for whom V will become the new successor and predecessor. You will have to show that only O(log n) nodes will be affected, located and modified, otherwise you cannot keep the operations discussed within this scope of the necessary complexity.


问:
Why does storm not supply a mechanism for supplying topology necessary dependent jars other than the fat jar?
Following is a question that I had posted at the incubator-storm-user mailing list (verbatim). I had decided to open up the question here as well, because it also contains a conceptual side to it, which might be answered by non-storm users.

I am no python expert and am also a newbie to storm.

I have gone over the
  storm source code
  in order to see how to add jars to the classpath. Obviously, the
  preferred mechanism is the fat jar (as specified in
  Micheal Noll's tutorial
  and
  another post on the storm-user mailing list).
  The second seemingly available mechanism is via the USER_CONF_DIR
  which amounts to os.path.expanduser("~/.storm") but this does not
  allow for topology independent versioning of the same jars (e.g.
  apache-commons-aaa version x and version y). There does not seem to be
  a third way. Many other Java based technologies do give a way to amend
  the classpath. Why doesn't storm?

To generify the question a bit, why would a (clustered) java software framework/container not supply a mechanism for adding app specific dependent jars, but force you to use fat jars?

答:
First off, let's talk about what Storm is supposed to be.  From their front page we get:

Storm is a distributed realtime computation system. Similar to how Hadoop provides a set of general primitives for doing batch processing, Storm provides a set of general primitives for doing realtime computation. Storm is simple, can be used with any programming language, is used by many companies, and is a lot of fun to use!

And from their wiki we also get:

Unfortunately, these data processing technologies are not realtime systems, nor are they meant to be. There's no hack that will turn Hadoop into a realtime system; realtime data processing has a fundamentally different set of requirements than batch processing.

  However, realtime data processing at massive scale is becoming more and more of a requirement for businesses. The lack of a "Hadoop of realtime" has become the biggest hole in the data processing ecosystem.

  Storm fills that hole.

With the "money quote" being this part:

Storm provides a set of general primitives for doing realtime computation. Storm is simple...

So Storm started out as something that was intended to be small, crazy-fast1, and simple.

And while I haven't pulled the jar file to see its actual size, my expectation based upon the description of the project is that the "fat jar file" is reasonably small.  If it isn't, then I think the project has missed one of its original goals.

The fact that they are attempting to create a set of primitives for this type of calculation also implies that they are trying to keep things concise.  Or said another way, they are trying to avoid bloat and are focusing on providing just a core set of features.

We also need to consider simplicity being one of the primary goals of the project.  Really Good Simplicity (tm) extends beyond the API calls and into the package itself.  Not having a lot of configuration options makes it easier and simpler to deploy the project.

When you roll those three elements together, I think the converse of your question is an appropriate answer.  Why would you want the additional configuration ability that you're describing?  It will complicate deployment (therefore less simple), encourages moving away from a tight feature set, and you're potentially worrying about a trivial file size anyway.

And that's your architectural answer.  It wasn't done because it was never intended to be supported that way.  Architecture and design involves cutting off pathways so the shape can be formed or defined.  While I certainly didn't design the Storm package, I can see where their architects may have rejected what you're asking about in order to achieve the other goals of the project.

1 Okay fine, real time systems are better defined as systems that will guarantee a response within a fixed period of time.


问:
In C++ is casting to find bad pointers undefined behavior?
By accident I found that with a polymorphic type using dynamic_cast back to the derived class will throw a 'bad cast' error if the pointer is no longer valid. Is this undefined behavior or could this be a way to check for valid pointers without using smart pointers?

I'm not really against using smart pointers as they serve a real need, but I dislike the syntax. I don't have anything against templated types but I find smart pointers to bloat the code and I'm not a fan of macro's to try and avoid that bloat. I wish C++ included something in the language syntax itself vs using the template feature but with this question I'm more concerned about what is happening below and if this is a valid and defined way to checking for valid pointers as this gives an exception every time from my tests.

```<code>#include <string>
#include <map>

using namespace std;

class Base
{
public:
    virtual ~Base(){}
};

class Derived : public Base
{
public:
    virtual ~Derived(){}
};

class Storage
{
private:
    map<string, Base*> storage;
public:
    void AddItem(string name, Base* base)
    {
        if (storage.find(name) == storage.end())
        {
            storage[name] = base;
        }
    }

    template <class T>
    T& FindItem(string name)
    {
        if (storage.find(name) != storage.end())
        {
            Base* item = storage[name];

            return dynamic_cast<T&>(*item);
        }

        throw;
    }
};

int main()
{
    Storage store;

    // force 'd' to go out of scope for our test
    {
        Derived d;

        store.AddItem("test", &d);
    }

    // this will throw a bad cast exception
    Derived& test = store.FindItem<Derived>("test");

    return 0;
}
</code>```

答:
dynamic-cast needs to deference the pointer to find the proper offset it should be at, dereferencing an invalid pointer is undefined behavior,

one thing you might see:

```<code>class Derived2 : public Base
{
public:
    virtual ~Derived2(){}
};

int main()
{
    Storage store;

    {
        Derived d;

        store.AddItem("test", &d);
    }

    {
        Derived2 d2;

        Derived2& test = store.FindItem<Derived2>("test");//might not throw an exception
        //test might refer to d2
    }

    return 0;
}
</code>```

Messing about with a void* buffer and placement new and destroy will let me insert anything in there.

Just go with smart pointers and learn to appreciate them for the blessing that they are.

Body:
dynamic-cast needs to deference the pointer to find the proper offset it should be at, dereferencing an invalid pointer is undefined behavior,

one thing you might see:

class Derived2 : public Base
{
public:
    virtual ~Derived2(){}
};

int main()
{
    Storage store;

    {
        Derived d;

        store.AddItem("test", &d);
    }

    {
        Derived2 d2;

        Derived2& test = store.FindItem<Derived2>("test");//might not throw an exception
        //test might refer to d2
    }

    return 0;
}

Messing about with a void* buffer and placement new and destroy will let me insert anything in there.

Just go with smart pointers and learn to appreciate them for the blessing that they are.


答:
This is, indeed, undefined behaviour.

dynamic_cast needs to look up the run-time type for your pointer, which will generally require dereferencing it, and this is already UB.

Even if an implementation somehow avoid dereferencing the pointer - say by storing a lookup table with the type of each live object, indexed by address range - the fact that your object went out of scope means the same address could be reused by some other object. So, even in this (very contrived) scenario, you wouldn't necessarily get the result you want.

The only answer is to manage lifetimes correctly. As ratchet freak says, smart pointers are probably your best bet here.

Title: In C++ is casting to find bad pointers undefined behavior?

Body:
By accident I found that with a polymorphic type using dynamic_cast back to the derived class will throw a 'bad cast' error if the pointer is no longer valid. Is this undefined behavior or could this be a way to check for valid pointers without using smart pointers?

I'm not really against using smart pointers as they serve a real need, but I dislike the syntax. I don't have anything against templated types but I find smart pointers to bloat the code and I'm not a fan of macro's to try and avoid that bloat. I wish C++ included something in the language syntax itself vs using the template feature but with this question I'm more concerned about what is happening below and if this is a valid and defined way to checking for valid pointers as this gives an exception every time from my tests.

```<code>#include <string>
#include <map>

using namespace std;

class Base
{
public:
    virtual ~Base(){}
};

class Derived : public Base
{
public:
    virtual ~Derived(){}
};

class Storage
{
private:
    map<string, Base*> storage;
public:
    void AddItem(string name, Base* base)
    {
        if (storage.find(name) == storage.end())
        {
            storage[name] = base;
        }
    }

    template <class T>
    T& FindItem(string name)
    {
        if (storage.find(name) != storage.end())
        {
            Base* item = storage[name];

            return dynamic_cast<T&>(*item);
        }

        throw;
    }
};

int main()
{
    Storage store;

    // force 'd' to go out of scope for our test
    {
        Derived d;

        store.AddItem("test", &d);
    }

    // this will throw a bad cast exception
    Derived& test = store.FindItem<Derived>("test");

    return 0;
}
</code>```


问:
How is quality important to the programmer, the person?
I didn't ask how the quality of the software is important to the product itself, the customers/users, the manager or the company. I want to know how it is important to the programmer that build it.

I'll be interested in any books (please specify the chapter), articles, blog post, and of course your personal opinion on the subject regardless your experience.

答:
I do the simplest thing that will work for the client on the client's budget. Anything extra is time I'm stealing from playing playmobil and lego with my 5 year old son.

If things change and the client wants a modification, I do that and charge for it.

I do not look at long-term "potential" issues unless the client is paying for that, and they invariably aren't.

Ultimately, simple one-page scripts with no fancy algos and no bleeding-edge dependencies mean that any changes is trivial, even 1 year down the road.


问:
Sharing source code of my online game?
So one of my long-standing projects is an online fan-game that's been running for a good four years now, and is at least somewhat well-known among the related community. To give you an idea, Alexa ranks my online game higher than the official website for the franchise my game is based on.

One thing I've been wondering is, would it be a good idea to make the game's source code publicly viewable?

The reasoning for the idea is that this will allow the more programmer-oriented people in the community discover how the game works internally, and research certain features to determine possible outcomes of events, and share this knowledge with other users. For instance, they would be able to discover the exact chances of various treasures appearing in Chests, rather than just having a statistical analysis.

Major reasoning against it is "people can copy it", but honestly there are already copycat sites out there and many of them fall flat on their face simply because they try to be my game and either just don't get any attention in the first place, or get called out on being a rip-off by other members of the community.

These two points have been like a see-saw in my mind, tipping back and forth between "I should totally do it" and "nowai, src iz myne!" (not really like that :p) So I was hoping that I might be able to get some advice here, perhaps someone else has been through this and might have seasoned advice to offer?

答:
To avoid analysis like the probability of events can be avoided if you store all such constants in a config-file, which you do not opensource (or at least not with the real values).

Creating a copy is always a risk, but you gain the power of other interested developers, which might help to improve your game/code.

But if your community is stable you should not frighten to loose them if a copy of your game pops up. They will only switch if the copy is much improved.

Title: Sharing source code of my online game?


问:
How to efficiently troubleshoot or test new code when hardware setup to reproduce bugs is difficult or impossible to obtain?
I work at a mid-sized company (150ish employees, ~10 size engineering team), and most of my projects involve interfacing with lab equipment (oscilloscopes, optical spectrum analyzers, etc) for the purpose of semi-automated test applications.  I have run into a few different scenarios where I am unable to efficiently troubleshoot or test new code because I no longer or never had the hardware setup available to me.

Example 1: A setup where 10-20 "burn-in" processes are run independently using a bench top type sensor - I was able to obtain one such sensor for testing and could occasionally steal a second for simulating all of the facets of interfacing to multiple devices (searching, connecting, streaming, etc).

Eventually a bug showed up (and ultimately ended up being in the device firmware & drivers) that was very difficult to reproduce accurately with only one unit, but hit near "show stopper" levels when 10-20 of these devices were in use simultaneously.  This is still unsolved and is ongoing.

Example 2: A test requiring an expensive optical spectrum analyzer as its core component.  The device is pretty old, legacy according to the manufacturer who was acquired by a larger company and basically dissolved, and its only documentation was a long winded (and uninformative) document that seems poorly translated.  During initial development I was able to keep the device at my desk, but now its tied up, both physically and in schedule during its 24/7 multi-week tests.

When bugs show up related or unrelated to the device, I often need to go through the trouble of testing code external to the application and fitting it in, or writing code blindly and attempting to squeeze in some testing time in between runs, as much of the program logic requires the OSA and the rest of the test hardware to be in place.

I guess my question is how should I approach this? I could potentially spend time developing device simulators, but figuring that into the development estimate will balloon it more than most would probably appreciate.  It may not accurately reproduce all issues either, and it's pretty rare to see the same equipment used twice around here.  I could get better at unit testing...etc...I could also be loud about the issue and make others understand that temporary delays will be required, not much more than a headache for Research and Development but usually a perceived as a joke when pitched to manufacturing.

答:
You're trying to solve a problem that isn't yours to solve.

Management needs to prioritize access to the equipment.  That may mean you end up with greater access, but it may also mean you end up with less.

Present the challenges you have in an objective format to your management team and ask them for guidance.  Your presentation would be a lot stronger if you collaborated with the others who also need access, so all of you can present your case at the same time.

From there, the company (management) has to prioritize who gets access and when.  It's a business decision that they need to make since the (lack of) availability of the resources is impacting business development.


答:
You are effectively coding blind.

If management will not pay for test devices, then there is a high likelihood of bugs, or even the development taking longer than it would if you did have real devices to use.

The cost of the devices needn't be completely allocated to the "development" cycle. Maybe they could be rotated into production use, or as a backup. Could they even be resold second hand elsewhere?

Try and cost the bug fixing phases, in both time and money and show the overall cost to your team/company.

Title: How to efficiently troubleshoot or test new code when hardware setup to reproduce bugs is difficult or impossible to obtain?

Body:
I work at a mid-sized company (150ish employees, ~10 size engineering team), and most of my projects involve interfacing with lab equipment (oscilloscopes, optical spectrum analyzers, etc) for the purpose of semi-automated test applications.  I have run into a few different scenarios where I am unable to efficiently troubleshoot or test new code because I no longer or never had the hardware setup available to me.

Example 1: A setup where 10-20 "burn-in" processes are run independently using a bench top type sensor - I was able to obtain one such sensor for testing and could occasionally steal a second for simulating all of the facets of interfacing to multiple devices (searching, connecting, streaming, etc).

Eventually a bug showed up (and ultimately ended up being in the device firmware & drivers) that was very difficult to reproduce accurately with only one unit, but hit near "show stopper" levels when 10-20 of these devices were in use simultaneously.  This is still unsolved and is ongoing.

Example 2: A test requiring an expensive optical spectrum analyzer as its core component.  The device is pretty old, legacy according to the manufacturer who was acquired by a larger company and basically dissolved, and its only documentation was a long winded (and uninformative) document that seems poorly translated.  During initial development I was able to keep the device at my desk, but now its tied up, both physically and in schedule during its 24/7 multi-week tests.

When bugs show up related or unrelated to the device, I often need to go through the trouble of testing code external to the application and fitting it in, or writing code blindly and attempting to squeeze in some testing time in between runs, as much of the program logic requires the OSA and the rest of the test hardware to be in place.

I guess my question is how should I approach this? I could potentially spend time developing device simulators, but figuring that into the development estimate will balloon it more than most would probably appreciate.  It may not accurately reproduce all issues either, and it's pretty rare to see the same equipment used twice around here.  I could get better at unit testing...etc...I could also be loud about the issue and make others understand that temporary delays will be required, not much more than a headache for Research and Development but usually a perceived as a joke when pitched to manufacturing.