答:
An alternative to friend (well, in a sense) that I use frequently is a pattern that I've come to know as access_by. It's pretty simple:

```<code>class A {
  void priv_method(){};
 public:
  template <class T> struct access_by;
  template <class T> friend struct access_by;
}
</code>```

Now, suppose class B is involved in testing A. You can write this:

```<code>template <> struct access_by<B> {
  call_priv_method(A & a) {a.priv_method();}
}
</code>```

You can then use this specialization of access_by to call private methods of A. Basically, what this does is put the onus of declaring friendship into the header file of the class that wants to call A's private methods. It also lets you add friends to A without changing A's source. Idiomatically, it also indicates to whoever reads the source of A that A does not indicate B a true friend in the sense of extending its interface. Rather, the interface of A is complete as given and B needs special access into A (testing being a good example, I've also used this pattern when implementing boost python bindings, sometimes a function that needs to be private in C++ is handy to expose into the python layer for the implementation).

Title: Unit test private method in c++ using a friend class

Body:
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.

Body:
An alternative to friend (well, in a sense) that I use frequently is a pattern that I've come to know as access_by. It's pretty simple:

class A {
  void priv_method(){};
 public:
  template <class T> struct access_by;
  template <class T> friend struct access_by;
}

Now, suppose class B is involved in testing A. You can write this:

template <> struct access_by<B> {
  call_priv_method(A & a) {a.priv_method();}
}

You can then use this specialization of access_by to call private methods of A. Basically, what this does is put the onus of declaring friendship into the header file of the class that wants to call A's private methods. It also lets you add friends to A without changing A's source. Idiomatically, it also indicates to whoever reads the source of A that A does not indicate B a true friend in the sense of extending its interface. Rather, the interface of A is complete as given and B needs special access into A (testing being a good example, I've also used this pattern when implementing boost python bindings, sometimes a function that needs to be private in C++ is handy to expose into the python layer for the implementation).


问:
Databases: Where should the application logic run?
http://highscalability.com/blog/2010/11/9/facebook-uses-non-stored-procedures-to-update-social-graphs.html talks about how Facebook moved logic out of the database into the application in order to improve ease of development (scaling better across employees instead of across databases).

Are there any studies/articles/benchmarks that evaluate the business and technical tradeoffs of running as much of the logic in the database versus in the application?

Specifically, I'm wondering what scales better (both in terms of the database performance and ease of development as the business grows):

Scenario 1 (Logic in database)

Running as much of the logic on the database end.

Using database-specific SQL extensions/features.

Using stored procedures.

Few queries over short transactions, low network overhead.

Scenario 2 (Logic in application)

Running as much of the logic on the application end.

Limiting oneself to features which are common across all major databases.

Not using stored procedures.

Many queries over long transactions, high network overhead.

What kind of people-scaling overhead can one expect in Scenario 1?

What kind of database-scaling overhead can one expect in Scenario 2?

答:
Scalability isn't the only issue in making this choice (and I do know of successful databases with trillions of records so databases are more scalable than you think). Nor is it probably the most important.

First you need to look at the meaning of the data. Something like Facebook is tied intrinsically to its application and thus putting the logic there isn't as risky as a business application which has to get its data from imports, database jobs, user data entry from several different applications including some that perhaps the business has no control over. So the risk to data integrity is the first and most important thing to consider when making this choice.

Also how the data will be used and in what environment is critical. How is the information audited? Are there regulatory requirements?  How is the reporting done? Do I need to be able to reuse the logic in a different reporting system as well as in the user application? If so the logic needs to rest outside of the application. Do I need to do exports of the data and how is that affected by the logic being in the application. Does that mean the people writing the reporting and export code will not have the ability to see what the logic is because they don't have access to application code? That can be a major problem.

Another consideration is the scalability which includes the performance. How much scalability do you need? Very few things need the scalability of a Facebook. How much performance do you need? Designing for scalability when you will never need it leads to less than optimum results.  Will the methods you use to put logic in the application have a negative impact on database performance (many ORMs for instance write terrible database code).

Then there is the argument about less time for development which is ridiculous. If you know what you are doing, putting the logic in the database does not take more time than putting it in the application. It is just that most application developers aren't SQL specialists. However, is saving the devs time to get better at SQL really a plus? No it is not because that choice almost always comes at a cost of performance on the database and at the cost of data integrity.

What I am trying to say is there is no one size fits all. There are some applications where putting the logic in the application makes sense and some where it does not, but thinking there are only one or two critical factors to consider when making the choice is generally a mistake.

OwnerDisplayName: Gili

ContentLicense: CC BY-SA 3.0

OwnerDisplayName: HLGEM


答:
Answering my own question (aggregating everything I've read so far):

Separation of Concerns

Implement the business logic in the application in order to benefit from the richer development, testing and debugging environment offered outside the database.

Data integrity and cross-cutting concerns (e.g. auditing, reporting) should reside in the database.

Databases need an abstraction layer to avoid code duplication and enable you to quickly update SQL statements when the schema is changed. The abstraction layer can reside in the application or database.

Performance

Prepared statements are as fast as stored procedures.

Network overhead is negligible, unless you need to transfer large amounts of data from the server to the client and back again.

Security

Stored procedures aren't any safer than dynamic SQL for injection attacks

Stored procedures allows you to grant permissions in terms of API methods instead of the table/view level. Meaning, instead of "Customers should only be allowed to view table Account and update table Balance" you have "Customers should only be allowed to invoke TransferFunds()". You should be able to emulate the same permission scheme using views.

Common use-cases

If the database needs to support multiple applications, the abstraction layer should probably reside in the database in the form of stored procedures. This is the most frequently cited use-case by DBAs for implementing logic in the database.

If the application needs to support multiple databases, the abstraction layer should probably reside in the application layer.

Miscellaneous

Your developers should be well versed in SQL. Learning the language is a lot easier than you think. Don't fool yourself: developers that seek to avoid SQL will produce scalability problems.

Summary: Contrary to popular belief, you shouldn't use stored procedures for performance or security reasons. You should use them to support multiple applications, to enforce data integrity and to implement cross-cutting concerns that cannot be easily implemented in the application layer.

Feel free to push all remaining logic into the application layer.

Title: Databases: Where should the application logic run?

Body:
http://highscalability.com/blog/2010/11/9/facebook-uses-non-stored-procedures-to-update-social-graphs.html talks about how Facebook moved logic out of the database into the application in order to improve ease of development (scaling better across employees instead of across databases).

Are there any studies/articles/benchmarks that evaluate the business and technical tradeoffs of running as much of the logic in the database versus in the application?

Specifically, I'm wondering what scales better (both in terms of the database performance and ease of development as the business grows):

Scenario 1 (Logic in database)

Running as much of the logic on the database end.

Using database-specific SQL extensions/features.

Using stored procedures.

Few queries over short transactions, low network overhead.

Scenario 2 (Logic in application)

Running as much of the logic on the application end.

Limiting oneself to features which are common across all major databases.

Not using stored procedures.

Many queries over long transactions, high network overhead.

What kind of people-scaling overhead can one expect in Scenario 1?

What kind of database-scaling overhead can one expect in Scenario 2?

ContentLicense: CC BY-SA 4.0


问:
Method waits for user action
I have a structural problem for an application I'm working on.  In the interest of full disclosure, it is for a university assignment so I'm not looking for you to code me an answer, just help me think through the best approach.

I'm building a game using an OO approach.  I have an abstract class called Player from which several types derive.  These represent the computer and human players.  So I have a derived HumanPlayer class which must provide an implementation for a method called ChooseCard.  The way the user selects a card is by clicking on a card in a GUI.  So the card will be identified by the user through an event handler.

The relevant part of my code is listed below.  At the moment the Game class loops through each player and calls the PlayCard method on each Player.  I'm just not sure how to program the ChooseCard method in the HumanPlayer class so that it can wait for the user to select a card to play but have the UI remain responsive.   Ideally I want to be able to treat each of the derived player types the same (ie as the base class Player).

This question is asking basically the same thing I am but I don't really like the answers.

The answer to this question is interesting, using the TaskCompletionSource class.

I'm not fixed on this structure if there is a superior solution although I need to keep the class structure.

Edits:
Added a class diagram for the models of my application as well as a screenshot of what the gameboard looks like (currently).

Here is my current thinking:
The user will click on the card they want to play.  The click event will propagate to the bound CardViewModel (At this point the action could be handled at the Model or ViewModel layer).  Now the CardViewModel (or Card) doesn't know who is interested in knowing that the user selected it.  The interested party will be the PlayerViewModel/HumanPlayer to whom the Card belongs, but they will only be interested when they are expecting a response from the user.  I.e. when HumanPlayer.PlayCard() is called.

So I'm thinking that the CardViewModel/Card should raise an event to which the HumanPlayer object can subscribe to when it is interested in the user making a card selection.

I can make HumanPlayer.ChooseCard() subscribe to the CardSelected events of each of the cards.  I'm just not sure how to make the method wait without blocking until one of those events fires.

```<code>abstract public class Player
{
    public IReadOnlyList<Card> Cards { get { return cards.AsReadOnly(); } }

    public Card PlayCard()
    {
        var cardToPlay = ChooseCard();
        // ...
    }

    protected abstract Card ChooseCard();
}

public class HumanPlayer : Player
{
    protected override Card ChooseCard()
    {
        // TODO: request a card from the user.
        throw new NotImplementedException();
    }
}

public class Game
{
    private List<Player> livingPlayers = new List<Player>();

    public void PlayRound()
    {
        var cardsPlayedByPlayers = GetCardsPlayed();
        // ...
    }

    private Dictionary<Player, Card> GetCardsPlayed()
    {
        var cardsPlayedByPlayers = new Dictionary<Player, Card>();

        foreach (var player in livingPlayers.Where(p => !p.IsDead))
        {
            // Player.PlayCard() called here getting chosen card from the player.
            cardsPlayedByPlayers.Add(player, player.PlayCard());
        }

        return cardsPlayedByPlayers;
    }
}
</code>```

Update:

I've put the final code up on GitHub here since the assignment is over.  You can now see the full code clearly and if you would like to critique it, I'd be keen to hear your thoughts.

答:
thanks for all your input.  It seems the consensus is to use threads to manage things.  I currently have a solution that doesn't use threads at the moment and I'd like a critique.  I realised that if you were playing the game in real life you need to wait until ALL players are ready to play.  Hence I need an IsReady property for each player.  Since I'm implementing INPC on basically everything the Game object can be aware of when each player's ready status changes.  Here is my code as it stands now:</p>

```<code>abstract public class Player
{
    public IReadOnlyList<Card> Cards { get { return cards.AsReadOnly(); } }

    public Card PlayCard()
    {
        if (!IsReady)
        {
            throw new InvalidOperationException("Cannot play card when player is not ready.");
        }

        var cardToPlay = ChooseCard();
        // ...
    }

    public abstract bool IsReady { get; }
    protected abstract Card ChooseCard();
}

public class HumanPlayer : Player
{
    protected override Card ChooseCard()
    {
        // return the selected card.
    }

    public override bool IsReady
    {
        get
        {
            // return true if a card is selected.
        }
    }
}

public class Game
{
    private List<Player> livingPlayers = new List<Player>();

    public bool CanPlayRound {
        get
        {
            // check that all Player.IsReady returns true.
        }
    }

    public void PlayRound()
    {
        var cardsPlayedByPlayers = GetCardsPlayed();
        // ...
    }

    private Dictionary<Player, Card> GetCardsPlayed()
    {
        var cardsPlayedByPlayers = new Dictionary<Player, Card>();

        foreach (var player in livingPlayers.Where(p => !p.IsDead))
        {
            // Player.PlayCard() called here getting chosen card from the player.
            cardsPlayedByPlayers.Add(player, player.PlayCard());
        }

        return cardsPlayedByPlayers;
    }
}
</code>```

Title: Method waits for user action

Body:
thanks for all your input.  It seems the consensus is to use threads to manage things.  I currently have a solution that doesn't use threads at the moment and I'd like a critique.  I realised that if you were playing the game in real life you need to wait until ALL players are ready to play.  Hence I need an IsReady property for each player.  Since I'm implementing INPC on basically everything the Game object can be aware of when each player's ready status changes.  Here is my code as it stands now:

abstract public class Player
{
    public IReadOnlyList<Card> Cards { get { return cards.AsReadOnly(); } }

    public Card PlayCard()
    {
        if (!IsReady)
        {
            throw new InvalidOperationException("Cannot play card when player is not ready.");
        }

        var cardToPlay = ChooseCard();
        // ...
    }

    public abstract bool IsReady { get; }
    protected abstract Card ChooseCard();
}

public class HumanPlayer : Player
{
    protected override Card ChooseCard()
    {
        // return the selected card.
    }

    public override bool IsReady
    {
        get
        {
            // return true if a card is selected.
        }
    }
}

public class Game
{
    private List<Player> livingPlayers = new List<Player>();

    public bool CanPlayRound {
        get
        {
            // check that all Player.IsReady returns true.
        }
    }

    public void PlayRound()
    {
        var cardsPlayedByPlayers = GetCardsPlayed();
        // ...
    }

    private Dictionary<Player, Card> GetCardsPlayed()
    {
        var cardsPlayedByPlayers = new Dictionary<Player, Card>();

        foreach (var player in livingPlayers.Where(p => !p.IsDead))
        {
            // Player.PlayCard() called here getting chosen card from the player.
            cardsPlayedByPlayers.Add(player, player.PlayCard());
        }

        return cardsPlayedByPlayers;
    }
}


问:
Should I have a queue with SMS requests to picked up by a separate process or connect directly to the API?
I created an email queue where I put the requests for emails to be sent. If the SMTP server is unavailable, the requests are not lost.

When the SMTP server gets back online, the background service will pick up the requests to send the emails and process accordingly.

Question: I now have a requirement to deliver text messages with high certainty, but also to give feedback about a wrong phone number if that is possible. Should I have something like my mail queue to send text messages to my user phones or not?

I think it makes sense if we're talking about marketing messages, but what about text messages sent to users to verify their phone numbers?

What if their phone number is typed incorrectly? The phone API will tell me right away but if I put the request in the queue, I won't be able to let them know about it.

Rephrasing of the question: Should I care about the immediate feedback and loose the ability to deliver all SMS messages in case of temporary failure?

答:
Depending on the API for sending text messages, there are two possibilities for meeting those business requirements.

If there are separate API calls to verify a phone number and to send a text message, you can use a queue for the actual sending and verify the validity of the phone number just before you put the text message in the queue.

If there is only an API call to send a text message, which informs you about success/failure after the fact and where the failure codes are descriptive enough, you could send the message initially from the context of the user request. If that fails with a temporary error, add the message to a queue for later retries.


问:
How to minimize networking cost of distributed game database?
We've been working on a networked online game project which will run in near future and
looking for a satisfying solution for our distributed game database. We didn't take networking costs
into account so far.

We have following constraints:

1) We planned to use MySql but we can review alternatives if offered solution makes sense.

2) We planned to host multiple game servers on different geographical regions such as USA, Europe and Asia.

3) Every gamer usually connect to the nearest game server and distributed database node in order to reduce networking costs and lags.

