答:
What if you define an interface, say IChatBehaviour which has one method called Execute which takes in a message and a cmd object:

```<code>public Interface IChatBehaviour
{
    public void execute(String message, CMD cmd);
}
</code>```

In your code, you then implement this interface and define the behaviours you want:

```<code>public class RegisterLastNick implements IChatBehaviour
{
    public void execute(String message, CMD cmd)
    {
        if (message.toLowerCase().startsWith(".register"))
        {
            cmd.registerLastNick(channel, sender, message);
        }
    }
}
</code>```

And so on for the rest.

In your main class, you then have a list of behaviours (List<IChatBehaviour>)which your IRC bot implements. You could then replace your if statements with something like this:

```<code>for(IChatBehaviour behaviour : this.behaviours)
{
    behaviour.execute(message, cmd);
}
</code>```

The above should reduce the amount of code you have. The above approach would also allow you to supply additional behaviours to your bot class without modifying the bot class itself (as per the Strategy Design Pattern).

If you want only one behaviour to fire at any one time, you can change the signature of the execute method to yield true (the behaviour has fired) or false (the behaviour did not fire) and replace the above loop with something like this:

```<code>for(IChatBehaviour behaviour : this.behaviours)
{
    if(behaviour.execute(message, cmd))
    {
         break;
    }
}
</code>```

The above would be more tedious to implement and initialize since you need to create and pass all the extra classes, however, it should make your bot easily extensible and modifiable since all your behaviour classes will be encapsulated and hopefully independent from each other.

Title: Is there a more intelligent way to do this besides a long chain of if statements or switch?

Body:
I'm implementing an IRC bot that receives a message and I'm checking that message to determine which functions to call. Is there a more clever way of doing this? It seems like it'd quickly get out of hand after I got up to like 20 commands. </p>

<p>Perhaps there's a better way to abstract this?    </p>

```<code> public void onMessage(String channel, String sender, String login, String hostname, String message){

        if (message.equalsIgnoreCase(".np")){
//            TODO: Use Last.fm API to find the now playing
        } else if (message.toLowerCase().startsWith(".register")) {
                cmd.registerLastNick(channel, sender, message);
        } else if (message.toLowerCase().startsWith("give us a countdown")) {
                cmd.countdown(channel, message);
        } else if (message.toLowerCase().startsWith("remember am routine")) {
                cmd.updateAmRoutine(channel, message, sender);
        }
    }
</code>```

Body:
What if you define an interface, say IChatBehaviour which has one method called Execute which takes in a message and a cmd object:

public Interface IChatBehaviour
{
    public void execute(String message, CMD cmd);
}

In your code, you then implement this interface and define the behaviours you want:

public class RegisterLastNick implements IChatBehaviour
{
    public void execute(String message, CMD cmd)
    {
        if (message.toLowerCase().startsWith(".register"))
        {
            cmd.registerLastNick(channel, sender, message);
        }
    }
}

And so on for the rest.

In your main class, you then have a list of behaviours (List<IChatBehaviour>)which your IRC bot implements. You could then replace your if statements with something like this:

for(IChatBehaviour behaviour : this.behaviours)
{
    behaviour.execute(message, cmd);
}

The above should reduce the amount of code you have. The above approach would also allow you to supply additional behaviours to your bot class without modifying the bot class itself (as per the Strategy Design Pattern).

If you want only one behaviour to fire at any one time, you can change the signature of the execute method to yield true (the behaviour has fired) or false (the behaviour did not fire) and replace the above loop with something like this:

for(IChatBehaviour behaviour : this.behaviours)
{
    if(behaviour.execute(message, cmd))
    {
         break;
    }
}

The above would be more tedious to implement and initialize since you need to create and pass all the extra classes, however, it should make your bot easily extensible and modifiable since all your behaviour classes will be encapsulated and hopefully independent from each other.


问:
Is there a more intelligent way to do this besides a long chain of if statements or switch?
I'm implementing an IRC bot that receives a message and I'm checking that message to determine which functions to call. Is there a more clever way of doing this? It seems like it'd quickly get out of hand after I got up to like 20 commands. </p>

<p>Perhaps there's a better way to abstract this?    </p>

```<code> public void onMessage(String channel, String sender, String login, String hostname, String message){

        if (message.equalsIgnoreCase(".np")){
//            TODO: Use Last.fm API to find the now playing
        } else if (message.toLowerCase().startsWith(".register")) {
                cmd.registerLastNick(channel, sender, message);
        } else if (message.toLowerCase().startsWith("give us a countdown")) {
                cmd.countdown(channel, message);
        } else if (message.toLowerCase().startsWith("remember am routine")) {
                cmd.updateAmRoutine(channel, message, sender);
        }
    }
</code>```

答:
Use a dispatch table. This is a table containing pairs ("message part", pointer-to-function).  The dispatcher then will look like this (in pseudo code):

```<code>for each (row in dispatchTable)
{
    if(message.toLowerCase().startsWith(row.messagePart))
    {
         row.theFunction(message);
         break;
    }
}
</code>```

(the equalsIgnoreCase can be handled as a special case somewhere before, or if you have many of those tests, with a second dispatch table).

Of course, what pointer-to-function has to look like depends on your programming language. Here is an example in C or C++. In Java or C# you will probably use lambda expressions for that purpose, or you simulate "pointer-to-functions" by using the command pattern. The free online book "Higher Order Perl" has a complete chapter about dispatch tables using Perl.

ContentLicense: CC BY-SA 3.0

Body:
Use a dispatch table. This is a table containing pairs ("message part", pointer-to-function).  The dispatcher then will look like this (in pseudo code):

for each (row in dispatchTable)
{
    if(message.toLowerCase().startsWith(row.messagePart))
    {
         row.theFunction(message);
         break;
    }
}

(the equalsIgnoreCase can be handled as a special case somewhere before, or if you have many of those tests, with a second dispatch table).

Of course, what pointer-to-function has to look like depends on your programming language. Here is an example in C or C++. In Java or C# you will probably use lambda expressions for that purpose, or you simulate "pointer-to-functions" by using the command pattern. The free online book "Higher Order Perl" has a complete chapter about dispatch tables using Perl.


答:
I'd probably do something like this:

```<code>public interface Command {
  boolean matches(String message);

  void execute(String channel, String sender, String login,
               String hostname, String message);
}
</code>```

Then you can have every command implement this interface, and return true when it matches the message.

```<code>List<Command> activeCommands = new ArrayList<>();
activeCommands.add(new LastFMCommand());
activeCommands.add(new RegisterLastNickCommand());
// etc.

for (Command command : activeCommands) {
    if (command.matches(message)) {
        command.execute(channel, sender, login, hostname, message);
        break; // handle the first matching command only
    }
}
</code>```

Body:
I'd probably do something like this:

public interface Command {
  boolean matches(String message);

  void execute(String channel, String sender, String login,
               String hostname, String message);
}

Then you can have every command implement this interface, and return true when it matches the message.

List<Command> activeCommands = new ArrayList<>();
activeCommands.add(new LastFMCommand());
activeCommands.add(new RegisterLastNickCommand());
// etc.

for (Command command : activeCommands) {
    if (command.matches(message)) {
        command.execute(channel, sender, login, hostname, message);
        break; // handle the first matching command only
    }
}


问:
Algorithm to reduce calls to mapping API
A random distribution of points lies on a map.

This data lies behind an API, and I want to grab the complete set of points within a given bounding box.

I can query the API with the bounding box and the API will return the set of points that fall within that box.

The problem is that the API will limit the result set to 10 items, with no pagination and no indication if there are more points that have been omitted.

So I made a recursive algorithm that takes a bounding box and requests the points that lie within it. If the result set is exactly 10 items, then I split the bounding box into four quadrants and recurse.

It works fine but my question is this: if want to minimize the number of API calls, what is the optimal way to split the bounding box?

Splitting it into quadrants was just an arbitrary decision. When there are a lot of points on the map, I have to drill down many levels before I start getting meaningful results. So I imagine it might be faster to split the box into, say, 9, 16, or more sections. But if I do that, then I eventually get to a point where a lot of requests are returning 0 results which isn't so efficient.

Also, does the size of the limit on the results set affect the answer?

(This is all assuming that I have no prior knowledge of nominal point density in the bounding box)

答:
I do not think that there is much you can do about it. If you know the point density, you could break down the quadrants accordingly.

If the points do not change you could cache them, so initially you would have a relatively high amount of calls to the API which will eventually minimize itself as your application matures.


答:
How you divide the bounding box is a matter of optimizing API calls.  Break it into quadrants and you risk to have to subdivide those further for not being small enough.  Break it into grid and you risk to make superfluous API calls when quadrants would do.

Ideally you'd want to break it into a number of boxes that divides the number of points into 10 points each.  However, the problem with 10 is that you cannot know if there are more points, so we'll have to settle with 9.

Statistics approach

At this point, the deciding factor is determined by statistics.  Statistically, what are the chances that an area will have exactly 9 points contained within?  I'm guessing this is easily determined by your current zoom.  If you are zoomed out, you're likely not going to get only 9 points in quadrant.  In order to eliminate this variable, stick with physical measurements (miles, kilometers, etc.) since they are not going to change with zoom.  You'll have to simply do the extra work of calculating the physical measurements from your current zoom (number of points in an area defined by width*height = number of points / kilometer^2 * width * height).

