问:
Unit test private method in c++ using a friend class
I know that this is a debated practice, but let's suppose that this is the best option for me. I am wondering about what is the actual technique to do this. The approach that I see is this:

1) Make a friend class that of the class who's method I want to test.

2) In the friend class, create a public method(s) that call the private method(s) of the tested class.

3) Test the public methods of the friend class.

Here is a simple example to illustrate the above steps:

```<code>#include <iostream>

class MyClass
{
  friend class MyFriend; // Step 1

  private:
  int plus_two(int a)
  {
    return a + 2;
  }
};

class MyFriend
{
public:
  MyFriend(MyClass *mc_ptr_1)
  {
    MyClass *mc_ptr = mc_ptr_1;
  }

  int plus_two(int a) // Step 2
  {
    return mc_ptr->plus_two(a);
  }
private:
  MyClass *mc_ptr;
};

int main()
{
  MyClass mc;
  MyFriend mf(&mc);
  if (mf.plus_two(3) == 5) // Step 3
    {
      std::cout << "Passed" << std::endl;
    }
  else
    {
      std::cout << "Failed " << std::endl;
    }

  return 0;
}
</code>```

Edit:

I see that in the discussion following one of the answers people are wondering about my code base.

My class has methods that are called by other methods; none of these methods should be called outside the class, so they should be private. Of course they could be put into one method, but logically they are much better separate. These methods are complicated enough to warrant unit testing, and due to performance issues I will very likely have to re-factor these methods, hence it would be nice to have a test to make sure that my re-factoring didn't break anything. I am not the only one working on the team, though I am the only one who is working on this project including the tests.

Having said the above, my question was not about whether it is a good practice to write unit tests for private methods, though I appreciate the feedback.

答:
You can write your code with lots of workarounds to stop you having to use friends.

You can write classes and never have any private methods at all. All you need to then do is make implementation functions within the compilation unit, let your class call them and pass in any data members they need to access.

And yes it will mean you can change the signatures or add new "implementation" methods without changing your header in the future.

You have to weigh up though whether or not it is worth it. And a lot will really depend on who is going to see your header.

If I'm using a 3rd party library I'd rather not see friend declarations to their unit testers. I don't want to build their library either and have their tests run when I do. Unfortunately too many 3rd party open source libraries I have built do that.

Testing is the job of the writers of the library, not its users.

However not all classes are visible to the user of your library. Lots of classes are "implementation" and you implement them the best way to ensure they work properly. In those, you may still have private methods and members but want unit testers to test them. So go ahead and do it that way if that will lead to robust code quicker, that is easy to maintain for those who need to do so.

If the users of your class are all within your own company or team, you can also relax a bit more about that strategy, assuming it's allowed by your company's coding standards.


问:
Is there a language-agnostic specification for "string natural sorting order"?
As I painfully try to find a good natural sorting algorithm written in JavaScript, I then stumble upon a bunch of different implementations, interesting blog posts, and answers on StackOverflow.

Each implementation provides its technical tricks. However, the more I looked into it the more a question became very clear: "Is there actually any language-agnostic specification regarding natural sorting order of strings?"

I mean, if not, then how could one expect to write a piece of code that is actually "correct for everyone" or "agreed on by the community"? I would have expected a specification stating the result of the compromises/decisions made, at least for English, as it is simple (no accents/diacritics)...

Note that I wrote "language-agnostic" as I would expect this specification to then be used to implement solutions in different languages, not only in JavaScript, C#, or Java.

Resources:

Sorting for Humans: Natural Sort Order

Alphanum: JavaScript Natural Sorting Algorithm

www.davekoelle.com/alphanum.html

How to sort strings in JavaScript

Natural sort of alphanumerical strings in JavaScript

答:
The algorithms for determining which string comes first when comparing two strings are called collation algorithms and the sort order they produce is called the collation order.

Unfortunately, there is no agreed upon global collation order. To make matters worse, the correct sorting order is not only language dependent, but can even differ between different contexts.

One example of language difference is that in German the accented characters are ordered immediately after their unaccented counterparts (ö comes immediately after o), but in Swedish the accented characters come right at the end of the alphabet (ö comes after z). And as for usage differences, phone books and dictionaries can have different sort orders.

Although there is no global collation order, there are collation orders that generally give a reasonable order independent of the natural language that the words are written in and there are collation algorithms that can be tailored to either give a reasonable sort order or to give the absolute correct order for a given culture and usage.

One such algorithm is the "Unicode Collation Algorithm", which can be found at http://www.unicode.org/reports/tr10/. This algorithm can be tailored for a wide range of collation orders and comes with a default configuration that gives a reasonable ordering for all Unicode codepoints. The algorithm does not depend on any particular programming language.

The introduction section of the standard gives a nice overview of the difficulties in correctly collating text.

Another algorithm is described in ISO standard 14651.

Besides the various national collation orders, there is also a standardized collation order for the European languages, called the European Ordering Rules (EOR).

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 3.0


问:
Is this a commonly encountered situation in C++? Is there a pattern to handle it?
I am writing a game in C++, and something I have noticed is that I have many resource files which need to be loaded after a particular point in initialization.

For example, OpenGL textures and VAOs can't be created until there's a current OpenGL context. Once loaded, they will never be modified, so it is most convenient to make them global.

If these objects could be created without a current OpenGL context, this would be trivial to do:

```<code>const texture ground_texture = load_texture("ground.png");
const texture robot_texture = load_texture("robot.png");
const model robot_model = load_model("robot.obj");
</code>```

where texture and model are simple POD structs containing (among other things) OpenGL object IDs.

Instead, I can do this:

```<code>texture ground_texture;
texture robot_texture;
model robot_model;

void load_resources() {
    ground_texture = load_texture("ground.png");
    robot_texture = load_texture("robot.png");
    robot_model = load_model("robot.obj");
}
</code>```

and then call load_resources after the OpenGL context is initialized. But that requires about twice as much code (three times if these globals are also declared in a header file as well) and loses the const modifier.

It could conceivably be produced by a simple script to reduce duplication - then the only downside compared to the original non-working code is that the globals aren't const.

There's also this:

```<code>class texture_loader;
class model_loader;
static std::vector<const texture_loader*> tex_loaders;
static std::vector<const model_loader*> model_loaders;

class texture_loader {
    mutable texture tex;
    mutable bool initialized;
    const char *filename;
public:
    texture_loader(const char *filename)
        : initialized(false), filename(filename)
    {
        tex_loaders.push_back(this);
    }

    void load() const {
        tex = load_texture(filename);
        initialized = true;
    }

    operator texture() const {
        assert(initialized);
        return tex;
    }
};
// similarly for model_loader

const texture_loader ground_texture("ground.png");
const texture_loader robot_texture("robot.png");
const model_loader robot_model("robot.obj");

void load_textures() {
    for(texture_loader *t : tex_loaders) t->load();
    for(model_loader *m : model_loaders) m->load();
}
</code>```

but that seems like quite a lot of complexity for something that is conceptually simple. Also, texture_loader and model_loader (and anything_else_loader) would need to be exposed outside the resource loading module in order for other code to be able to use the globals.

Is this a commonly encountered case? How is it typically solved?

答:
Make an object that loads those textures, and require a constructor parameter for the object that sets up the prerequisite.

```<code>class OpenGLContext
{
public:
    OpenGLContext() { // set up context etc }
}

class TextureRepository
{
public:
     TextureRepository(OpenGLContext& context) { // set up textures }
     TextureRepository() = delete;
}
</code>```

Since the ctor of OpenGLContext sets up the context, and the repo requires a reference to that object, you have a natural way of expressing that dependency, and the compiler will tell you if you forget about it.

This approach can be extended to all kinds of resources with such dependencies.

Body:
Make an object that loads those textures, and require a constructor parameter for the object that sets up the prerequisite.

class OpenGLContext
{
public:
    OpenGLContext() { // set up context etc }
}

class TextureRepository
{
public:
     TextureRepository(OpenGLContext& context) { // set up textures }
     TextureRepository() = delete;
}

Since the ctor of OpenGLContext sets up the context, and the repo requires a reference to that object, you have a natural way of expressing that dependency, and the compiler will tell you if you forget about it.

This approach can be extended to all kinds of resources with such dependencies.


问:
Heap vs Stack Memory in java
I have some doubt on Heap and stack memory in java..

whether those are memory space or algorithm(procedure) of storing data at run time.

Here is the class

```<code>class HeapStack {

    String str = "test"; // heap memory

    int a = 10;// heap memory

    private void Test(){

        int a = 10;// stack memory

        String str = "test";// heap memory

    }

}
</code>```

am i correct?

答:
You are partially correct. Java works based on pointers, and all variables pointing to objects are pointers (officially called references). The memory for these variables are allocated on stack in case there are defined inside a method or on heap if they are fields.
The value of data itself is as you defined it: all objects + primitives defined as fields, live on heap while primitives defined inside methods live on stack.

In Java memory allocation is pretty much the same for both stack and heap (as different from C which has a more complex allocation logic for heap): for stack is just push and for heap there is a mechanism called bump the pointer. The big difference is in memory reclaiming; for stack is jut pop while for heap there is the renowned garbage collector.

A more accurate commented class would be:

```<code>class HeapStack {

    String str /*heap*/ = "test"; // heap memory
    int a /*heap*/ = 10;// heap memory

    private void Test() {
        int a /*stack*/ = 10;// stack memory
        String str /*stack*/ = "test";// heap memory
    }
}
</code>```

Title: Heap vs Stack Memory in java

Body:
You are partially correct. Java works based on pointers, and all variables pointing to objects are pointers (officially called references). The memory for these variables are allocated on stack in case there are defined inside a method or on heap if they are fields.
The value of data itself is as you defined it: all objects + primitives defined as fields, live on heap while primitives defined inside methods live on stack.

In Java memory allocation is pretty much the same for both stack and heap (as different from C which has a more complex allocation logic for heap): for stack is just push and for heap there is a mechanism called bump the pointer. The big difference is in memory reclaiming; for stack is jut pop while for heap there is the renowned garbage collector.

A more accurate commented class would be:

class HeapStack {