We've been thinking to develop a logic in one of our server side layers that will check the user location he wants to connect from. Then, replicate user specific data from one database node to another if the check operation results that the gamer attempt to connect from a different region than he did before.

We wonder that is the correct way to do that?

Of course we have to think disaster cases.
For that purpose, what can we do if one of the distributed database node fails?

We don't think to replicate all data between database nodes because it causes high networking costs.

Thanks

答:
I would avoid any ad-hoc, on-demand, database replication. Ideally you want a single consistent, logical user database across all of your nodes, for disaster purposes.

@Wardy's recommendation of a service bus is a good one.

I won't discuss different cluster architectures, but will address the issue of network bandwidth and transaction volume.

With high transaction volume systems, you do often run into an issue where there is so much DML (or transaction volumne) that you can't do full transaction based replication; one way to reduce overall replication bandwidth is not to replicate transaction logs, but to do snapshot based replication in a delayed, larger granularity frequency than the average record update frequency. I call this coalescing or collapsing the stream but I don't know if those terms accurately describes reducing the volume in this way.

For example, if your average active player record updates every 15 seconds to its local database node, you can setup a 10 minute replication cycle, and coalesce 40 average updates per record into a single replication pull. Only records that are modified since last pull will be transmitted, and you'll replicate a single record even though there may have been 40 updates since the last synchronization. This reduces your potential network volume by an obvious ratio.

In this model, things like row-level trigger based auditing doesn't work because you don't get all transactions, just the latest, so you must work that out in your design.

As to implementations, a good example is Sybase iAnywhere Mobilink. But I've also seen it implemented in-house on top of various database flavors.


问:
Shipping unmodified open source applications with closed source apps
I am creating a closed source application whose task is to launch other open source applications (similar to start menu of windows).

So i have included various opensource applications under licences like :

GNU-GPL

LGPL

MIT license

Apple Public Source License Version 2.0

Apache creative commons

CeCILL

I have not modified the opensource applications and i am ready to publish source of the opensource applications,
but i do not want to disclose the source code of my launcher application.

I intend to offer the whole stuff free with a commercial hardware.  i.e. i am charging only for hardware and not for software. Can i do so ?

Further in future i intend to sell the whole software bunch by including only the cost incurred for developing the closed source module, can i do so ?

I have gone through the gpl documentation but i am not able to relate the scenario with the information in docs.

Please explain the answer w.r.t. the individual licence, so that i can exclude the applications incase their license does not permit me to do so!

答:
The Open Source licenses in general do not prohibit you to charge a fee for the distribution of the software. You are even allowed to charge a fee without providing any added value, though I am not sure how many people would make use of that.

The catch is that under the GPL you must give your users exactly the same rights that you have gotten yourself, so you can't forbid your users to resell the (GPL) software for a lower amount. With other licenses, the freedoms you need to give your users vary.

With regards to your launcher application, this is covered under the GPL FAQ under I'd like to incorporate GPL-covered software in my proprietary system. Can I do this?

You cannot incorporate GPL-covered software in a proprietary system. The goal of the GPL is to grant everyone the freedom to copy, redistribute, understand, and modify a program. If you could incorporate GPL-covered software into a non-free system, it would have the effect of making the GPL-covered software non-free too.

A system incorporating a GPL-covered program is an extended version of that program. The GPL says that any extended version of the program must be released under the GPL if it is released at all. This is for two reasons: to make sure that users who get the software get the freedom they should have, and to encourage people to give back improvements that they make.

