问:
Optimal communication pattern to update subscribers
What is the optimal way to update the subscriber's local model on changes C on a central model M? ( M + C -> M_c)

The update can be done by the following methods:

Publish the updated model M_c to all subscribers. Drawback: if the model is big in contrast to the change it results in much more data to be communicated.

Publish change C to all subscribes. The subscribers will then update their local model in the same way as the server does. Drawback: The client needs to know the business logic to update the model in the same way as the server. It must be assured that the subscribed model stays equal to the central model.

Calculate the delta (or patch) of the change (M_c - M = D_c) and transfer the delta. Drawback: This requires that calculating and applying the delta (M + D_c = M_c) is an cheap/easy operation.

If a client newly subscribes it must be initialized. This involves sending the current model M. So method 1 is always required.

Think of playing chess as a concrete example: Subscribers send moves and want to see the latest chess board state. The server checks validity of the move and applies it to the chess board. The server can then send the updated chessboard (method 1) or just send the move  (method 2) or send the delta (method 3): remove piece on field D4, put tower on field D8.

答:
Your assumptions are a little off

Publish the updated model M_c to all subscribers. Drawback: if the
  model is big in contrast to the change it results in much more data to
  be communicated.

What you're describing here is essentially the pub-sub (ie publishers/subscribers) model. Even at scale, it's not very expensive to do because the data being returned is largely the same. Because it's essentially a one-way communication, the response will be essentially the same for all users. Fire-and-forget and create cache points in between if you need to scale larger.

Publish change C to all subscribes. The subscribers will then update
  their local model in the same way as the server does. Drawback: The
  client needs to know the business logic to update the model in the
  same way as the server. It must be assured that the subscribed model
  stays equal to the central model.

Now we have a problem. Every client maintains it's own state independent of the server. That means, every response needs to be specifically tailored to the request that's received. Ideally, you'll want to minimize the amount of state that's shared between the clients and the servers.

In games, they do this by only passing along the most basic state information. Even then it's usually done over a UDP connection so that packets that get dropped aren't re-requested. That's why, when games lag they'll usually continue to work but in strange and un-predictable ways. To the game, the simulation is still going on even if everybody else is frozen in time. In a lot of cases it'll even lag the player locally because their own actions need to be received and verified on the server before the action is taken locally.

Ever wonder why most fast paced games can't scale to hundreds/thousands of players. Here's your reason.

Calculate the delta (or patch) of the change (M_c - M = D_c) and
  transfer the delta. Drawback: This requires that calculating and
  applying the delta (M + D_c = M_c) is an cheap/easy operation.

Works good in theory but synchronization is a tricky business. For example, lets say 15 users are editing a document collaboratively. Edits are organized as transactions much like a database and updates are applied chronologically.

Edits can just be synchronized using time right? Wrong, because there's no guarantee that everybody's clock is in perfect sync. So the only option is to employ a central server to handle transaction management. It's somewhat optimal but when you throw in a hundred hosts that all require two-way communication with the central server, things may grind to a halt.

Hybrid-Models

There are a few cases of hybrid communications models that can push the limits by limiting or shifting accessibility to the central server.

Case 1: Infinite Lists

Lets take your first and second models and mix them into a new one. You want each user to maintain individual state but also want to decrease the load on the main server. Simple, organize the data in reverse-chronological order and only allow your users to access it in that order.

For example, in the original model lets say you have two users. One who is constantly updating to the latest and one who updates twice a year. The response to the person who constantly syncs is pretty small because their state is pretty consistent with the master data set. OTOH. the other user needs to update a massive amount of data after each request to maintain a consistent state with the server.

In the hybrid model, who cares if users have consistent state with the host. Just give them the most recent, if they want more give them the most recent after that, and so on. Worst case, everybody keeps requesting data until eventually their dataset is 100% consistent with the server. In the usual case, they'll only care about the most recent changes which means that the data being made available to the public is essentially a subset of the whole.

A smaller footprint means warm caches, quicker lookups, and lighter weight responses. This is the basic model that most news organizations and social media use today. You have a blog archive that stretches back to 1992, who cares... 99% of your users only want to read the stuff you've written in the past month. Reddit likes to hug 5 of your articles while the internet as a whole ignores the rest, then add frequency analysis to your cache expiration model. Warm caches mean faster lookups which is where your bottleneck will be if you manage to reach scales large enough to care about this sort of stuff.

Case 2: Peer-to-Peer Win

Lets say you actually want your data to be 100% consistent with the host and we're talking about a lot of data. Even if you manage to implement delta updates, if your local copy is far out of sync (or starting fresh) you'll still have a long ways to go.

The answer is simple. Divide and conquer. All you need to do is find a way to break up the data into logical chunks (ex split the data into 10MB chunks), create a map of the hashes of that data for quick/easy lookup/comparison.

OK, now you can request the data from the server in chunks but what if you wanted to go even faster. The answer is simple, separate the hashmap and the actual data into different pieces, de-centralize the host to make every connected node a host, and allow every node to download chunks from every other node.

It's very difficult to scale data transfers when you have a bunch of nodes pulling data from a central point but if everybody is fetching data from everybody, scalability becomes a non-issue.

Want to super-charge downloads. Simple. Request random chunks and for every time a chunk is requested but not available, it's priority increases. That ensures maximum diversity across hosts so there will be no bottleneck on any specific chunk of data.

Sound familiar? It should, what I described is the basis for the BitTorrent protocol. That's why 5 thousand people all downloading the same 2GB movie can still manage to do so at very data transfer rates. It's also why taking down one, or five, or 10 hosts still doesn't kill the swarm. All nodes in the swarm are constantly in communication with other nodes of the swarm but not necessarily every other node, just enough of them to keep the download going. Network communications don't get much more de-centralized or fault-tolerant than that.

As for your 'Chess' example. I know a lot of people like to romanticize about the compexity of chess by talking about the large number of possible combinations. In reality the number of variables involved is so small that the problem domain is practically insignificant.

You're talking about 64 possible spaces on a board and 32 possible pieces for each space. If you compress the pieces down into a bitmap where every piece represents a single bit. That means it takes 64 32-bit words or 256 bytes of data. To put the scale into perspective, there is more data contained in this sentence than there are possible combinations on a chess board.