    String str /*heap*/ = "test"; // heap memory
    int a /*heap*/ = 10;// heap memory

    private void Test() {
        int a /*stack*/ = 10;// stack memory
        String str /*stack*/ = "test";// heap memory
    }
}


问:
Handling repetitive unit testing tasks
This problem arose whilst writing a simple 3D vector class.

The class contained methods (Java, so no operator overloading) for addition, subtraction, multiplication, and division. These methods performed this operation between the instance they were called on, and another vector or single value.

When it came to writing the unit tests, I was unsure how I should approach testing this class.

The three options I could come up with were as follows:

Test the Add, Sub, Mul, and Div methods separately (two for each, vector and value), with different values for each

Test the methods separately with the same values each time, but different expected results

Don't test the methods as they are very simple (not good for coverage)

What method would be most desirable in this situation? This pretty much also applies to any other scenarios where a task is very repetitive.

答:
I don't really see this as a Question and Answer problem but an entirely subjective one.  The 'correct' answer is the one that gets the most complete and accurate set of tests.

Boredom is the most defining obstacle with your 'problem': At one end of the spectrum errors will creep in because you're so bored by the repetition that your eyes glaze over and loose attention to detail.

At the other end you devise an elaborate automated test structure which keeps you challenged, but is inevitably error prone due to unexpected quirks (ie bugs) and esoteric maintenance issues.  Too far up this end and you need tests for your testing code.

As individuals our path-of-the-least-errors will vary.  Just know there is one and walk the line that you think works best for you.

Title: Handling repetitive unit testing tasks


问:
Representing list of polymophic objects in db
Let's suppose I have a list of derived objects from some base:

```<code>class Circle : public Shape;
class Rectangle : public Shape;
</code>```

There is object, which has vector of Shape * as member variable:

```<code>class Screen {
    std::vector<Shape *> shapes_;
}
</code>```

But now I need to persist this in database (PostgreSQL to be precise). Only way I thought of is to have table per class, something like this:

```<code>table screen ();

table circle (
    int screen_id;
);

table rectangle (
    int screen_id;
);
</code>```

And after retrieving from object of type Screen do query for Circles and Rectangles with screen.id. Should be doable.

However I fear that when number of types grows (and it will), it would mean many db queries for just one object retrieval/persist.

Right know we'll have about 10 types I think? That's 11 db queries just to retrieve one Screen object.

So my questing is, is there better way to achieve my goal? I'm fine with redesigning my code if needed, I just would like some O(1) solution in correlation to number of types (my solution is O(n) ).

Thank you guys ^_^

NOTE: based on comment I'm adding that tables of Circles and Rectangles etc. will be used only to put together Screen object. I don't access (look-up, retrieve, persist, ...) to them individually, only as parts of Screen(s). They don't even have to be in their own table. Just didn't find a way to nicely put it all together :/

答:
All you need is one table, with a simple design.  You need

A field for the uid

Possibly a field for a timestamp (you may need that, you may not, don't know your particular circumstances).

A field in which you serialize the Screen object and all the Shapes it contains.

That means just one write to save and one read to recover the Screen and its shapes.  Why do more, given how simple your requirements are?

I recommend you serialize to a json format.  Postgresql now has a JSON data type and JSON operators and functions.  So you can validate and examine the serialized data in the db if you want to, without having to extract and normalize it.

Other benefits of this approach:

If you later decide to serialize somewhere else (into a file or memory cache, for example), it would require minimal change to the code.

No need to change your db schema if you add new types of Shapes or change the structure of any existing objects.


问:
Do we need to test 32-bit software in 64-bit Windows?
I'm working in a software development team as software developer. I've been working on the same project for three years now. The software is a 32-bit desktop based C# application in .NET 4. Our target platform in Windows 7 (we had to support Windows XP till last year). The software communicates with various custom hardware for which custom drivers are written. The hardware manufacturing and driver software is written by our client. There is different driver for 32-bit and 64-bit Windows of course.

During our system testing phase, we execute all/most test cases in both 32-bit and 64-bit Windows 7. I can't recall if we got any bug in our software that exist in only one flavor of Windows. Having this experience I've started to wonder, do we really need to test 32-bit software on 64-bit Windows?

What's the industry standard?

答:
I would test any installer on as many different Windows setups as possible as from my experience the installers are most likely to fail on different systems.

Otherwise, as you know from your experience with the given software, bugs are most unlikely to just show up on 32-bit or 64-bit, and you can take some calculated risk.

Firstly, you should be having many test cycles with very little code changing between the later cycles as you get close to shipping. Any time you can save, you can use to create more test cases, and/or allow more (and hence smaller) cycles, so giving quicker feedback. (The risk of spending time testing X may be more than the risk of not testing Y, because you are testing X too much.)

Therefore

Try to test on the “other bitness” to what you used for the proceeding test cycle.

If you know the “bitness” your developer use, start with testing on other one.

Divide the test cases up between the “bitness” to give come coverage on each

But swap them between the “binnes” on each test cycle.


问:
How to predict a future simulation state
We have a program that combines the simulation of an aircraft system and predefined pedagogical scenarios for trainee pilots to learn how to use this system.

When we follow the normal scenario, chapter after chapter, everything goes smoothly.

Now, when the trainee skips the chapter N and goes directly to the chapter N+1, the simulation goes snafu because the chapter N was not executed by the simulation, resulting in an incoherent state.

As a remedy, we write the desired simulation state in the scenario file, just after the chapter entry point.

The problem is it's not possible to predict the simulation state for chapter N if we don't know the scenario first by heart. And some scenarios are very complex. A developer has to spend a long time studying the scenario to get an accurate picture of what is expected by the trainee then he jumps to chapter N.

The software doesn't need persistence. That is, we don't have to save the simulation state when the program is not running.

The simulation state is managed by ~200 000 variables. It is not possible for us to make a snapshot of the simulation state at every step because it would be highly impracticable, and each time the scenario is updated, the snapshot would be out of date.

We also don't have access externally to all variables since some are private and are out of bounds (And even if we had access, it would be a bad idea, given the sheer amount of data).

Is it a common problem and are there best practices and known solutions to tackle this issue ?

答:
The simulation state is managed by ~200 000 variables. It is not
  possible for us to make a snapshot of the simulation state at every
  step because it would be highly impracticable, and each time the
  scenario is updated, the snapshot would be out of date.

This sounds like a problem not only for running the simulation at a given chapter, but also for testing it. In order to test something you need to know the preconditions, i.e. the expected state at the beginning of the test. It's not reasonable to expect programmers working on a system that involves 200,000 variables to correctly foresee every effect of changes they make on the system, so automated testing seems like an absolute requirement for something like this.

The software doesn't need persistence. That is, we don't have to save
  the simulation state when the program is not running.

While it may not be a requirement that you be able to save the state of the simulator for each trainee, the fact that you're asking this question indicates that you do, in fact, need to be able to save the state of the simulation at various points so that you can load specific configurations on demand. Again, this will not only solve your problem, but also pay dividends in terms of testing and debugging.

If you cannot reasonably save the actual state of the simulation, another option is to be able to record and play back user actions. This is really just another way to record state, but instead of recording the state of the system at a given time, you instead record all the steps that get you to that state. In a deterministic system the same series of inputs will always result in the same final state. This approach may have some advantages -- since you're not recording the actual state of the system, it doesn't matter if the way the system is implemented changes; all that matters is that the actions expected of the user at each step don't change. Also, the space needed to record the user's actions might not be as great as that needed to record the total state of the system.


问:
How to force "program to an interface" without using a java Interface in java 1.6
In java 1.8 they have wonderful new "default interface methods".  In 1.6 how close can we come?  The goal: use code to keep clients from being able to tell that a class is not a java interface.  If we preserve the right to refactor the class name into a Java Interface we don't need to create a Java interface now.  We just provide the class.  Later, refactoring so the class name becomes an interface wont even touch client code.

From Telastyn's answer in Understanding "programming to an interface":

The "Dependency Inversion Principle" says that an object shouldn't control the creation  of its dependencies, it should just advertise what dependency it needs and let the caller provide it. But it doesn't specify whether the dependency should be a concrete type or an interface.

I want to take advantage of this lack of distinction. I also want to interpret the principle "program to an interface" to mean, "I shouldn't be able to tell if any client code is working with a java Interface or a java Class".  So much so, that later someone could swap out the class for a java interface with the same name and no client code would need to be touched.  That may seem overly strict and not exactly what was meant by these design principles (which try to be ignorant of java's particular quirks) but I'd love to pull it off.

Here's why:  Our development environment doesn't use continuous integration.  Releases that force everyone to integrate their code happen once every... well it hasn't happened in all the years I've been working there.  Worse than that, testing is hugely manual for reasons I wont even attempt to justify.  This means: writing a class that will get used by other people is essentially published because changing it will break someones stream or tested code that is closed and closed hard.  This means: no refactoring the signature of anything public on a shared class.  It feels the same as I expect writing an API for a library must feel.

I believe in YAGNI.  I don't want to do a BDUF.  But this situation tempts me to do silly things like put a Java Interface (big I) on every shared class even though, for now, they only have one implementation.  This is against YAGNI, it annoys developers who consider an unneeded interface to be clutter.

What I really want is the freedom to add that Interface, and maybe alternate implementations, later if needed.  I want to be 100% sure I can do this even when I can't even see all the code that might be written against my widely shared class.  I can only be that sure if I use the compiler to FORCE users to program to my interface (little i).

The question: Can you break this protection w/o using reflection from outside the trusted package?  Is the following the right way to achieve this?  In this environment you only get one shot at getting this right.  I want to know if there is anyway to lock me down to the old implementation from outside the trusted package.  All the commented code is "future" code. Except for the errors in main, which should always be errors.

Here we see someone trying their best to lock us down to an implementation:

```<code>package untrusted;

import trusted.AmIAnInterfaceWithDefaultImplementation;
import trusted.WhoKnowsWhatImplementation;

public class Activate {

    public static void main(String[] args) {
        System.out.println( WhoKnowsWhatImplementation.thisProvides().letsFindOut() );

        AmIAnInterfaceWithDefaultImplementation i =
            WhoKnowsWhatImplementation.thisProvides();

        System.out.println( i.letsFindOut() );

        //Error: AmIAnInterfaceWithDefaultImplementation i = new AmIAnInterfaceWithDefaultImplementation();
        //Error: The constructor AmIAnInterfaceWithDefaultImplementation() is not visible
    }
    //Error: public class ImGonnaForceYouToBeAClass extends AmIAnInterfaceWithDefaultImplementation {}
    //Error: The type ImGonnaForceYouToBeAClass cannot subclass the final class AmIAnInterfaceWithDefaultImplementation
}
</code>```

Prints: Default implementation twice.

Here we choose the implementation to provide in a static factory method.  It's only because we're in the same package that the constructor works.

```<code>package trusted;

public class WhoKnowsWhatImplementation {
     public static AmIAnInterfaceWithDefaultImplementation thisProvides() {
        return new AmIAnInterfaceWithDefaultImplementation();
        //return new IAintNoInterfaceNoMore();
    }
}
</code>```

The class below provides both the interface (small i) and the implementation but because the only constructor is protected and the class is final nothing outside the trusted package can force the interface and implementation to stay together.

```<code>package trusted;

/**
 *  Please don't instantiate directly as this may become an Interface.
 *  Use WhoKnowsWhatImplementation
 */
public final class AmIAnInterfaceWithDefaultImplementation {

    protected AmIAnInterfaceWithDefaultImplementation(){}

    public String letsFindOut() {
        return "Default implementation";
    }
}

//public interface AmIAnInterfaceWithDefaultImplementation{
//  public String letsFindOut();
//}
</code>```

We're free to switch to being an interface and push the implementation out to a new class

```<code>package trusted;

//public class IAintNoInterfaceNoMore implements AmIAnInterfaceWithDefaultImplementation {
//
//  @Override
//  public String letsFindOut() {
//      return "Shiny new implementation";
//  }
//}
</code>```

The need for the 'trusted' package comes from a desire not to have the static factory method live on the same class it's instantiating.  It would have to move when we switched to a Java Interface which would impact client code.  That is why the constructor had to be package accessible.

Can you lock this down as a class from outside the trusted package without using reflection?  Is your way of locking it down something that is reasonable to protect against?  What else would you do to protect against getting locked down?  Is there a better approach in java 1.6?

I'd also be interested to know if there is anyway to protect against reflection beyond the java doc begging you not to instantiate it directly but I suspect there isn't.

Many designs fail to adhere to all the design principles. This one violates the open closed principle: classes should be open to extension but closed to modification.  However, this is an attempt to ensure that the classes clients can stay closed even if it changes into a Java Interface.

The example refactoring shown here switches to an interface and implementation class.  It's worth noting that instead it might be decided that the class should actually be abstract.  When we switch to java 1.8, it might even end up as an interface with default methods on it.  The whole point is to preserve the right to make this decision later so we don't have to make it now when we don't know which to do and don't really care.

EDIT: I appreciate all these answers.  Before I accept one, what I'm waiting for is analysis of how vulnerable this approach is to getting locked down to being a class.  I'm willing to accept one that shoots down this whole idea by showing me code that dooms it to forever be a class.  Accepting one that claims it's a sound idea is a nice ego boost but I'd really rather fail here than in the code base.  So convincing me that it's a sound idea is the harder job.

What I've learned from these responses:

Converting from the class to the java interface requires that clients recompile

The class must not expose any more than the java interface could (e.g., no static methods)

Some will insist classes implement Java Interfaces upfront regardless of when they are needed, sigh

The need to recompile the client code strikes me as the most significant issue to be aware of so I'm accepting Maarten Winkels answer.  Thank you all and happy coding.

答:
Creating an interface is the best solution to your problem, and your only arguments against them are:

You won't ever have multiple implementations (YAGNI)

What I really want is the freedom to add that Interface and alternate implementations later if needed.

Interfaces are not just for switching implementations at run-time. Giving yourself ability to change the implementation behind an API without having to change client code is a valid reason to define a capital-I interface.

Your fellow developers find it difficult to navigate to implementations

(...) it annoys developers who like to be able to click on code and go right to the implementation not the Interface

It's trivially easy to navigate to implementations of a given method call in Eclipse: hold Ctrl and hover over the method call; a dropdown will appear with the Open Implementation option.

I haven't used IntelliJ in a while, but you can do it similarly there.

Don't give up on interfaces so easily. Solving your problem is one of their primary benefits.


问:
Understanding Boyer-Moore Algorithm
Edit: I've found the original publication. It seems to me that the original does not have a l′(i). But I could be wrong because the definition of rpr(i) is so obscure to me. I'm not sure how it makes use of it when rpr(i) is negative and what happens when no such reoccurrence is found.

I'm trying to implement Boyer-Moore algorithm according to this.
 I'm not sure if it is part of a book or if it's just some university notes. According to it (just before Theorem 0.2.4):

Definition: Let l′(i) denote the length of the largest suffix of P[i..n] that is also a prefix of P, if one exists. If none exists, then let l′(i) be zero.

And then it continues somewhere else with:

If, during the search stage, a mismatch occurs at position i − 1 of P and L′(i) > 0, then the good suffix rule shifts P by n − L′(i) places to the right, so that the L′(i) - length prefix of the shifted P aligns with the L′(i) - length suffix of the unshifted P. In the case that L′(i) = 0, the good suffix rule shifts P by n − l′(i) places.

Note that the rules work correctly even when l′(i) = 0.

Beware that indices are 1-based.

The part I'm having trouble with is the bold one. For example if we have the pattern abcde for which l′(5) = 0 and if we test this against abcze; the first mismatch occurs on d vs z. Now that l′(5) is 0, we need to shift it n - l′(5) characters to the right and thus lost our chance to find the matching.
Edit: WRONG. It should really shift n - l′(5) characters because there is no z or e in the pattern prior to the character we're checking.

So I'm wondering if I'm missing something or not. Should I ignore l′(i) when it's zero?

答:
So, after working on the algorithm a little more I got it working. The answer to my question is:

It should be shifted n - l′(i) characters to the right even when l′(i) = 0.

When l′(i) is zero, that means the following:

L′(i) is zero. So no reoccurring substring was found to the left that has a differing previous character. E.g:

```<code>mismatch:               v -----
 pattern: a b c Z a b c Z a b c
   index: 1 2 3 4 5 6 7 8 9 0 1
          0                 1
</code>```

A mismatch occurs on Z. There is a reoccurring substring abc to the left, but it starts with Z too. So it's no good. L′(9) is 0.

In this case, abc matches the prefix of the whole pattern, abc. l′(9) = 3  which is length of the longest substr-prefix match.

n - l′(9) = 11 - 3 = 8 shifts let us continue checking pattern[1..3] against already matched abc in the original text.

Pattern has no prefix that matches the already matched substring so far.

So it is impossible to find a matching unless we shift n - l′(i) = n characters to the right. I'm still not sure how the original publication handles the case when L′(i) is zero though.

Title: Understanding Boyer-Moore Algorithm

Body:
So, after working on the algorithm a little more I got it working. The answer to my question is:

It should be shifted n - l′(i) characters to the right even when l′(i) = 0.

When l′(i) is zero, that means the following:

L′(i) is zero. So no reoccurring substring was found to the left that has a differing previous character. E.g:

mismatch:               v -----
 pattern: a b c Z a b c Z a b c
   index: 1 2 3 4 5 6 7 8 9 0 1
          0                 1

A mismatch occurs on Z. There is a reoccurring substring abc to the left, but it starts with Z too. So it's no good. L′(9) is 0.

In this case, abc matches the prefix of the whole pattern, abc. l′(9) = 3  which is length of the longest substr-prefix match.

n - l′(9) = 11 - 3 = 8 shifts let us continue checking pattern[1..3] against already matched abc in the original text.

Pattern has no prefix that matches the already matched substring so far.

So it is impossible to find a matching unless we shift n - l′(i) = n characters to the right. I'm still not sure how the original publication handles the case when L′(i) is zero though.


问:
DB modeling for staffing demand and supply
TL;DR - I'm looking for guidance with my database design.  I am concerned that my existing design is inefficient and won't be able to handle large numbers of employees.

This is going to be long, so please bear with me.
I am in the process of creating a JEE application for staffing demand, supply and usage kind of web application.

So far, I have done the following (the easy part)
Core DB models like Employee, department, location etc.

Key points about demand and supply structure:

Allocation for each employee can happen between 0.1 to 1.0.

Each new employee automatically gets allocated to a pool project for 1.0

Need to track an employee's allocation to a granularity of a week's allocation. May be required to have daily allocation tracking
in future.

An employee can be allocated partially (between 0.1 to 1.0) or completely (1.0) for a demand.

Demand is further split into weeks and actual allocation needs to be tracked for each employee on each of this weeks. An employee
allocated to a demand may be allocated fully or partially to some or
all of the weeks for this demand.

I am planning to build the demand DB presentation as 3 tables.

Demand Master (DM): This will contain entry for each new demand created. Basically number of employees required and the over all duration of the demand.

DemandLineItem (DLI): Is the level 2 of demand data that stores the employee requirements for the demand.

DemandLineItemDetails(DLID): is the level 3 of details, that keeps details of each allocation for an employee at week level.

The relationship I envision for these 3 tables is like this

```<code>DemandMaster(DM) <-- 1 to many --> DemandLineItem (DLI) <-- 1 to many --> DemandLineItemDetails (DLID)
</code>```

So here is a dummy data set:

```<code>Table DM:
DemandId <--> StartDate <--> EndDate
Demand1  <--> 10 Feb 2014 <--> 24 Feb 2014

Table DLI:
DemandId <--> DliId <--> EmployeeRoleRequirement
Demand1  <--> Dli1  <--> Foreman
Demand1  <--> Dli2  <--> LineManager
Demand1  <--> Dli3  <--> Manager

Table DLID:

DLIID <--> DLID_ID <--> allocationstart <--> allocationend
Dli1  <--> DLIID1  <--> 10 Feb 2014 <--> 17 feb 2014
Dli1  <--> DLIID2  <--> 18 feb 2014 <--> 24 feb 2014
Dli2  <--> DLIID3  <--> 18 feb 2014 <--> 24 feb 2014
Dli3  <--> DLIID4  <--> 10 Feb 2014 <--> 17 feb 2014
</code>```

The problem statement:

This is an inefficient way of creating an tracking a demand, because of the number of joins involved.

With the number of increased demands, the DLI and DLID data will increase and will be difficult to do fast CRUD operations.

If I transpose a similar structure to supply structure, the number of weeks of data for a current employee will be huge, especially because supply structure needs to accommodate at least 2 years of data into future as "un-used" OR "available" allocations.

The fact that allocations committed to a demand needs also be subtracted from the above "un-used" or "available" pool makes it more complex.

Is there a better way of maintaining data like this (week/day level data for each employee)?

Maybe a better DB model OR different approach?

I am using mysql-workbench and mysql database for the designing.
Planning to use JPA (hibernate provider) as ORM.

答:
I think it's important that you keep the structure as is. But you'll also want to make a flattened structure for viewing the information. (This is probably what you're seeing as inefficient).

You can approach this in two ways, you can do a deferred "agent-based" ETL into a more flattened schema. Or you can use Materialized Views (or their equivalent on your database platform) to precache the searches for you without needing the agent.

In CQRS, this distinction is called Read Model vs. Write Model


答:
The only choice that is clearly wrong is "Don't test the methods as they are very simple."

Not testing is bad testing, regardless of how simple the methods are.

Some developers favor very spare unit tests, in which "only one thing can fail." As a result, even simple methods might deserve many individual test functions/methods.

To reduce boilerplate, excess "testing noise," and boredom, my preference is longer tests that really give each base method a good run for their money (at minimum including some simple cases, and some edge cages).

I would use a hybrid of choice 2 and choice 1: Use at least some of the same values in tests of your different Add, Sub, etc. methods, with different expected results (choice 2). Common inputs will simplify understanding not just of the testing code, but also the scope of testing--an important element as, over time, the ideal is to extend the tests to be fuller, richer, and cover more cases.

But some methods like Div and Mul beg for some tests that are different from those for additive operations (e.g. testing divide by zero). So for simplicity, start with choice 2, then to properly exercise useful edge cases, a dash of choice 1 (adding different inputs).

Title: Handling repetitive unit testing tasks

Body:
This problem arose whilst writing a simple 3D vector class.

The class contained methods (Java, so no operator overloading) for addition, subtraction, multiplication, and division. These methods performed this operation between the instance they were called on, and another vector or single value.

When it came to writing the unit tests, I was unsure how I should approach testing this class.

The three options I could come up with were as follows:

Test the Add, Sub, Mul, and Div methods separately (two for each, vector and value), with different values for each

Test the methods separately with the same values each time, but different expected results

Don't test the methods as they are very simple (not good for coverage)

What method would be most desirable in this situation? This pretty much also applies to any other scenarios where a task is very repetitive.


问:
Seeking advice writing functional requirements
I inherited a project that I've been maintaining for approximately a year now. The project primarily revolves around performing various financial calculations for the end user. It's roughly 100,000 lines of spaghetti code held together with duct tape and gumption. I've been slowly going through and refactoring the code as I have to make changes to it, and adding inline comments where helpful, but there's no formal documentation.

I've been tasks with rewriting the software on our company's new platform (I know, the worst decision a person can ever make is a complete rewrite, but in this case it's necessary, as the entire architecture and framework involved is changing). As the first step of this, I need to come up with a set of functional requirements. However, I'm at something of a loss on where to start and how to go about it. The scope of it is just so enormous that I'm not even sure where to begin.

Has anyone else had a similar experience? Where did you start with the documentation for the new project? Are there any resources out there I could consult? I could write the technical specifications of it today without an issue, but I've never before had to write functional requirements.

I know it's not normally part of the developer's responsibility to write functional requirements - someone in the business department should do this. However, it was apparently decided I was the best person for the job as to most of the people in our business department, the way it works is just "magic".

答:
I started programming in 1999 and I provide software outsourcing services since 2009 as my own business. During this time I participated to over 300 software engineering projects for over 100 customers in different countries.

The good news are that the only one company with good specifications I've seen is NASA. The others usually have a specifications which is better than nothing.

First of all there are several types of documents involved in software development lifecycle:

Business Plan - this document gives explanation how much will the software bring (or save), how much resources it will need to be created, how much is the cost of ownership.

Functional Requirements - this is a more particular document which describes in detail what problems should the software be able to solve. This document is usually created by a person who knows the business well enough, and in your case that should be someone familiar with financial calculations.

Technical Specification - The document created by CTO or Architect or experienced senior IT employee etc. It describes the approach to the problem and answers the question "How will we make it".

Note: This is not the complete list, it's more closer to minimal required set.

So I guess you are trying to make the last one of these docs without having the first two. I'd suggest to get at least a functional requirements first and based on this document you'll be able to make a Technical Specification for the solution based on the new platform.


问:
How can I simplify the following Access Control system design?
I couldn't find a better title for this...

I am trying to create an Access Control for my application and I am having serious trouble with building not an insane system, mainly for performance as this system will reside in an SQL database and will be used excessively throughout the app (every query will be using it for fetching data)

So here is my scenario and my current design:

My system has 3 modules and each has the general CRUD actions - list, view, update, create, delete; and sometimes has more specific actions like - user.view.creator, user.update.photo, user.update.metadata, storage.upload, storage.download etc.

I want my system to have "tasks" or "operations" and they will be hierarchical, for example storage.view will have a child storage.download.

This is for the operations. This part I have no problem implementing and designing. My biggest problem is designing the connection between a user and the tasks. Both RBAC and ACL doesn't fit my needs in this case, so I am trying to build my own. I cannot implement RBAC because in RBAC the roles are static but in my case the roles themselves are dependent of the resource and the group that this resource belongs to. For example, Group A's role photographer can only upload a photo from the storage, while the Group B's photographer can also delete the photo from the storage. Therefore, to keep things somewhat simple, I decided to add a new resource GROUP and every all the files, roles etc must BELONG to some group. On the other hand, the user just gets mapped to a group; they never BELONG to a group, they just access resources in groups. This makes perfect sense and works seamlessly and is not very complex - the queries are simpler, so I have space to cluster the databases etc.

However, now here comes the problem that just doesn't fit in my current design. I have another resource, CLIENT. The problem is, in the one organization, a user can have different access to different clients. So for example, lets say I have Group A, that has Clients 1 to 25. A specific user that belongs to that group, can have something like:

```<code>Client 1 - Manager
Client 2 - Assistant
Client 3 - SomeOtherRole
</code>```

And when he fetches a list of clients, the user will only see 3 clients. I really don't know what I should do to achieve this in the most performant way possible. My question is, how should I proceed with designing this part of my system? And a better question, how can I simplify this system?

答:
ACLs (also sometimes known as IBAC or Identity-based access control) and RBAC (role-based access control) are not enough as you found out through your use case. The reason is: you are using additional metadata or attributes. Attributes are simply key-value pairs for instance the ownership of a photo, the nature of the action (e.g. CRUD as in your example) or the type of object you are working on (picture, blog post, metadata, page...).

What you want to do is create simple authorization rules based on those attributes e.g.

A user with the role=editor can do the action=edit on an object of type=photo if and only if photo.owner==user.id

To do this, you need to turn to ABAC - attribute-based access control. ABAC extends RBAC as it brings additional attributes based on which you can make decisions and more importantly it gives you relationships (such as the ownership relationship in my example).

ABAC makes it extremely simple to implement your use cases. There is a standard called XACML (eXtensible Access Control Markup Language) which implements ABAC and it would solve your problem relatively easily. XACML gives you:

an authorization architecture with the notion of a policy enforcement point (PEP) which protects your resource, a policy decision point (PDP) which makes decisions based on the previously defined authorization policies, and a policy information point (PIP) from which you can retrieve additional metadata (e.g. the object's owner).

a policy language which you can use to implement your most advanced authZ scenarios

a request/response scheme used to send a question such as "Can Alice edit doc #123?" and receive an answer e.g. "Permit".

The cool thing about XACML is that you can extend it to cater for device-based access control, time-sensitive access control or even authentication-sensitive access control.

Here are some more resources to help you get started:

ABAC - a report by NIST

OASIS XACML - the standard website

ALFA the Axiomatics Language for Authorization - a free policy authoring tool for Eclipse


问:
An algorithm for finding converse duplicates of ordered pairs
Given an array of ordered pairs of values, what algorithm will find converse duplicates? [Converse meaning the same values, but in the opposite order.]

That is, given [ab,ac,ad,bc,bd,ca,db] is there an efficient way to find ca and db, being the converse duplicates for ac and bd?

The application is simple enough: the ordered pairs are edges in a directed graph and if there is a converse edge then a single double-ended edge is to be drawn rather than one edge in each direction. The values are strings, being node names.

It can be viewed as a lookup in a sparse array. Given coordinates (a,b), check whether (b,a) exists. However, common programming languages do not (appear to) provide sparse 2d arrays.

I have written a solution in ruby using hash-of-hash, but it's about 20 lines of awkward code and an unsatisfying outcome. Writing the same code in a language like C# or Java would be longer. A better solution is sought, in pseudocode or a description (steps) of the algorithm. Either way, I am seeking an answer that describes how to find the solution as well as the benefits and drawbacks of the particular algorithm.

I haven't attempted to define 'efficient' or 'better', and performance is not an overriding consideration for a drawing of a few hundred nodes.

The nodes are not sorted, so the default algorithm would be, for each pair, to form the converse and brute-force search the preceding half. A binary search would require a prior sort. A solution based on hash indexing should be much faster.

答:
Here's a working solution with decent performance.

```<code>ordered = lambda x, y: (x, y) if x <= y else (y, x)

def makeArrows(edges):
  """
  input: a sequence of (src, dst) pairs, maybe some reciprocal.
  output: generator yielding (src, dst, is_double_ended) triples.
  """
  undirected_edges = set()
  for src, dst in edges:
    edge = ordered(src, dst)  # both 'ab' and 'ba' become ('a', 'b') here
    if edge in undirected_edges:
      # we found a reciprocal; there can only be one pair like 'ab' + 'ba',
      # so we remove it and output as double-ended
      undirected_edges.remove(edge)
      yield (src, dst, True)
    else:
      # accumulate an edge and wait; a reciprocal might be ahead
      undirected_edges.add(edge)
  # all edges not removed by now are one-ended
  for (src, dst) in undirected_edges:
    yield (src, dst, False)
</code>```

Now we can try it. Since Python strings are sequences, here I short-cut 'ab' instead of ('a', 'b').

```<code>raw_edges = ['ab', 'ac', 'ad', 'bc', 'bd', 'ca', 'db']

>>> list(makeArrows(raw_edges))
[('c', 'a', True), ('d', 'b', True), ('b', 'c', False), ('a', 'b', False), ('a', 'd', False)]
</code>```

Body:
Here's a working solution with decent performance.

ordered = lambda x, y: (x, y) if x <= y else (y, x)

def makeArrows(edges):
  """
  input: a sequence of (src, dst) pairs, maybe some reciprocal.
  output: generator yielding (src, dst, is_double_ended) triples.
  """
  undirected_edges = set()
  for src, dst in edges:
    edge = ordered(src, dst)  # both 'ab' and 'ba' become ('a', 'b') here
    if edge in undirected_edges:
      # we found a reciprocal; there can only be one pair like 'ab' + 'ba',
      # so we remove it and output as double-ended
      undirected_edges.remove(edge)
      yield (src, dst, True)
    else:
      # accumulate an edge and wait; a reciprocal might be ahead
      undirected_edges.add(edge)
  # all edges not removed by now are one-ended
  for (src, dst) in undirected_edges:
    yield (src, dst, False)

Now we can try it. Since Python strings are sequences, here I short-cut 'ab' instead of ('a', 'b').

raw_edges = ['ab', 'ac', 'ad', 'bc', 'bd', 'ca', 'db']

>>> list(makeArrows(raw_edges))
[('c', 'a', True), ('d', 'b', True), ('b', 'c', False), ('a', 'b', False), ('a', 'd', False)]


答:
Practical Software Requirements is out of print, but if you can get hold of it, you might find it useful. It is not written from the point of view of your problem, but it does suggest approaches that result in functional requirements that have a very high signal/noise ratio, and starts from the bottom up to some degree.

in addition Volere provide a variety of resources - templates, documents, and consultancy - to aid in documenting and comprehending requirements. I found their templates very useful, though some discrimination on choice of templates is required.

All the usual disclaimers apply: I have no involvement with either of the above sources, but have found them useful.

Title: Seeking advice writing functional requirements

Body:
I inherited a project that I've been maintaining for approximately a year now. The project primarily revolves around performing various financial calculations for the end user. It's roughly 100,000 lines of spaghetti code held together with duct tape and gumption. I've been slowly going through and refactoring the code as I have to make changes to it, and adding inline comments where helpful, but there's no formal documentation.

I've been tasks with rewriting the software on our company's new platform (I know, the worst decision a person can ever make is a complete rewrite, but in this case it's necessary, as the entire architecture and framework involved is changing). As the first step of this, I need to come up with a set of functional requirements. However, I'm at something of a loss on where to start and how to go about it. The scope of it is just so enormous that I'm not even sure where to begin.

Has anyone else had a similar experience? Where did you start with the documentation for the new project? Are there any resources out there I could consult? I could write the technical specifications of it today without an issue, but I've never before had to write functional requirements.

I know it's not normally part of the developer's responsibility to write functional requirements - someone in the business department should do this. However, it was apparently decided I was the best person for the job as to most of the people in our business department, the way it works is just "magic".


问:
When writing object-oriented code, should I always be following a design pattern?
Is there a conceivable design pattern for any object-oriented program? I ask this because recently I saw an implementation of a Door class with a Lock. It was part of a test and the answer said that the code is following the Null Object pattern:

class Lock
{
public:
    virtual void close() = 0;
    virtual void open() = 0;
    virtual bool is_open() const = 0;
    virtual ~Lock() { }
};

class DummyLock
    : public Lock
{
private:
    DummyLock();
    DummyLock(const DummyLock&) = delete;
    DummyLock& operator=(const DummyLock&) = delete;

private:
    void close() { }
    void open() { }
    bool is_open() const { return true; }

public:
    static DummyLock m_instance;
};

class Door
{
public:
    Door() : m_lock(DummyLock::m_instance) { }
    Door(Lock &lock) : m_lock(lock) { }

public:
    Lock& get_lock() const { return m_lock; }

private:
    Lock &m_lock;
};
```

This made me think: This code follows a good design pattern even though the description is so simple (this class is designing a door class with a lock), so if I am writing more complex code, should there always be some design pattern that I am following?

答:
I will buck the trend a little, because the answer is more subtle than other answers are letting on.  Every class you write should not employ a design pattern, but most non-trivial programs you write likely should.

A non-trivial program without any design patterns indicates:

Your program is so unique that no portion of it is similar to common problems programmers have faced before. Or

Your program contains those common problems, but you've solved them in a better way that no one has thought of before.

Both scenarios are highly unlikely, no offense.

That doesn't mean the design pattern should drive your design, or that you should insert one indiscriminately because you think it will look bad if you don't.  The wrong design pattern is worse than none.

What it does mean is you should look at a lack of design patterns in your overall program as a code smell.  Something that makes you take a second look and reevaluate if your design couldn't be cleaner.  If at that point you decide to leave design patterns out of a program, that should be a deliberate, informed decision, not happenstance.

For example, you don't say, "I need to model a door and a lock, what design pattern should I use?"  However, if you designed it first without using any design patterns, that should prompt you afterward to say something like, "I have an awful lot of null checks in this code, I wonder if there's a design pattern that could help manage those."

See the difference?  It's a subtle but important distinction.


问:
Should we avoid object creation in Java?
I was told by a colleague that in Java object creation is the most expensive operation you could perform. So I can only conclude to create as few objects as possible.

This seems somewhat to defeat the purpose of object oriented programming. If we aren't creating objects then we are just writing one long class C style, for optimization?

答:
Joshua Bloch (one of Java platform creators) wrote in his book Effective Java in 2001:

Avoiding object creation by maintaining your own object pool is a bad
  idea unless the objects in the pool are extremely heavyweight. A
  prototypical example of an object that does justify an object pool is
  a database connection. The cost of establishing the connection is
  sufficiently high that it makes sense to reuse these objects.
  Generally speaking, however, maintaining your own object pools
  clutters up your code, increases memory footprint, and harms
  performance. Modern JVM implementations have highly optimized garbage
  collectors that easily outperform such object pools on lightweight
  objects.


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

    String name;
    int id;

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

Now I can invoke the following statement:

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

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

If I define a single explicit constructor as follows:

```<code> class Employee{

    String name;
    int id;

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

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

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

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

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

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

答:
First of all, default constructor is not generated, its provided by compiler if no-argument constructor is not written explicitly.

When you do not explicitly write a no-argument constructor for a class, the compiler won't complain as long as objects are built without parameter constructors.(since compiler allows default constructor to create objects, which itself gives call to no-argument constructor).

But if you do define a no-argument constructor, when compiling, compiler will check for the call to constructor and its definition in class. It's just like authenticating any other method of a class.

So it will give an error if you call no-argument constructor after defining a parameterised constructor, since it finds no no-argument constructor explicitly defined in class. And, this is logically correct since, if you want to block creation of objects without any data in it, this is one good way.

For example, consider that an employee object must have an employee id associated to it.
For achieving this, define a single argument constructor and don't define no-argument constructor.


答:
How old is your app?

Almost two years ago I inherited a similar situation in a 5 years old app and we keep calm and carry on, small, small continuous improvements.

If I could, I would start from the client and the final user.  I'd be gathering requirements in the same way as a new project.  It's likely the user / client needs have changed or they have new ideas.  The app very likely has failed functionality that I don't need to re-implement.  I'd be using it as a mere "mockup" example.

In this way I have the advantage of actually showing a product to people who already know the problem. And understanding the code I can ask the right question about the behavior.

Technology also improved and it might offer another possible point of view on the meaning of your app.

That's what I would do if I were so lucky to have the chance to start from scratch.


答:
Games typically have common resources that are created once an then stay
resident. However, I would advise against exposing such resources as global
variables. A better option would be to handle all resource management
via a ResourceManager type. The resource manager might be a singleton.

The resource manager should work basically as a cache of resources.
Allowing you to request a resource by an identifier, such as the file name,
loading the resource transparently if it is not cached or just returning
an existing instance. The resource manager might also be able to to pre-load
resources once the application starts. It is also the entity responsible
for managing the lifetime of resources.

Conceptually, it could look something like this:

```<code>class ResourceManager {
public:

    // Preload important stuff.
    // This should probably be called at startup,
    // but after the rendering context is created.
    void preloadResources();

    // Find or load a new resource.
    // If the resource is already available, this is a quick
    // table lookup, else, it is loaded and cached.
    const Texture * findOrLoadTexture(const string & filename);

    // Other methods for other resource types...
    // Or you could have a generic 'Resource' base type.
};
</code>```

Then in the game logic code, referencing a resource becomes very simple:

```<code>void Game::init()
{
    ResourceManager::preloadResources();
}

void Player::init()
{
    robot_texture = ResourceManager::findOrLoadTexture("robot.png");
    robot_model   = ResourceManager::findOrLoadModel("robot.obj");
}
</code>```

You can get very sophisticated with a ResourceManager, adding a smart
cache that can "garbage collect" unused resources. Once you have a solid
interface installed, this becomes easy. Also, your would probably
not be using raw pointers directly, but smart pointers instead (like std::shared_ptr)
to keep correct and efficient track of the lifetime of the resources.

Title: Is this a commonly encountered situation in C++? Is there a pattern to handle it?

Body:
I am writing a game in C++, and something I have noticed is that I have many resource files which need to be loaded after a particular point in initialization.

For example, OpenGL textures and VAOs can't be created until there's a current OpenGL context. Once loaded, they will never be modified, so it is most convenient to make them global.

If these objects could be created without a current OpenGL context, this would be trivial to do:

```<code>const texture ground_texture = load_texture("ground.png");
const texture robot_texture = load_texture("robot.png");
const model robot_model = load_model("robot.obj");
</code>```

where texture and model are simple POD structs containing (among other things) OpenGL object IDs.

Instead, I can do this:

```<code>texture ground_texture;
texture robot_texture;
model robot_model;

void load_resources() {
    ground_texture = load_texture("ground.png");
    robot_texture = load_texture("robot.png");
    robot_model = load_model("robot.obj");
}
</code>```

and then call load_resources after the OpenGL context is initialized. But that requires about twice as much code (three times if these globals are also declared in a header file as well) and loses the const modifier.

It could conceivably be produced by a simple script to reduce duplication - then the only downside compared to the original non-working code is that the globals aren't const.

There's also this:

```<code>class texture_loader;
class model_loader;
static std::vector<const texture_loader*> tex_loaders;
static std::vector<const model_loader*> model_loaders;

class texture_loader {
    mutable texture tex;
    mutable bool initialized;
    const char *filename;
public:
    texture_loader(const char *filename)
        : initialized(false), filename(filename)
    {
        tex_loaders.push_back(this);
    }

    void load() const {
        tex = load_texture(filename);
        initialized = true;
    }

    operator texture() const {
        assert(initialized);
        return tex;
    }
};
// similarly for model_loader

const texture_loader ground_texture("ground.png");
const texture_loader robot_texture("robot.png");
const model_loader robot_model("robot.obj");

void load_textures() {
    for(texture_loader *t : tex_loaders) t->load();
    for(model_loader *m : model_loaders) m->load();
}
</code>```

but that seems like quite a lot of complexity for something that is conceptually simple. Also, texture_loader and model_loader (and anything_else_loader) would need to be exposed outside the resource loading module in order for other code to be able to use the globals.

Is this a commonly encountered case? How is it typically solved?

Body:
Games typically have common resources that are created once an then stay
resident. However, I would advise against exposing such resources as global
variables. A better option would be to handle all resource management
via a ResourceManager type. The resource manager might be a singleton.

The resource manager should work basically as a cache of resources.
Allowing you to request a resource by an identifier, such as the file name,
loading the resource transparently if it is not cached or just returning
an existing instance. The resource manager might also be able to to pre-load
resources once the application starts. It is also the entity responsible
for managing the lifetime of resources.

Conceptually, it could look something like this:

class ResourceManager {
public:

    // Preload important stuff.
    // This should probably be called at startup,
    // but after the rendering context is created.
    void preloadResources();

    // Find or load a new resource.
    // If the resource is already available, this is a quick
    // table lookup, else, it is loaded and cached.
    const Texture * findOrLoadTexture(const string & filename);

    // Other methods for other resource types...
    // Or you could have a generic 'Resource' base type.
};

Then in the game logic code, referencing a resource becomes very simple:

void Game::init()
{
    ResourceManager::preloadResources();
}

void Player::init()
{
    robot_texture = ResourceManager::findOrLoadTexture("robot.png");
    robot_model   = ResourceManager::findOrLoadModel("robot.obj");
}

You can get very sophisticated with a ResourceManager, adding a smart
cache that can "garbage collect" unused resources. Once you have a solid
interface installed, this becomes easy. Also, your would probably
not be using raw pointers directly, but smart pointers instead (like std::shared_ptr)
to keep correct and efficient track of the lifetime of the resources.


问:
Does this Relational Database Model make sense?
Here is a flat version of my datamodel. It is sensor readings for various data acquisition equipment.

https://i1295.photobucket.com/albums/b628/colnewman26/Work%20Screen%20Shots/RobinDataModel_zpsdfc40151.png~original

Here is my Relational Database model. Does this make sense.

https://i1295.photobucket.com/albums/b628/colnewman26/RobinDataModel_zps847d94b5.png~original

If not what you suggest?

答: Seems to me you may have over normalized this based on the original table design.  Unless you are certain that you will need an indeterminate number of factors, you pay a pretty high penalty in insertion and retrieval of data with that schema.  Having worked with high data volume sensors (GPS readings) I found that performance considerations pay a heavy role as you start viewing trending data as the data volume grows.</p>


问:
Why design a modern language without an exception-handling mechanism?
Many modern languages provide rich exception handling features, but Apple's Swift programming language does not provide an exception handling mechanism.

Steeped in exceptions as I am, I'm having trouble wrapping my mind around what this means. Swift has assertions, and of course return values; but I'm having trouble picturing how my exception-based way of thinking maps to a world without exceptions (and, for that matter, why such a world is desirable). Are there things I can't do in a language like Swift that I could do with exceptions? Do I gain something by losing exceptions?

How for example might I best express something like

```<code>try:
    operation_that_can_throw_ioerror()
except IOError:
    handle_the_exception_somehow()
else:
     # we don't want to catch the IOError if it's raised
    another_operation_that_can_throw_ioerror()
finally:
    something_we_always_need_to_do()
</code>```

in a language (Swift, for example) that lacks exception handling?

答:
```<code> int result;
 if((result = operation_that_can_throw_ioerror()) == IOError)
 {
  handle_the_exception_somehow();
 }
 else
 {
   # we don't want to catch the IOError if it's raised
   result = another_operation_that_can_throw_ioerror();
 }
 result |= something_we_always_need_to_do();
 return result;
</code>```

In C you would end up with something like the above.

Are there things I can't do in Swift that I could do with exceptions?

No, there isn't anything.  You just end up handling result codes instead of exceptions.

Exceptions allow you to reorganize your code so that error handling is separate from your happy path code, but that is about it.

Body:
 int result;
 if((result = operation_that_can_throw_ioerror()) == IOError)
 {
  handle_the_exception_somehow();
 }
 else
 {
   # we don't want to catch the IOError if it's raised
   result = another_operation_that_can_throw_ioerror();
 }
 result |= something_we_always_need_to_do();
 return result;

In C you would end up with something like the above.

Are there things I can't do in Swift that I could do with exceptions?

No, there isn't anything.  You just end up handling result codes instead of exceptions.

Exceptions allow you to reorganize your code so that error handling is separate from your happy path code, but that is about it.


问:
In the light of the open / closed principle, is shared code ownership still important?
I was recently thinking about the following. According to the open / close principle, once a piece of code X has been implemented and tested, it should not be modified any more.

X can still be replaced by another piece of code implementing the same interface (maybe with a better implementation), or new functions and methods can be added to it. But the part that is already implemented and (thoroughly) tested should now work as a black box that can be invoked from the outside but should not be modified any more.

So, if the open / close principle is implemented correctly, shared code ownership should not be so important anymore because no one will need to modify a finished, self-contained piece of code. This seems quite natural to me but I haven't heard of this idea before. Is there any literature or school proposing this thesis: open / close principle makes shared code ownership less important?

答:
I think you have taken this concept a little too literally. The open/closed principle refers to the entity within the design of the software. Of course once something is done and tested you won't want to modify it anymore. You shouldn't modify it. It should be considered closed. However, in the course of unit tests, external dependencies may vary that you have no control over. Data structures may change, a new test case may arise that was not considered during its initial production.

As @RobertHarvey mentions in comments, the implementation is always open for modification. Bugs need to be fixed and they can't be fixed through extension. However, what remains closed is the intended behavior of the class. Once the behavior is established, that is what is closed. If a test begins to fail, the entity may need to be modified to correct for the introduction of that bug (through whatever vector it came in on). However, in all cases, the intended behavior of the entity should remain static and predictable.

That being said, it ownership remains a requirement doesn't it? Even if the expectation is that you'll never have to touch that code again because it's tested and it works, you have to be prepared for the abnormal condition. It may not be as high a priority, but shared ownership will always be necessary. You're right in that it isn't "as important", but it is still necessary to have covered. Will the "owner" care most of the time? Of course not. However, if things do start blowing up and hitting the fan, then the lack of shared ownership can be catastrophic.


答:
The devil is in the details. If you read through the chapter on OCP in Patterns, Practices, and Principles, Martin explains that the "closed" nature of OCP is closed to a specific type of change. Once you've discovered a need for a change you close off the artifact for changes that are similar to that one.

For instance, lets say you have to implement the order fulfillment system for an e-commerce company. At the first pass, you interface directly with your company's chosen shipping provider. As the company grows, you need to support different shipping companies. Having to change your component, you decide to protect your component from future modifications to how shipping is handled.

This is how OCP is intended to be interpreted. You can't predict every change your code will need. But whenever you do change it, close the door for that category of changes.

Title: In the light of the open / closed principle, is shared code ownership still important?

Body:
I was recently thinking about the following. According to the open / close principle, once a piece of code X has been implemented and tested, it should not be modified any more.

X can still be replaced by another piece of code implementing the same interface (maybe with a better implementation), or new functions and methods can be added to it. But the part that is already implemented and (thoroughly) tested should now work as a black box that can be invoked from the outside but should not be modified any more.

So, if the open / close principle is implemented correctly, shared code ownership should not be so important anymore because no one will need to modify a finished, self-contained piece of code. This seems quite natural to me but I haven't heard of this idea before. Is there any literature or school proposing this thesis: open / close principle makes shared code ownership less important?


问:
Who provides hardware resources in private cloud?
I find myself confusing to understand the concept of private cloud. If a company has an offshore data-center, and now if the company wants to move into a private cloud, what does the company has to do?

If I am correct, in order to use the term cloud, there should be virtualization. If there is no virtualization, there is no cloud. So is a private cloud, where you virtualize your existing data center? Or is it simply throwing out your existing hardware and purchasing hardware from a cloud provider, so that now all your resources are on the Internet?

And also how does the private cloud differ from virtual private cloud?

答:
My understanding is that a "Private Cloud" is a cloud which is used solely by one organization. It does not matter if it is a third party or a hosted service.

The opposite is a "public cloud" which means that the cloud services are open for public use.

Now, regarding "virtual private cloud". This is using virtualization services to create a private cloud. For example, you have a single server which virtualizes 3 servers (an FTP server, a Web server and a DB Server). They all belong to the same "Virtual Cloud" and they are private because they are solely used by your company.

Anyway, Cloud is a buzzword nowadays. My understanding is that it always involve virtualization, be it in an infrastructure, platform or service level. This is what creates the other terms IaaS, PaaS and SaaS.

For reference you can check: http://en.wikipedia.org/wiki/Cloud_computing also maybe the presentations from https://courses.edx.org/courses/BerkeleyX/CS-169.1x/2013_Summer/info

I hope this helps.


问:
Alternative to language purity

Purity

One of the interesting concepts in Haskell is the purity. However, I am wondering what the pragmatic reasons behind this is - let me explain a bit more before you reject my question.

My main point is that we are going to have side-effect no matter how we might encapsulate these in a language. So, even if a programming language like Haskell is pure, we are just "postponing" the side-effects till a later point.

I understand the idea that purity makes reasoning about programs easier (referential transparency and so on). In Haskell, we encapsulate all side-effects in the type system (the IO monad). As such, we cannot have a side-effect without propagating the IO monad down through the types of all functions calling our impure function, so to speak.

As such, I am very keen on the idea of separating pure functions from impure ones in the type system. This seems like a good way to force ourselves to limit such effects.

Still, Haskell is often getting bashed because of its pure nature - people say it isn't practical or pragmatic. Whether this is true or not is another matter, but the fact is that many people reject Haskell for this reason.

An alternative approach? (let us call it "type pollution")

To me, it seems that the main winning point is not purity itself, but the separation of pure and impure code. If encapsulating IO in a monad is too impractical, why don't we try a simpler approach?

What if we instead labelled every return type and argument type in the system as pure or impure. The D language has en explicit "pure" keyword, but I am thinking that we let functions be pure by default and only mark impure functions.

In an ML-like language this could look like this:

```<code>let square x = x * x

let impure getDbData connectionString = ...

let impure getMappedDbData mapping =
    let dbData = getDbData "<some connection info>"
    in map mapping dbData

let main =  // Compiler error, as it is not marked as impure
    let mappedData = getMappedData square
    in ...
</code>```

Further, calling any impure function would "pollute" the calling functions return type, turning it impure. If it wasn't labelled as such, it would give a compile error.

(of course, passing functions as arguments would need to be checked against the expected purity as well, but it should be easy to infer the expected "purity" of arguments)

(the "impure" label could be inferred as well, by I guess it is better to keep this one explicit, for readability)

Pure functions on the other hand, can be passed anywhere, no matter the expected purity. We could give a pure function as input to a function accepting an impure one. So it is not a symmetric relationship - therefore the word "pollution".

All in all, this would explicitly (and statically checked) separate the codebase into a pure and impure part. In many ways, it is close to the functionality of an IO monad (although the asymmetry probably rules out a 1-to-1 mapping between the two), but with an implicit unwrapping done automatically. Most importantly, many programmers would find it more intuitive and pragmatic than an explicit IO monad or something similar.

And unlike the completely impure solutions, this gives a lot more safety to reason about the pure parts (without standing too much in our way, when defining the impure ones). And all in all, it is mostly a statically enforced version of what most functional programmers consider best practice anyway (the separation).

TL;DR;

Has something like the above described approach ever been tried out? If not, is there any reason why not (both technical, practical, theoretic and philosophical reasons are interesting)?

And finally, would such a purity check be easier to accept for people who claim Haskell is impractical?

Disclaimer

I do not personally hold any grudges towards Haskell and the choice of using monads for IO. In fact, I find Haskell to be one of the most elegant languages in use, and maybe the one language I enjoy the most.

Further, it is clear that the above mentioned approach does not offer something that the IO monad does not - the only thing is that it more closely (visually) resembles impure languages like OCaml, F# and so on, which is bound to make it easier to grasp for many people. In fact, taking existing F# code and adding some "impure" labels would be the only visual difference in code.

Hence, this could be an easy step towards purity for languages that do not have the same ecosystem surrounding monads as Haskell has.

答:
I think you've reinvented monads! Let's look at what we have here, we can "dirty" a pure computation implicitly and use it in an impure one, and we can call impure function from another impure one.

That sounds a lot like monads, we can dirty a pure value with return, to call another function from an impure function, we can just use >>=

```<code>apply :: (a -> IO b) -> IO a -> IO b
apply f a = a >>= f
</code>```

Now your approach is a little more familiar to people from other languages: we all have some sort of purity check running through our heads to try to figure out what's happening where.

The disadvantage is that by making these things a language level concept, we've made it very difficult to build on. In Haskell, there's a whole library of normal, user defined functions that work across all monads. If we baked IO wholesale into the language we'd be forced to make all of these functions primitive!

By minimizing the amount of dark magic around how purity is handled, we can actually make things easier to work with from userland.

Title: Alternative to language purity

Body:
I think you've reinvented monads! Let's look at what we have here, we can "dirty" a pure computation implicitly and use it in an impure one, and we can call impure function from another impure one.

That sounds a lot like monads, we can dirty a pure value with return, to call another function from an impure function, we can just use >>=

apply :: (a -> IO b) -> IO a -> IO b
apply f a = a >>= f

Now your approach is a little more familiar to people from other languages: we all have some sort of purity check running through our heads to try to figure out what's happening where.

The disadvantage is that by making these things a language level concept, we've made it very difficult to build on. In Haskell, there's a whole library of normal, user defined functions that work across all monads. If we baked IO wholesale into the language we'd be forced to make all of these functions primitive!

By minimizing the amount of dark magic around how purity is handled, we can actually make things easier to work with from userland.


答:
In embedded programming, exceptions were traditionally not allowed, because the overhead of the stack unwinding you have to do was deemed an unacceptable variability when trying to maintain real-time performance.  While smartphones could technically be considered real time platforms, they are powerful enough now where the old limitations of embedded systems don't really apply anymore.  I just bring it up for the sake of thoroughness.

Exceptions are often supported in functional programming languages, but so rarely used that they may as well not be.  One reason is lazy evaluation, which is done occasionally even in languages that are not lazy by default.  Having a function that executes with a different stack than the place it was queued to execute makes it difficult to determine where to put your exception handler.

The other reason is first class functions allow for constructs like options and futures that give you the syntactic benefits of exceptions with more flexibility.  In other words, the rest of the language is expressive enough that exceptions don't buy you anything.

I'm not familiar with Swift, but the little I've read about its error handling suggests they intended for error handling to follow more functional-style patterns.  I've seen code examples with success and failure blocks that look very much like futures.

Here's an example using a Future from this Scala tutorial:

```<code>val f: Future[List[String]] = future {
  session.getRecentPosts
}
f onFailure {
  case t => println("An error has occured: " + t.getMessage)
}
f onSuccess {
  case posts => for (post <- posts) println(post)
}
</code>```

You can see it has roughly the same structure as your example using exceptions. The future block is like a try.  The onFailure block is like an exception handler.   In Scala, as in most functional languages, Future is implemented completely using the language itself.  It doesn't require any special syntax like exceptions do.  That means you can define your own similar constructs. Maybe add a timeout block, for example, or logging functionality.

Additionally, you can pass the future around, return it from the function, store it in a data structure, or whatever.  It's a first-class value.  You're not limited like exceptions which must be propagated straight up the stack.

Options solve the error handling problem in a slightly different way, which works better for some use cases.  You're not stuck with just the one method.

Those are the sorts of things you "gain by losing exceptions."

Title: Why design a modern language without an exception-handling mechanism?

Body:
Many modern languages provide rich exception handling features, but Apple's Swift programming language does not provide an exception handling mechanism.

Steeped in exceptions as I am, I'm having trouble wrapping my mind around what this means. Swift has assertions, and of course return values; but I'm having trouble picturing how my exception-based way of thinking maps to a world without exceptions (and, for that matter, why such a world is desirable). Are there things I can't do in a language like Swift that I could do with exceptions? Do I gain something by losing exceptions?

How for example might I best express something like

```<code>try:
    operation_that_can_throw_ioerror()
except IOError:
    handle_the_exception_somehow()
else:
     # we don't want to catch the IOError if it's raised
    another_operation_that_can_throw_ioerror()
finally:
    something_we_always_need_to_do()
</code>```

in a language (Swift, for example) that lacks exception handling?

Body:
In embedded programming, exceptions were traditionally not allowed, because the overhead of the stack unwinding you have to do was deemed an unacceptable variability when trying to maintain real-time performance.  While smartphones could technically be considered real time platforms, they are powerful enough now where the old limitations of embedded systems don't really apply anymore.  I just bring it up for the sake of thoroughness.

Exceptions are often supported in functional programming languages, but so rarely used that they may as well not be.  One reason is lazy evaluation, which is done occasionally even in languages that are not lazy by default.  Having a function that executes with a different stack than the place it was queued to execute makes it difficult to determine where to put your exception handler.

The other reason is first class functions allow for constructs like options and futures that give you the syntactic benefits of exceptions with more flexibility.  In other words, the rest of the language is expressive enough that exceptions don't buy you anything.

I'm not familiar with Swift, but the little I've read about its error handling suggests they intended for error handling to follow more functional-style patterns.  I've seen code examples with success and failure blocks that look very much like futures.

Here's an example using a Future from this Scala tutorial:

val f: Future[List[String]] = future {
  session.getRecentPosts
}
f onFailure {
  case t => println("An error has occured: " + t.getMessage)
}
f onSuccess {
  case posts => for (post <- posts) println(post)
}

You can see it has roughly the same structure as your example using exceptions. The future block is like a try.  The onFailure block is like an exception handler.   In Scala, as in most functional languages, Future is implemented completely using the language itself.  It doesn't require any special syntax like exceptions do.  That means you can define your own similar constructs. Maybe add a timeout block, for example, or logging functionality.

Additionally, you can pass the future around, return it from the function, store it in a data structure, or whatever.  It's a first-class value.  You're not limited like exceptions which must be propagated straight up the stack.

Options solve the error handling problem in a slightly different way, which works better for some use cases.  You're not stuck with just the one method.

Those are the sorts of things you "gain by losing exceptions."


问:
GPL - No version mentioned
```<code>This software is allowed to use under GPL or you need to obtain Commercial License
 to use it in non-GPL project.
</code>```

The above is mentioned on an open source project. It does not mention GPLv3 or GPLv2 explicitly. Does that mean I can use it as GPLv2/3 as per my convenience (as we can with LGPL)

I'm an open source newbie, so I just want to clarify this.

答: If no version is mentioned, you can use it under any version of the GPL, including version 1. It is for this reason that "any version" is not recommended, because the GPLv1 is much weaker than GPLv2 or GPLv3.</p>

Title: GPL - No version mentioned


问:
Unit testing in node.js and mocking modules
I'm trying to test this wrapper to request that I made:

// lib/http-client.js
var app = require('app'),
    request = require('request');

exports.search = function(searchTerm, next) {
  var options = {
    url: 'https://api.datamarket.azure.com/Bing/Search/Web',
    qs: {
      'Query': '\'' + searchTerm + '\'',
      'Adult': '\'Off\'',
      '$format': 'json',
      '$top': 10
    },
    auth: {
      user: app.get('bing identifier'),
      pass: app.get('bing identifier')
    }
  };

  request(options, function(err, res, body){

    if (err) return next(err);
    // TODO: parse JSON and return results
  });
};
```

<p>where <code>app</code> is an instance of express.  The question is, how do I test the function of this "module" without having to touch the internet? If I was to do this in other languages I would have mocked the request module but I don't know if that's the best way to do it in node.js.</p>

<pre class="lang-js prettyprint-override"><code>// NODE_PATH=lib

describe('Http Client', function(){
  it('should return error if transport failed', function(){
    var c = require('http-client'),
        results = 'foo';
    // request mock should return results when called
    c.search('foo', function(err, results){
      results.should.eql(res);
    });
    // TODO
  });
  it('should return an error if JSON parsing failed', function(){
    // TODO
  });
  it('should return results', function(){
    // TODO
  });
});
</code>```

答:
I recently did this. Forgot where I read about it but it's pretty easy.

Here's the basics of my code.

```<code>var express = require('express');
var http    = require('http');

var MyServer = function(options) {
  var app = express();
  app.get(/^\/foo.html/, sendFoo);
  app.get(/^\/bar.html/, sendBar);
  var server = options.server || http.createServer(app);
  server.listen(options.port);

  function sendFoo(req, res) {
     res.writeHead(200);
     res.write("foo");
     res.end();
  }

  function sendBar(req, res) {
     res.writeHead(200);
     res.write("bar");
     res.end();
  }

  this.close = function() {
     server.close();
  }
};
</code>```

As you can see my server either users http.createServer or the one I pass in. Maybe I should always pass it in? But in any case. I made a mock server

```<code>var events = require('events');

var MockHTTPServer = function() {
  var eventEmitter = new events.EventEmitter();
  var self = this;

  this.once = eventEmitter.once.bind(eventEmitter);

  this.listen = function() {
    eventEmitter.emit('listening', self, 0);
  };

  this.close = function() {
  };
};
</code>```

And a MockResponse

```<code>var MockResponse = function(callback) {
  this.headers = {};
  this.statusCode = -1;
  this.body = undefined;

  this.setHeader = function(key, value) {
    this.headers[key] = value;
  }.bind(this);

  this.writeHead = function(statusCode, headers) {
    this.statusCode = statusCode;
    Object.keys(headers).forEach(function(key) {
      this.headers[key] = headers[key];
    }.bind(this));
  }.bind(this);

  this.write = function(data, encoding) {
    this.body = data.toString(encoding);
  }.bind(this);

  this.end = function() {
    var fn = callback;
    callback = undefined;
    fn(this);
  }.bind(this);
};
</code>```

Note this is not a complete response mock. I just tried it in my tests and only added the functions that were called.

To actually test I made a test server

```<code>var Promise = require('promise');

var TestServer = function(callback) {
  var server = new MyServer({
    server: new MockHTTPServer,
  }, callback);

  this.close = function() {
    server.close();
  };

  var request = function(req, callback) {
    var res = new MockResponse(callback);
    server.handleRequest(req, res);
  };

  var getP = function(url) {
    return new Promise(function(resolve, reject) {
      request({ url: url, method: 'GET'}, resolve);
    });
  };

  this.getP = getP;
  this.request = request;
};
</code>```

Which, using mocha, I can test like this

```<code>describe('test server', function() {

  var server;

  before(function(done) {
    server = new TestServer(done);
  });

  describe('test', function() {
    it('serves bar', function(done) {
      server.getP("http://localhost/bar.html").then(function(res) {
        res.body.should.containEql("bar");
      }).then(done, done);
    });

    it('serves foo', function(done) {
      server.getP("http://localhost/foo.html").then(function(res) {
        res.body.should.containEql("foo");
      }).then(done, done);
    });
  });

  after(function(done) {
    server.close();
    done();
  });

});
</code>```

You can see I just make up request objects on the fly

Body:
I recently did this. Forgot where I read about it but it's pretty easy.

Here's the basics of my code.

var express = require('express');
var http    = require('http');

var MyServer = function(options) {
  var app = express();
  app.get(/^\/foo.html/, sendFoo);
  app.get(/^\/bar.html/, sendBar);
  var server = options.server || http.createServer(app);
  server.listen(options.port);

  function sendFoo(req, res) {
     res.writeHead(200);
     res.write("foo");
     res.end();
  }

  function sendBar(req, res) {
     res.writeHead(200);
     res.write("bar");
     res.end();
  }

  this.close = function() {
     server.close();
  }
};

As you can see my server either users http.createServer or the one I pass in. Maybe I should always pass it in? But in any case. I made a mock server

var events = require('events');

var MockHTTPServer = function() {
  var eventEmitter = new events.EventEmitter();
  var self = this;

  this.once = eventEmitter.once.bind(eventEmitter);

  this.listen = function() {
    eventEmitter.emit('listening', self, 0);
  };

  this.close = function() {
  };
};

And a MockResponse

var MockResponse = function(callback) {
  this.headers = {};
  this.statusCode = -1;
  this.body = undefined;

  this.setHeader = function(key, value) {
    this.headers[key] = value;
  }.bind(this);

  this.writeHead = function(statusCode, headers) {
    this.statusCode = statusCode;
    Object.keys(headers).forEach(function(key) {
      this.headers[key] = headers[key];
    }.bind(this));
  }.bind(this);

  this.write = function(data, encoding) {
    this.body = data.toString(encoding);
  }.bind(this);

  this.end = function() {
    var fn = callback;
    callback = undefined;
    fn(this);
  }.bind(this);
};

Note this is not a complete response mock. I just tried it in my tests and only added the functions that were called.

To actually test I made a test server

var Promise = require('promise');

var TestServer = function(callback) {
  var server = new MyServer({
    server: new MockHTTPServer,
  }, callback);

  this.close = function() {
    server.close();
  };

  var request = function(req, callback) {
    var res = new MockResponse(callback);
    server.handleRequest(req, res);
  };

  var getP = function(url) {
    return new Promise(function(resolve, reject) {
      request({ url: url, method: 'GET'}, resolve);
    });
  };

  this.getP = getP;
  this.request = request;
};

Which, using mocha, I can test like this

describe('test server', function() {

  var server;

  before(function(done) {
    server = new TestServer(done);
  });

  describe('test', function() {
    it('serves bar', function(done) {
      server.getP("http://localhost/bar.html").then(function(res) {
        res.body.should.containEql("bar");
      }).then(done, done);
    });

    it('serves foo', function(done) {
      server.getP("http://localhost/foo.html").then(function(res) {
        res.body.should.containEql("foo");
      }).then(done, done);
    });
  });

  after(function(done) {
    server.close();
    done();
  });

});

You can see I just make up request objects on the fly