However, in many cases you can distribute the GPL-covered software alongside your proprietary system. To do this validly, you must make sure that the free and non-free programs communicate at arms length, that they are not combined in a way that would make them effectively a single program.

The difference between this and “incorporating” the GPL-covered software is partly a matter of substance and partly form. The substantive part is this: if the two programs are combined so that they become effectively two parts of one program, then you can't treat them as two separate programs. So the GPL has to cover the whole thing.

If the two programs remain well separated, like the compiler and the kernel, or like an editor and a shell, then you can treat them as two separate programs—but you have to do it properly. The issue is simply one of form: how you describe what you are doing. Why do we care about this? Because we want to make sure the users clearly understand the free status of the GPL-covered software in the collection.

If people were to distribute GPL-covered software calling it “part of” a system that users know is partly proprietary, users might be uncertain of their rights regarding the GPL-covered software. But if they know that what they have received is a free program plus another program, side by side, their rights will be clear.

So, in short, if your launcher just spawns the GPL code in a different process and you don't advertise your launcher application as containing or incorporating the GPL code, there are no problems. In that case, the various programs are considered to be independent works for copyright law.

The GPL license is the most strict one in this regard. The other licenses mentioned are easier to incorporate in a proprietary application.


问:
Context Switching behavior?
I need to ask a question that have been bugging me for some time now:

If I have a single core and one OS thread, this thread will get 100% of the CPU time and all is good.

If I have a single core and two or more OS threads, they will share the CPU time using time slices.

So, is the time slices always the same amout of time no matter how many threads?

What I'm trying to get at, is the amout of work the CPU can do the same when I have two threads or 10000 threads?
I'm well aware that each individual thread will progress slower since they share a resource, but the actual amount of work the CPU can do, will it be the same?

e.g.

```<code>[T1 ] [T2 ] [T1 ] [T2 ] [T1 ] [T2 ] [T1 ] [T2 ] [T1 ] [T2 ]

[T1 ] [T2 ] [T3 ] [T4 ] [T5 ] [T6 ] [T1 ] [T2 ] [T3 ] [T4 ]

----time-------------------------------------------------->
img. 1
</code>```

In the illustration above, there are 2 vs 6 threads, but the total amount of work would be the same.
Is this true?
Or are there something else that affects this when there are more threads, that cause each slice to be smaller or the context switch between the threads to be longer?

e.g.

```<code>[T1 ] [T2 ] [T1 ] [T2 ] [T1 ] [T2 ] [T1 ] [T2 ] [T1 ] [T2 ]

[T1 ]   [T2 ]    [T3 ]    [T4 ]    [T5 ]    [T6 ]    [T1 ]

----time-------------------------------------------------->
img. 2
</code>```

I'm not asking if it is a good idea to use 1000 threads...

[Edit]

Trying to clarify what I'm trying to understand:

Given x amount of time, e.g. 1 minute.
And given that the code does not use locks or any other thread interrupting code.

If I have two threads, there will be y% time spent on context switching.
If I have 1000 threads, will y be a greater number?, or will it be the same as in the previous case?

答:
Context switching itself imposes an overhead on the system, because the OS has to perform book-keeping on which threads exist, which are running, which are ready, which have already received their fair share, etc. In a well-designed OS this overhead is not great, and usually it is not dependent on the number of threads (up to some hard maximum), but it is definitely there.

Everything else is system-dependent. For instance, a scheduler may decrease the nominal length of each slice depending on how many many candidates there are, or it may not. As always, a reasonable answer to decide what to do in your case can only come from running careful performance tests on your system.

Title: Context Switching behavior?


问:
How can a new programmer impress the software engineer (boss)?
I'm working at my first programming job. My boss is a very smart software engineer, and I feel
like I have very little to offer compared to him. Problem is, he is always busy, and needs someone to help him out. I feel like I'm not good enough, but I still want to succeed. I want to be a great programmer.

What can I do to impress him?

Thank you.

答:
I liked the story posted in the answer, but it's more entertaining than a reliable answer.

It's normal that everyone are just like you: trying to be better at what we do, that's human. But the horrible truth is that there are so little chances you will be the best at it.

Concerning myself, I always feared humility concerns, because I just hate those little childish fights about who's right and who's not, and here is why.

As long as you are not one of the best, you are better trying to work to get more experience comparing what you know and do to what best programmers know and do.

You could say I compare myself to the best programmers, but that's just half right:
 - I'm better comparing myself to the best, knowing that I'm just ridiculous compared to them, so that makes the principle of comparing pretty stupid and useless
 - I don't consider their fame but rather what they achieved to get it, because in reality, most geniuses myths fade away when you know true fact like how business works. It doesn't change the fact they achieved great work, but remember that experience is difficult to evaluate if you think about the working conditions.
 - In the end, this process avoids the competition process which is really disturbing for me and help me focusing on what is important: learning by practice, but also learning with the help of a good curiosity engine.

You can admire somebody all you want, thinking he is so better than all other employees or other programmers you'll meet, but you have to remember that the world is vast and that the guy you admire is in fact quite average compared to other better experienced people there are out there, so maybe you'll feel better once you've impressed him, but you'll feel the same against other people with better experience than him, so it will be all for nothing.

Quit this petty game and try to find more interesting subjects you might have heard about, because this engineer you are talking about is certainly busy working for something less great that you're thinking.

ContentLicense: CC BY-SA 2.5


问:
Is there a programming pattern, design pattern, or naming convention for moving data between related schemas?
I'm working on a web application that is publicly accessible. (Really) Long story short, we have two sets of tables in the database with relatively the same names and relatively the same data. The first set of tables are used by our web site, which I will call Set A. The second set of tables are used by an Oracle Forms application, which I will call Set B.

The reasons for duplicated tables:

The data in Set B is the Holy Grail of information. Allowing the public to change this has legal repercussions.

The public can partially fill out all of the forms in our web application, and in one final button click, finalize their information. They then have to pay a fee before downstream processing begins. Users may start, stop and restart this process any number of times.

My current task is to copy data from Set B into Set A in one operation, so that form fields are pre-populated. If we don't do this, every page in our web application has to pull data from Set A first, and if it is missing fall back to Set B (which sometimes involves data conversions).

I have this built and functioning correctly, but I'm not real keen on the names I've used: *Converter

I'm really trying to avoid a "service" object. Having read I Shall Call It.. SomethingManager at Coding Horror, naming anything with the word "service" makes me want to write a sibling blog post titled "I Shall Call It.. SomethingService."

My lead developer didn't like the "Converter" naming convention. I've searched for programming and design patterns for moving data between similar tables and I haven't found anything.

I've thought about "Migration" but this implies changing the database schema iteratively over a period of time (ala Active Record Database Migrations).

Whatever the name or pattern is, I'd like it to clearly communicate:

Information is being pulled from one set of tables

Mapped to a common object model

And inserted into another schema

I also feel like I'm not the only person who has encountered this problem.

Is there a programming pattern, design pattern, or naming convention for moving data between related schemas?

Update: One of the biggest problems I have is that the web site tables (Set A) don't have primary or foreign keys! We have a bunch of meta data hidden in constants, whose values get mashed together sometimes into a single column.

@kevincline's answer to write a stored procedure is actually why I choose to handle this specific situation in code. We have a stored procedure to move data from Set A into Set B, and Oh. My. Goodness. The hoops the poor PL/SQL developer had to jump through to untangle our mess was nothing short of a miracle.

In this case, the code was much easier to write and maintain outside of the database because our web application ... well. Think of every database design best practice imaginable and then do exactly the opposite.

答:
If you want to give a name to "moving data between related schemas": In Datawarehousing this is called ETL:

From Extract_transform_load@wikipedia

In computing, extract, transform, and load (ETL) refers to a process in database usage and especially in data warehousing that:

Extracts data from outside sources

Transforms it to fit operational needs, which can include quality levels

Loads it into the end target (database, more specifically, operational data store, data mart, or data warehouse)


问:
Create a collection with "average points" of N items from a pool with items of various points
Let's say I have a question pool to generate exams out of it. Each question contains a difficulty from 1 (hard) to 99 (easy). The questions are available in a hash / array (adapt to your favorite languages naming, I'm going with hash as it is a ruby implementation) in the following format:

```<code>questions = {
  :55 => [<#Question 1>, <#Question 18>],
  :8  => [<#Question 70>],
  :43 => [<#Question 105>]
}
</code>```

The hash keys denote the difficulty, whereas the value is a list of questions with said difficulty.

The aim is to be able to create an "exam" with N questions from the pool. Each exam generated should contain questions from "all" difficulty levels (not from each number, but having questions with lower, medium, and higher ratings). Also, each exam generated should have +/- the same difficulty X (e.g. 75).

How do you go about selecting questions from various difficulties so you have a) a result of N size and b) matching the average difficulty of X?

答:
You're imposing three constraints here:

a specific total number of questions

several pools of questions of similar difficulty, where the exam should contain elements of each pool

a predefined average difficulty

As ratchet freak said, this is a knapsack problem and therefore hard to solve, although if the list of questions is reasonably small a complete search can still work.