Even if you make all of the clients 'dumb' (which isn't necessary considering the simple rule set) and isolate all business logic to a central server, the problem doesn't become any more difficult.

Here's the process flow for a 'dumb client' model:

Client sends move to host

Host updates global state

Host published new global state to players

Players update their board to match

Rinse & Repeat

As with most things in programming, if you choose an appropriate data structure the code will practically write itself.

Now, consider what it takes to represent than something like a first person shooter where 3-dimensional body positions and bullet trajectories are being calculated and propagated to multiple players in real-time. Ever wonder why you die a lot more when you're lagging? It's because those calculations need to take place on the host server to be accurately synchronized with the game time. A slow connection to the game host will always be a disadvantage, no matter how skilled a player is.

Aside: You could further compress the digital word format used to represent board pieces. By limiting it to only one bit for each piece type. 6 different types of pieces plus a sign bit to mark a piece as either black or white. That means a piece can be effectively represented by a 8-bit (ie rounded up, to the closest byte boundary) word. Which means the data being communicated literally takes up less space than the following ASCII art.

```<code>8 ║♜♞♝♛♚♝♞♜
7 ║♟♟♟♟♟♟♟♟
6 ║… … … … … … … …
5 ║… … … … … … … …
4 ║… … … … … … … …
3 ║… … ♘… … … … …
2 ║♙♙♙♙♙♙♙♙
1 ║♖… ♗♕♔♗♘♖
  ╚═══════════════
   a b c d e f g h
</code>```

Source: http://recessiondodgetovictory.wordpress.com/2011/01/12/ascii-chessboard/

In fact, you could literally just use a 2-D array of UTF-8 chess characters to track the game state.

Body:
Your assumptions are a little off

Publish the updated model M_c to all subscribers. Drawback: if the
  model is big in contrast to the change it results in much more data to
  be communicated.

What you're describing here is essentially the pub-sub (ie publishers/subscribers) model. Even at scale, it's not very expensive to do because the data being returned is largely the same. Because it's essentially a one-way communication, the response will be essentially the same for all users. Fire-and-forget and create cache points in between if you need to scale larger.

Publish change C to all subscribes. The subscribers will then update
  their local model in the same way as the server does. Drawback: The
  client needs to know the business logic to update the model in the
  same way as the server. It must be assured that the subscribed model
  stays equal to the central model.

Now we have a problem. Every client maintains it's own state independent of the server. That means, every response needs to be specifically tailored to the request that's received. Ideally, you'll want to minimize the amount of state that's shared between the clients and the servers.

In games, they do this by only passing along the most basic state information. Even then it's usually done over a UDP connection so that packets that get dropped aren't re-requested. That's why, when games lag they'll usually continue to work but in strange and un-predictable ways. To the game, the simulation is still going on even if everybody else is frozen in time. In a lot of cases it'll even lag the player locally because their own actions need to be received and verified on the server before the action is taken locally.

Ever wonder why most fast paced games can't scale to hundreds/thousands of players. Here's your reason.

Calculate the delta (or patch) of the change (M_c - M = D_c) and
  transfer the delta. Drawback: This requires that calculating and
  applying the delta (M + D_c = M_c) is an cheap/easy operation.

Works good in theory but synchronization is a tricky business. For example, lets say 15 users are editing a document collaboratively. Edits are organized as transactions much like a database and updates are applied chronologically.

Edits can just be synchronized using time right? Wrong, because there's no guarantee that everybody's clock is in perfect sync. So the only option is to employ a central server to handle transaction management. It's somewhat optimal but when you throw in a hundred hosts that all require two-way communication with the central server, things may grind to a halt.

Hybrid-Models

There are a few cases of hybrid communications models that can push the limits by limiting or shifting accessibility to the central server.

Case 1: Infinite Lists

Lets take your first and second models and mix them into a new one. You want each user to maintain individual state but also want to decrease the load on the main server. Simple, organize the data in reverse-chronological order and only allow your users to access it in that order.

For example, in the original model lets say you have two users. One who is constantly updating to the latest and one who updates twice a year. The response to the person who constantly syncs is pretty small because their state is pretty consistent with the master data set. OTOH. the other user needs to update a massive amount of data after each request to maintain a consistent state with the server.

In the hybrid model, who cares if users have consistent state with the host. Just give them the most recent, if they want more give them the most recent after that, and so on. Worst case, everybody keeps requesting data until eventually their dataset is 100% consistent with the server. In the usual case, they'll only care about the most recent changes which means that the data being made available to the public is essentially a subset of the whole.

A smaller footprint means warm caches, quicker lookups, and lighter weight responses. This is the basic model that most news organizations and social media use today. You have a blog archive that stretches back to 1992, who cares... 99% of your users only want to read the stuff you've written in the past month. Reddit likes to hug 5 of your articles while the internet as a whole ignores the rest, then add frequency analysis to your cache expiration model. Warm caches mean faster lookups which is where your bottleneck will be if you manage to reach scales large enough to care about this sort of stuff.

Case 2: Peer-to-Peer Win

Lets say you actually want your data to be 100% consistent with the host and we're talking about a lot of data. Even if you manage to implement delta updates, if your local copy is far out of sync (or starting fresh) you'll still have a long ways to go.

The answer is simple. Divide and conquer. All you need to do is find a way to break up the data into logical chunks (ex split the data into 10MB chunks), create a map of the hashes of that data for quick/easy lookup/comparison.

OK, now you can request the data from the server in chunks but what if you wanted to go even faster. The answer is simple, separate the hashmap and the actual data into different pieces, de-centralize the host to make every connected node a host, and allow every node to download chunks from every other node.

It's very difficult to scale data transfers when you have a bunch of nodes pulling data from a central point but if everybody is fetching data from everybody, scalability becomes a non-issue.

Want to super-charge downloads. Simple. Request random chunks and for every time a chunk is requested but not available, it's priority increases. That ensures maximum diversity across hosts so there will be no bottleneck on any specific chunk of data.

Sound familiar? It should, what I described is the basis for the BitTorrent protocol. That's why 5 thousand people all downloading the same 2GB movie can still manage to do so at very data transfer rates. It's also why taking down one, or five, or 10 hosts still doesn't kill the swarm. All nodes in the swarm are constantly in communication with other nodes of the swarm but not necessarily every other node, just enough of them to keep the download going. Network communications don't get much more de-centralized or fault-tolerant than that.

As for your 'Chess' example. I know a lot of people like to romanticize about the compexity of chess by talking about the large number of possible combinations. In reality the number of variables involved is so small that the problem domain is practically insignificant.

You're talking about 64 possible spaces on a board and 32 possible pieces for each space. If you compress the pieces down into a bitmap where every piece represents a single bit. That means it takes 64 32-bit words or 256 bytes of data. To put the scale into perspective, there is more data contained in this sentence than there are possible combinations on a chess board.

Even if you make all of the clients 'dumb' (which isn't necessary considering the simple rule set) and isolate all business logic to a central server, the problem doesn't become any more difficult.

Here's the process flow for a 'dumb client' model:

Client sends move to host

Host updates global state

Host published new global state to players

Players update their board to match

Rinse & Repeat

As with most things in programming, if you choose an appropriate data structure the code will practically write itself.

Now, consider what it takes to represent than something like a first person shooter where 3-dimensional body positions and bullet trajectories are being calculated and propagated to multiple players in real-time. Ever wonder why you die a lot more when you're lagging? It's because those calculations need to take place on the host server to be accurately synchronized with the game time. A slow connection to the game host will always be a disadvantage, no matter how skilled a player is.

Aside: You could further compress the digital word format used to represent board pieces. By limiting it to only one bit for each piece type. 6 different types of pieces plus a sign bit to mark a piece as either black or white. That means a piece can be effectively represented by a 8-bit (ie rounded up, to the closest byte boundary) word. Which means the data being communicated literally takes up less space than the following ASCII art.

8 ║♜♞♝♛♚♝♞♜
7 ║♟♟♟♟♟♟♟♟
6 ║… … … … … … … …
5 ║… … … … … … … …
4 ║… … … … … … … …
3 ║… … ♘… … … … …
2 ║♙♙♙♙♙♙♙♙
1 ║♖… ♗♕♔♗♘♖
  ╚═══════════════
   a b c d e f g h

Source: http://recessiondodgetovictory.wordpress.com/2011/01/12/ascii-chessboard/

In fact, you could literally just use a 2-D array of UTF-8 chess characters to track the game state.


问:
Why do so few large websites run a Microsoft stack?
Off the top of my head, I can think of a handful of large sites which utilize the Microsoft stack

Microsoft.com

Dell

MySpace

PlentyOfFish

StackOverflow

Hotmail, Bing, WindowsLive

However, based on observation, nearly all of the top 500 sites seem to be running other platforms.What are the main reasons there's so little market penetration?

Cost?

Technology Limitations?

Does Microsoft cater to corporate / intranet environments more then public websites?

I'm not looking for market share, but rather large scale adoption of the MS stack.

答: I'll throw in a vote for "tradition".  During the whole dot-com run-up, "everybody knew" you had to have a big Sun or HP server running Apache, so that's what people bought.  And when start-ups tried to emulate the successful companies, they used the same stuff.  And since IIS didn't really offer any compelling features (unless you consider Front Page extensions...) there really wasn't any reason for anyone to consider a MS stack.  Especially when you could run Apache and/or Perl CGI scripts on a 4-CPU Sun box, while dual-core Pentium II Windows boxes were fairly exotic.  Now that the hardware is no longer a barrier, we're seeing more large sites on the MS stack, but I think that for most there's still no compelling reason to switch to (or start with) it.</p>

ContentLicense: CC BY-SA 2.5


问:
Are GUIs ever programmed in DirectX for higher performance?
I've been researching GDI a little and on some websites I'm lead to believe it can hardly draw a few boxes, while on others it can easily be used in an interactive charting application.

So I'm wondering what is used in applications like Excel where there can be a lot movement like scrolling through a large amount of data fast? Could DirectX be used and would it increase performance? Is it used?

答: Sort of - some of Microsoft's newer APIs such as Direct2d and WPF leverage your graphics card for drawing GUIs. DirectX itself (more specifically Direct3D) isn't usually used for GUIs outside of a video game that contains them.

ContentLicense: CC BY-SA 3.0


问:
Passing an object between different handlers or a Superclass that contains most of the logic
I'm going to try to make this as concise and concrete as possible, but apologies since I can think of multiple ways to make it work.  This question might also relate to handling production workflows or manufacturing, but I have no experience in these areas.

I have a problem where I need to move an Object, O, from different states to other states (like a Nondeterministic finite automata). The problem is the Object can be in different states at the same time, and the interaction sometimes matters.

For example say there are 10 states, O can be in up to 3 of those states at the same time. I'm a bit lost as to what type of code design I should use to model this.  The two ideas I am thinking about are

Pass O from handler to handler, and manage the transitions between states, and keep some sort of info in O saying which states they are in, so that each state can figure out what to do based on what other states O is in.

Have a larger Superclass that handles which states O is in, and handles the interactions.

I'd normally say 1. but handling all the interactions between handlers in each handler sounds messy.

What would be the better option between these 2? Or is there another method that is preferred?

** Update and Clarification **

As a concrete example. The Object can be in one of many physical locations, while it can also be in one of several stages of processing (The object might move back and forth between locations, or back and forth between the stages of processing). As additional complexity each physical location might have sublocations, but I think I can ignore that for now.  So if it's clearer, it can be considered to be two independent automata, but choosing the edge to move to the next state in either automata depends on it's state from both automata.

答:
If I understand your question correctly, you could design your code similar to the outline below:

A StateObjectContainer class that holds references to the current state, the object, and to the state manager. This class is responsible to the metadata (the references) associated with the contained object.

A State class with a collection of StateObjectContainers. Also has the ability to add objects to the current state.

A StateManager class that has references to all state instances and exposes functionality to query them for information.

A StateDecider class that determines the next logical states given an object and a snap shot of all states.

An event or callback that is called when an object is ready to change states and is given that object as an argument.

When an object is ready to change states:

Get a snapshot of all current states

Calculate the next logical states

Add the object to each of the calculated states.


答:
Sounds like your object needs a location field (and maybe a location class or interface to help ensure valid values) and a second field for processing stage which could probably be represented by an enum of the possible stages.

```<code>enum ProcessingStage { STAGE_1, STAGE_2,... STAGE_N; }

class MyObject {
    String location;
    ProcessingStage stage;
    ...
}
</code>```

Surely there is some limit to the number of processing-stage combinations.  Even if there are 10 possible processing-stages, and it can be in 3 of them at once (though not the same 3 across the board), that's 10x9x8 = 720 possible processing-stage combinations.  I'm guessing the number of valid combinations is much smaller, like maybe 30, in which case you could represent the combinations in an enum:

```<code>enum ProcessingStage {
    CHASSIS_ASSEMBLY,
    CHASSIS_VERIFICATION_AND_DASHBOARD_ASSEMBLY,
    DASHBOARD_ASSEMBLY,
    PAINTING,...
}
</code>```

Otherwise instead of having a single processing-stage, you could store them in a list.  Don't let the client modify the list directly.  Instead, provide methods that check the validity of the processing-stage combinations.

```<code>private final List<ProcessingStage> procStages = new ArrayList<>();
private static final int MAX_STAGES = 3;

public synchronized void addStage(ProcessingStage ps) throws Exception {
    if (procStages.size() >= 3) {
        throw new Exception("Can't have more than 3 simultaneous stages");
    }
    if (procStages.size() < 1) {
        procStages.add(ps);
    } else {
        for (ProcessingStage testPs : procStages) {
            // Maybe you could start painting while still assembling,
            // but can't start assembling while you are painting.
            if ( !ps.isCompatibleWith(testPs) ) {
                throw new Exception("New stage " + ps +
                                    " is incompatible with an existing stage: " +
                                    testPs);
            }
        }
    }
}

public synchronized void removeStage(ProcessingStage ps) throws Exception {
    if (procStages.size() < 1) {
        throw new Exception("Can't remove a stage when there are none");
    }
    procStages.remove(ps);
}

/**
 In Java, the client cannot modify this list, but it still tracks
 the list used internally by this object (shares the underlying
 list) so that every time the client looks at an old list that they
 get from this method, it could be different.  Weird, but that's
 Java.
*/
public List<ProcessingStage> stageListView() {
    return Collections.unmodifiableList(procStages);
}
</code>```

I synchronized the methods so that stage transitions would be atomic and made them throw exceptions so that the caller has to handle what happens if another caller changes the state underneath them.

It occurs to me that you might want to look at Josh Bloch's Item 33: "Use EnumMap instead of ordinal indexing" (from Effective Java p. 161).  Regardless of the title and the language, he has a nice example of modeling states: SOLID, LIQUID, GAS and valid transitions: FREEZE(LIQUID, SOLID), MELT(SOLID, LIQUID)...  Then he creates a map of valid transitions.

Title: Passing an object between different handlers or a Superclass that contains most of the logic

Body:
I'm going to try to make this as concise and concrete as possible, but apologies since I can think of multiple ways to make it work.  This question might also relate to handling production workflows or manufacturing, but I have no experience in these areas.

I have a problem where I need to move an Object, O, from different states to other states (like a Nondeterministic finite automata). The problem is the Object can be in different states at the same time, and the interaction sometimes matters.

For example say there are 10 states, O can be in up to 3 of those states at the same time. I'm a bit lost as to what type of code design I should use to model this.  The two ideas I am thinking about are

Pass O from handler to handler, and manage the transitions between states, and keep some sort of info in O saying which states they are in, so that each state can figure out what to do based on what other states O is in.

Have a larger Superclass that handles which states O is in, and handles the interactions.

I'd normally say 1. but handling all the interactions between handlers in each handler sounds messy.

What would be the better option between these 2? Or is there another method that is preferred?

** Update and Clarification **

As a concrete example. The Object can be in one of many physical locations, while it can also be in one of several stages of processing (The object might move back and forth between locations, or back and forth between the stages of processing). As additional complexity each physical location might have sublocations, but I think I can ignore that for now.  So if it's clearer, it can be considered to be two independent automata, but choosing the edge to move to the next state in either automata depends on it's state from both automata.

Body:
Sounds like your object needs a location field (and maybe a location class or interface to help ensure valid values) and a second field for processing stage which could probably be represented by an enum of the possible stages.

enum ProcessingStage { STAGE_1, STAGE_2,... STAGE_N; }

class MyObject {
    String location;
    ProcessingStage stage;
    ...
}

Surely there is some limit to the number of processing-stage combinations.  Even if there are 10 possible processing-stages, and it can be in 3 of them at once (though not the same 3 across the board), that's 10x9x8 = 720 possible processing-stage combinations.  I'm guessing the number of valid combinations is much smaller, like maybe 30, in which case you could represent the combinations in an enum:

enum ProcessingStage {
    CHASSIS_ASSEMBLY,
    CHASSIS_VERIFICATION_AND_DASHBOARD_ASSEMBLY,
    DASHBOARD_ASSEMBLY,
    PAINTING,...
}

Otherwise instead of having a single processing-stage, you could store them in a list.  Don't let the client modify the list directly.  Instead, provide methods that check the validity of the processing-stage combinations.

private final List<ProcessingStage> procStages = new ArrayList<>();
private static final int MAX_STAGES = 3;

public synchronized void addStage(ProcessingStage ps) throws Exception {
    if (procStages.size() >= 3) {
        throw new Exception("Can't have more than 3 simultaneous stages");
    }
    if (procStages.size() < 1) {
        procStages.add(ps);
    } else {
        for (ProcessingStage testPs : procStages) {
            // Maybe you could start painting while still assembling,
            // but can't start assembling while you are painting.
            if ( !ps.isCompatibleWith(testPs) ) {
                throw new Exception("New stage " + ps +
                                    " is incompatible with an existing stage: " +
                                    testPs);
            }
        }
    }
}

public synchronized void removeStage(ProcessingStage ps) throws Exception {
    if (procStages.size() < 1) {
        throw new Exception("Can't remove a stage when there are none");
    }
    procStages.remove(ps);
}

/**
 In Java, the client cannot modify this list, but it still tracks
 the list used internally by this object (shares the underlying
 list) so that every time the client looks at an old list that they
 get from this method, it could be different.  Weird, but that's
 Java.
*/
public List<ProcessingStage> stageListView() {
    return Collections.unmodifiableList(procStages);
}

I synchronized the methods so that stage transitions would be atomic and made them throw exceptions so that the caller has to handle what happens if another caller changes the state underneath them.

It occurs to me that you might want to look at Josh Bloch's Item 33: "Use EnumMap instead of ordinal indexing" (from Effective Java p. 161).  Regardless of the title and the language, he has a nice example of modeling states: SOLID, LIQUID, GAS and valid transitions: FREEZE(LIQUID, SOLID), MELT(SOLID, LIQUID)...  Then he creates a map of valid transitions.


问:
try-catch in javascript... isn't it a good practice?
There is a provision for try-catch block in javascript. While in java or any other language it is mandatory to have error handling, I don't see anybody using them in javascript for greater extent. Isn't it a good practice or just we don't need them in javascript?

答:
Possibly another reason try/catch is not used very much in Javascript is the construct wasn't available in the very first versions of Javascript ...it was added later.

As a result, some older browsers don't support it. (In fact, it may cause a parser/syntax error in some older browsers, something that's more difficult to "program defensively" against than most other types of errors.)

More importantly, since it wasn't available initially, the Javascript builtin functions that were initially released (what one would call the "library" functions in many languages) don't make use of it. (It doesn't work very well to "catch" an error from someobject.somefunction() if it doesn't "throw" but instead just returns "null" when it encounters a problem.)

Yet another possible reason is the try/catch mechanism didn't seem to be necessary initially (and still doesn't seem all that useful). It's really needed only when calls are routinely nested several levels deep; just returning some sort of ERRNO would work fine for direct calls (although to make it really useful whenever it's available, best practice in most languages is to use it everywhere rather than just on deeply nested calls). As Javascript logic was originally expected to be small and simple (after all, it's just an adjunct to a webpage:-), function calls weren't expected to be deeply nested, and so a try/catch mechanism didn't seem necessary.


答:
Your different states sound more like activities. If they were states you would use Nouns to describe them (example; "full", "empty", "box", "container"). If they were activities then you would use Adjectives to describe them (example; "opening", "processing", "making").

Your object can be at a given location (i.e. a state), but it's doing many things at once (i.e. activities). Therefore, you would have an internal collection of activities that the object contains, but it may not be responsible for the logic of those activities. Each activity could implement that logic internally.

I'd create a new object to represent the factory, which contains the object at different locations (i.e. their state). The factory object would add/remove activities to objects when those activities report they are finished or not.

Here is a mockup

```<code> class ActivityContext
 {
      // data that is needed by
      // other activities when
      // doing work.
 }

 interface Activity
 {
      public void DoWork(ActivityContext);
      public bool DoneWork(ActivityContext);
 }

 class MyObject
 {
      public string Location;
      public List<Activity> CurrentActivities;

      public void WorkOnActivites() {...}
      public void Add(Activity) {...}
      public void Remove(Activity) {...}
 }

 class Factory
 {
      public List<MyObject> objects;

      public void ChangeLocation(MyObject) {...}
      public void Add(MyObject) {...}
      public void Remove(MyObject) {...}
      // .. and other methods
 }
</code>```

You would create new objects that implement the Activity interface, add them to MyObject when that object needs to perform that activity, or change it's location. To find objects and manage them you use the Factory object.

EDIT:

I added the class ActivityContext as a data object. These objects are created and passed to an Activity when it does work. Each Activity can update the context data so that other activites can receive that data when they do work. This allows activities to be aware of what other activities are doing without directly referencing those activities.

Body:
Your different states sound more like activities. If they were states you would use Nouns to describe them (example; "full", "empty", "box", "container"). If they were activities then you would use Adjectives to describe them (example; "opening", "processing", "making").

Your object can be at a given location (i.e. a state), but it's doing many things at once (i.e. activities). Therefore, you would have an internal collection of activities that the object contains, but it may not be responsible for the logic of those activities. Each activity could implement that logic internally.

I'd create a new object to represent the factory, which contains the object at different locations (i.e. their state). The factory object would add/remove activities to objects when those activities report they are finished or not.

Here is a mockup

 class ActivityContext
 {
      // data that is needed by
      // other activities when
      // doing work.
 }

 interface Activity
 {
      public void DoWork(ActivityContext);
      public bool DoneWork(ActivityContext);
 }

 class MyObject
 {
      public string Location;
      public List<Activity> CurrentActivities;

      public void WorkOnActivites() {...}
      public void Add(Activity) {...}
      public void Remove(Activity) {...}
 }

 class Factory
 {
      public List<MyObject> objects;

      public void ChangeLocation(MyObject) {...}
      public void Add(MyObject) {...}
      public void Remove(MyObject) {...}
      // .. and other methods
 }

You would create new objects that implement the Activity interface, add them to MyObject when that object needs to perform that activity, or change it's location. To find objects and manage them you use the Factory object.

EDIT:

I added the class ActivityContext as a data object. These objects are created and passed to an Activity when it does work. Each Activity can update the context data so that other activites can receive that data when they do work. This allows activities to be aware of what other activities are doing without directly referencing those activities.


问:
How to write a program that diffs on hierarchy changes?
Why is it that diff programs work on a line-by-line basis instead of a hierarchal one?

All code can be expressed in a hierarchy, even though it's not immediately apparent.

Most of the data we work with is hierarchal as well.

What are the potential issues with building a piece of software that can diff based on hierarchy?

答:
Because usually, diffs are created to be able to compare any file, not only hierarchical-organized source code or data.

Because in order to obtain a tree from a source code, one needs to parse it first. Reading lines - every app can do that. Being able to parse C++, Ada, Java, COBOL, Haskell and hundreds of programming languages and non-programming languages is not so easy.

Because showing some code as a tree will be extremely ugly. Imagine PHP code mixed with HTML with a deep hierarchy (including PHP code in HTML attributes).

But in some particular contexts when we are sure to have a limited set of languages, like Visual Studio, it would be nice to have a tree-based diff, indeed (as an option, with a choice between text-based and tree-based diff).


问:
Is it a performance hit to create threads that loop a lot to check for things?
This is a generic question that I've always wondered.

In general, is it intensive for a CPU to create threads that perform "while not true ..." loops or similar?

For example, suppose I do:

```<code>// pseudo-code
new Thread(function() {
    while (!useHasDoneSomething) {
        // do nothing...
    }
    alert("you did something!");
}
</code>```

So it's just a piece of code that runs in a thread that waits for something to happen.

For whatever reason I imagine that this would pressure the CPU. After all, even though it's just one little loop, it's re-running the loop the instant that a cycle is done. Wouldn't this mean that it's going through the cycle many times per millisecond? ... Per nanosecond!?

The operating system will "handle" the program and the thread(s), right? But that's still an awful lot of attention to running a loop. If the CPU has nothing else to do, wouldn't it just focus on that loop, thereby consuming all the idle time?

What if I create 1000 threads that all do the same loop? How might that affect performance/CPU cycles?

Furthermore, is this how events function internally? When you're 'listening' for an event in Java, .NET, Javascript etc (such as a button press or a window resize), has a thread that loops been created?

答: The <code>//do nothing </code> part inside while condition in normal scenario is WAIT on some semaphore, or in other terms SLEEP. Sleep until some interrupt has woken you up. And hence the thread goes in "sleep state" or lets just say "not running state". Only the processes which are in running state consumes CPU. The sleep state process will not consume CPU. They may be consuming memory, but that memory will be swapped out internally by virtual memory system. So even if you create 1000 such threads they will not be posing much threat to your system. </p>

Body: The //do nothing  part inside while condition in normal scenario is WAIT on some semaphore, or in other terms SLEEP. Sleep until some interrupt has woken you up. And hence the thread goes in "sleep state" or lets just say "not running state". Only the processes which are in running state consumes CPU. The sleep state process will not consume CPU. They may be consuming memory, but that memory will be swapped out internally by virtual memory system. So even if you create 1000 such threads they will not be posing much threat to your system.


答:
Your instinct is correct.  Busy-waiting like that is described as

Spinning can be a valid strategy in certain circumstances, most notably in the implementation of spinlocks within operating systems designed to run on SMP systems. In general, however, spinning is considered an anti-pattern and should be avoided, as processor time that could be used to execute a different task is instead wasted on useless activity.

Instead, you should consider a concurrency control primitive that allows the thread to truly go idle until it has useful work to do, for example a semaphore or a condition variable:

For many applications, mutual exclusion is not enough. Threads attempting an operation may need to wait until some condition  holds true. A busy waiting loop, like

```<code>while not( condition ) do
   // nothing
end
</code>```

will not work, as mutual exclusion will prevent any other thread from entering the monitor to make the condition true. Other "solutions" exist. Such as having a loop that unlocks the monitor, waits a certain amount, locks the monitor and check for the condition P. Theoretically, it works and will not deadlock, but issues arise. It's hard to decide an appropiate amount of waiting time, too small and the thread will hog the CPU, too big and it will be apparently unresponsive. What is needed is a way to signal the thread when the condition P is true (or could be true).
  The solution is condition variables. Conceptually a condition variable is a queue of threads, associated with a monitor, on which a thread may wait for some condition to become true. Thus each condition variable  is associated with an assertion . While a thread is waiting on a condition variable, that thread is not considered to occupy the monitor, and so other threads may enter the monitor to change the monitor's state. In most types of monitors, these other threads may signal the condition variable to indicate that assertion  is true in the current state.

Title: Is it a performance hit to create threads that loop a lot to check for things?

Body:
This is a generic question that I've always wondered.

In general, is it intensive for a CPU to create threads that perform "while not true ..." loops or similar?

For example, suppose I do:

```<code>// pseudo-code
new Thread(function() {
    while (!useHasDoneSomething) {
        // do nothing...
    }
    alert("you did something!");
}
</code>```

So it's just a piece of code that runs in a thread that waits for something to happen.

For whatever reason I imagine that this would pressure the CPU. After all, even though it's just one little loop, it's re-running the loop the instant that a cycle is done. Wouldn't this mean that it's going through the cycle many times per millisecond? ... Per nanosecond!?

The operating system will "handle" the program and the thread(s), right? But that's still an awful lot of attention to running a loop. If the CPU has nothing else to do, wouldn't it just focus on that loop, thereby consuming all the idle time?

What if I create 1000 threads that all do the same loop? How might that affect performance/CPU cycles?

Furthermore, is this how events function internally? When you're 'listening' for an event in Java, .NET, Javascript etc (such as a button press or a window resize), has a thread that loops been created?

Body:
Your instinct is correct.  Busy-waiting like that is described as

Spinning can be a valid strategy in certain circumstances, most notably in the implementation of spinlocks within operating systems designed to run on SMP systems. In general, however, spinning is considered an anti-pattern and should be avoided, as processor time that could be used to execute a different task is instead wasted on useless activity.

Instead, you should consider a concurrency control primitive that allows the thread to truly go idle until it has useful work to do, for example a semaphore or a condition variable:

For many applications, mutual exclusion is not enough. Threads attempting an operation may need to wait until some condition  holds true. A busy waiting loop, like

while not( condition ) do
   // nothing
end

will not work, as mutual exclusion will prevent any other thread from entering the monitor to make the condition true. Other "solutions" exist. Such as having a loop that unlocks the monitor, waits a certain amount, locks the monitor and check for the condition P. Theoretically, it works and will not deadlock, but issues arise. It's hard to decide an appropiate amount of waiting time, too small and the thread will hog the CPU, too big and it will be apparently unresponsive. What is needed is a way to signal the thread when the condition P is true (or could be true).
  The solution is condition variables. Conceptually a condition variable is a queue of threads, associated with a monitor, on which a thread may wait for some condition to become true. Thus each condition variable  is associated with an assertion . While a thread is waiting on a condition variable, that thread is not considered to occupy the monitor, and so other threads may enter the monitor to change the monitor's state. In most types of monitors, these other threads may signal the condition variable to indicate that assertion  is true in the current state.


答:
In general, is it intensive for a CPU to create threads that perform "while not true ..." loops or similar?

Yes. Using such a loop is called busy waiting and it is called that for a reason. These busy loops check the condition as often and as fast as the processor can manage it, with the result that, if you stay in the loop long enough, the processor load goes reliably to 100%.

What if I create 1000 threads that all do the same loop? How might that affect performance/CPU cycles?

It only creates more work for the CPU doing noting.

Furthermore, is this how events function internally? When you're 'listening' for an event in Java, .NET, Javascript etc (such as a button press or a window resize), has a thread that loops been created?

No. Busy loops are a form of polling and a very inefficient one at that as well. Operating systems have other mechanisms to detect that an event has happened (e.g. an interrupt or a specific call) and they have mechanisms to let a thread wait for it without consuming CPU time.
These mechanisms will also be used to implement the event mechanisms of languages like Java.


问:
Is there a point to unit tests that stub and mock everything public?
When doing unit tests the "proper" way, i.e. stubbing every public call and return preset values or mocks, I feel like I'm not actually testing anything. I'm literally looking at my code and creating examples based on the flow of logic through my public methods. And every time the implementation changes, I have to go and change those tests, again, not really feeling that I'm accomplishing anything useful (be it mid- or long-term). I also do integration tests (including non-happy-paths) and I don't really mind the increased testing times. With those, I feel like I'm actually testing for regressions, because they have caught multiple, while all that unit tests do is show me that the implementation of my public method changed, which I already know.

Unit testing is a vast topic, and I feel like I'm the one not understanding something here. What's the decisive advantage of unit testing vs integration testing (excluding the time overhead)?

答:
When doing unit tests the "proper" way, i.e. stubbing every public
call and return preset values or mocks, I feel like I'm not actually
testing anything. I'm literally looking at my code and creating
examples based on the flow of logic through my public methods.

This sounds like the method you are testing needs several other class instances (which you have to mock), and calls several methods on its own.

This type of code is indeed difficult to unit-test, for the reasons you outline.

What I have found helpful is to split up such classes into:

Classes with the actual "business logic". These use few or no calls to other classes and are easy to test (value(s) in - value out).

Classes that interface with external systems (files, database, etc.). These wrap the external system and provide a convenient interface for your needs.

Classes that "tie everything together"

Then the classes from 1. are easy to unit-test, because they just accept values and return a result. In more complex cases, these classes may need to perform calls on their own, but they will only call classes from 2. (and not directly call e.g. a database function), and the classes from 2. are easy to mock (because they only expose the parts of the wrapped system that you need).

The classes from 2. and 3. cannot usually be meaningfully unit-tested (because they don't do anything useful on their own, they are just "glue" code). OTOH, these classes tend to be relatively simple (and few), so they should be adequately covered by integration tests.

An example

One class

Say you have a class which retrieves a price from a database, applies some discounts and then updates the database.

If you have this all in one class, you'll need to call DB functions, which are hard to mock. In pseudocode:

```<code>1 select price from database
2 perform price calculation, possibly fetching parameters from database
3 update price in database
</code>```

All three steps will need DB access, so a lot of (complex) mocking, which is likely to break if the code or the DB structure changes.

Split up

You split into three classes: PriceCalculation, PriceRepository, App.

PriceCalculation only does the actual calculation, and gets provided the values it needs. App ties everything together:

```<code>App:
fetch price data from PriceRepository
call PriceCalculation with input values
call PriceRepository to update prices
</code>```

That way:

PriceCalculation encapsulates the "business logic". It's easy to test because it does not call anything on its own.

PriceRepository can be pseudo-unit-tested by setting up a mock database and testing the read and update calls. It has little logic, hence few codepaths, so you do not need too many of these tests.

App cannot be meaningfully unit-tested, because it is glue-code. However, it too is very simple, so integration testing should be enough. If later App gets too complex, you break out more "business-logic" classes.

Finally, it may turn out PriceCalculation must do its own database calls. For example because only PriceCalculation knows which data its needs, so it cannot be fetched in advance by App. Then you can pass it an instance of PriceRepository (or some other repository class), custom-tailored to PriceCalculation's needs. This class will then need to be mocked, but this will be simple, because PriceRepository's interface is simple, e.g. PriceRepository.getPrice(articleNo, contractType). Most importantly, PriceRepository's interface isolates PriceCalculation from the database, so changes to the DB schema or data organisation are unlikely to change its interface, and hence to break the mocks.

Note: I recently noticed that this concept is fairly similar to Alistair Cockburn's Hexagonal architecture. So I guess I've just been reinventing the wheel...or maybe great minds think alike?

Body:
When doing unit tests the "proper" way, i.e. stubbing every public
call and return preset values or mocks, I feel like I'm not actually
testing anything. I'm literally looking at my code and creating
examples based on the flow of logic through my public methods.

This sounds like the method you are testing needs several other class instances (which you have to mock), and calls several methods on its own.

This type of code is indeed difficult to unit-test, for the reasons you outline.

What I have found helpful is to split up such classes into:

Classes with the actual "business logic". These use few or no calls to other classes and are easy to test (value(s) in - value out).

Classes that interface with external systems (files, database, etc.). These wrap the external system and provide a convenient interface for your needs.

Classes that "tie everything together"

Then the classes from 1. are easy to unit-test, because they just accept values and return a result. In more complex cases, these classes may need to perform calls on their own, but they will only call classes from 2. (and not directly call e.g. a database function), and the classes from 2. are easy to mock (because they only expose the parts of the wrapped system that you need).

The classes from 2. and 3. cannot usually be meaningfully unit-tested (because they don't do anything useful on their own, they are just "glue" code). OTOH, these classes tend to be relatively simple (and few), so they should be adequately covered by integration tests.

An example

One class

Say you have a class which retrieves a price from a database, applies some discounts and then updates the database.

If you have this all in one class, you'll need to call DB functions, which are hard to mock. In pseudocode:

1 select price from database
2 perform price calculation, possibly fetching parameters from database
3 update price in database

All three steps will need DB access, so a lot of (complex) mocking, which is likely to break if the code or the DB structure changes.

Split up

You split into three classes: PriceCalculation, PriceRepository, App.

PriceCalculation only does the actual calculation, and gets provided the values it needs. App ties everything together:

App:
fetch price data from PriceRepository
call PriceCalculation with input values
call PriceRepository to update prices

That way:

PriceCalculation encapsulates the "business logic". It's easy to test because it does not call anything on its own.

PriceRepository can be pseudo-unit-tested by setting up a mock database and testing the read and update calls. It has little logic, hence few codepaths, so you do not need too many of these tests.

App cannot be meaningfully unit-tested, because it is glue-code. However, it too is very simple, so integration testing should be enough. If later App gets too complex, you break out more "business-logic" classes.

Finally, it may turn out PriceCalculation must do its own database calls. For example because only PriceCalculation knows which data its needs, so it cannot be fetched in advance by App. Then you can pass it an instance of PriceRepository (or some other repository class), custom-tailored to PriceCalculation's needs. This class will then need to be mocked, but this will be simple, because PriceRepository's interface is simple, e.g. PriceRepository.getPrice(articleNo, contractType). Most importantly, PriceRepository's interface isolates PriceCalculation from the database, so changes to the DB schema or data organisation are unlikely to change its interface, and hence to break the mocks.

Note: I recently noticed that this concept is fairly similar to Alistair Cockburn's Hexagonal architecture. So I guess I've just been reinventing the wheel...or maybe great minds think alike?

ContentLicense: CC BY-SA 4.0


问:
Does the ability to start a GPL add-on GPL-ize a program (Gstreamer)
This question is asked in regards to gstreamer but it could apply to any add-on based architecture.

I have a Gstreamer based application that can ship as proprietary because I use unmodified Gstreamer in it with all LGPL parts.  I may, however, also need to issue a version where one Gstreamer plugin is GPL.  As far as I can tell that would contaminate the whole program.

If instead of including the Gstreamer pipeline specification in the program, I publish it with the ability to read a pipeline spec from an external file (coded per some set of instructions - i.e. as a GstParseLaunch()-able specification) can I release the program as proprietary and the pipe-spec files as GPL?  How far apart would I need to publish those items, that is, would the program be in one distribution and the specs separately released in another?

What if the program is never truly released but is instead an embedded application sold inside an appliance and the appliance is sold preloaded with both the proprietary part and tghe non-proprietary part?

答:
Most of the answers can be found in the GPL FAQ.

For the interaction between GPL and non-free software, the basic rule is that they can only co-exist if they can both be executed as stand-alone programs. They may communicate with each other through standard inter-process communication features, but they should be separate programs as far as the OS is concerned.
The major difference between GPL and LGPL in this is that the LGPL also allows dynamically linked libraries to be used by a non-free program.

Where it concerns plug-ins, the only things that affect the license status are the format of the plug-ins and the way that the plug-in and the main program interact after the plug-in has been loaded.
If the plug-ins are separate programs, or the application treats them as such, then it is possible to have a GPL plug-in in a non-free program. If the plug-ins are libraries with any kind of back-and-forth communication, then you can't use GPL plug-ins with your non-free program.

As far as I can tell, an external specification of the plug-ins to load is not going to make it acceptable (in the view of the licenses) to use a GPL plug-in with a non-free program. You are right that the one GPL plug-in will contaminate the whole program.

(L)GPL software and embedded devices is a whole topic of its own.

The short version here is that, if you distribute a device that is loaded with GPL software, you are distributing the software, so you must make the sources available to the buyers of your device (assuming the software can be upgraded without physically modifying the device).

The intention of the GPL has always been that end-users should be able to replace the device's software with their own versions, but apparently the GPLv2 has a loophole here. The GPLv3 has made that intent an explicit requirement.


问:
ASP.Net or WPF(C#)?
Our team is divided on this and I wanted to get some third-party opinions.

We are building an application and cannot decide if we want to use .Net WPF Desktop Application with a WCF server, or ASP.Net web app using jQuery. I thought I'd ask the question here, with some specs, and see what the pros/cons of using either side would be. I have my own favorite and feel I am biased.

Ideally we want to build the initial release of the software as fast as we can, then slow down and take time to build in the additional features/components we want later on. Above all we want the software to be fast. Users go through records all day long and delays in loading records or refreshing screens kills their productivity.

Application Details:

I'm estimating around 100 different screens for initial version, with plans for a lot of additional screens being added on later after the initial release.

We are looking to use two-way communication for reminder and event systems

Currently has to support around 100 users, although we've been told to allow for growth up to 500 users

We have multiple locations

Items to consider (maybe not initially in some cases but in future releases):

Room for additional components to be added after initial release (there are a lot of of these... perhaps work here than the initial application)

Keyboard navigation

Performance is a must

Production Speed to initial version

Low maintenance overhead

Future support

Softphone/Scanner integration

Our Developers:

We have 1 programmer who has been learning WPF the past few months and was the one who suggested we use WPF for this.

We have a 2nd programmer who is familiar with ASP.Net and who may help with the project in the future, although he will not be working on it much up until the initial release since his time is spent maintaining our current software.

There is me, who has worked with both and am comfortable in either

We have an outside company doing the project management, and they are an ASP.Net company.

We plan on hiring 1-2 others, however we need to know what direction we are going in first

Environment:

General users are on Windows 2003 server with Terminal Services. They connect using WYSE thin-clients over an RDP connection. Admin staff has their own PCs with XP or higher. Users are allowed to specify their own resolution although they are limited to using IE as the web browser.

Other locations connects to our network over a MPLS connection

Based on that, what would you choose and why?

答:
If you only have one programmer who has been learning WPF and you are considering having your team take the jump to WPF then why not use Silverlight instead? You get many of the advantages of WPF but still maintain the ability to leave your project as a web app. Since you are looking at having a large modularized project it would make sense to use PRISM with WPF or Silverlight to make MVVM simpler.

My team recently made the choice to use Silverlight over asp.net. It has been a fantastic choice for us. We initially had only a single developer who knew any silverlight. Then we all took a week training class that was mostly useless, but at least got our feet wet. In the end we had to hire two contractors to help us with the creation of the bulk of our UI framework. The majority of our team still is not confident in their silverlight skills. Myself, the initial team member with knowledge of silverlight, and the two contractors are the ones doing the bulk of the SL development. After that we have two dedicated back-end members. I would say it took us about 2 months after making the decision to move to Silverlight that we really had anything concrete put together. However, now we have a wonderful product that feels very much like a client side application that is running inside of a web browser and does not be installed on any machine locally. Development has been under a year in total and we're near ready to release or first release candidate.

Some things to consider:

WPF or silverlight, whichever you choose there will be a fair amount that your developers will need to learn.

Silverlight can run out of browser if need be. If you do this it is pretty easy to set it up so that if you ever roll out a new version then the installed out of browser SL program will automatically update itself.

Silverlight does not include all the controls that WPF has.

My final note is that if you want to churn out code as fast as possible then its pretty obvious you should go with ASP.NET. My major qualms with ASP is that unless you discipline your team it is easy for an ASP.NET project to become cluttered and messy. If you think you will be able to deal with the initial overhead of getting up to speed with the technologies then Silverlight or WPF will allow you a lot of wonderful possibilities.

Title: ASP.Net or WPF(C#)?


问:
End-to-end tests versus unit tests, should tests be decoupled?
At our company we typically make sure that we write an end-to-end test for our websites/web apps. That means we access a URL, fill in a form, submit the form to another URL and check the results of the page. We do this to test form validation, test that the HTML templates have the correct context variables, etc.

We also use it to indirectly test the underlying logic.

I was told by a co-worker that the reason for this is that we can rip out and change the underlying implementation at any point as long as the end-to-end tests pass.

I'm wondering if this sort of decoupling makes sense or if it's just a way to avoid writing tests for smaller units of code?

答:
It verifies system behavior, whereas unit tests verify unit behavior. The benefits and costs for each are different.  You could do one or the other or both.

At my work we do Acceptance Test Driven Development without unit tests which sounds similar to what you've described.  We started out doing both and over time, eventually eliminated unit testing do to the cost exceeding the benefits for us.

That being said I think the cost/benefit for your problem domain and environment should drive the decisions to engage in any development practice, different automated testing practices included.  Rather than faith, I prefer all practices to have empirical evidence within the context of there use to back them up.


答:
Threads should wait for incoming events, not for variable changes.

Incoming events are semaphores becoming available, message queues becoming not empty or time elapsed:

```<code>semGet()
msqRead()
sleep()
</code>```

From the thread point of view, these function calls are blocking: the thread waits until the event has come, leaving CPU load to other threads.

From the system point of view, the thread is marked as 'Waiting for event' and will not be scheduled as long as the event has not come.

About hardware events, they are handled through interrupts which are electric signals to the CPU and which trigger the execution of ISR (interrupt service routines), whose role is to produce a software event on semaphores, message queues or time.

Body:
Threads should wait for incoming events, not for variable changes.

Incoming events are semaphores becoming available, message queues becoming not empty or time elapsed:

semGet()
msqRead()
sleep()

From the thread point of view, these function calls are blocking: the thread waits until the event has come, leaving CPU load to other threads.

From the system point of view, the thread is marked as 'Waiting for event' and will not be scheduled as long as the event has not come.

About hardware events, they are handled through interrupts which are electric signals to the CPU and which trigger the execution of ISR (interrupt service routines), whose role is to produce a software event on semaphores, message queues or time.


问:
Maturity User Guide, Documentation and Ease-of-learning PHP-framework
I'm at the very start of a longtime running project with continual development. Because of that I'm hoping to make a good decision in which Framework will be right for this.

Previously I've worked with Codeigniter. A plusside is the huge community with a great User Guide. A few of the downsides are the backwards compatibility with PHP4 which holds it back and (therefor) the lack of OOP.

Because of that, I'm considering the use of a Framework like Kohana or Yii. I'm writing 'considering' because I'm not sure that the User Guide, Documentation is sufficient for us.

My question is not to start a blog-like upside / downside comparison. My question is whether or not you have experienced drawbacks from a more or less imcomplete User Guide, Documentation like Kohana or Yii.

答: I've found kohana's documentation to be lacking. I chose Laravel instead for my company and I can't recommend it enough. It's well documented and I think you can get a team up to speed pretty quick with it.</p>


答:
Actually end-to-end tests, or integration tests are more important than unit tests since they assure that you have a fully working system. Unit tests don't cover the integration part of a system, which is a complicated task especially in large projects.

However as it has been said, you should do unit testing also, since it is more complicated to catch the edge cases in integration testing.

Title: End-to-end tests versus unit tests, should tests be decoupled?

Body:
At our company we typically make sure that we write an end-to-end test for our websites/web apps. That means we access a URL, fill in a form, submit the form to another URL and check the results of the page. We do this to test form validation, test that the HTML templates have the correct context variables, etc.

We also use it to indirectly test the underlying logic.

I was told by a co-worker that the reason for this is that we can rip out and change the underlying implementation at any point as long as the end-to-end tests pass.

I'm wondering if this sort of decoupling makes sense or if it's just a way to avoid writing tests for smaller units of code?


问:
Are regular expressions a programming language?
In the academic sense, do regular expressions qualify as a programming language?

The motivation for my curiosity is an SO question I just looked at which asked "can regex do X?" and it made me wonder what can be said in the generic sense about the possible solutions using them.

I am basically asking, "are regular expressions Turing complete"?

答:
It is difficult to answer questions of type "is X a Y", if participants of the debate use different definitions of X and Y. It could be that for some definitions, the answer is "yes", and for some definitions the answer is "no". Especially if the answer depends on technical details where the different definitions differ. Also this discussion contains some misinformation, so please have a patience with a longer answer.

What do we mean by a "programming language"?

A simple answer could be "a language used to create programs". Sure, but: what kind of programs? What about a language that could be used to create some kinds of programs, but not other kinds of programs? Here are two specific examples to illustrate the extreme cases:

1) An imaginary language called M works like this: If the program contains the single letter "m", it creates a game of Minesweeper. Everything else is a syntax error.

Intuitively, this is not what we mean by saying "a programming language". But the marketing department of M could argue that it technically fulfills the definition, because it can be used to create a program. Sure, the compiler does some critical parts for you, but that's what compilers do, don't they? A compiler of the C language also translates some simple words into dozens of processor instructions. The M compiler just goes further and makes your job even simpler.

2) If you install the original version of the famous Turbo Pascal, you can write many kinds of programs. But you cannot write a game that runs in the web browser, because the necessary API is simply not there.

So what exactly is the thing that makes Turbo Pascal a programming language, but M doesn't have it? Simply speaking, you can do more in Pascal than in M. But imagine we have a M.NET, which creates a Minesweeper game running in a web browser. So now we have something that Pascal can do and M.NET can't, but we also have something that M.NET can do and Pascal can't. Why should we consider the advantages of Pascal important, and the advantages of M.NET irrelevant?

The answer is that you can write all kinds of algorithms in Pascal, but you can't write algorithms in M or M.NET. Sure, M compiles your command "m", and C compiles your command "strcmp". But you can put "strcmp" in a larger context, for example compare two files line by line, or read thousand strings and sort them alphabetically, or... well, millions of other things. And it is precisely this ability to use given commands in any algorithm which makes the essence of a programming language.

What exactly is an algorithm, and more importantly, what is "any algorithm"? In computer science we use the words Turing-complete. The idea is that there is a set of computer languages, where each of them is able to simulate all of them. One of those languages is the Turing machine, which is why they are called like that. Pascal is there, C is there, Java is there, Python is there, Lisp is there, Smalltalk is there, even XSLT is there. Our hypothetical M and M.NET are not there. You can learn about this more at any university providing a decent computer science course, but the idea is that a Turing-complete language can do anything that another Turing-complete language can do, if you give them the minimum necessary API. (If you give some web-browser API to Pascal, you can create all kinds of games in the web browser. If you give web-browser API to M, you are still only able to create Minesweeper.) We could say metaphorically that if you remove all APIs from a programming language, the important stuff is what remains.

What do we mean by "regular expressions"?

Different programming languages implement them slightly differently. But the original idea was that regular expressions express so-called regular languages. Note that we do not speak about programming languages here, but about (pseudo-)human languages. Imagine that you find some exotic tribe speaking a language consisting only of words "ba", "baba", "bababa" and so on. You could describe this language verbally as "a syllable 'ba' repeated one or more times" or using a regular expression as "(ba)+".

The regular expressions are supposed to express: "nothing", "this letter", "this, followed by that", "this or that", "this, repeated one or more times", and "not this". -- That is the mathematical definition. Anything else is just a convenient shortcut built from the previous components. For example "this, repeated two or three times" can be translated as "this, followed by this, followed by (this or nothing)", but it could be more convenient to write "ba{2,3}" than "baba(ba)?".

In real life, a typical implementation of "regular expressions" implements more than this. For example, using the mathematical definition, a language of "aba", "aabaa", "aaabaaa" and so on -- any number of "a"s, followed by a "b", followed by the same number of "a"s -- is not a regular language. However, many "regular expressions" used today could detect it, using the additional concept of "the same thing that we found before", written as "(a+)b\1". Using this additional concept, we can do some cool things, for example detect words consisting of prime number of letters. Still, we can't do any algorithm... for an explanation why, please study a textbook on formal languages.

So, back to the original topic: are regular expressions (defined either as: expressions describing regular languages in Chomsky hierarchy; or as: the former, plus the \1 operation) a programming language (defined as: Turing-complete)? The answer is no. No, you cannot implement any algorithm using regular expressions, and the ability to implement any algorithm is what people studying computer science typically understand as the essence of programming language.

Of course, anyone can change the answer by insisting on a different definition. As I wrote at the beginning, the technical details are important here. If you get them wrong, you get a wrong answer.

And if you are not interested in technical details, the answer could be: Can you use regular expressions (and nothing else) to make a program? No. So why call it a programming language? (However, an answer like this was downloaded and deleted here, which is why I wrote this longer version.)

EDIT: Also, anyone can create a library implementing their own new variant of "regular expressions" with some added new features. At some moment, the new features may be enough for the whole system to become Turing-complete. A trivial example would be embedding a Turing-complete language using some new syntax; but it can also happen less obviously. Maybe it already happened.


问:
Evaluate one's skill and improve it?
I've taught myself a set of scripting and programming languages and right now I am very pleased with C#, I am the type of person that learns best by doing it and while I am able to create pretty much any kinda of application, my coding and skills are not as good as I wish.

How could I evaluate my skills and see what I should be doing and prioritizing in order to improve my skills specifically with/for C# ?

I've looked around but couldn't find anything specific to my case and perhaps this question doesn't even belong here but rather stackoverflow but I was unsure of it.

Programming is not my job you could say its more like a hobby to me (I work on a pretty different field) and I often use it to sell some applications or for personal usage on my free time.

Would love some guidance if you think you need more information feel free to let me know on a comment or if you think this should be else where or is not a question for this place feel free to let me know and I will remove it.

答: If you are looking to find out about your skills it might be beneficial to look for programming problems to try and solve. I'm sure there are problems from textbooks you could find or something along those lines. I find that practice with solving programming questions/problems can give you a good indication of what you know and what you might want to brush up on. Hope this helps.</p>

Title: Evaluate one's skill and improve it?


问:
How do you stay focused at work?
Sometimes, the things I have to do for my job are interesting and engaging.  Sometimes, they aren't.  Occasionally, they really aren't.

Do you have any particular strategies or tricks for dealing with those dull stretches when your brain would rather be doing anything other than what you're supposed to be doing, particularly when the Internet and its boundless opportunities for interesting Slack beckon?

答: Avoid web browsing non-work related sites (whoops, better go now!)</p>

Title: How do you stay focused at work?


问:
Ship Early, Ship Never
This started as a "Note to Self," so please excuse me if the frustration is all too evident and the writing is less than stellar...

Three major subjects I've had at the forefront of my mind lately:

Motivation

Learning (Curiosity)

Doing (Making)

I've been studying motivation and incentives for months now. It seems there are an infinite number of different motivations that people might have for doing things (I realize that sounds trite but bear with me). I've been really drawn to it because I'm desperate to find out why I do the things I do and why I don't do the things that I want to do but don't do.

I'm in the midst of reading Paul Graham's excellent Hackers and Painters book. In it, he makes the case that hackers and painters are very similar because they are both "makers." Painters make paintings. Hackers make software. Painters don't necessarily need to understand the chemical composition of paint to make beautiful paintings. And hackers don't necessarily need to know 1's and 0's to make beautiful software.

Graham then draws the distinction between disparate computer science fields:

some people seem to be studying mathematics

some people seem to be studying the computers themselves

the hackers are making software.

The difference is incredibly important. It seems the motivation for some is to make beautiful things. And the motivation for the others is to learn out of curiosity. Certain motivations seem obvious to me, but curiosity seems a bit less obvious. I would certainly consider myself as a curious person with a seemingly unquenchable thirst to learn just about everything I can. But this is exactly where the problem comes up.

The thing that scares me so much is that I desperately want to make things. I desperately want to do things. I want to write a book. I want to paint a painting. I want to compose a song. I want to do things like travel. But the strangeness is that I also want to learn things. I want to learn to play guitar. I want to learn about art history. I want to learn more about philosophy and literature.

The key seems to be the balance between learning and doing... between studying and making.

While I'm not sure how much one should learn about a given thing before doing it, I know for certain that I find myself constantly on one side rather than the other. As it stands now (and as far as I can tell I've always been this way), I am a learner and not a doer. I've read great books. I've practiced guitar for years. I've spent countless hours studying programming.

But I've written 0 books. I've composed 0 songs. I've coded 0 beautiful programs. I've painted 0 beautiful paintings. I've started 0 viable businesses.

The scary part of all this is that there are probably countless unfinished works of art in the world. Is this my misanthropic revenge against society and culture to never produce or finish any of the works of art that I start? Perhaps the worst part (aside from this being my natural inclination), is the fact that I f***ing know better. I just finished books like "Getting Things Done" and "Making Ideas Happen." I've aggregated and synthesized countless words of wisdom on how to do things and how to make things.

Imagine the horror of going through life without being able to do the things you want to do. If this is something you've struggled with (and hopefully overcome), please share. If not... perhaps some delicious pity would make me feel better.

[UPDATE: Just wanted to send a quick thanks to everyone that shared their thoughts. I deliberately left the question somewhat open-ended in hopes of encouraging discussion and having others refashion the central problem around their similar experience, and I think it worked out great... there's a lot of amazing insight here to work with and it was really helpful. Thanks again.]

答:
This is the same as my answer on stackoverflow:

"Dan Pink on the surprising science of motivation" is a TED talk that discusses why we do some of the things we do.  You seem to be overly focused on the mastery part of things where you learn how to do something really well and enjoy honing that skill.

Dr. Phil's Life Law captures some of this:

Life Law #3: People do what works.
  Strategy: Identify the payoffs that
  drive your behavior and that of
  others.

Even the most destructive behaviors
  have a payoff. If you did not perceive
  the behavior in question to generate
  some value to you, you would not do
  it. If you want to stop behaving in a
  certain way, you've got to stop
  "paying yourself off" for doing it.

Find and control the payoffs, because
  you can't stop a behavior until you
  recognize what you are gaining from
  it. Payoffs can be as simple as money
  gained by going to work to
  psychological payoffs of acceptance,
  approval, praise, love or
  companionship. It is possible that you
  are feeding off unhealthy, addictive
  and imprisoning payoffs, such as
  self-punishment or distorted
  self-importance.

Be alert to the possibility that your
  behavior is controlled by fear of
  rejection. It's easier not to change.
  Try something new or put yourself on
  the line. Also consider if your need
  for immediate gratification creates an
  appetite for a small payoff now rather
  than a large payoff later.

While overcoming perfectionistic tendencies is part of the solution, another part is understanding the payoff for inaction.  Do you fear the new challenges you'd have in writing a book or composing a song?  Is there the question of how useful would such a book or song be?  At the same time, I'd likely argue you are doing what you like in learning about all this material.

A Strengths Finder blog notes:

My Strengthsfinder 2.0 report said, "People who are especially talented in the Learner theme have a great desire to learn and want to continuously improve. In particular, the process of learning, rather than the outcome, excites them."

People who know me well will confirm this one for you, particularly the part about process versus learning. That's not to say I'm someone who relishes processes themselves, but that I love being in the throes of learning itself.

This learner theme is one of my trifecta of themes that seem to be all parts of one - Input, Intellection and Learner. The seem to all be about information - gathering it, thinking about it, learning more.

This is just to give more perspective here as I have been here many times before and likely will again.

Title: Ship Early, Ship Never


问:
Building a Graph Editor - How to create a data driven graph
I am developing a graph-editor that uses drag and drop to build hierarchical graphs (containing nodes and links). Each node in the graph should be linked to a table in our database (SQL Server). I did a lot of research about libraries based on javascript or/and JSON specifications to draw nodes and links. There are a lot of great examples to follow, but I have no idea about the way I can link a graph to a database (SQL Server, Oracle, MySQL...). I thought about this architecture (Question posted on stackexchange.com)

I have looked at the D3 library. It creates data-driven charts, but I think it only uses flat files, and not relational databases.
First can you please tell me if my architecture is well thought out? And second can you give me some ideas about the way I can link my graphs to the DBMS? Thanks a lot.

答:
D3 is a great library, whose pretty clever design is the result of many years of research. It is the descendant of Protovis, a library that was already very nice at its time. Then the author, Mike Bostock, moved on to something more dynamic (differences are outlined here).

There is a fair amount of weirdness at first sight in D3. The ways you bind visual elements to the data, respond to changes, update the graphs, etc. may not seem intuitive at first. But after a few experiments, following the numerous tutorials and reading the extensive documentation, you become quite productive.

In a first order approximation, you can think of D3 as an SVG canvas. It allows you to create and manipulate, not unlike jQuery, the SVG DOM in an efficient, cross-browser manner. Then realize you can, instead of manually creating SVG nodes, define systematic (i.e. declarative) mappings from data to visual elements. On top of that, D3 allows you do customize, animate, let the user interact with the graph - and many more things.

Regarding your question about the architecture, I think the SO question you link to answers most of it. Yes, it is sound, and it is the way to go if you want to pull your data from a RDMS.

The way we usually design D3 apps is the following:

assume your application is going to eat JSON data - you can always turn other formats to JSON on the server-side, and JSON is much more flexible than all other formats (except perhaps XML but once you've tried to json_encode() a PHP array, you never look back).

create a static index.html file, putting the necessary boostrapping code in a companion app.js file (and a maybe a CSS - the usual stuff). You may want to use one of the examples as a starting point.

create a static data.json file in the exact format you expect the server to send your data. Put some sample data inside. You can also put this JSON data directly inside your app.js script - JSON is Javascript after all.

work on your frontend logic, refine the JSON data format, etc. until you have a decent prototype.

setup a simple web server (e.g. Apache), have it serve the JSON file, and make your prototype work with this instead of the local file

create a server-side script that generate the same "static" file (e.g. using PHP). Test your app.

have the PHP script connect to the database, generate the JSON file on the fly and send it

Now you can work on improving the application: defining different URLs to pull different data streams, create means for the user to filter the data, etc.

These are just ideas to get started. The point here is to minimize the amount of changes between each step, so you learn things one by one, and keep focused on the parts that are really difficult: the client application. Binding to a server that generates real-time data is just a step forward once you have a good app.


问:
What are the main differences between FUML and the Executable UML profile?
I'd like to know what are the main difference between the Foundational Subset for Executable UML models and the Executable UML profile (which followed the Schlaer-Mellor methodology).

Thank you

答:
Quote from Ed Seidewitz to this exact question:

fUML is the culmination of a long quest of Stephen Mellor's at OMG, so, in that sense, it is targeted at Executable UML. However, since the OMG community interested in UML execution semantics goes beyond just the Shlaer-Mellor community (submitters, for example, included IBM and Care, as well as Mentor Graphics and [then] Kennedy-Carter), the resulting specification had to be targeted at (generic) executable UML.

The goal of the specification is to give a precise semantics to a reasonable executable subset of UML, not to be specific to any executable modeling methodology. Stephen's goal, though, was, of course, that this would also provide the basis for the next step in Executable UML, providing execution tool interoperability through standardization.

As to Alf, that is again a compromise among the desires of the various submitters. There was a strong general feeling on the submission team, however, that it had to syntactically "look like Java/C++/C#" to be accepted in the "mainstream" (IBM pushed particularly hard for an essentially Java-syntax minimum compliance point), and C-legacy syntax makes any language unfortunately much harder to process. Bit strings were an absolute requirement of the real-time folks -- but note that, at least, Alf bit strings are abstracted from just being the integers they are in C and Java.

So, Alf is intended to look familiar to programmers who are not already in the executable UML camp, but to have the underlying concurrent data-flow activity model execution semantics of fUML. I see this as similar to the decision to make Java look like C++, though it also has very different underlying semantics.

It remains to be seen how well it will work -- but it already has sparked a good deal of vendor interest.

This means that fUML is an e xecutable UML and not E xecutable UML


答:
I had the same problem after getting into the world of programming. One thing I came to know is.. there is no end!... if you don't find it. Every day or month or year there are updates and many things get added.

But when it comes to the point where we should get a conclusion it becomes harder and harder.I would like to repeat the saying. No matter how much you know but, you should be expert in whatever you know. To this point I think you can go ahead and take some online free quiz  and tests and problems. Where ever you fail take some time and read it once and continue till you get a solution.

Books are always a good friends but they can be best if you practice. Of course Practice is one of the important step in programming.

Once if you get a good control over what that language is, then its OK. You are on your way. Along with books I would prefer documentation. Books cannot cover all the things about an API they are introductory. Some times they can give a good knowledge.

Do some applications on your own. Consider some applications and try to clone them and it should be just for the sake of your understanding. I'll say you one more thing that I do which might sound little crazy. I keep stackoverflow open all the time. When ever I see a question that comes under my favorite tags, I read the problem. If I know I'll try to answer or else I'll wait till it gets an answer. This way I got to know about a new problem and a solution as well.

Now, when you hear a problem statement and if it is new to you and if you are able to solve it then its great. You are in a good way. But when it comes to the point about how efficiently you can do it with best design considerations and so on does matter. this way you can get to know about how you good you are. With that said all the best and hope this helps.

Title: Evaluate one's skill and improve it?

Body:
I've taught myself a set of scripting and programming languages and right now I am very pleased with C#, I am the type of person that learns best by doing it and while I am able to create pretty much any kinda of application, my coding and skills are not as good as I wish.

How could I evaluate my skills and see what I should be doing and prioritizing in order to improve my skills specifically with/for C# ?

I've looked around but couldn't find anything specific to my case and perhaps this question doesn't even belong here but rather stackoverflow but I was unsure of it.

Programming is not my job you could say its more like a hobby to me (I work on a pretty different field) and I often use it to sell some applications or for personal usage on my free time.

Would love some guidance if you think you need more information feel free to let me know on a comment or if you think this should be else where or is not a question for this place feel free to let me know and I will remove it.


问:
Diagrams used to model the architecture and functionality of a website
I am attempting to understand what UML models/diagrams can be used to communicate a websites architecture.

The model or models' purpose is to communicate the architecture and functionality of a website to technical people (other software developers and engineers).

Website Features:

- The website is a recipe search engine

- Server side code is Python. Client side uses HTML, CSS, JQuery and AJAX.

- The website will have a Web Crawler/Indexer

- Infinite Scrolling is utilised when viewing search results so I will need to model asynchronous requests (both GET and POST).

The diagrams I am tending towards are Component Diagram (to communicate the architecture) and Sequence Diagram (to communicate the functionality of a HTTP request).

What diagrams have you used in the past to communicate the architecture and functionality of a website to technical people?

答:
If you think that UML models and diagrams only serve to communicate the architecture to technical people, you might probably be wrong, since architecture has to be communicated to a lot of other people, especially to those sitting in management with black suits and wanting to have some good reasons why money/time/resource has to be spent in order to realize a specific architecture.

That's also one of the reasons, why UML provides such a large set of different diagrams, which simply aim at different stakeholders with different (technical) knowledge.

Another reason for using different diagrams is simply the complexity of a project. In general you can have static (concerning structures), dynamic (concerning runtime behavior) and allocation (concerning environment mapping) views on a software project. Including them in one diagram would result in a big mess, so you split them up to just have a part of the overall-complexity in one diagram.

Relating to your approach, the component diagram is a static view on the system and the sequence diagram is a dynamic view on the system, so this is quite a good start for documenting architecture.

It's also clear that you don't have the time/money to document each and every possible view/diagram for your system. The consequence is that you have to choose the most important ones, but between which criteria? One the one hand, you have to determine the main kind of complexity in your system. Since web projects have mainly runtime behavior, you would concentrate on the dynamic view of your system. On the other hand, quality attributes like performance or availability play an important role in determining your efforts in documenting, since they are cross-cutting your whole project and therefore cost a lot if you missjudge them.

And as I mentioned above, if black-suited guys hear the cost-bell ringing, they want to get thorough justification and what would in this case be better than having some diagrams in your pocket describing the most complex system-parts with stakeholder-adjusted complexity?

In order to get a general understanding on architecture documentation, I strongly recommend the paper by Philippe Kruchten Architectural Blueprints - The 4+1 View Model After you have read it, it might be much easier for you to determine which models/diagrams you need.


答:
If you're programming for fun/hobby anyway, why not release something useful/interesting through GitHub or other open access site? Besides sharing what you have, you could get some evaluation of your programming style/level, especially if you mention that you'll welcome comments.

Such an activity may also lead to collaboration on one of your or someone else's project. Being able (and willing) to collaborate is a nice skill to cultivate and some might even say it's necessary for an experienced programmer.

Title: Evaluate one's skill and improve it?


答:
It sounds like you're doing this for fun, and just looking to increase your overall knowledge. In some ways that makes things harder because presumably you don't have any particular priorities on what you learn? And while you may want to learn, there's nothing you are specifically focussed on.

I mean, if you have a specific problem to solve, then in many ways life becomes easy - you focus on the problem and learn whatever is necessary to solve it. And in fact, that's how I've always tended to pick up new technologies. In a few cases, for example when .net first came out, I invented the problem myself in order to learn c# and asp.net, then proceeded to solve it. (Had an idea for a web site, went away and built it.)

So, as others have said, you could go away and almost "invent" problems, then enhance your skills by solving them. And you specifically mention c#....I'm just thinking that there must be lots of opportunities to develop small, useful utilities in the Windows Phone arena right now. It's just a thought (and the task of deciding what people might be useful may be difficult).

For example I know a guy who's a really good c# developer and is just one of those people who is interested in technology. He wanted to get into Windows Phone and started writing a couple of small apps. These days he tweets every now and then about how his app is one of the top downloaded apps. Not sure if he earns anything from it, all it is is an alarm clock app, so quite noddy. But you can imagine he's achieved exactly what he wanted in terms of his learning experience.

Lastly since you mention c#, are you aware that Microsoft offer certification qualifications in a number of technology areas? Clearly this is aimed at software professionals, but there's nothing to stop you......

But again, the whole point here is to give you something to focus on.

Title: Evaluate one's skill and improve it?