Now the tricky part is obtaining these statistics.  This is largely determined by how your application works.  If the users provide these points, then it is entirely variable and you'll have to keep a running tally of number of points / kilometer^2.  If these points are static, then you can do some optimization within your program.

Given the average density (number of points / kilometer^2) and the standard deviation, you can aim for one standard deviation from 9, and you will have an 84% (68% + 16% tail for being more than one standard deviation towards zero) chance of having all your points fall between 9 and 0.  Once you know the maximum density from this calculation, the height and width will be the inverse of the maximum density multiplied by 9 minus the standard deviation.

I realize this is sort of a technical answer, but it would optimize.  However also consider that a map isn't uniformly distributed, so it would be optimal only if the distribution is consistent with the rest of the map.  It may not work well for say, a city.

Alternative approach

An alternative approach if you have static point data could be to simply perform monte-carlo simulations, starting with subdividing into 2x2 squares and then moving to 3x3, 4x4, et cetera.  Count the number of total API calls and pick the one requiring the least.  Hope that helps!

Title: Algorithm to reduce calls to mapping API

Body:
A random distribution of points lies on a map.

This data lies behind an API, and I want to grab the complete set of points within a given bounding box.

I can query the API with the bounding box and the API will return the set of points that fall within that box.

The problem is that the API will limit the result set to 10 items, with no pagination and no indication if there are more points that have been omitted.

So I made a recursive algorithm that takes a bounding box and requests the points that lie within it. If the result set is exactly 10 items, then I split the bounding box into four quadrants and recurse.

It works fine but my question is this: if want to minimize the number of API calls, what is the optimal way to split the bounding box?

Splitting it into quadrants was just an arbitrary decision. When there are a lot of points on the map, I have to drill down many levels before I start getting meaningful results. So I imagine it might be faster to split the box into, say, 9, 16, or more sections. But if I do that, then I eventually get to a point where a lot of requests are returning 0 results which isn't so efficient.

Also, does the size of the limit on the results set affect the answer?

(This is all assuming that I have no prior knowledge of nominal point density in the bounding box)


答:
I would choose one coordinate (x/y) and find dividing line that divides returned points to two parts, ideally 5/5.

This way you don't call api extremely lot of time if there are dots clustered really close to corner of your original rectangle.

Another thing, if you have some good heuristic for density, you could skip calls for large rectangles and start with small enough so there is only small chance that they will be empty or contain lot more than 10 points.

eg. if you suspect cluster in top left corner and maybe few points in the rest, you could ask for 3 rectangles, one with cluster (and expect to recurse down) one under (or on side of it) and the rest.


问:
What if(event) statement means in JavaScript?
I'm rather new to JavaScript and programming in general so I am pretty much only used to seeing if statements that have some kind of comparison operator like, if (x < 10) or if(myBool).

I have seen an if statement checking against an event, but I don't understand what or why the event is being checked like that.  What's the semantic meaning behind that check or comparison?

Here is the code in question:

```<code>if(event){
    event.preventDefault();
}
</code>```

答:
Javascript has a feature called type coercion. There's a nice reference/tutorial for booleans here, so I'll not go into detail as to what gets type-coerced to what. A common shorthand for casting to a boolean from any type of myVariable is to boolean-negate it twice: !!myVariable.

Objects (which is what a javascript event usually is) evaluate to true if they're non-null and non-undefined. Empty objects (with length === 0) also evaluate to true.

Boolean operators short-circuit evaluation, meaning that it's common to shorthand one-line if-blocks like this:

```<code>event && event.preventDefault();
</code>```

Functions can also be type coerced into boolean trues. This is a valid piece of javascript:

```<code>if(event.preventDefault) { // Note if event is undefined this WILL throw an error
    event.preventDefault();
}
// or, avoiding the error
if(event && event.preventDefault) {
    event.preventDefault();
}
</code>```

The code snippet you posted can commonly be seen in event handlers, though it's usually unnecessary: an event propagator is probably breaking contract if it's passing an undefined event handle to the handler. (And if that is a valid contract, it's probably bad design)

Body:
Javascript has a feature called type coercion. There's a nice reference/tutorial for booleans here, so I'll not go into detail as to what gets type-coerced to what. A common shorthand for casting to a boolean from any type of myVariable is to boolean-negate it twice: !!myVariable.

Objects (which is what a javascript event usually is) evaluate to true if they're non-null and non-undefined. Empty objects (with length === 0) also evaluate to true.

Boolean operators short-circuit evaluation, meaning that it's common to shorthand one-line if-blocks like this:

event && event.preventDefault();

Functions can also be type coerced into boolean trues. This is a valid piece of javascript:

if(event.preventDefault) { // Note if event is undefined this WILL throw an error
    event.preventDefault();
}
// or, avoiding the error
if(event && event.preventDefault) {
    event.preventDefault();
}

The code snippet you posted can commonly be seen in event handlers, though it's usually unnecessary: an event propagator is probably breaking contract if it's passing an undefined event handle to the handler. (And if that is a valid contract, it's probably bad design)


答:
You are using Java - so make it beautiful ;-)

I would probably do this using Annotations:

Create a custom Method Annotation

```<code>@IRCCommand( String command, boolean perfectmatch = false )
</code>```

Add the Annotation to all relevant Methods in the Class e.g.

```<code>@IRCCommand( command = ".np", perfectmatch = true )
doNP( ... )
</code>```

In your constructor use Reflections to create an HashMap of Methods from all annotated Methods in your class:

```<code>...
for (Method m : getDeclaredMethods()) {
if ( isAnnotationPresent... ) {
    commandList.put(m.getAnnotation(...), m);
    ...
</code>```

In your onMessage Method, just do a loop over commandList trying to match the String on each one and calling method.invoke() where it fits.

```<code>for ( @IRCCommand a : commanMap.keyList() ) {
    if ( cmd.equalsIgnoreCase( a.command )
         || ( cmd.startsWith( a.command ) && !a.perfectMatch ) {
        commandMap.get( a ).invoke( this, cmd );
</code>```

Body:
You are using Java - so make it beautiful ;-)

I would probably do this using Annotations:

Create a custom Method Annotation

@IRCCommand( String command, boolean perfectmatch = false )

Add the Annotation to all relevant Methods in the Class e.g.

@IRCCommand( command = ".np", perfectmatch = true )
doNP( ... )

In your constructor use Reflections to create an HashMap of Methods from all annotated Methods in your class:

...
for (Method m : getDeclaredMethods()) {
if ( isAnnotationPresent... ) {
    commandList.put(m.getAnnotation(...), m);
    ...

In your onMessage Method, just do a loop over commandList trying to match the String on each one and calling method.invoke() where it fits.

for ( @IRCCommand a : commanMap.keyList() ) {
    if ( cmd.equalsIgnoreCase( a.command )
         || ( cmd.startsWith( a.command ) && !a.perfectMatch ) {
        commandMap.get( a ).invoke( this, cmd );


问:
Simplifying data search using .NET
An example on the asp.net site has an example of using Linq to create a search feature on a Music album site using MVC. The code looks like this -

```<code>public ActionResult Index(string movieGenre, string searchString)
{
    var GenreLst = new List<string>();

    var GenreQry = from d in db.Movies
                   orderby d.Genre
                   select d.Genre;

    GenreLst.AddRange(GenreQry.Distinct());
    ViewBag.movieGenre = new SelectList(GenreLst);

    var movies = from m in db.Movies
                 select m;

    if (!String.IsNullOrEmpty(searchString))
    {
        movies = movies.Where(s => s.Title.Contains(searchString));
    }

    if (!string.IsNullOrEmpty(movieGenre))
    {
        movies = movies.Where(x => x.Genre == movieGenre);
    }

    return View(movies);
}
</code>```

I have seen similar examples in other tutorials and I have tried them in a real-world business app that I develop/maintain. In practice this pattern doesn't seem to scale well because as the search criteria expands I keep adding more and more conditions which looks and feels unpleasant/repetitive. How can I refactor this pattern?

One idea I have is to create a column in every table that is "searchable" which could be a computed column that concatenates all the data from the different columns (SQL Server 2008). So instead of having movie genre and title it would be something like.

```<code>if (!String.IsNullOrEmpty(searchString))
{
    movies = movies.Where(s => s.SearchColumn.Contains(searchString));
}
</code>```

What are the performance/design/architecture implications of doing this?

I have also tried using procedures that use dynamic queries but then I have just moved the ugliness to the database. E.g.

```<code>CREATE PROCEDURE [dbo].[search_music]
    @title as varchar(50),
    @genre as varchar(50)
AS

-- set the variables to null if they are empty
IF @title = '' SET @title = null
IF @genre = '' SET @genre = null

SELECT m.*
FROM view_Music as m
WHERE
    (title = @title OR @title IS NULL)
    AND (genre LIKE '%' +  @genre + '%' OR @genre IS NULL)
ORDER BY Id desc
OPTION (RECOMPILE)
</code>```

Any suggestions? Tips?

答:
It sounds like you are looking for Full-text search.

After columns have been added to a full-text index, users and applications can run full-text queries on the text in the columns. These queries can search for any of the following:

One or more specific words or phrases (simple term)

Title: Simplifying data search using .NET


问:
Count unique visitors by group of visited places
I'm facing the problem of counting the unique visitors of groups of places.

Here is the situation:

I have visitors that can visit places. For example, that can be internet users visiting web pages, or customers going to restaurants. A visitor can visit as much places as he wishes, and a place can be visited by several visitors. A visitor can come to the same place several times.

The places belong to groups. A group can obviously contain several places, and places can belong to several groups.

Given that, for each visitor, we can have a list of visited places, how can I have the number of unique visitors per group of places?

Example: I have visitors A, B, C and D; and I have places x, y and z.

I have these visiting lists:

```<code>[
 A -> [x,x,y,x],
 B -> [],
 C -> [z,z],
 D -> [y,x,x,z]
]
</code>```

Having these number of unique visitors per place is quite easy:

```<code>[
 x -> 2, // A and D visited x
 y -> 2, // A and D visited y
 z -> 2  // C and D visited z
]
</code>```

But if I have these groups:

```<code>[
 G1 -> [x,y,z],
 G2 -> [x,z],
 G3 -> [x,y]
]
</code>```

How can I have this information?

```<code>[
 G1 -> 3, // A, C and D visited x or y or z
 G2 -> 3, // A, C and D visited x or z
 G3 -> 2  // A and D visited x or y
]
</code>```

Additional notes :

There are so many places that it is not possible to store information about every possible group;

It's not a problem if approximation are made. I don't need 100% precision. Having a fast algorithm that tells me that there were 12345 visits in a group instead of 12543 is better than a slow algorithm telling the exact number. Let's say there can be ~5% deviation.

I have a finite number of visitors and a finite number of places. I don't have so much places (approximately 60 for now, but it can grow to 200) but I have quite many visitors (estimated to 50 millions and this number could grow to 200 millions in the next months).

Is there an algorithm or class of algorithms that addresses this type of problem?

答:
As you point out, storing the number of visitors for each possible permutation would be a massive amount of data, or at least a table in your database with a massive number of records.

There's however really no way around it, you're going to have to store it, else how can you remember what the previous count was in order to increase it?

So what you do is you store only those permutations and their count where there actually have been visitors (My guess would be that that would be a lot less than the total possible number of permutations, for example if you're counting visitors to your store locations around the world, a lot of people will visit the few stores in their general area but never those on the other side of the world).

Find some way to encode the actual set uniquely (say as a hash of sorts), then use that as a key into a database table.

When you've determined the hash for a person, look up that hash in the visitor count table. If it exists, increase the count. If it doesn't exist, insert a new record with count = 1.

Another table can then hold that hash in relation to your locations, so you can retrieve the locations belonging to each hash for reporting purposes. Say a simple table [location_id, hash] where the combination is the primary key, both being themselves foreign keys into your locations table and counts table respectively. (and those records too ony inserted at the time you insert a new record into the counts table)

That means initial inserts are relatively slow, updates are as fast as they're going to get, and so is retrieval. Which, for a large potential set of data from which you're only going to be using a relatively small subset is the best you can hope for.


问:
How can my team avoid frequent errors after refactoring?
To give you a little background: I work for a company with roughly twelve Ruby on Rails developers (+/- interns). Remote work is common. Our product is made out of two parts: a rather fat core, and thin up to big customer projects built upon it. Customer projects usually expand the core. Overwriting of key features does not happen. I might add that the core has some rather bad parts that are in urgent need of refactorings. There are specs, but mostly for the customer projects. The worst part of the core are untested (not as it should be...).

The developers are split into two teams, working with one or two PO for each sprint. Usually, one customer project is strictly associated with one of the teams and POs.

Now our problem: Rather frequently, we break each other's stuff. Someone from Team A expands or refactors the core feature Y, causing unexpected errors for one of Team B's customer projects. Mostly, the changes are not announced over the teams, so the bugs hit almost always unexpected.  Team B, including the PO, thought about feature Y to be stable and did not test it before releasing, unaware of the changes.

How to get rid of those problems? What kind of 'announcement technique' can you recommend me?

答:
"Mostly, the changes are not announced over the teams, so the bugs hit almost always unexpected"

Communications problem anyone? What about (in addition to what everyone else has already pointed out, that you should be rigorous testing) making sure that there is proper communication? That people are made aware that the interface they're writing to is going to change in the next release and what those changes will be?

And give them access to at least a dummy interace (with empty implementation) as soon as possible during development so they can start writing their own code.

Without all that, unit tests won't do much except point out during the final stages that there's something out of whack between parts of the system. You want to know that, but you want to know it early, very early, and having the teams talk to each other, coordinate efforts, and actually have frequent access to the work the other team is doing (so regular commits, not one massive commit after several weeks or months, 1-2 days before delivery).

Your bug is NOT in the code, certainly not in the code of the other team that didn't know you were messing around with the interface they're writing against. Your bug is in your development process, the lack of communication and collaboration between people. Just because you're sitting in different rooms doesn't mean you should isolate yourselves from the other guys.


问:
Should XmlDocument.xml be Included in Source Control
In a Web API 2 project, in the project properties, I have enabled the output of an XML documentation file.

By default, Visual Studio 2013 wants to check this into TFS.  I'm pretty sure that I'm going to exclude it, but wondered what the general opinion is on this?

答:
If a file 'X' can be thrown away and always completely re-generated from files that are in source control, then the general rule is that file 'X' should not be placed in source control.

The main exceptions to this rule are:

There are rare scenarios where the file needs to be edited manually and those edits need to be preserved.

If generating the file is time consuming or otherwise costly/inconvenient and the file is expected to change only rarely. In this case can it be beneficial to put the file under source control anyway to speed up the build process.


答:
What I would do is this:

Group the commands you have into groups. (you have at least 20 right now)

At first level, categorize by group, so you have user name related command, song commands, count commands, etc.

Then you go in each group's method, this time you will get the original command.

This will make this more manageable. More benefit when the number of 'else if' grows too much.

Of course, sometimes having these 'if else' wouldn't be a big problem.
I don't think 20 is that bad.


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

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

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

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

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

答:
One approach might be to split your codebase into two parts (e.g., by extracting a library, engine, module, whatever) and publish only one part as open source.

By this you would make it harder to copy the whole game, while at the same time interested people could look up how certain things work.

Title: Sharing source code of my online game?


问:
MVC data binding
I'm using MVC but I've read that MVVM is sort of about data binding and having pure markup in your views that data bind back to the backend via the data-* attributes. I've looked at knockout but it looks pretty low level and I feel like I can make a library that does this and is much easier to use where basically you only need to call 1 javascript function that will data bind your entire page because of the data-* attributes you assign to html elements.

The benefits of this (that I see) is that your view is 100% decoupled from your back-end so that a given view never has to be changed if your back-end changes (ie for asp.net people no more razor in your view that makes your view specific to MS).

My question would be, I know there is knockout out there but are there any others that provide this data binding functionality for MVC type applications? I don't want to recreate something that may already exist but I want to make something "better" and easier to use than knockout.

To give an example of what I mean here is all the code one would need to get data binding in my library. This isn't final but just showing the idea that all you have to do is call 1 javascript function and set some data-* attribute values and everything ties together. Is this worth seeing through?

```<code>    <script>
        $(function () {

            // this is all you have to call to make databinding for POST or GET to work
            DataBind();
        });
    </script>

<form id="addCustomer" data-bind="Customer" data-controller="Home" data-action="CreateCustomer">
    Name: <input type="text" data-bind="Name" data-bind-type="text" />
    Birthday: <input type="text" data-bind="Birthday" data-bind-type="text" />
    Address: <input type="text" data-bind="Address" data-bind-type="text" />
    <input type="submit" value="Save" id="btnSave" />
</form>

=================================================

// controller action
[HttpPost]
        public string CreateCustomer(Customer customer)
        {
            if(customer.Name == "Rick")
                return "success";

            return "failure";
        }

// model
public class Customer
    {
        public string Name { get; set; }
        public DateTime Birthday { get; set; }
        public string Address { get; set; }
    }
</code>```

答:
Check out TodoMVC. There you'll find a few dozens of modern JS frameworks with an easy to evaluate code sample.

Picking any of them should be far easier than rolling your own solution. I know the temptation is great. Been there, done that. But on your own you cannot beat thousands of man-hours that went into developing a solid framework.

Title: MVC data binding


答:
JavaScript has the concept of "truthy" and "falsy" values.

The following values are falsey:

false

null

undefined

0

NaN

'' (empty string)

All other values are truthy.

When a variable is cast to a boolean its "truthiness" is checked. When evaluated in an if statement, or any of ?:, ||, and &&, the variable is automatically cast to a boolean for the purposes of the check (the variable itself isn't changed).

What this means is that:

```<code>if (event) {
</code>```

is essentially treated as:

```<code>if (Boolean(event)) {
</code>```

This sort of check is often used to verify that a variable exists before using methods on it. In this case it prevents a null reference error on undefined variables.

Note: Truthiness is not the same as checking a variable against true or false.

I.E.

```<code>if (foo) {
</code>```

is not the same as

```<code>if (foo == true) {
</code>```

A simple example of where this fails is when comparing against an object:

```<code>var foo = {};
if (foo) {
    console.log('this works!');
}
if (foo == true) {
    console.log('this doesn\'t work!');
}
</code>```

Title: What if(event) statement means in JavaScript?

Body:
I'm rather new to JavaScript and programming in general so I am pretty much only used to seeing if statements that have some kind of comparison operator like, if (x < 10) or if(myBool).

I have seen an if statement checking against an event, but I don't understand what or why the event is being checked like that.  What's the semantic meaning behind that check or comparison?

Here is the code in question:

```<code>if(event){
    event.preventDefault();
}
</code>```

Body:
JavaScript has the concept of "truthy" and "falsy" values.

The following values are falsey:

false

null

undefined

0

NaN

'' (empty string)

All other values are truthy.

When a variable is cast to a boolean its "truthiness" is checked. When evaluated in an if statement, or any of ?:, ||, and &&, the variable is automatically cast to a boolean for the purposes of the check (the variable itself isn't changed).

What this means is that:

if (event) {

is essentially treated as:

if (Boolean(event)) {

This sort of check is often used to verify that a variable exists before using methods on it. In this case it prevents a null reference error on undefined variables.

Note: Truthiness is not the same as checking a variable against true or false.

I.E.

if (foo) {

is not the same as

if (foo == true) {

A simple example of where this fails is when comparing against an object:

var foo = {};
if (foo) {
    console.log('this works!');
}
if (foo == true) {
    console.log('this doesn\'t work!');
}


问:
Public versus private inheritance when some of the parent's methods need to be exposed?
Public inheritance means that all fields from the base class retain their declared visibility, while private means that they are forced to 'private' within the derived class's scope.

What should be done if some of the parent's members (say, methods) need to be publicly exposed?

I can think of two solution. Public inheritance somewhat breaks encapsulation. Furthermore, when you need to find out where is the method foo() defined, one needs to look at a chain of base classes.

Private inheritance solves these problems, but introduces burden to write wrappers (more text). Which might be a good thing in the line of verbosity, but makes changes of interfaces incredibly cumbersome.

What considerations am I missing? What constraints on the type of project are important? How to choose between the two (I am not even mentioning 'protected')?

Note that I am targeting non-virtual methods. There isn't such a discussion for virtual methods (or is there).

答:
You can expose items that would otherwise have some kind of restricted access (i.e., private or protected) without writing a wrapper function by using the using directive:

```<code>class base {
public:
    base();
    virtual ~base();
    void do_something();
    void do_something_else();
private:
    // elided
};

class derived : private base {
public:
    derived();
    virtual ~derived();
    using base::do_something();
};
</code>```

In the above, the derived class exposes base::do_something() as a public method, but not base::do_something_else().

Body:
You can expose items that would otherwise have some kind of restricted access (i.e., private or protected) without writing a wrapper function by using the using directive:

class base {
public:
    base();
    virtual ~base();
    void do_something();
    void do_something_else();
private:
    // elided
};

class derived : private base {
public:
    derived();
    virtual ~derived();
    using base::do_something();
};

In the above, the derived class exposes base::do_something() as a public method, but not base::do_something_else().


问:
Genetic Algorithm new generation exponentially increasing
I'm programming Genetic Algorithm in C++ and after searching all kind of ways of doing GA'a operators (selection, crossover, mutation) I came up with a doubt.

Let's say I have an initial population of 500. My selection will consist in getting the top 20% of 500(based on best fitness). So I get 100 individuals to mate. When I do the crossover I'll get 2 children where both together have 50% of surviving. So far so good. I start the mutation, and everything's ok.. Now when I start choosing the Next generation, I see that I have a big number of children (in this case, 4950 if you wanna know). Now the thing is, every time I run GA, if I send all the children to the next generation, the number of individuals per generation will increase exponentially.

So there must be a way of choosing the children to fulfill a new generation without getting out of this range of the initial population.

What I'm asking here is if there is anyway of choosing the children to fill the new generations OR should I choose somehow (and maybe reduce) the parents to mate so I don't get so many children in the end.

答:
Before I answer your question I have to ask you.
When you run your GA, did you actually see a gain in your solution?
In other words, after each iteration the new generations that you have are actually better than the previous ones?

If you do, then I am shockingly surprised because

As Mushy have pointed out very correctly: your GA is just a sugarcoating of simulated annealing (or Monte Carlo)

As entropy increases because you just mix-and-match, the search space to be explored will keep increasing. And as we are well know, after a few generations, your solutions will degenerate, the only two things that I can see keep that from happening are that

(a) you have a set of rules on any or the operations you have..
cross-over, selection, mutation, or others if you are creative
enough..

(b) divine intervention, you stick your human hands in and
intervene at some or all of the iterations (done through some added
heuristic in fitness function, or you can have at iteration 1 do this, 2 do that, ...)

Disclaimer: I am no expert in this area, but even people like me know you have to put heuristic in there somewhere.


问:
How do I find the JavaScript that is invoked when I click on a button or a link in a web-page (part of a data mining project)?
I tried to use the 'inspect element' of the firebug addon for Firefox but it doesn't give me any link to the javascript.

For example I got this from the firebug add-on:

    text of the link

```

But there is no link to the actual javascript or anything that I can use to directly go to the said link.

How do I accomplish this? I need this as part of a personal data mining project that I am doing.

答:
I would recommend using Chrome for this.  The inspect and debugging tools allow you to view the js source files along with the html and css.

Steps:
Right click on the element in question in Google Chrome. Click inspect element which is the last item in the menu. The developer menu will popup in the bottom of the screen. The html for the selected element that you right clicked on will be highlighted. From here you can click the "Event Listeners" tab located in the far right panel of the developers menu. Choose your selected listener and it will show you the associated javascript file. Hope this helps!


问:
Branching strategy for frequent releases
We have very frequent releases and we use Git for version control. When i am mentioning about frequency, please assume it to include bug-fixes and feature release too. All releases are eventually merged into ‘mainline’. When a release is deployed on production and if a bug is identified, people start fixing the bug on the same branch from which the latest release was deployed on production. They do not create a new bug-fix branch for the same. I feel that’s not the right way to go for. There are several components and each component has a different owner, and thus, different perspective. Though I have not initiated talks with them, I am sure there will be a lot of resistance. Main issue that they might cite would be, “There’s a lot of work involved in creating and tracking branches especially when there are so frequent deployments on production. This will consume a lot of dev effort.”

Do you think that fixing bug on the same branch from which release was done, a good idea? If yes, how do you manage it? Using tags?

I know that best practices may not always be applicable due to several factors but still I would like to know what might be a good approach for branching in a scenario where releases/bug-fixes happen almost on a daily basis.

Edit: Thanks everyone for sharing your views and for the useful links. I think the main concern i have here is this: Do you think that fixing bug on the same branch from which release was done, a good idea? Is this approach fine in the long run or are we messing up things just to realize it later?

答:
Reintegrating several times a day into the mainline is a fully valid strategy - it has indeed a name, it is called continuous integration. If this is a good strategy for your team or not depends mainly on how well your automatic tools for quality assurance are, and if your team is used to deliver "baby steps". To apply CI with sucess, you should have an automatic build server running, a lot of automatic unit and integration test and ideally something like a (semi)automatic way of deploying (which includes versioning and tagging).

If that's not the case, it is probably better to apply a more conservative model and to work with different branches, giving you the chance of collecting features and bug fixes in separate places before the final decision is made if the a specific change will be integrated into the mainline (or not).

It is of course possible to combine these strategies. For example, let the CI server deal with the mainline, from which your software is delivered. Develop every "new feature" in a development branch or separate feature branches. The latter are reintegrated into the mainline when they have reached a certain quality. Urgent bugfixes go directly into the mainline (and soon delivered from there) - because they are urgent. The feature branches prevent your team of bringing half-baked features into the mainline (and so unintentionally into production because of an urgent bug-fix delivery). Changes from the mainline should be at least once a day be reintegrated into all feature branches.

Other, more sophisticated models are possible, depending on the number of stakeholders involved (for example, do you have a QA team? How do they work? Which state of the software will they test?). What you have to do is to think about your environment and which model suits you best - what goals you have, what problems you see with the current model, and what you want to improve.


问:
Software architecture for two similar classes which require different input parameters for the same method
I am writing Java code to simulate a supply chain.
The supply chain can be simulated in either
an intermediate stocking or a cross-docking configuration.
So, I wrote two simulator objects IstockSimulator and XdockSimulator.
Since the two objects share certain behaviors
(e.g. making shipments, demand arriving),
I wrote an abstract simulator object AbstractSimulator
which is a parent class of the two simulator objects.

The abstract simulator object has a method runSimulation()
which takes an input parameter of class SimulationParameters.
Up till now, the simulation parameters only contains fields
that are common to both simulator objects,
such as randomSeed, simulationStartPeriod and simulationEndPeriod.
However, I now want to include fields that are specific to the type of simulation that is being run,
i.e. an IstockSimulationParameters class for an intermediate stocking simulation,
and a XdockSimulationParameters class for a cross-docking simulation.

My current idea is take the method runSimulation()
out of the AbstractSimulator class,
but to put a runSimulation(IstockSimulationParameters) method
in the IstockSimulator class,
and a runSimulation(XdockSimulationParameters) method
in the IstockSimulator class.
I am worried however, that this approach will lead to code duplication.

What should I do?

Edited

Currently, the AbstractSimulator class defines the runSimulation method
which calls other abstract methods
that are only defined by the concrete child classes.

```<code>public abstract class AbstractSimulator {
    public void runSimulation(SimulationParameters params) {
        int startPeriod = params.startPeriod;
        int endPeriod = params.endPeriod;
        for (int t = startPeriod; t < endPeriod; ++t) {
            submitReports(t);
            makeShipments(t);
            demandArrives(t);
        }
    }
    protected abstract void submitReports(int t);
    protected abstract void makeShipments(int t);
}
</code>```

One of the differences between the IstockSimulator and the XdockSimulator
is that in an intermediate stocking configuration,
tier 3 facilities submit reports to tier 2 facilities,
while in a cross-docking configuration,
tier 3 facilities submit reports to tier 1 facilities.
Thus the IstockSimulator and the XdockSimulator
have their own implementations of the methods submitReports and makeShipments.

What worked for me

Thank you for your answers.
Inspired by your answers, and after sleeping it over,
I came up with my own answer based on refactoring.
See below.

答:
Inspired by your answers,
and after sleeping it over,
I came up with a different and elegant solution
which involves refactoring the code.

I define a class SupplyChain which contains
information about the supply chain topology, the lead times for shipments, etc.
I define two different simulator classes IstockSimulator and XdockSimulator.
The replenishment policy and the simulation parameters (initial conditions)
are given to the IstockSimulator at the time of its creation.
Similarly for the XdockSimulator.
Thus there is only one runSimulation method
that takes in an input parameter of SimulationParameters.

This is what it looks like in Java code.

```<code>SupplyChain supplyChain = // create new supply chain
SimulationParameters simulationParameters = // define simulation parameters
IstockSimulator isim = new IstockSimulator(supplyChain,
    istockPolicies, istockInitialConditions);
isim.runSimulation(simulationParameters);
XdockSimulator xsim = new XdockSimulator(supplyChain,
    xdockPolicies, xdockInitialConditions);
xsim.runSimulation(simulationParameters);
</code>```

Body:
Inspired by your answers,
and after sleeping it over,
I came up with a different and elegant solution
which involves refactoring the code.

I define a class SupplyChain which contains
information about the supply chain topology, the lead times for shipments, etc.
I define two different simulator classes IstockSimulator and XdockSimulator.
The replenishment policy and the simulation parameters (initial conditions)
are given to the IstockSimulator at the time of its creation.
Similarly for the XdockSimulator.
Thus there is only one runSimulation method
that takes in an input parameter of SimulationParameters.

This is what it looks like in Java code.

SupplyChain supplyChain = // create new supply chain
SimulationParameters simulationParameters = // define simulation parameters
IstockSimulator isim = new IstockSimulator(supplyChain,
    istockPolicies, istockInitialConditions);
isim.runSimulation(simulationParameters);
XdockSimulator xsim = new XdockSimulator(supplyChain,
    xdockPolicies, xdockInitialConditions);
xsim.runSimulation(simulationParameters);


问:
Best practices when creating/modeling databases?
I learned at the University some steps to model a database:

Model the problem using the Extended Entity-Relationship Model.

Extract the functional dependencies

Apply some algorithms to normalize the database (3NF or Boyce-Codd)

Create the database

I'm studying Computer Science and since I received that course I'm wondering if I always need to do those steps when creating a complex database for an specified problem.

For example, do PHP / .NET / .. programmers always do that? or there are some tools to simplify that process, maybe using another way of represent the problem instead of the EERM?

答:
It depends on your skill set. If you are a database administrator then you might follow the steps that you described because in this case you want to reduce the cost of queries and maintain/improve data integrity.

However, if you're a developer you probably want your application to compile/build/run as a priority and abstract your storage mechanism using an Object Relational Model (ORM) in which case you will think of your persistence more in terms of object relations than entity relations. So you would

Choose your application stack

Code your object functions and properties

Perform some action on objects including updating properties

Save objects to storage

ContentLicense: CC BY-SA 2.5


问:
Design Patterns for Javascript
A lot of web frameworks have a MVC-style layout to code and approaching problems. What are some good similar paradigms for JavaScript? I'm already using a framework (jQuery) and unobtrusive js, but that still doesn't address the problem I run into when I have more complex web apps that require a lot of javascript, I tend to just end up with a bunch of functions in a single, or possibly a few files. What's a better way to approach this?</p>

答:
Using jQuery is a great start. JavaScript in a browser augments the frontend, there isn't a MVC "pattern" or anything to follow. There are some "best practices" that help keep the code clean.

Separate functions for separate things. Bindings in one, actions in another. Make use of this as well as classes for actions.

Remember that JavaScript allows a great deal of flexibility, passing closures around as they are created can help simplify your bindings and lighten the code.

Shield from the global scope, only expose what is necessary.

Use JSLint to keep your code up to standards.

For server side / non-browser JavaScript (like Node.js) there are several great frameworks for building off of. It might be worth while browsing through the source to see if you pick up on any thing.

I moved this to a more in-depth entry for the interested.

Title: Design Patterns for Javascript


问:
Memory read/write access efficiency
I've heard conflicting information from different sources, and I'm not really sure which one to believe. As such, I'll post what I understand and ask for corrections. Let's say I want to use a 2D matrix. There are three ways that I can do this (at least that I know of).

1:

```<code>int i;
char **matrix;
matrix = malloc(50 * sizeof(char *));
for(i = 0; i < 50; i++)
    matrix[i] = malloc(50);
</code>```

2:

```<code>int i;
int rowSize = 50;
int pointerSize = 50 * sizeof(char *);
int dataSize = 50 * 50;
char **matrix;
matrix = malloc(dataSize + pointerSize);
char *pData = matrix + pointerSize - rowSize;
for(i = 0; i < 50; i++) {
    pData += rowSize;
    matrix[i] = pData;
}
</code>```

3:

```<code>//instead of accessing matrix[i][j] here, we would access matrix[i * 50 + j]
char *matrix = malloc(50 * 50);
</code>```

In terms of memory usage, my understanding is that 3 is the most efficient, 2 is next, and 1 is least efficient, for the reasons below:

3: There is only one pointer and one allocation, and therefore, minimal overhead.

2: Once again, there is only one allocation, but there are now 51 pointers. This means there is 50 * sizeof(char *) more overhead.

1: There are 51 allocations and 51 pointers, causing the most overhead of all options.

In terms of performance, once again my understanding is that 3 is the most efficient, 2 is next, and 1 is least efficient. Reasons being:

3: Only one memory access is needed. We will have to do a multiplication and an addition as opposed to two additions (as in the case of a pointer to a pointer), but memory access is slow enough that this doesn't matter.

2: We need two memory accesses; once to get a char *, and then to the appropriate char. Only two additions are performed here (once to get to the correct char * pointer from the original memory location, and once to get to the correct char variable from wherever the char * points to), so multiplication (which is slower than addition) is not required. However, on modern CPUs, multiplication is faster than memory access, so this point is moot.

1: Same issues as 2, but now the memory isn't contiguous. This causes cache misses and extra page table lookups, making it the least efficient of the lot.

First and foremost: Is this correct? Second: Is there an option 4 that I am missing that would be even more efficient?

答:
I assume that you mean the HPC environment as indicated in comment. I assume you mean also that matrix is large. As general rules

In most cases you can preallocate the data at the beginning anyway so the cost of the overhead is minimal - why bother with ms timing when your program is running for days/hours anyway running over and over this array?

In most cases you allocate large amount of data - malloc overhead for such data is minimal - why bother with few kB of overhead when you deal with GB of data

In most cases programmers are bad at timings. So the rule is to benchmark as much as possible to get the real times and overheads (though there are a few papers on modelling HPC systems you might want to read - models are extremely useful too and can be relatively simple for memory bound problems)

Regarding the specified example - it largely depend on how you access the data. In many cases you want to co-design the data structure for specific algorithm and for specific platform. In most cases you want to exploit memory hierarchy (from slowest to fastest: network, disk, main memory, cache, registers) as much as possible which means that you want to use spatial and temporal locality. Not getting into details it means that you want to:

Access data that is near data you already accessed (spatial locality)

Reuse data you already accessed (temporal locality)

That depends on your algorithm - you might for example use space filling curve if you perform cellar automata or stencil like operations (for example Z curve). The exact details depend on your platform (cache associativity, streaming auto detection etc.).

Properly exploiting it can have a dramatic speedup just when tweaked in simple way. For example matrix multiplication simply reordering loops can give speedup of several orders of magnitude (try reorder loops yourself, bonus question - if you change a size so you do not align with cache line what happens?):

```<code>const size_t size = 4096;
double (*a)[size] = malloc(sizeof(double [size]));
double (*b)[size] = malloc(sizeof(double [size]));
double (*c)[size] = malloc(sizeof(double [size]));
for (int i = 0; i < size; i++) {
    for (int j = 0; j < size; j++) {
        c[i][j] = 0;
        for (int k = 0; k < size; k++) {
            c[i][j] += a[i][k] * b[k][j];
        }
    }
}
</code>```

Then you can further employ such techniques as loop tiling etc. Please also note that when you parallelize the code you need to avoid such things like false sharing i.e. two threads accessing data on same cache line will cause it to be sent back and forth between processors, which is slow (for Core i3/i5/i7 architecture, at least the newer ones, it downgrades the access to memory to L3 cache speed IIRC).

For more complex structure then double you also need to consider AOS vs SOA structure. The first one is 'normal' C/C++ array of structures and it's good if you can exploit cache locality - when you access first element the rest is likely to be in cache too. The second one keeps each field of structure in separate array - while it has cost of worse cache locality it improves the vectorization/SPMD as the loading of single field happens in single step and improves streaming.

The good news is that for some cases, like linear operations, there are well-know libraries/APIs, such as BLAS.

Bottom line is that probably variation of option 3 is the best way. Depending on your operations you may want to pad the data to full cache line or order a data in clever way. However probably you might want to just use BLAS library from your HPC vendor if all you do is the linear operations.

Option 2-like operation are probably employed mostly when you have unstructured access.

Title: Memory read/write access efficiency

Body:
I assume that you mean the HPC environment as indicated in comment. I assume you mean also that matrix is large. As general rules

In most cases you can preallocate the data at the beginning anyway so the cost of the overhead is minimal - why bother with ms timing when your program is running for days/hours anyway running over and over this array?

In most cases you allocate large amount of data - malloc overhead for such data is minimal - why bother with few kB of overhead when you deal with GB of data

In most cases programmers are bad at timings. So the rule is to benchmark as much as possible to get the real times and overheads (though there are a few papers on modelling HPC systems you might want to read - models are extremely useful too and can be relatively simple for memory bound problems)

Regarding the specified example - it largely depend on how you access the data. In many cases you want to co-design the data structure for specific algorithm and for specific platform. In most cases you want to exploit memory hierarchy (from slowest to fastest: network, disk, main memory, cache, registers) as much as possible which means that you want to use spatial and temporal locality. Not getting into details it means that you want to:

Access data that is near data you already accessed (spatial locality)

Reuse data you already accessed (temporal locality)

That depends on your algorithm - you might for example use space filling curve if you perform cellar automata or stencil like operations (for example Z curve). The exact details depend on your platform (cache associativity, streaming auto detection etc.).

Properly exploiting it can have a dramatic speedup just when tweaked in simple way. For example matrix multiplication simply reordering loops can give speedup of several orders of magnitude (try reorder loops yourself, bonus question - if you change a size so you do not align with cache line what happens?):

const size_t size = 4096;
double (*a)[size] = malloc(sizeof(double [size]));
double (*b)[size] = malloc(sizeof(double [size]));
double (*c)[size] = malloc(sizeof(double [size]));
for (int i = 0; i < size; i++) {
    for (int j = 0; j < size; j++) {
        c[i][j] = 0;
        for (int k = 0; k < size; k++) {
            c[i][j] += a[i][k] * b[k][j];
        }
    }
}

Then you can further employ such techniques as loop tiling etc. Please also note that when you parallelize the code you need to avoid such things like false sharing i.e. two threads accessing data on same cache line will cause it to be sent back and forth between processors, which is slow (for Core i3/i5/i7 architecture, at least the newer ones, it downgrades the access to memory to L3 cache speed IIRC).

For more complex structure then double you also need to consider AOS vs SOA structure. The first one is 'normal' C/C++ array of structures and it's good if you can exploit cache locality - when you access first element the rest is likely to be in cache too. The second one keeps each field of structure in separate array - while it has cost of worse cache locality it improves the vectorization/SPMD as the loading of single field happens in single step and improves streaming.

The good news is that for some cases, like linear operations, there are well-know libraries/APIs, such as BLAS.

Bottom line is that probably variation of option 3 is the best way. Depending on your operations you may want to pad the data to full cache line or order a data in clever way. However probably you might want to just use BLAS library from your HPC vendor if all you do is the linear operations.

Option 2-like operation are probably employed mostly when you have unstructured access.


问:
Do you do custom tests/work for a potential employer before the interview?
Every shop I've worked at we have followed what I thought was a standard hiring sequence:

Solicit resumes

Phone screen applicants we are interested in

In-person interview

In some shops, second in-person interview (just w/ CEO for example)

Most places I apply to follow something along these lines. But some shops want to give me a test or ask me to build something after I send in my resume. They usually say "congratulations, you've made it to stage 2 of our hiring process!" But for all I know they are asking every applicant they get a resume from to do the same thing.

This annoys me because it doesn't scale. If I'm applying for a lot of positions I can't spend all my time doing work that potentially can only land me one job. Plus there's no shared dedication to the process. If we do a 45 minute phone screen, that's 45 minutes the company commits to me and 45 minutes I commit to the company in hopes of a potential match.

Do you guys have a policy regarding these sorts of things?

答:
We ask all potential employees to write a simple class library and unit test before the in-person or phone interview. We give most people who hand in a CV this test, but we couch this as a "we would like to interview you -- before you arrive, please do this coding assignment and send it to xxxx". Some notes:

I would expect the test we give to be under an hour's work to accomplish.

We do review the code in depth -- make sure it compiles, make sure the unit tests test what they are suppose to test, check for obvious performance issues, etc. I dare say that we spend almost as much time reviewing each test as the applicant does writing it.

It gives us something to talk about during the interview process. We ask questions why they did things one way or another, ask about unit tests, etc. Because we give the applicant our requirements, this also allows us to keep track of how he/she handles vague requirements (you'd be surprised on the number of people who assume the same time zone when handling time comparisons).

You'd be surprised on the number of applicants that simply cannot code. Yes, we're probably filtering out a few employees that would work out. But, I would not give a hire/no-hire decision without seeing actual code the applicant has written.

I don't trust what is on the applicant's CV. However, I don't trust what they hand in either. Frankly, the assignment can be Google'd and copied from the web. Whether or not we hire is based on a mix of how they answer questions, their prior experience based on their CV, and how they do on the assignment.

When I apply for a new job, I would not be put off by a test if it is obviously to see how I code and if the code is reviewed during the interview.


问:
Reconciling the Boy Scout Rule and Opportunistic Refactoring with code reviews
I am a great believer in the Boy Scout Rule:

Always check a module in cleaner than when you checked it out." No
  matter who the original author was, what if we always made some
  effort, no matter how small, to improve the module. What would be the
  result? I think if we all followed that simple rule, we'd see the end
  of the relentless deterioration of our software systems. Instead, our
  systems would gradually get better and better as they evolved. We'd
  also see teams caring for the system as a whole, rather than just
  individuals caring for their own small little part.

I am also a great believer in the related idea of Opportunistic Refactoring:

Although there are places for some scheduled refactoring efforts, I
  prefer to encourage refactoring as an opportunistic activity, done
  whenever and wherever code needs to cleaned up - by whoever.
  What this means is that at any time someone sees some code that isn't
  as clear as it should be, they should take the opportunity to fix it
  right there and then - or at least within a few minutes

Particularly note the following excerpt from the refactoring article:

I'm wary of any development practices that cause friction for
  opportunistic refactoring ... My sense is that most teams don't do
  enough refactoring, so it's important to pay attention to anything
  that is discouraging people from doing it. To help flush this out be
  aware of any time you feel discouraged from doing a small refactoring,
  one that you're sure will only take a minute or two. Any such barrier
  is a smell that should prompt a conversation. So make a note of the
  discouragement and bring it up with the team. At the very least it
  should be discussed during your next retrospective.

Where I work, there is one development practice that causes heavy friction - Code Review (CR). Whenever I change anything that's not in the scope of my "assignment" I'm being rebuked by my reviewers that I'm making the change harder to review. This is especially true when refactoring is involved, since it makes "line by line" diff comparison difficult. This approach is the standard here, which means opportunistic refactoring is seldom done, and only "planned" refactoring (which is usually too little, too late) takes place, if at all.

I claim that the benefits are worth it, and that 3 reviewers will work a little harder (to actually understand the code before and after, rather than look at the narrow scope of which lines changed - the review itself would be better due to that alone) so that the next 100 developers reading and maintaining the code will benefit. When I present this argument my reviewers, they say they have no problem with my refactoring, as long as it's not in the same CR. However I claim this is a myth:

(1) Most of the times you only realize what and how you want to refactor when you're in the midst of your assignment. As Martin Fowler puts it:

As you add the functionality, you realize that some code you're adding
  contains some duplication with some existing code, so you need to
  refactor the existing code to clean things up... You may get something
  working, but realize that it would be better if the interaction with
  existing classes was changed. Take that opportunity to do that before
  you consider yourself done.

(2) Nobody is going to look favorably at you releasing "refactoring" CRs you were not supposed to do. A CR has a certain overhead and your manager doesn't want you to "waste your time" on refactoring. When it's bundled with the change you're supposed to do, this issue is minimized.

The issue is exacerbated by Resharper, as each new file I add to the change (and I can't know in advance exactly which files would end up changed) is usually littered with errors and suggestions - most of which are spot on and totally deserve fixing.

The end result is that I see horrible code, and I just leave it there. Ironically, I feel that fixing such code not only will not improve my standings, but actually lower them and paint me as the "unfocused" guy who wastes time fixing things nobody cares about instead of doing his job. I feel bad about it because I truly despise bad code and can't stand watching it, let alone call it from my methods!

Any thoughts on how I can remedy this situation ?

答:
I can remember 25 years or so ago "cleaning up" code that I happened to be working on for other purposes, mostly by reformatting comment blocks and tabbing/column alignments to make the code neat and therefore easier to understand (no actual functional changes). I happen to like code that's neat and well-ordered. Well, the senior developers were furious. It turns out they used some sort of file compare (diff) to see what had changed, compared to their personal copies of the file, and now it was giving all sorts of false positives. I should mention that our code library was on a mainframe and had no version control -- you basically overwrote whatever was there, and that was it.

The moral of the story? I dunno. I guess it's that sometimes you can't please anyone except yourself. I wasn't wasting time (in my eyes) -- the cleaned up code was easier to read and understand. It's just that the primitive change control tools used by others put some extra one-shot work on them. The tools were too primitive to ignore space/tabbing and reflowed comments.


答:
While every system needs effective test suites (which means, among other things, automation), and while these tests, if used effectively, will catch these conflicts sooner than they are now, this does not address the underlying problems.

The question reveals at least two underlying problems: the practice of modifying the 'core' in order to satisfy requirements for individual customers, and the failure of the teams to communicate and coordinate their intent to make changes. Neither of these are root causes, and you will need to understand why this is being done before you can fix it.

One of the first things to be determined is whether both the developers and the managers realize there is a problem here. If at least some do, then you need to find out why they either think they cannot do anything about it, or choose not to. For those who do not, you might try to increase their ability to anticipate how their current actions may create future problems, or replace them with people who can. Until you have a workforce that is aware of how things are going wrong, you are unlikely to be able to fix the problem (and perhaps not even then, at least in the short term.)

It may be difficult to analyze the problem in abstract terms, at least initially, so focus on a specific incident that resulted in a problem, and try to determine how it happened. As the people involved are likely to be defensive, you will need to be alert for self-serving and post-hoc justifications in order to find out what is really happening.

There is one possibility that I hesitate to mention because it is so unlikely: the customers' requirements are so disparate that there is insufficient commonality to justify shared core code. If this is so, then you actually have multiple separate products, and you should manage them as such, and not create an artificial coupling between them.

Title: How can my team avoid frequent errors after refactoring?

Body:
To give you a little background: I work for a company with roughly twelve Ruby on Rails developers (+/- interns). Remote work is common. Our product is made out of two parts: a rather fat core, and thin up to big customer projects built upon it. Customer projects usually expand the core. Overwriting of key features does not happen. I might add that the core has some rather bad parts that are in urgent need of refactorings. There are specs, but mostly for the customer projects. The worst part of the core are untested (not as it should be...).

The developers are split into two teams, working with one or two PO for each sprint. Usually, one customer project is strictly associated with one of the teams and POs.

Now our problem: Rather frequently, we break each other's stuff. Someone from Team A expands or refactors the core feature Y, causing unexpected errors for one of Team B's customer projects. Mostly, the changes are not announced over the teams, so the bugs hit almost always unexpected.  Team B, including the PO, thought about feature Y to be stable and did not test it before releasing, unaware of the changes.

How to get rid of those problems? What kind of 'announcement technique' can you recommend me?


问:
Type casting variables in PHP, what is the practical reason for doing this?
PHP, as most of us know, has weak typing.  For those who don't, PHP.net says:

PHP does not require (or support) explicit type definition in variable declaration; a variable's type is determined by the context in which the variable is used.

Love it or hate it, PHP re-casts variables on-the-fly.  So, the following code is valid:

```<code>$var = "10";
$value = 10 + $var;
var_dump($value); // int(20)
</code>```

PHP also allows you to explicitly cast a variable, like so:

```<code>$var = "10";
$value = 10 + $var;
$value = (string)$value;
var_dump($value); // string(2) "20"
</code>```

That's all cool...  but, for the life of me, I cannot conceive of a practical reason for doing this.

I don't have a problem with strong typing in languages that support it, like Java.  That's fine, and I completely understand it.  Also, I'm aware of - and fully understand the usefulness of - type hinting in function parameters.

The problem I have with type casting is explained by the above quote.  If PHP can swap types at-will, it can do so even after you force cast a type; and it can do so on-the-fly when you need a certain type in an operation.  That makes the following valid:

```<code>$var = "10";
$value = (int)$var;
$value = $value . ' TaDa!';
var_dump($value); // string(8) "10 TaDa!"
</code>```

So what's the point?

Take this theoretical example of a world where user-defined type casting makes sense in PHP:

You force cast variable $foo as int → (int)$foo.

You attempt to store a string value in the variable $foo.

PHP throws an exception!! ← That would make sense.  Suddenly the reason for user defined type casting exists!

The fact that PHP will switch things around as needed makes the point of user defined type casting vague.  For example, the following two code samples are equivalent:

```<code>// example 1
$foo = 0;
$foo = (string)$foo;
$foo = '# of Reasons for the programmer to type cast $foo as a string: ' . $foo;

// example 2
$foo = 0;
$foo = (int)$foo;
$foo = '# of Reasons for the programmer to type cast $foo as a string: ' . $foo;
</code>```

A year after originally asking this question, guess who found himself using typecasting in a practical environment?  Yours Truly.

The requirement was to display money values on a website for a restaurant menu.  The design of the site required that trailing zeros be trimmed, so that the display looked something like the following:

Menu Item 1 .............. $ 4
Menu Item 2 .............. $ 7.5
Menu Item 3 .............. $ 3
```

<p>The best way I found to do that wast to cast the variable as a float:</p>

```$price = '7.50'; // a string from the database layer.
echo 'Menu Item 2 .............. $ ' . (float)$price;
```

PHP trims the float's trailing zeros, and then recasts the float as a string for concatenation.

答:
In a weakly-typed language, type-casting exists to remove ambiguity in typed operations, when otherwise the compiler/interpreter would use order or other rules to make an assumption of which operation to use.

Normally I would say PHP follows this pattern, but of the cases I've checked, PHP has behaved counter-intuitively in each.

Here are those cases, using JavaScript as a comparison language.

String Concatentation

Obviously this is not a problem in PHP because there are separate string concatenation (.) and addition (+) operators.

JavaScript

```<code>var a = 5;
var b = "10"
var incorrect = a + b; // "510"
var correct = a + Number(b); // 15
</code>```

String Comparison

Often in computer systems "5" is greater than "10" because it doesn't interpret it as a number.  Not so in PHP, which, even if both are strings, realizes they are numbers and removes the need for a cast):

JavaScript

```<code>console.log("5" > "10" ? "true" : "false"); // true
</code>```

PHP

```<code>echo "5" > "10" ? "true" : "false";  // false!
</code>```

Function signature typing

PHP implements a bare-bones type-checking on function signatures, but unfortunately it's so flawed it's probably rarely usable.

I thought I might be doing something wrong, but a comment on the docs confirms that built-in types other than array cannot be used in PHP function signatures - though the error message is misleading.

PHP

```<code>function testprint(string $a) {
    echo $a;
}

$test = 5;
testprint((string)5); // "Catchable fatal error: Argument 1 passed to testprint()
                      //  must be an instance of string, string given" WTF?
</code>```

And unlike any other language I know, even if you use a type it understands, null can no longer be passed to that argument (must be an instance of array, null given).  How stupid.

Boolean interpretation

[Edit]: This one is new. I thought of another case, and again the logic is reversed from JavaScript.

JavaScript

```<code>console.log("0" ? "true" : "false"); // True, as expected. Non-empty string.
</code>```

PHP

```<code>echo "0" ? "true" : "false"; // False! This one probably causes a lot of bugs.
</code>```

So in conclusion, the only useful case I can think of is... (drumroll)

Type truncation

In other words, when you have a value of one type (say string) and you want to interpret it as another type (int) and you want to force it to become one of the valid set of values in that type:

```<code>$val = "test";
$val2 = "10";
$intval = (int)$val; // 0
$intval2 = (int)$val2; // 10
$boolval = (bool)$intval // false
$boolval2 = (bool)$intval2 // true
$props = (array)$myobject // associative array of $myobject's properties
</code>```

I can't see what upcasting (to a type that encompasses more values) would really ever gain you.

So while I disagree with your proposed use of typing (you essentially are proposing static typing, but with the ambiguity that only if it was force-cast into a type would it throw an error — which would cause confusion), I think it's a good question, because apparently casting has very little purpose in PHP.

Body:
In a weakly-typed language, type-casting exists to remove ambiguity in typed operations, when otherwise the compiler/interpreter would use order or other rules to make an assumption of which operation to use.

Normally I would say PHP follows this pattern, but of the cases I've checked, PHP has behaved counter-intuitively in each.

Here are those cases, using JavaScript as a comparison language.

String Concatentation

Obviously this is not a problem in PHP because there are separate string concatenation (.) and addition (+) operators.

JavaScript

var a = 5;
var b = "10"
var incorrect = a + b; // "510"
var correct = a + Number(b); // 15

String Comparison

Often in computer systems "5" is greater than "10" because it doesn't interpret it as a number.  Not so in PHP, which, even if both are strings, realizes they are numbers and removes the need for a cast):

JavaScript

console.log("5" > "10" ? "true" : "false"); // true

PHP

echo "5" > "10" ? "true" : "false";  // false!

Function signature typing

PHP implements a bare-bones type-checking on function signatures, but unfortunately it's so flawed it's probably rarely usable.

I thought I might be doing something wrong, but a comment on the docs confirms that built-in types other than array cannot be used in PHP function signatures - though the error message is misleading.

PHP

function testprint(string $a) {
    echo $a;
}

$test = 5;
testprint((string)5); // "Catchable fatal error: Argument 1 passed to testprint()
                      //  must be an instance of string, string given" WTF?

And unlike any other language I know, even if you use a type it understands, null can no longer be passed to that argument (must be an instance of array, null given).  How stupid.

Boolean interpretation

[Edit]: This one is new. I thought of another case, and again the logic is reversed from JavaScript.

JavaScript

console.log("0" ? "true" : "false"); // True, as expected. Non-empty string.

PHP

echo "0" ? "true" : "false"; // False! This one probably causes a lot of bugs.

So in conclusion, the only useful case I can think of is... (drumroll)

Type truncation

In other words, when you have a value of one type (say string) and you want to interpret it as another type (int) and you want to force it to become one of the valid set of values in that type:

$val = "test";
$val2 = "10";
$intval = (int)$val; // 0
$intval2 = (int)$val2; // 10
$boolval = (bool)$intval // false
$boolval2 = (bool)$intval2 // true
$props = (array)$myobject // associative array of $myobject's properties

I can't see what upcasting (to a type that encompasses more values) would really ever gain you.

So while I disagree with your proposed use of typing (you essentially are proposing static typing, but with the ambiguity that only if it was force-cast into a type would it throw an error — which would cause confusion), I think it's a good question, because apparently casting has very little purpose in PHP.


问:
DAL Exception handling in a MVP application
In a MVP win forms application I'm handling exceptions as follows in DAL.

Since the user messaging is not a responsibility of DAL, I want to move it in to my Presentation class.

Could you show me a standard way to do that?

```<code>    public bool InsertAccount(IBankAccount ba)
    {
        string selectStatement = @"IF NOT EXISTS (SELECT ac_no FROM BankAccount WHERE ac_no=@ac_no) BEGIN INSERT INTO BankAccount ...";

        using (SqlConnection sqlConnection = new SqlConnection(db.ConnectionString))
        {
            using (SqlCommand sqlCommand = new SqlCommand(selectStatement, sqlConnection))
            {
                try
                {
                    sqlConnection.Open();
                    sqlCommand.Parameters.Add("@ac_no", SqlDbType.Char).Value = ba.AccountNumber;
                    //
                    //

                    sqlCommand.ExecuteNonQuery();
                    return true;
                }
                catch (Exception e) { MessageBox.Show(("Error: " + e.Message)); }
                if (sqlConnection.State == System.Data.ConnectionState.Open) sqlConnection.Close();
                return false;
            }

        }
    }
</code>```

EDIT2 :

So based on the answers I re edited the post and now my exception handling code looks like this...

DAL

```<code>public bool InsertAccount(IBankAccount ba)
{
    try
    {
        sqlConnection.Open();
        //
    }
    catch (SqlException)
    {
        throw new Exception("DataBase related Exception occurred");
    }
    catch (Exception)
    {
        throw new Exception("Exception occurred");
    }
}
</code>```

BankAccountPresenter

```<code>    private void SaveBankAccount()
    {
        try
        {
           _DataService.InsertAccount(_model);
        }
        catch (Exception e) { MessagingService.ShowErrorMessage(e.Message); }
    }
</code>```

Why I've caught exceptions in DAL is that even at the moment I'm not logging errors, I may have to do it in future.

And also this way I can differentiate the error massages in DAL, whether it's sql related or general.

I've used messaging service in my presenter when showing error messages.

Does this meaning full? Can this be simplified?

答:
Instead of catching the exception, why don't you just let it bubble up to the calling code? So either your model or controller (depending on how you call InsertAccount) would have the ability to catch the exception (or, in fact, any exception) and display it to the user in an appropriate fashion.

My general rule is to only catch an exception when I can do something to fix it or I have no choice but to deal with it. Your DAL can't fix it, and it has a choice: pass it to someone upstream to handle it.

To address your edit, I would discourage creating a new, generic exception and passing it up. What does that do for users? They only care that something has failed, not that it's the database or another component. If you want to do error logging from inside your DAL (and I do think that's a compelling reason to catch exceptions), catch it, log it, and then re-throw that exception up to the caller. That way you get the best of both worlds--you have handled the exception in an important way for your code, and your presenter can figure out how it wants to present the exception to the user.


问:
Combinatorial explosion of interfaces: How many is too many?
I'm a relative newcomer to OOP, and I'm having a bit of trouble creating good designs when it comes to interfaces.

Consider a class A with N public methods. There are a number of other classes, B, C, ..., each of which interacts with A in a different way, that is, accesses some subset (<= N) of A's methods.

The maximum degree of encapsulation is achieved by implementing an interface of A for each other class, i.e. AInterfaceForB, AInterfaceForC, etc.

However, if B, C, ... etc. also interact with A and with each other, then there will be a combinatorial explosion of interfaces (a maximum of n(n-1), to be precise), and the benefit of encapsulation becomes outweighed by a code-bloat.

What is the best practice in this scenario?

Is the whole idea of restricting access to a class's public functions in different ways for other different classes just silly altogether? One could imagine a language that explicitly allows for this sort of encapsulation (e.g. instead of declaring a function public, one could specify exactly which classes it is visible to); Since this is not a feature of C++, maybe it's misguided to try to do it through the back door with interaces?

答:
This would indicate to me that a class is too large and/or in-cohesive (https://en.wikipedia.org/wiki/Cohesion_%28computer_science%29). Otherwise you should be guided to the interface by the purpose of the class. Are you trying to do too much in a single class?

Express as small an amount of functionality as possible via the actual public interface of the class but keep it flexible.
For example: Say you have a data storage class that can process SQL. Do not put application specific "helper" methods in there. Just use a generic get, put, update, delete methods which take SQL queries. The rest (e.g. std::vector<Record> getDepartmentRecords(const DeptId& dept)) can be handled in wrapping classes.

The last thing is that you should not try to design explicitly for a client of your class, just put the operations on the class that most make sense for it. If some other class wants to restrict their dependencies on your class then it is up to them to decide if they want to use an intermediary interface. Personally I think this is good practise when using third party libraries but for internal dependencies it shouldn't really be necessary (beyond the normal class hierarchy interfaces of course!)


问:
Why/how does Java use a controlled mechanism to pause threads for GC?
I know that Java uses a controlled mechanism to allow threads to be paused. If I understood correctly, they put a read from a protected page at the end of e.g. loops, and change the protection of that page if they want the thread to be paused.

What I don't understand is why this is necessary and whether this can even work. The only reason I can think of to make this necessary is that you don't have to have all pointers on the heap, and you can also just have them in registers. However, if you'd use the TSS, wouldn't you have the same data too?

However, what I find more interesting is how they handle system calls. What happens when the thread is doing a slow read of a file over e.g. a network? Does the GC way? Does the GC forgo a run and try again a moment later? What happens when the system call takes very long?

答:
If you don't pause the world, the object graph can be modified concurrently to the GC's work. New objects are added, existing references are rewritten under your feet, already-marked objects become unreachable, and not all of these modifications might become visible to the GC at the same time or in the same order. For example, consider this code:

```<code>Object b = new Something();
// Now the GC reaches obj and scans its fields.
obj.next = b;
b = obj;
// Now the GC decides to scan the stack of this thread.
// It finds that b refers to an object it has already seen,
// so the new Something() is never marked and wrongly GC'd.
</code>```

Like almost any concurrency problem, correctly solving it is quite complicated and has much potential for subtle and hard-to-find errors. There are algorithms that can do it, and they are used in some advanced VMs, but they're far more complicated and usually have lower throughput. It's far simpler to just use the most coarse synchronization available.

Body:
If you don't pause the world, the object graph can be modified concurrently to the GC's work. New objects are added, existing references are rewritten under your feet, already-marked objects become unreachable, and not all of these modifications might become visible to the GC at the same time or in the same order. For example, consider this code:

Object b = new Something();
// Now the GC reaches obj and scans its fields.
obj.next = b;
b = obj;
// Now the GC decides to scan the stack of this thread.
// It finds that b refers to an object it has already seen,
// so the new Something() is never marked and wrongly GC'd.

Like almost any concurrency problem, correctly solving it is quite complicated and has much potential for subtle and hard-to-find errors. There are algorithms that can do it, and they are used in some advanced VMs, but they're far more complicated and usually have lower throughput. It's far simpler to just use the most coarse synchronization available.