However, if you're willing to have the average difficulty vary a bit more, you could simply choose a predefined number of questions randomly from each pool, which requires only linear effort and will almost always yield a near-average total difficulty. Possibly, even a try-until-satisfactory approach is cheaper than the original problem.


问:
How to measure his own skill in a programming language?

Possible Duplicate:

  How Can I Know Whether I Am a Good Programmer?

As many programmers I have worked in several languages. While of course there are some that I am more at ease than other, I do not have a real way to precisely measure my skill in a specific language.

So I thought of a system which allows me to help me with that. I am looking for 5 common criteria in programming languages, to which I will have a value from 1 (junior) to 4 ( Senior) to represent my skill.

I however have no real idea of the criteria I should choose for that.

Does anybody have suggestion ?

Thanks.

答:
The ability to read and understand any (reasonably well written) code in that language is the most important criterion to measure mastership.

The ability to write code to solve any problem doesn't say much; just consider a C programmer who claims the ability to write C++. Since C is more-or-less a subset of C++, the C programmer can solve any problem by writing an appropriate C program and using the C++-compiler to compile it, so technically it's C++. Likewise, many programer learn just enough of a new language so they can apply the old idioms. You can write FORTRAN in any language.

By the same argument, LOC/hour says nothing. A programmer who writes Perl programs that look like C programs probably generates more LOC/hour than a Perl programmer who writes idiomatic Perl code.


答:
Even with a single threaded app running on a single core machine you're going to get context switches as the OS will want to run multiple applications, similar with 2 apps running on a dual core machine, you'll still get switches. Its just that having many threads running mean you get more context switches.

On Windows the scheduled time slices (or quanta) is a fixed 10ms (IIRC). A thread can give up part of its slice by sleeping, which is why you occasionally see sleep(0) calls in code. Its a way to say "I'm only going to do nothing for a bit, someone else can have a go before they're scheduled".

Another thing that can cause a context switch is locking. If you lock on a waitable object, you're giving up the rest of your slice - no point waiting for the object to be signaled by a different thread if that thread hasn't had a chance to run after all!

This is the main cause of excessive switching - too much locking.

When a context switch happens, the CPU has to store away the state of the registers and load the registers that were stored for the other thread, possibly it will have to flush a cache to get different memory in that the other thread wants to work with. This takes time, and although its "CPU time" its wasted housekeeping, ie its not spent making your program do what its supposed to do.

For example, I once worked on an enterprise program that spent more time switching than doing useful work. Once we solved the locking bug, performance improved dramatically - suddenly the CPU coudl perform useful work rather than simply spin between threads.

Title: Context Switching behavior?

Body:
I need to ask a question that have been bugging me for some time now:

If I have a single core and one OS thread, this thread will get 100% of the CPU time and all is good.

If I have a single core and two or more OS threads, they will share the CPU time using time slices.

So, is the time slices always the same amout of time no matter how many threads?

What I'm trying to get at, is the amout of work the CPU can do the same when I have two threads or 10000 threads?
I'm well aware that each individual thread will progress slower since they share a resource, but the actual amount of work the CPU can do, will it be the same?

e.g.

```<code>[T1 ] [T2 ] [T1 ] [T2 ] [T1 ] [T2 ] [T1 ] [T2 ] [T1 ] [T2 ]

[T1 ] [T2 ] [T3 ] [T4 ] [T5 ] [T6 ] [T1 ] [T2 ] [T3 ] [T4 ]

----time-------------------------------------------------->
img. 1
</code>```

In the illustration above, there are 2 vs 6 threads, but the total amount of work would be the same.
Is this true?
Or are there something else that affects this when there are more threads, that cause each slice to be smaller or the context switch between the threads to be longer?

e.g.

```<code>[T1 ] [T2 ] [T1 ] [T2 ] [T1 ] [T2 ] [T1 ] [T2 ] [T1 ] [T2 ]

[T1 ]   [T2 ]    [T3 ]    [T4 ]    [T5 ]    [T6 ]    [T1 ]

----time-------------------------------------------------->
img. 2
</code>```

I'm not asking if it is a good idea to use 1000 threads...

[Edit]

Trying to clarify what I'm trying to understand:

Given x amount of time, e.g. 1 minute.
And given that the code does not use locks or any other thread interrupting code.

If I have two threads, there will be y% time spent on context switching.
If I have 1000 threads, will y be a greater number?, or will it be the same as in the previous case?


问:
Is creating subclasses for specific instances a bad practice?
Consider the following design

```<code>public class Person
{
    public virtual string Name { get; }

    public Person (string name)
    {
        this.Name = name;
    }
}

public class Karl : Person
{
    public override string Name
    {
        get
        {
            return "Karl";
        }
    }
}

public class John : Person
{
    public override string Name
    {
        get
        {
            return "John";
        }
    }
}
</code>```

Do you think there is something wrong here? To me Karl and John classes should be just instances instead of classes as they are exactly the same as :

```<code>Person karl = new Person("Karl");
Person john = new Person("John");
</code>```

Why would I create new classes when instances are enough? The classes does not add anything to the instance.

答:
A lot of people answered already. Thought I'd give my own personal perspective.

Once upon a time I worked on an app (and still do) that creates music.

The app had an abstract Scale class with several subclasses: CMajor, DMinor, etc. Scale looked something like so:

```<code>public abstract class Scale {
    protected Note[] notes;
    public Scale() {
        loadNotes();
    }
    // .. some other stuff ommited
    protected abstract void loadNotes(); /* subclasses put notes in the array
                                          in this method. */
}
</code>```

The music generators worked with a specific Scale instance to generate music. The user would select a scale from a list, to generate music from.

One day, a cool idea came to my mind: why not allow the user to create his/her own scales? The user would select notes from a list, press a button, and a new scale would be added to the list available scales.

But I wasn't able to do this. That was because all the scales are already set at compile time - since they are expressed as classes. Then it hit me:

It's often intuitive to think in terms of 'superclasses and subclasses'. Almost everything can be expressed through this system: superclass Person and subclasses John and Mary; superclass Car and subclasses Volvo and Mazda; superclass Missile and subclasses SpeedRocked, LandMine and TrippleExplodingThingy.

It's very natural to think in this way, especially for the person relatively new to OO.

But we should always remember that classes are templates, and objects are content poured into these templates. You can pour whatever content you want into the template, creating countless possibilities.

It's not the job of the subclass to fill the template. It's the job of the object. The job of the subclass is to add actual functionality, or expand the template.

And that's why I should have created a concrete Scale class, with a Note[] field, and let objects fill in this template; possibly through the constructor or something. And eventually, so I did.

Every time you design a template in a class (e.g., an empty Note[] member that needs to be filled, or a String name field that needs to be assigned a value), remember that it's the job of the objects of this class to fill in the template (or possibly those creating these objects). Subclasses are meant to add functionality, not to fill in templates.

You might be tempted to create a "superclass Person, subclasses John and Mary" kind of system, like you did, because you like the formality this gets you.

This way, you can just say Person p = new Mary(), instead of Person p = new Person("Mary", 57, Sex.FEMALE). It makes things more organized, and more structured. But as we said, creating a new class for every combination of data isn't good approach, since it bloats the code for nothing and limits you in terms of runtime abilities.

So here's a solution: use a basic factory, might even be a static one. Like so:

```<code>public final class PersonFactory {
    private PersonFactory() { }

    public static Person createJohn(){
        return new Person("John", 40, Sex.MALE);
    }

    public static Person createMary(){
        return new Person("Mary", 57, Sex.FEMALE);
    }

    // ...
}
</code>```

This way, you can easily use the 'presets' the 'come with the program', like so: Person mary = PersonFactory.createMary(), but you also reserve the right to design new persons dynamically, for example in the case that you want to allow the user to do so. E.g.:

```<code>// .. requesting the user for input ..
String name = // user input
int age = // user input
Sex sex = // user input, interpreted
Person newPerson = new Person(name, age, sex);
</code>```

Or even better: do something like so:

```<code>public final class PersonFactory {
    private PersonFactory() { }

    private static Map<String, Person> persons = new HashMap<>();
    private static Map<String, PersonData> personBlueprints = new HashMap<>();

    public static void addPerson(Person person){
        persons.put(person.getName(), person);
    }

    public static Person getPerson(String name){
        return persons.get(name);
    }

    public static Person createPerson(String blueprintName){
        PersonData data = personBlueprints.get(blueprintName);
        return new Person(data.name, data.age, data.sex);
    }

    // .. or, alternative to the last method
    public static Person createPerson(String personName){
        Person blueprint = persons.get(personName);
        return new Person(blueprint.getName(), blueprint.getAge(), blueprint.getSex());
    }

}

public class PersonData {
    public String name;
    public int age;
    public Sex sex;

    public PersonData(String name, int age, Sex sex){
        this.name = name;
        this.age = age;
        this.sex = sex;
    }
}
</code>```

I got carried away. I think you get the idea.

Subclasses are not meant to fill in the templates set by their superclasses. Subclasses are meant to add functionality. Object are meant to fill in the templates, that's what they're for.

You shouldn't be creating a new class for every possible combination of data. (Just like I shouldn't have created a new Scale subclass for every possible combination of Notes).

Her'es a guideline: whenever you create a new subclass, consider if it adds any new functionality that doesn't exist in the superclass. If the answer to that question is "no", than you might be trying to 'fill in the template' of the superclass, in which case just create an object. (And possibly a Factory with 'presets', to make life easier).

Hope that helps.

Body:
A lot of people answered already. Thought I'd give my own personal perspective.

Once upon a time I worked on an app (and still do) that creates music.

The app had an abstract Scale class with several subclasses: CMajor, DMinor, etc. Scale looked something like so:

public abstract class Scale {
    protected Note[] notes;
    public Scale() {
        loadNotes();
    }
    // .. some other stuff ommited
    protected abstract void loadNotes(); /* subclasses put notes in the array
                                          in this method. */
}

The music generators worked with a specific Scale instance to generate music. The user would select a scale from a list, to generate music from.

One day, a cool idea came to my mind: why not allow the user to create his/her own scales? The user would select notes from a list, press a button, and a new scale would be added to the list available scales.

But I wasn't able to do this. That was because all the scales are already set at compile time - since they are expressed as classes. Then it hit me:

It's often intuitive to think in terms of 'superclasses and subclasses'. Almost everything can be expressed through this system: superclass Person and subclasses John and Mary; superclass Car and subclasses Volvo and Mazda; superclass Missile and subclasses SpeedRocked, LandMine and TrippleExplodingThingy.

It's very natural to think in this way, especially for the person relatively new to OO.

But we should always remember that classes are templates, and objects are content poured into these templates. You can pour whatever content you want into the template, creating countless possibilities.

It's not the job of the subclass to fill the template. It's the job of the object. The job of the subclass is to add actual functionality, or expand the template.

And that's why I should have created a concrete Scale class, with a Note[] field, and let objects fill in this template; possibly through the constructor or something. And eventually, so I did.

Every time you design a template in a class (e.g., an empty Note[] member that needs to be filled, or a String name field that needs to be assigned a value), remember that it's the job of the objects of this class to fill in the template (or possibly those creating these objects). Subclasses are meant to add functionality, not to fill in templates.

You might be tempted to create a "superclass Person, subclasses John and Mary" kind of system, like you did, because you like the formality this gets you.

This way, you can just say Person p = new Mary(), instead of Person p = new Person("Mary", 57, Sex.FEMALE). It makes things more organized, and more structured. But as we said, creating a new class for every combination of data isn't good approach, since it bloats the code for nothing and limits you in terms of runtime abilities.

So here's a solution: use a basic factory, might even be a static one. Like so:

public final class PersonFactory {
    private PersonFactory() { }

    public static Person createJohn(){
        return new Person("John", 40, Sex.MALE);
    }

    public static Person createMary(){
        return new Person("Mary", 57, Sex.FEMALE);
    }

    // ...
}

This way, you can easily use the 'presets' the 'come with the program', like so: Person mary = PersonFactory.createMary(), but you also reserve the right to design new persons dynamically, for example in the case that you want to allow the user to do so. E.g.:

// .. requesting the user for input ..
String name = // user input
int age = // user input
Sex sex = // user input, interpreted
Person newPerson = new Person(name, age, sex);

Or even better: do something like so:

public final class PersonFactory {
    private PersonFactory() { }

    private static Map<String, Person> persons = new HashMap<>();
    private static Map<String, PersonData> personBlueprints = new HashMap<>();

    public static void addPerson(Person person){
        persons.put(person.getName(), person);
    }

    public static Person getPerson(String name){
        return persons.get(name);
    }

    public static Person createPerson(String blueprintName){
        PersonData data = personBlueprints.get(blueprintName);
        return new Person(data.name, data.age, data.sex);
    }

    // .. or, alternative to the last method
    public static Person createPerson(String personName){
        Person blueprint = persons.get(personName);
        return new Person(blueprint.getName(), blueprint.getAge(), blueprint.getSex());
    }

}

public class PersonData {
    public String name;
    public int age;
    public Sex sex;

    public PersonData(String name, int age, Sex sex){
        this.name = name;
        this.age = age;
        this.sex = sex;
    }
}

I got carried away. I think you get the idea.

Subclasses are not meant to fill in the templates set by their superclasses. Subclasses are meant to add functionality. Object are meant to fill in the templates, that's what they're for.

You shouldn't be creating a new class for every possible combination of data. (Just like I shouldn't have created a new Scale subclass for every possible combination of Notes).

Her'es a guideline: whenever you create a new subclass, consider if it adds any new functionality that doesn't exist in the superclass. If the answer to that question is "no", than you might be trying to 'fill in the template' of the superclass, in which case just create an object. (And possibly a Factory with 'presets', to make life easier).

Hope that helps.


问:
Combine union with distinct
Situation: I need distinct results from two tables, that both have duplicates.
I would like to know if I should combine UNION and DISTINCT.

Example 1 - Only use distinct

```<code>SELECT DistinctValue
FROM Table1
UNION
SELECT DistinctValue
FROM Table2
</code>```

Example 2 - Combine distinct and union

```<code>SELECT DISTINCT DistinctValue
FROM Table1
UNION
SELECT DISTINCT DistinctValue
FROM Table2
</code>```

The results are the same, but are there any performance differences?

答:
The answer depends on the statistics/optimizer etc. The first query logically asks you to take the two result sets and union them(which implicitly removes duplicates reference). The second says take each result set and remove duplicates, then union them.

In the random data case I would expect better performance from the first one. But if your data is appropriately skewed the second could be better. For example if Table1 had millions of results and no duplicates and Table2 had millions of results but distinct brings it down to just a few records, then the later might work better since it couldn't compare the Table2 entries to the Table1 entries before getting rid of them.

I ran it against some data I had laying around which produced the same query plan for both in SQL Server. Really you need to profile it with your data.

Title: Combine union with distinct


问:
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.

答:
There are a few options to do this, but keep in mind that they (in essence) modify the public interface of your modules, to give you access to internal implementation details (effectively transforming unit testing into tightly coupled client dependencies, where you should have no dependencies at all).

you could add a friend (class or function) declaration to the tested class.

you could add #define private public to the beginning of your test files, before #include-ing the tested code. In case the tested code is an already-compiled library though, this could make the headers no longer match already compiled binary code (and cause UB).

you could insert a macro in your tested class and decide at a later date what that macro means (with a different definition for testing code). This would allow you to test internals, but it would also allow third party client code to hack into your class (by creating their own definition in the declaration you add).


问:
How big sites scale up and optimize to massive traffic?
How do sites like Facebook and Twitter optimize their sites for massive traffic. Aside from spending big bucks on getting the best servers, what can be optimized in your code to accommodate massive traffic?

I've read about caching your pages to static HTML, but that's impractical for social networking sites where the pages are constantly updated.

答:
Content Delivery Network

Facebook uses static content delivery network for serving photos and videos. Check the source of any image in facebook and you will see something like fbcdn.net.


问:
Presentation VS Application layer in DDD
I have trouble drawing a clear line between Presentation and Application layer in Domain Driven Design.

Where should Controllers, Views, Layouts, Javascript and CSS files go?

Is it in the Application or the Presentation layer?

And if they go all together in the same layer, what contains the other one? Is it empty?

答:
There is a big difference between the application layer and the presentation layer from a DDD view point.

Although DDD centers around how to model the domain using the DDD building blocks and concepts such as bounded contexts, Ubiquitous language and so, it is still vital to clearly identify and separate the various layers in your app.

The architecture plays a big role in implementing a successful DDD app. A famous architecture that gained a lot of hype lately is the onion architecture:

In this design the UI/Presentation layer and the application layer are clearly separated. Merging the 2 together introduces tight coupling between 2 layers that have clear separate concerns and responsibilities.

The Presentation layer should only house presentation logic. Avoid Smart UIs that know too much. This mainly houses the MVC's Controllers and views in addition to CSS, JS, templates, forms and everything that relates to response and request objects.

The actions issued through presentation are delegated to the application layer through commands. The application layer contains the application logic. It normally maps to a use case. It contains WHAT the system should do to satisfy a use case. A typical application service will ask a repository to return an aggregate then invoke an action on that aggregate.

Have a look at the sample project from Vaughn Vernon's IDDD


答: If your quantum (the time each thread gets to run) is the same, then you'll have the same number of context switches regardless of the number of threads (assuming no threads are blocked). The amount of time each thread gets will be affected, but the context switching overhead will be constant.  This is in an idea world; obviously, in the real world, you'll have locks and resource contention, so many processes will be waiting on I/O or otherwise not ready, so there will be more context switching overhead, and it's possible that the amount of time spent switching can exceed the amount of time spent actually running user code. The amount of extra time is entirely dependent on your workload, which is why it's not possible to generally predict the amount of overhead.

Title: Context Switching behavior?


问:
What is the argument for never forcing a push in a DVCS (Mercurial)?
I always preach never to force push anything, because that adds ambiguity to the repository server.

In this specific example, we collaborate with a customer and they "skip a step" and force push instead of appropriately pulling and merging. This takes the ambiguity of what code is good, what code is bad, out of their working directory and into the server. Two heads on this branch, which one do I use, etc. I am looking to use a hook to disallow force pushing, I just didn't want to lock down that ability if there was a good use case for it.

We are relatively new (2 or 3 years) to DVCS, moving from SVN previously. What are the arguments for not doing a force push in a DVCS?  What exceptions exist for this hard and fast rule?

答:
The main reason not to force a push is that it forces everyone else to do rebases or force pulls, and any outstanding branches will not merge cleanly.  Also, when beginners don't really understand how to use DVCS yet, a force push is usually a sign that you forgot a step, like doing a pull or merge first, and you can accidentally lose history or even committed code.

There are some teams who force push regularly as a matter of course.  They just build it into their regular workflow.  For example, a team that works on one subsystem of the Linux kernel might diverge from the "mainline" but regularly force a push to get itself back synced up.  I think you have to have a fairly disciplined and DVCS-experienced team for this to work well, though.


问:
Why implement a lexer as a 2d array and a giant switch?
I'm slowly working to finish my degree, and this semester is Compilers 101. We're using the Dragon Book. Shortly into the course and we're talking about lexical analysis and how it can be implemented via deterministic finite automata (hereafter, DFA). Set up your various lexer states, define transitions between them, etc.

But both the professor and the book propose implementing them via transition tables which amount to a giant 2d array (the various non-terminal states as one dimension, and the possible input symbols as the other) and a switch statement to handle all of the terminals as well as dispatch to the transition tables if in a non-terminal state.

The theory is all well and good, but as someone who's actually written code for decades, the implementation is vile. It's not testable, it's not maintainable, it's not readable, and it's a pain and a half to debug through. Worse yet, I can't see how it would be remotely practical if the language was UTF capable. Having a million or so transition table entries per non-terminal state gets unweildy in a hurry.

So what's the deal? Why is the definitive book on the subject saying to do it this way?

Is the overhead of function calls really that much? Is this something that works well or is necessary when the grammar isn't known ahead of time (regular expressions?)? Or perhaps something that handles all cases, even if more specific solutions will work better for more specific grammars?

(note: possible duplicate "Why use an OO approach instead of a giant switch statement?" is close, but I don't care about OO. A functional approach or even saner imperative approach with standalone functions would be fine.)

And for the sake of example, consider a language that only has identifiers, and those identifiers are [a-zA-Z]+. In the DFA implementation, you'd get something like:

```<code>private enum State
{
    Error = -1,
    Start = 0,
    IdentifierInProgress = 1,
    IdentifierDone = 2
}

private static State[][] transition = new State[][]{
    ///* Start */                  new State[]{ State.Error, State.Error (repeat until 'A'), State.IdentifierInProgress, ...
    ///* IdentifierInProgress */   new State[]{ State.IdentifierDone, State.IdentifierDone (repeat until 'A'), State.IdentifierInProgress, ...
    ///* etc. */
};

public static string NextToken(string input, int startIndex)
{
    State currentState = State.Start;
    int currentIndex = startIndex;
    while (currentIndex < input.Length)
    {
        switch (currentState)
        {
            case State.Error:
                // Whatever, example
                throw new NotImplementedException();
            case State.IdentifierDone:
                return input.Substring(startIndex, currentIndex - startIndex);
            default:
                currentState = transition[(int)currentState][input[currentIndex]];
                currentIndex++;
                break;
        }
    }

    return String.Empty;
}
</code>```

(though something that would handle end of file correctly)

Compared to what I would expect:

```<code>public static string NextToken(string input, int startIndex)
{
    int currentIndex = startIndex;
    while (currentIndex < startIndex && IsLetter(input[currentIndex]))
    {
        currentIndex++;
    }

    return input.Substring(startIndex, currentIndex - startIndex);
}

public static bool IsLetter(char c)
{
    return ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'));
}
</code>```

With the code in NextToken refactored out into its own function once you have multiple destinations from the start of the DFA.

答:
In practice these tables are generated from regular expressions that define the tokens of the language:

```<code>number := [digit][digit|underscore]+
reserved_word := 'if' | 'then' | 'else' | 'for' | 'while' | ...
identifier := [letter][letter|digit|underscore]*
assignment_operator := '=' | '+=' | '-=' | '*=' | '/='
addition_operator := '+' | '-'
multiplication_operator := '*' | '/' | '%'
...
</code>```

We have had utilities to generate lexical analyzers since 1975 when lex was written.

You are basically suggesting replacing regular expressions with procedural code.  This expands a couple of characters in a regular expression into several lines of code.  Handwritten procedural code for lexical analysis of any moderately interesting language tends to be both inefficient and difficult to maintain.

Body:
In practice these tables are generated from regular expressions that define the tokens of the language:

number := [digit][digit|underscore]+
reserved_word := 'if' | 'then' | 'else' | 'for' | 'while' | ...
identifier := [letter][letter|digit|underscore]*
assignment_operator := '=' | '+=' | '-=' | '*=' | '/='
addition_operator := '+' | '-'
multiplication_operator := '*' | '/' | '%'
...

We have had utilities to generate lexical analyzers since 1975 when lex was written.

You are basically suggesting replacing regular expressions with procedural code.  This expands a couple of characters in a regular expression into several lines of code.  Handwritten procedural code for lexical analysis of any moderately interesting language tends to be both inefficient and difficult to maintain.


答:
From memory, -- it's a long time since I've read the book, and I'm pretty sure I didn't read the latest edition, I for sure don't remember something looking like Java -- that part was written with the code being intended to be a template, the table being filled with a lex like lexer generator. Still from memory, there was a section on table compression (again from memory, it was written in such a way that it was also applicable to table driven parsers, thus perhaps further in the book than what you have seen yet).  Similarly, the book I remember assumed an 8-bit character set, I'd expect a section on handling bigger character set in later editions, probably as part of the table compression.  I've given an alternative way to handle that as an answer to a SO question.

There is a sure performance advantage in having a tight loop data driven in modern architecture: it's quite cache friendly (if you have compressed the tables), and jump prediction is as perfect as possible (one miss at the end of the lexem, perhaps one miss for the switch dispatching to the code which depend on the symbol; that's assuming that your table decompression can be done with predictable jumps).  Moving that state machine to pure code would decrease the jump prediction performance and perhaps increase the cache pressure.

Title: Why implement a lexer as a 2d array and a giant switch?

Body:
I'm slowly working to finish my degree, and this semester is Compilers 101. We're using the Dragon Book. Shortly into the course and we're talking about lexical analysis and how it can be implemented via deterministic finite automata (hereafter, DFA). Set up your various lexer states, define transitions between them, etc.

But both the professor and the book propose implementing them via transition tables which amount to a giant 2d array (the various non-terminal states as one dimension, and the possible input symbols as the other) and a switch statement to handle all of the terminals as well as dispatch to the transition tables if in a non-terminal state.

The theory is all well and good, but as someone who's actually written code for decades, the implementation is vile. It's not testable, it's not maintainable, it's not readable, and it's a pain and a half to debug through. Worse yet, I can't see how it would be remotely practical if the language was UTF capable. Having a million or so transition table entries per non-terminal state gets unweildy in a hurry.

So what's the deal? Why is the definitive book on the subject saying to do it this way?

Is the overhead of function calls really that much? Is this something that works well or is necessary when the grammar isn't known ahead of time (regular expressions?)? Or perhaps something that handles all cases, even if more specific solutions will work better for more specific grammars?

(note: possible duplicate "Why use an OO approach instead of a giant switch statement?" is close, but I don't care about OO. A functional approach or even saner imperative approach with standalone functions would be fine.)

And for the sake of example, consider a language that only has identifiers, and those identifiers are [a-zA-Z]+. In the DFA implementation, you'd get something like:

```<code>private enum State
{
    Error = -1,
    Start = 0,
    IdentifierInProgress = 1,
    IdentifierDone = 2
}

private static State[][] transition = new State[][]{
    ///* Start */                  new State[]{ State.Error, State.Error (repeat until 'A'), State.IdentifierInProgress, ...
    ///* IdentifierInProgress */   new State[]{ State.IdentifierDone, State.IdentifierDone (repeat until 'A'), State.IdentifierInProgress, ...
    ///* etc. */
};

public static string NextToken(string input, int startIndex)
{
    State currentState = State.Start;
    int currentIndex = startIndex;
    while (currentIndex < input.Length)
    {
        switch (currentState)
        {
            case State.Error:
                // Whatever, example
                throw new NotImplementedException();
            case State.IdentifierDone:
                return input.Substring(startIndex, currentIndex - startIndex);
            default:
                currentState = transition[(int)currentState][input[currentIndex]];
                currentIndex++;
                break;
        }
    }

    return String.Empty;
}
</code>```

(though something that would handle end of file correctly)

Compared to what I would expect:

```<code>public static string NextToken(string input, int startIndex)
{
    int currentIndex = startIndex;
    while (currentIndex < startIndex && IsLetter(input[currentIndex]))
    {
        currentIndex++;
    }

    return input.Substring(startIndex, currentIndex - startIndex);
}

public static bool IsLetter(char c)
{
    return ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'));
}
</code>```

With the code in NextToken refactored out into its own function once you have multiple destinations from the start of the DFA.


问:
The right algorithm to get perfect combination
I am working on a self-study project but I cannot come up with a reliable answer.

Here is the deal:

I start with 500cm sticks.  I have orders from customers who want smaller sticks.  I am willing to cut my 500cm stick into as many as 7 pieces.

How can I determine which combination of customer orders to use for each stick to minimize waste?

This is some sample customer order data:

```<code>+-----------+--------+
| Firm Name | Length |
+-----------+--------+
| "firm1",  | 34,    |
| "firm2",  | 43,    |
| "firm3",  | 52,    |
| "firm4",  | 61,    |
| "firm5",  | 62,    |
     ...
| "firm26", | 102,   |
| "firm27", | 152,   |
| "firm28", | 153,   |
| "firm29", | 163,   |
| "firm30", | 202,   |
+-----------+--------+
</code>```

The important part is the algorithm should give minimize scrap.

I thought that I could use a genetic algorithm but it does not return the correct solution every time.

The important thing is all cutting to pieces work orders must be 500cm in total. Or it should be near to that length according to given waste length. Quantity could be higher than the order and can be put to the stock.

答:
I did some work in a college operating systems class about allocation of memory blocks with different sized files using the best-fit, worst-fit, first-fit algorithms, which if you think about it is essentially the same process for this problem.  The overarching theme was without knowing all of the requests ahead of time you can't go through all the possible orientations and find the 'least' scrap.  You can get close using something like best-fit but then a different set of orders could make that worse than first-fit and so on as you can't guarantee to look forward far enough to optimize everything fully in a realistic system.  </p>

<p>Just doing some quick situations with a few sticks and a few orders and varying the order in which the orders come in should explain why any algorithm you have might not always return the 'most correct' solution.  </p>

Body:
I did some work in a college operating systems class about allocation of memory blocks with different sized files using the best-fit, worst-fit, first-fit algorithms, which if you think about it is essentially the same process for this problem.  The overarching theme was without knowing all of the requests ahead of time you can't go through all the possible orientations and find the 'least' scrap.  You can get close using something like best-fit but then a different set of orders could make that worse than first-fit and so on as you can't guarantee to look forward far enough to optimize everything fully in a realistic system.

Just doing some quick situations with a few sticks and a few orders and varying the order in which the orders come in should explain why any algorithm you have might not always return the 'most correct' solution.


答:
This particular problem is a variation on a well known (and well studied) problem known as the cutting stock problem.

In the classic definition of this problem, consider that you have large rolls of product of a given width.  You need to cut them into the smaller width rolls with minimum waste (and knife changes):

The reason that this is so well studied is that it has huge impacts on industrial processes with even small gains in efficiency.  It shows up in paper (rolls of paper), film (rolls of film), and metal industries with additional interesting variations for each of them (cutting paper to A4 size involves two cuts on different machines that can have different specifications (one being cheaper).  The glass industry has another similar problem known as the guillotine problem because it needs to get cut into rectangular pieces rather than working with rolls.

This problem is also equivalent to the knapsack problem.

Knowing these things, there are a number of different algorithms that attempt to solve this class of problem that goes into a too many funky math symbols, conjectures, and other papers.

Good enough answers are possible quickly, perfect answers take a long time because you will need to enumerate most if not all of the possibilities.

Title: The right algorithm to get perfect combination

Body:
I am working on a self-study project but I cannot come up with a reliable answer.

Here is the deal:

I start with 500cm sticks.  I have orders from customers who want smaller sticks.  I am willing to cut my 500cm stick into as many as 7 pieces.

How can I determine which combination of customer orders to use for each stick to minimize waste?

This is some sample customer order data:

```<code>+-----------+--------+
| Firm Name | Length |
+-----------+--------+
| "firm1",  | 34,    |
| "firm2",  | 43,    |
| "firm3",  | 52,    |
| "firm4",  | 61,    |
| "firm5",  | 62,    |
     ...
| "firm26", | 102,   |
| "firm27", | 152,   |
| "firm28", | 153,   |
| "firm29", | 163,   |
| "firm30", | 202,   |
+-----------+--------+
</code>```

The important part is the algorithm should give minimize scrap.

I thought that I could use a genetic algorithm but it does not return the correct solution every time.

The important thing is all cutting to pieces work orders must be 500cm in total. Or it should be near to that length according to given waste length. Quantity could be higher than the order and can be put to the stock.


答:
You're asking about a class of equivalent problems i.e. the bin-packing algorithm (which is NP hard see http://en.wikipedia.org/wiki/Bin_packing_problem). You can't guarantee a perfect solution for any number of customers and sticks within a (reasonable) linear amount of time. What you can do is use heuristics to get a 'best effort' solution.

Check out bin packing and think about how to map your problem to the usual best effort solutions is probably the best approach.


问:
Writing software without unit testing
Usually, when I write software, I use unit tests for each function to test if it is working without any problems. However, recently I have found myself writing some software that are not really amenable to unit testing. For example, writing code for an operating system, where standard libraries are not available. Another example is writing the constraints of an Integer Linear Programming problem, where no solution can be seen until all the constraints have been added. In these cases, I have struggled to debug my code, since identifying which part of the code is causing problems has been very difficult. Any suggestions how to deal with these cases?

Update: I wanted to write the page-mapping functionality of an operating system. The system used 4-level paging. My code used one function each to go from one level of page table to the next. Although I knew the algorithm was right, the system was not working as expected. However, I was not able to find out which function was creating the problem, since it was impossible to know the exact correct output of each function. Instead, I had to do an endless series of trials and errors (something that took me over a week) to find out the problem.

Thanks.

答:
Hardware-dependend test can be hard to unit-test, indeed, until you have a reliable simulator available. OS / kernel dependent code can be unit tested by providing an abstract interface to the OS or kernel functions which allows to mock these functions out Of course, when your OS functions do not behave the way you expect them to behave, you might provide unit tests for these functions, one after another, to find out how they really work.

But the code for solving an "Integer Linear Programming" problem is typically well testable:

the ILP solver can be unit-tested by using lots of small problems with only few constraints

each of the constraints is typically a small, standalone boolean function, which is perfect for unit testing

In fact, if you want to test if you implemented the right constraints, and the only way to check this is to run your black-box ILP solver with a constraint vector of size >10000, then you might have a problem with your integration tests, not with your unit tests. But for such big problem spaces, the constraints are typically parametric, and the number of constraints is typically a parameter as well, which offers you the chance to test it with "n constraints" first where n is choosen a very small number.

Title: Writing software without unit testing


问:
Accuracy of "calculator algorithms"
I am building a library class that provides functionality for mathematical operations on BigDecimals (and a few on BigIntegers). Now, BigIntegers are quite easy to master and pleasant to use. BigDecimals can be tricky, but in the end, it finally pays off.

I want my class to provide results accurate up to a specified level of accuracy (like, number of places after the decimal point). This is where Math fails me because it supports operations on double. Now double supports 15-16 significant digits (not 15-16 places after decimal.) Hence, I've decided to upgrade to Bigdecimal.

But now, the problem is where can I find algorithms that support arbitrary precision calculations? Moreover, I would like to make my BigMath(so I call it) analogous to its sibling in the java.lang package. Then it struck me that if I opt for algorithms used by scientific calculators, then I might achieve the required level of accuracy.

So here are my (related) questions:

Can I achieve the required level of accuracy using calculator algorithms?

If yes, then where can I find the required algorithms?

Are there any caveats lurking in my approach?

UPDATE:
Right now, I have just added support for the sqrt(BigDecimal) method. It makes use of the Newtonian method (and a special trick to generate a good estimate).

So, here's the entire BigMath class:

```<code>package in.blogspot.life_on_the_heap.bigmath;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;

/**
 * @author ambigram_maker
 */
public class BigMath {

    public static void main(String[] args) {
        BigDecimal number = new BigDecimal("91.91");
        BigDecimal sqrt = sqrt(number);
        System.out.println("number = " + number);
        System.out.println("sqrt(number) = " + sqrt);
        System.out.println("number = " +
                                   sqrt.multiply(sqrt, getContext(sqrt, DEFAULT_PREC))
                                           .stripTrailingZeros());
    }

    public static final BigDecimal TWO = BigDecimal.valueOf(2L);

    /*
     * The default number of places after the decimal. This is also the
     * *minimum* precision provided by this class.
     */
    private static final int DEFAULT_PREC = 20;
    /*
     * Maintains the "precision" or the number of digits after the decimal.
     */
    private static int precision = DEFAULT_PREC;

    public static void setPrecision(int precision_) {
        if (precision_ < DEFAULT_PREC) {
            precision = DEFAULT_PREC;
        } else {
            precision = precision_;
        }
    }

    public static int getPrecision() {
        return precision;
    }

    public static BigDecimal sqrt(BigDecimal decimal) {
        return sqrt(decimal, precision);
    }

    public static BigDecimal sqrt(BigDecimal decimal, int P_A_D) {
        // quick exit checks:
        if (decimal.compareTo(BigDecimal.ZERO) < 0) {
            return BigDecimal.valueOf(Double.NaN);
        }
        BigDecimal
                answer,     // The storage for the guesses.
                original,   // The result of squaring the guesses
                epsillon;   // The tolerance of this method.
        MathContext context = getContext(decimal, P_A_D);
        {
        /*
         * Obtain a good estimate of the square-root for the initial guess.
         * This is done by obtaining the "top" half of the bits of the decimal.
         */
            BigInteger integer = decimal.toBigInteger();
            answer = new BigDecimal
                             (integer.shiftRight(integer.bitLength() >>> 1));
        }
        original = answer.multiply(answer);
        epsillon = getEpsillon(P_A_D);
        while (original.subtract(decimal).abs().compareTo(epsillon) > 0) {
            answer = answer.subtract(original.subtract(decimal)
                                             .divide(TWO.multiply(answer),
                                                            context));
            original = answer.multiply(answer);
        }
        return answer.round(context);
    }

    public static BigDecimal getEpsillon(int precision) {
        return new BigDecimal("1E-" + precision);
    }

    private static MathContext getContext(BigDecimal decimal, int precision) {
        int beforePoint = (decimal.toString()).indexOf('.');
        if (beforePoint == -1) beforePoint = decimal.toString().length();
        return new MathContext(beforePoint + precision);
    }
}
</code>```

The output is the desired one:

```<code>number = 91.91
sqrt(number) = 9.586970324351692703533
number = 91.91
</code>```

Because I am quite happy with the result, I am determined to move ahead. Hence, I seek advice.

答:
As people are hinting in the comments, if you want to do this for the fun of doing it, that's one thing, but if you want a library of scientific functions to use, you should use one that's already been written by experts.  There's a list at http://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic#Libraries

The open-source libraries listed there are also a place to look for (if not find!) readable code.

Algorithms like this are part of numerical analysis; see Wikipedia for that, too.  The famous "Numerical Recipes" books give both code and discussion for many kinds of calculations.

If you're talking about physical electronic calculators (as opposed to programs that are also called "calculators"), there are three reasons why I doubt you could use calculator code as a prototype for your arbitrary precision math library.

I don't know of any calculator company that has released the software and hardware designs of its calculators.

I've never heard of an electronic calculator with arbitrary precision arithmetic.  A typical scientific calculator has a fixed precision.  There will be no clue within the code how to extend a given function to a given larger precision (whereas the writers of, e.g., GNU MPFR will have solved these problems).  For instance, what precision intermediate results will it need?  How many more times will you need to go through the loops?  Is the algorithm one that will work reasonably fast, or will it slow down too much, as you add precision?

A given calculator may have very advanced math hardware (to do Taylor series for instance) or very primitive hardware (can't even multiply two-digit numbers).   The code will probably be hand-written machine code without more-readable source code.  You'd need to understand and emulate both the functions of the hardware and code in your software.  An interesting hobby but maybe not the one you were thinking of.

Title: Accuracy of "calculator algorithms"


问:
Which programming language first came up with the finally block?
Which programming language first came up with the finally block?

I ask purely out of curiosity.

It is a very useful piece of syntactic sugar, and whoever first created it surely has a very impressive grasp of solutions to programming problems.

(Note: it is deceptively difficult to find an answer to this question...)

答:
According to wikipedia the first to introduce this was NIL.

The cleanup behavior now generally called "finally" was introduced in NIL (New Implementation of LISP) in the mid- to late-1970s as UNWIND-PROTECT.


答:
The motivation for the particular algorithm is largely that it's a learning exercise, so it tries to stay close to the idea of a DFA, and keep states and transitions very explicit in the code.  As a rule, nobody would actually manually write any of this code anyway - you would use a tool to generate code from a grammar.  And that tool wouldn't care about the readability of the code because it isn't source code, it's an output based on the definition of a grammar.

Your code is cleaner for someone maintaining a hand-written DFA, but a little farther removed from the concepts being taught.


问:
What kind of game mechanics makes sense to be handled on client side?
I am aware of that is a difficult question and depends on the game mechanics and game type being applied.
So, many answers can be given. For the sake of simplicity, it would be better to consider a typical online MMO
game in order to make easy to find a satisfying answer.

This is the question partly related to my previous question in terms of reducing networking cost.

Ernest Adams & Joris Dormans who are the authors of the book had well described five major game mechanics which
are widely used in many online games. (By the way, the book is very useful who needs to obtain new approaches to game mechanics.)

Above mentioned book describes five major mechanics as follows:

1) Physics

2) Internal Economy

3) Progression mechanisms

4) Tactical maneuvering

5) Social interaction

Of course, every game has its own characteristics depending on the game scenario and additional mechanics can be
added to the game logic. However, one of the real difficulty is that deciding which mechanics are better to
implement on client side and which are not.
These are crucial decisions because each of them may have side effects including client side cheating risk and
network bandwidth usage.

Many designer prefers to implement physics mechanics on server side in networked games because it is the most guarantied way to
prevent cheating although it needs much more network bandwidth and powerful hosting investment.
However, I think others are open for discussing.

We've been working to implement all above mechanics in our game project with Unity3D and C#.
We had planned to implement all of them in server game logic. But now, we think that it might be possible to implement
some of them in client side scripts rather than using fully authorative server. So, it means we need to implement
semi-authorative server logic where some mechanics managed by server logic and others controlled in client side scripts.

We need semi-authorative architecture design ideas to speed up our project.

Thanks

UPDATE:
It would be better to isolate the question.
I know that, client side prediction, interpolation and extrapolation that all have to be implemented on server side. These are primary physics requirements that allow me to provide character movements smoothly. Client passes predictions, server approves them or sends back corrections. This is OK.

If we consider the internal economy, this type of games typically encompasses items easily identified as resources : money, energy, ammunition, and so on. However, a game’s economy is not limited to concrete, tangible items; it can also include abstractions such as health, popularity, and magical power.

How much risk would I take if I try to handle all of them in client side scripts in terms of cheating? In contrast, if I try to handle all of them on server side would I cause lot more traffic? How do I optimize it?

Other mechanics may also include similar crucial metrics that needs to be saved.

I think, anti-cheating mechanisms should be the most important thing for every commercial game developer. I seen many videos on youtube few years ago that teaches how to hack farmville game on client side.

答:
Almost all of them!

Now, this does depend on the type of game of course, but surprising as it may seem, most mechanics do need to be run on the client. Note that they only need to be run on the client. The server must always have the final say. I'm talking about a simulation.

Physics are the most obvious case of all. If you jump, the server may receive that information after 100ms, and another player in 100ms more. There isn't time to confirm that you may jump until after 200ms at the least. Your client must do something. It's simulation may need to be corrected, but in most cases 200ms delays are unacceptable.

This "anti-lag" leads to many issues, and is a very complex topic which you should probably research independently.

Note that this also depends on the type of game. In a turn-based game, the server can do all the work safely, because you do not require immediate feedback.


问:
Function has two sets of arguments, the latter of which calls a nested function?
The function foo, has a nested function; bar. Calling foo with a second set of arguments feeds them into bar if bar is returned at the end of foo. How does this work and what is it called?

Are there any uses for it over simply having a single set of arguments that calls the function normally?

```<code>def foo(arg1):
    print(arg1)
    def bar(arg2,arg3):
        print (arg2,arg3)
    return bar

foo("hello")("hello","world")

>>>
hello
hello world
</code>```

答:
I can't speak to the Python-ness of this, but in schemes that frequently use function handlers/callbacks, I'll use your construct for creating these:

```<code>def getErrorHandler(message):
    def onError(error):
        print message + ":" + error
    return onError

panicHandler = getErrorHandler("Panic");
warningHandler = getErrorHandler("Warning");
...
panicHandler("Universe imploding");
</code>```

Output:

```<code>Panic: Universe imploding
</code>```

Body:
I can't speak to the Python-ness of this, but in schemes that frequently use function handlers/callbacks, I'll use your construct for creating these:

def getErrorHandler(message):
    def onError(error):
        print message + ":" + error
    return onError

panicHandler = getErrorHandler("Panic");
warningHandler = getErrorHandler("Warning");
...
panicHandler("Universe imploding");

Output:

Panic: Universe imploding


问:
Debug symbols change application execution
I have to set up remote debugging for a multi threaded application running on a embedded device. C++ is the language.

I've gotten so far and got the remote debugging working for a simple application, but when applying the same procedures on the multi threaded giant just don't work (the application starts behaving unpredictably when built with debug). There was no stopping of the execution (no breakpoints), just a continuous standard run, just with debug symbols.

What would cause a failure in debug mode in this environment? (once again, no breakpoints in debug mode, just continuous running)

答:
Since it's in C++, it could be a lot of things.

First and foremost, in debug mode, in most compilers, uninitialized variables will be filled with zeroes. In release mode, in most compilers, your uninitialized variables are filled with random garbage.

Another likely possibility is that a buffer overflow or other pointer malady (perhaps caused by uninitialized behavior above) is corrupting slightly different code due to the optimization differences between debug and release.

There's a bunch of others, but without more info it will be tough to say.


问:
Is it acceptable to ask management for pseudo code?
I'm a developer in the IT department of a large oil company. I received a spec document, basically in plain English, about business rules that need to be implemented in a new application. The rules are really difficult to translate into code, since I don't know all of the inner workings of the business.

Is it acceptable to ask management (the people who gave me the spec) for the rules in more of a pseudo code fashion or would I be looked at as if I had two heads?

"Management" in this case refers to guys who were once developers, but now have more of a management role here in IT.

答:
Don't ask for pseudocode.  If your superiors thought you needed that, they would have provided it already.

Here's what you should do instead:

Make your requirements testable

If it's not testable, it's not a requirement; it's a feature or wish.

More specifically, each individual requirement should be SMART:

Specific

Measurable

Assignable

Realistic

Timely

Gather your requirements in such a way that they are specific enough to write code against, measurable enough that you and the customer can agree on a criteria for declaring success, assignable to someone who can do the work, realistic enough to be achievable, and timely (you can estimate time of completion and set due dates).

Further Reading

Mastering the Requirements Process: Getting Requirements Right (3rd Edition)