答:
A line such as CurrentGame.CurrentPlayer would be a code smell to me. In fact there's something fishy about the whole question.

You say that the second method, StartWithCurrentPlayer, would require an additional SetCurrentPlayer method. But how is that different from what CurrentGame.CurrentPlayer already is in the first method? Where does the value for CurrentPlayer come from?

There seem to be 3 possible scenarios here, none of which really make sense with either of your approaches:

The game knows nothing about players until it's started.

In this scenario, I'd expect to see a method like this inside the Game class:

```<code> public void Start(Player player)
 {
     // Set stuff up
     this.currentPlayer = player;
 }
</code>```

The player can be changed at any time.

This is a legitimate use case, e.g. arcade or multiplayer games. It's a little difficult to plan for, though. You'd have a class that looks like this:

```<code> public void Start()
 {
     LoadLevel(CurrentPlayer.LastLevel);
     // Or whatever - some stuff that depends on CurrentPlayer
 }

 public Player CurrentPlayer
 {
     get { ... }
     set { ... }
 }
</code>```

You'd have to be very careful to make sure you do the proper setup/cleanup when CurrentPlayer is changed, otherwise I would foresee strange errors due to Sequential Coupling. For example, what happens when you try to start a game without setting any player? Still, this is a design decision, not necessarily an error.

The player must be set up prior to starting a game.

This essentially means that the Game has no lifetime or meaning of its own without a Player object, which cries out for a dependency tree:

```<code> public class Game
 {
     private readonly Player player;

     public Game(Player player)
     {
       if (player == null) throw new ArgumentNullException("player");
       this.player = player;
     }

     public void Start() { ... }
 }
</code>```

Your first example violates the Tell, Don't Ask principle. You should never (well, rarely) need to call a method on an object and provide the same object's data as a parameter. That's exactly the kind of what OOP is designed to avoid with encapsulation.

Your original second example is similar to #2. It's potentially correct, but only if that is actually your intent, and it is also the most complicated.

Try to think about object lifetimes. #1 implies that the Game lasts forever, but if you switch the Player then you need to restart the game. #2 implies that the Game lasts forever but continues from its current point even when the Player is changed. And #3 implies that the Player may last a lot longer than the Game (for example a role-playing game). All are valid, but use the appropriate one for your particular situation.

Body:
A line such as CurrentGame.CurrentPlayer would be a code smell to me. In fact there's something fishy about the whole question.

You say that the second method, StartWithCurrentPlayer, would require an additional SetCurrentPlayer method. But how is that different from what CurrentGame.CurrentPlayer already is in the first method? Where does the value for CurrentPlayer come from?

There seem to be 3 possible scenarios here, none of which really make sense with either of your approaches:

The game knows nothing about players until it's started.

In this scenario, I'd expect to see a method like this inside the Game class:

 public void Start(Player player)
 {
     // Set stuff up
     this.currentPlayer = player;
 }

The player can be changed at any time.

This is a legitimate use case, e.g. arcade or multiplayer games. It's a little difficult to plan for, though. You'd have a class that looks like this:

 public void Start()
 {
     LoadLevel(CurrentPlayer.LastLevel);
     // Or whatever - some stuff that depends on CurrentPlayer
 }

 public Player CurrentPlayer
 {
     get { ... }
     set { ... }
 }

You'd have to be very careful to make sure you do the proper setup/cleanup when CurrentPlayer is changed, otherwise I would foresee strange errors due to Sequential Coupling. For example, what happens when you try to start a game without setting any player? Still, this is a design decision, not necessarily an error.

The player must be set up prior to starting a game.

This essentially means that the Game has no lifetime or meaning of its own without a Player object, which cries out for a dependency tree:

 public class Game
 {
     private readonly Player player;

     public Game(Player player)
     {
       if (player == null) throw new ArgumentNullException("player");
       this.player = player;
     }

     public void Start() { ... }
 }

Your first example violates the Tell, Don't Ask principle. You should never (well, rarely) need to call a method on an object and provide the same object's data as a parameter. That's exactly the kind of what OOP is designed to avoid with encapsulation.

Your original second example is similar to #2. It's potentially correct, but only if that is actually your intent, and it is also the most complicated.

Try to think about object lifetimes. #1 implies that the Game lasts forever, but if you switch the Player then you need to restart the game. #2 implies that the Game lasts forever but continues from its current point even when the Player is changed. And #3 implies that the Player may last a lot longer than the Game (for example a role-playing game). All are valid, but use the appropriate one for your particular situation.


问:
Why is quantity in software still written as "1 result(s)"?
Lately, I've been noticing that a lot of software, be it a website, a client application, or a video game, often write a representation of quantity as follows: "1 result(s)". Now, I can understand why they would do that 20 years ago. But these days, shouldn't we have enough processing power and memory to be able to say "1 result" and "2 results"?

Is there some sort of special reason why it's still done this way?

Now before you tell me to Google it, I would. But the thing is, I have no idea what search terms to use. So even some suggested search terms would be welcome.

答:
Imlementing "1 result(s)" is easier and faster.

EDIT: And it makes the code shorter and therefore easier to understand.

ContentLicense: CC BY-SA 3.0


问:
What are the negatives of Development Managers as Scrum Masters?
It is commonly agreed that team managers should not be scrum masters, but I am struggling to see why.  For context, I am an Application Development Manager with 4 devs in a Scrum Team.  I come from a Scrum Master background, and have introduced scrum to the organisation.  I have built the team from scratch and made it clear that everything I do is to facilitate the team, and that they make the decisions.  As a team we are very open - they even silenced me at stand-ups for a while to eliminate the 'reporting' feel we were starting to get.  A lack of openness is generally the biggest argument against the manager as scrum master, but handled well, is easily overcome with the right culture.

I've been warned by experienced scrum coaches that this is a dangerous situation, and there are risks 'if things go badly'.  The way I see it the 2 positions do not conflict, in both roles I have the same aim for the team and individuals. Scrum resolves conflicts within the team, which could traditionally be a managers role. The self-managing nature of sprints takes away the allocation of work a manager would traditionally do.

All I really see left to pick up as a dev manager is making sure individuals needs are met, career objectives, workplace etc. I have a weekly catch up with each team member to raise any issues, and handle any admin tasks. A lot of this relates directly to the team, or my role as scrum master anyway.

I understand in large organisations how this could be unmanageable and a separate role but for a small organisation we could certainly not justify another Scrum Master or Development Manager.

Please enlighten me as to the pitfalls of Development Managers as Scrum Masters, excluding the points I raised above and have already overcome.

答:
I have actually seen what happens when a "technical manager" gets too heavily involved in the day-to-day mechanics of a project, and it isn't pretty. In our case, the manager in question was not the scrum master but was trying to co-opt some of those decisions; if we hadn't actually had a separate scrum master to play defense then it would have been far more painful.

(Incidentally, this was not my manager, so I feel fairly objective on this point.)

I'll go over what I saw as the primary conflicts of interest; if you don't think that any of these apply to your situation, then maybe you can do both. But make sure you re-check these assumptions on a regular basis to make sure you're not falling into any of these traps:

Technical managers are typically responsible for a certain role within multiple teams. If it's only one team, then it's more of a "lead" than a "manager". This spreading-out of responsibility means less time with the team and less time with the project/product, and tends to lead to "hit and run" style management.

Technical managers have many other managerial duties to the business. They need to do coaching/training, performance reviews, interviews/hiring, long-term infrastructure/resource planning, and more. This can easily become a full-time job by itself and means very little remains to spend on facilitating.

A busy schedule can also impose itself on the team; technical managers may need (or want) to pull team members into meetings at what the team deems to be an inopportune time. It's normally the scrum master's job to manage and try to eliminate interruptions, but it's impossible to be objective about that when you have your own schedule to worry about. Scrum masters rarely need to meet separately with team members because all of those meetings are already pre-scheduled (stand-ups, retrospectives, etc.)

Technical managers must deal with cross-cutting project concerns and their natural impulse will be to try to standardize everything - libraries, source control, algorithms, layouts, colours, whatever. While this can actually be a good thing for the company, it ultimately leaves no one to go to bat for what the team wants to do, and they may have very good reasons for wanting to do something differently. This runs counter to the "continuous improvement" ideals underlying Scrum and similar methodologies.

Managers who come from an expert background in the role they manage will have their own fairly strong ideas about how the work should be done and how long it should take. This is not a bad thing as a manager, but as a scrum master it will often mean biasing team members into designs or estimates that they wouldn't otherwise have agreed on - and they probably know more than you about the problem at hand.

Team members will always have trouble differentiating between a request and an order. They won't tell you this and may not even realize it themselves. Even if you make it clear that you are merely asking and not telling, in their minds, you are still their manager and there are career-level risks to saying "no". This is probably the most insidious of all the problems because there's nothing you can do about it - it's their attitude and not yours that matters.

If you're sure that you're never going to fall into any of these traps, then go for it... but I repeat, make sure you frequently validate your assumptions by talking to your team (and other teams/managers!) and make sure that they're not happening in a subtle or unconscious way that maybe you don't notice.

On a positive note, I'll add that the fact that you consider the issue important enough to actually ask the question means that you're probably pretty good at both roles. Caring about the team and not just your own career ambitions probably accounts for more than half of what good management is, in my books anyway.

...but being good at both doesn't necessarily mean you can be good at both at the same time, all the time. Be careful of that.


答:
Have you considered localization?

It may look simple to write something like:

```<code>var text = (count > 0) ? "items" : "item"
</code>```

But it's nowhere near that simple when you have to work in multiple languages. Here's an example, just using Google Translate:

```<code>Language        | Singular                  | Plural
----------------+---------------------------+-----------------
English         | 1 item found              | 2 items found
French          | 1 article trouvé          | 2 objets trouvés
Spanish         | 1 artículo encontrado     | 2 artículos encontrados
German          | 1 Artikel gefunden        | 2 Artikel gefunden
Hebrew          | מצא פריט 1                | 2 פריטים נמצאו
Arabic          | وجدت بند 1                | 2 أصناف تم العثور عليها
Korean          | 1 개 항목 발견             | 2 항목 발견
</code>```

Now, granted, Google Translate may not be doing a perfect job here. But isn't that partly the point? This isn't all that simple. You can't just add an "s" and be done with it. Not in production code, anyway. It's way simpler to just use the plural form with parentheses - you only have one resource to localize that way.

Title: Why is quantity in software still written as "1 result(s)"?

Body:
Lately, I've been noticing that a lot of software, be it a website, a client application, or a video game, often write a representation of quantity as follows: "1 result(s)". Now, I can understand why they would do that 20 years ago. But these days, shouldn't we have enough processing power and memory to be able to say "1 result" and "2 results"?

Is there some sort of special reason why it's still done this way?

Now before you tell me to Google it, I would. But the thing is, I have no idea what search terms to use. So even some suggested search terms would be welcome.

Body:
Have you considered localization?

It may look simple to write something like:

var text = (count > 0) ? "items" : "item"

But it's nowhere near that simple when you have to work in multiple languages. Here's an example, just using Google Translate:

Language        | Singular                  | Plural
----------------+---------------------------+-----------------
English         | 1 item found              | 2 items found
French          | 1 article trouvé          | 2 objets trouvés
Spanish         | 1 artículo encontrado     | 2 artículos encontrados
German          | 1 Artikel gefunden        | 2 Artikel gefunden
Hebrew          | מצא פריט 1                | 2 פריטים נמצאו
Arabic          | وجدت بند 1                | 2 أصناف تم العثور عليها
Korean          | 1 개 항목 발견             | 2 항목 발견

Now, granted, Google Translate may not be doing a perfect job here. But isn't that partly the point? This isn't all that simple. You can't just add an "s" and be done with it. Not in production code, anyway. It's way simpler to just use the plural form with parentheses - you only have one resource to localize that way.


答:
What are the negatives of Development Managers as Scrum Masters?

Development managers are hired to:

Solve development problems.

Monitor and reduce technical debt.

Grow the technical staff.

Their background and expertise predispose them to focus on technical issues.

On the other hand, project managers/scrum masters are hired to;

Ensure project success.

Assign work and triage bugs/questions to the appropriate development resources.

Collaborate with the development team to remove all obstacles that may delay project completion.

Relay project status to upper management.

When a project or a company grows to a certain size, it is inefficient and unwise to ask a development manager to perform both duties.

A development manager should be inclined to take "deep dives" into code and/or architecture, whereas a project manager/scrum master should always be concerned with the "50,000 foot" view of things.

Most development managers have spent years developing code. Development issues are very familiar to them.

Therefore, they are most useful when they are solving technical problems.

Project manager/scrum master roles require people who are very organized and very detailed oriented, but not super-technical.

When you can afford to let these people specialize on the things that they are good at, the business is most efficient.

And when you can offload scrum-related responsibilities from a development manger's plate, he/she can spend more time on technical issues and reducing technical debt.

Body:
It is commonly agreed that team managers should not be scrum masters, but I am struggling to see why.  For context, I am an Application Development Manager with 4 devs in a Scrum Team.  I come from a Scrum Master background, and have introduced scrum to the organisation.  I have built the team from scratch and made it clear that everything I do is to facilitate the team, and that they make the decisions.  As a team we are very open - they even silenced me at stand-ups for a while to eliminate the 'reporting' feel we were starting to get.  A lack of openness is generally the biggest argument against the manager as scrum master, but handled well, is easily overcome with the right culture.

I've been warned by experienced scrum coaches that this is a dangerous situation, and there are risks 'if things go badly'.  The way I see it the 2 positions do not conflict, in both roles I have the same aim for the team and individuals. Scrum resolves conflicts within the team, which could traditionally be a managers role. The self-managing nature of sprints takes away the allocation of work a manager would traditionally do.

All I really see left to pick up as a dev manager is making sure individuals needs are met, career objectives, workplace etc. I have a weekly catch up with each team member to raise any issues, and handle any admin tasks. A lot of this relates directly to the team, or my role as scrum master anyway.

I understand in large organisations how this could be unmanageable and a separate role but for a small organisation we could certainly not justify another Scrum Master or Development Manager.

Please enlighten me as to the pitfalls of Development Managers as Scrum Masters, excluding the points I raised above and have already overcome.


问:
Functional programming and stateful algorithms
I'm learning functional programming with Haskell. In the meantime I'm studying Automata theory and as the two seem to fit well together I'm writing a small library to play with automata.

Here's the problem that made me ask the question. While studying a way to evaluate a state's reachability I got the idea that a simple recursive algorithm would be quite inefficient, because some paths might share some states and I might end up evaluating them more than once.

For example, here, evaluating reachability of g from a, I'd have to exclude f both while checking the path through d and c:

So my idea is that an algorithm working in parallel on many paths and updating a shared record of excluded states might be great, but that's too much for me.

I've seen that in some simple recursion cases one can pass state as an argument, and that's what I have to do here, because I pass forward the list of states I've gone through to avoid loops. But is there a way to pass that list also backwards, like returning it in a tuple together with the boolean result of my canReach function? (although this feels a bit forced)

Besides the validity of my example case, what other techniques are available to solve this kind of problems? I feel like these must be common enough that there have to be solutions like what happens with fold* or map.

So far, reading learnyouahaskell.com I didn't find any, but consider I haven't touched monads yet.

(if interested, I posted my code on codereview)

答:
Functional programming doesn't get rid of state. It only makes it explicit! While it's true that functions like map will often "unravel" a "shared" data structure, if all you want to do is write a reachability algorithm then it's just a matter of keeping track of what nodes you already visited:

import qualified Data.Set as S
data Node = Node Int [Node] deriving (Show)

-- Receives a root node, returns a list of the node keyss visited in a depth-first search
dfs :: Node -> [Int]
dfs x = fst (dfs' (x, S.empty))

-- This worker function keeps track of a set of already-visited nodes to ignore.
dfs' :: (Node, S.Set Int) -> ([Int], S.Set Int)
dfs' (node@(Node k ns), s )
  | k  `S.member` s = ([], s)
  | otherwise =
    let (childtrees, s') = loopChildren ns (S.insert k s) in
    (k:(concat childtrees), s')

--This function could probably be implemented as just a fold but Im lazy today...
loopChildren :: [Node] -> S.Set Int -> ([[Int]], S.Set Int)
loopChildren []  s = ([], s)
loopChildren (n:ns) s =
  let (xs, s') = dfs' (n, s) in
  let (xss, s'') = loopChildren ns s' in
  (xs:xss, s'')

na = Node 1 [nb, nc, nd]
nb = Node 2 [ne]
nc = Node 3 [ne, nf]
nd = Node 4 [nf]
ne = Node 5 [ng]
nf = Node 6 []
ng = Node 7 []

main = print $ dfs na -- [1,2,5,7,3,6,4]
```

<p>Now, I must confess that keeping track of all this state by hand is pretty annoying and error prone (it's easy to use s' instead of s'', it's easy to pass the same s' to more than one computation...). This is where monads come in: they don't add anything you couldn't already do before but they let you pass the state variable around implicitly and the interface guarantees that it happens in a single-threaded manner.</p>

<hr>

<p>Edit: I'll attempt to give a more reasoning of what I did now: first of all, instead of just testing for reachability I coded a depth-first search. The implementation is going to look pretty much the same but the debugging looks a bit better.</p>

<p>In a stateful language, the DFS would look kind of like this:</p>

<pre class="lang-python prettyprint-override"><code>visited = set()  #mutable state
visitlist = []   #mutable state
def dfs(node):
   if isMember(node, visited):
       //do nothing
   else:
       visited[node.key] = true
       visitlist.append(node.key)
       for child in node.children:
         dfs(child)
</code>```

Now we need to find a way to get rid of the mutable state. First of all we get rid of the "visitlist" variable by making dfs return that instead of void:

visited = set()  #mutable state
def dfs(node):
   if isMember(node, visited):
       return []
   else:
       visited[node.key] = true
       return [node.key] + concat(map(dfs, node.children))
```

<p>And now comes the tricky part: getting rid of the "visited" variable. The basic trick is to use a convention where we pass the state as an additional parameter to functions that need it and have those functions return the new version of the state as an extra return value if they want to modify it.</p>

<pre class="lang-hs prettyprint-override"><code>let increment_state s = s+1 in
let extract_state s = (s, 0) in

let s0 = 0 in
let s1 = increment_state s0 in
let s2 = increment_state s1 in
let (x, s3) = extract_state s2 in
-- and so on...
</code>```

To apply this pattern to the dfs, we need to change it to receive the "visited" set as an extra parameter and to return the updated version of "visited" as an extra return value. Additionally, we need to rewrite the code so that we are always passing forward the "most recent" version of the "visited" array:

def dfs(node, visited1):
   if isMember(node, visited1):
       return ([], visited1) #return the old state because we dont want to  change it
   else:
       curr_visited = insert(node.key, visited1) #immutable update, with a new variable for the new value
       childtrees = []
       for child in node.children:
          (ct, curr_visited) = dfs(child, curr_visited)
          child_trees.append(ct)
       return ([node.key] + concat(childTrees), curr_visited)
```

The Haskell version does pretty much what I did here, except that it goes all the way and uses an inner recursive function instead of mutable "curr_visited" and "childtrees" variables.

As for monads, what they basically accomplish is implicitly passing the "curr_visited" around, instead of forcing you to do it by hand. Not only does this remove clutter from the code, but it also prevents you from making mistakes, such as forking state (passing the same "visited" set to two subsequent calls instead of chaining the state).

Body:
Functional programming doesn't get rid of state. It only makes it explicit! While it's true that functions like map will often "unravel" a "shared" data structure, if all you want to do is write a reachability algorithm then it's just a matter of keeping track of what nodes you already visited:

import qualified Data.Set as S
data Node = Node Int [Node] deriving (Show)

-- Receives a root node, returns a list of the node keyss visited in a depth-first search
dfs :: Node -> [Int]
dfs x = fst (dfs' (x, S.empty))

-- This worker function keeps track of a set of already-visited nodes to ignore.
dfs' :: (Node, S.Set Int) -> ([Int], S.Set Int)
dfs' (node@(Node k ns), s )
  | k  `S.member` s = ([], s)
  | otherwise =
    let (childtrees, s') = loopChildren ns (S.insert k s) in
    (k:(concat childtrees), s')

--This function could probably be implemented as just a fold but Im lazy today...
loopChildren :: [Node] -> S.Set Int -> ([[Int]], S.Set Int)
loopChildren []  s = ([], s)
loopChildren (n:ns) s =
  let (xs, s') = dfs' (n, s) in
  let (xss, s'') = loopChildren ns s' in
  (xs:xss, s'')

na = Node 1 [nb, nc, nd]
nb = Node 2 [ne]
nc = Node 3 [ne, nf]
nd = Node 4 [nf]
ne = Node 5 [ng]
nf = Node 6 []
ng = Node 7 []

main = print $ dfs na -- [1,2,5,7,3,6,4]

Now, I must confess that keeping track of all this state by hand is pretty annoying and error prone (it's easy to use s' instead of s'', it's easy to pass the same s' to more than one computation...). This is where monads come in: they don't add anything you couldn't already do before but they let you pass the state variable around implicitly and the interface guarantees that it happens in a single-threaded manner.

Edit: I'll attempt to give a more reasoning of what I did now: first of all, instead of just testing for reachability I coded a depth-first search. The implementation is going to look pretty much the same but the debugging looks a bit better.

In a stateful language, the DFS would look kind of like this:

visited = set()  #mutable state
visitlist = []   #mutable state
def dfs(node):
   if isMember(node, visited):
       //do nothing
   else:
       visited[node.key] = true
       visitlist.append(node.key)
       for child in node.children:
         dfs(child)

Now we need to find a way to get rid of the mutable state. First of all we get rid of the "visitlist" variable by making dfs return that instead of void:

visited = set()  #mutable state
def dfs(node):
   if isMember(node, visited):
       return []
   else:
       visited[node.key] = true
       return [node.key] + concat(map(dfs, node.children))

And now comes the tricky part: getting rid of the "visited" variable. The basic trick is to use a convention where we pass the state as an additional parameter to functions that need it and have those functions return the new version of the state as an extra return value if they want to modify it.

let increment_state s = s+1 in
let extract_state s = (s, 0) in

let s0 = 0 in
let s1 = increment_state s0 in
let s2 = increment_state s1 in
let (x, s3) = extract_state s2 in
-- and so on...

To apply this pattern to the dfs, we need to change it to receive the "visited" set as an extra parameter and to return the updated version of "visited" as an extra return value. Additionally, we need to rewrite the code so that we are always passing forward the "most recent" version of the "visited" array:

def dfs(node, visited1):
   if isMember(node, visited1):
       return ([], visited1) #return the old state because we dont want to  change it
   else:
       curr_visited = insert(node.key, visited1) #immutable update, with a new variable for the new value
       childtrees = []
       for child in node.children:
          (ct, curr_visited) = dfs(child, curr_visited)
          child_trees.append(ct)
       return ([node.key] + concat(childTrees), curr_visited)

The Haskell version does pretty much what I did here, except that it goes all the way and uses an inner recursive function instead of mutable "curr_visited" and "childtrees" variables.

As for monads, what they basically accomplish is implicitly passing the "curr_visited" around, instead of forcing you to do it by hand. Not only does this remove clutter from the code, but it also prevents you from making mistakes, such as forking state (passing the same "visited" set to two subsequent calls instead of chaining the state).

ContentLicense: CC BY-SA 4.0


问:
I'm writing about language syntax. Is there a language out there in which parameters are placed inside method name?
in JavaScript:

function getTopCustomersOfTheYear(howManyCustomers, whichYear) {
   // Some code here.
}
getTopCustomersOfTheYear(50, 2010);
```

<p>in C#:</p>

<pre class="lang-cs prettyprint-override"><code>public List<Customer> GetTopCustomersOfTheYear(int howManyCustomers,
 int whichYear)
{
   // Some code here
}
List<Customer> customers = GetTopCustomersOfTheYear(50, 2010);
</code>```

in PHP:

public function getTopCustomersOfTheYear($howManyCustomers, $whichYear)
{
   // Some code here
}
$customers = getTopCustomersOfTheYear(50, 2010);
```

<p>Is there any language out there which support this syntax:</p>

<pre class="lang-c prettyprint-override"><code>function GetTop(x)CustomersOfTheYear(y)
{
    // Some code here
}
returnValue = GetTop(50)CustomersOfTheYear(2010);
</code>```

Isn't it more semantic, more readable form of writing a function?

Update: The reason I'm asking this question is that, I'm writing an article about a new syntax for a new language. However, I thought that having such syntax for declaring methods could be nicer and more friendly to developers and would decrease learning-curve of the language, because of being more closer to natural language. I just wanted to know if this feature has already been contemplated upon or not.

答:
You can emulate this in python. For example,

def GetTop(customers, ofYear):
  #write some code here to get the customers

print GetTop(customers=50 ofYear=2010)
```

<p>or even</p>

<pre class="lang-python prettyprint-override"><code>def GetTop(**args):
  #write some code here using the same parameter names as above

print GetTop({customers: 50, ofYear: 2010})
</code>```

Body:
You can emulate this in python. For example,

def GetTop(customers, ofYear):
  #write some code here to get the customers

print GetTop(customers=50 ofYear=2010)

or even

def GetTop(**args):
  #write some code here using the same parameter names as above

print GetTop({customers: 50, ofYear: 2010})


问:
Authentication at my web site using other credentials
Suppose there are 2 web site: example.com I don't own and example2.com I own. I want to extend the functionality of example.com somehow.

example.com doesn't have any API. I want the users of example.com to be able to login at example2.com using their logins and passwords of example.com. However, since example.com doesn't have any API, it is not easy to do, perhaps, it is even impossible.

No doubt, no one would agree to enter their credentials of example.com at example2.com due to many obvious reasons.

So, is there any way to authenticate the users of example.com at example2.com (or somewhere else) using their original credentials?

答:
As far as I know, you need one (or more) of the following things to do single sign-on:

A shared root-level domain, e.g. all sites are subdomains of example.com. They can share a cookie this way, assuming both sites understand the format.

A shared credential database (SQL, LDAP, etc.) with both sites knowing how to validate the credentials (e.g. type of hashing used on the passwords).

A trust system such as WS-Federation supported by all participating sites.

An authentication API supported by at least one of the participating sites (such as OAuth).

From your rather vague description, it sounds like you lack any of the above, so the answer is no, you can't do this - not without tricking the users in an essentially criminal fashion.


问:
Scalability of using environment variables
I just moved into the Ruby on Rails world and with it I am being introduced to much more liberal use of environment variables than what I have been exposed to in the past. Specifically, it appears like there's an accepted convention to store third party API keys and secret tokens as environment variables.

NOTE: this is not a RoR-specific question. I only mention it to illustrate a point of view.

I certainly see the benefit of this approach; the largest of which is that one codebase can be identically deployed to multiple servers without changing code or fear that the the app will be using the wrong resource. However, I am wary about jumping on the band wagon.

First, the approach doesn't seem scalable on my development work station (laptop), or on servers. If I am working on 10 different websites, and each are using Amazon S3 (for instance), I need 10 different EVs. Management will be difficult:

naming collisions are a distinct possibility (especially if I am working on legacy projects that I dont have complete control over);

visibility is murky (which EVs exist on the target machine? which have been or can be decommissioned?);

no version control (who changed the EV? when? why?)

Second, one of the main selling-points as I understand it, is that using EVs takes the sensitive data out of the repository where prying eyes could see it. This only seems like it should be an issue for public repositories, which I have none. All my repos are private, often because of contractual issues like NDA or ownership rights.

How does all of this play out in real life scenarios? Is this approach better for some situations than others? Are there other pros that outweigh my concerns here?

答:
Environment variables are a set of key/value pairs for configuring... the environment (meaning things that pertain directly to the operating system, such as shared folder locations, for example).

As an application configuration tool, I've never been a big fan of environment variables or registry settings, preferring configuration files for all of the same reasons you have already stated.

Configuration files give you:

Complete control of the format used to store the settings

The ability to store objects, with the help of serialization

The ability to store complex structures such as trees, etc.


答:
In this case, you need to ask the owner of example.com to share with you his authentication method with you (if it's a friend of you, or a partner, otherwise it's very unlikely he accept to share something as sensitive with you).

Assuming the owner of example.com is using a MySQL database with a specific table for users and password and that he is willing to help you with this, here is a example of what to do:

he needs to create for you a remote MySQL user with read access to the users table from example2.com (e.g.: auth%[ip.of.example2.com]);

he also needs to permit remote connection to his MySQL database (firewall –preferably with ip filtering- and my.cnf);

then, he has to provide to you the way he store the password (hash algorithm, salt method…);

at this point, when a user try to login to example2.com, you just have to create a MySQL connection to his server, and check the credentials…

Even if all this is really moot, I hope this will help a little.

Title: Authentication at my web site using other credentials

Body:
Suppose there are 2 web site: example.com I don't own and example2.com I own. I want to extend the functionality of example.com somehow.

example.com doesn't have any API. I want the users of example.com to be able to login at example2.com using their logins and passwords of example.com. However, since example.com doesn't have any API, it is not easy to do, perhaps, it is even impossible.

No doubt, no one would agree to enter their credentials of example.com at example2.com due to many obvious reasons.

So, is there any way to authenticate the users of example.com at example2.com (or somewhere else) using their original credentials?


答: The environment variables should be stored in version control and managed with a system themselves. puppet, chef, etc are all designed to handle this and  will avoid many of the issues you mentioned. </p>

Title: Scalability of using environment variables

Body:
I just moved into the Ruby on Rails world and with it I am being introduced to much more liberal use of environment variables than what I have been exposed to in the past. Specifically, it appears like there's an accepted convention to store third party API keys and secret tokens as environment variables.

NOTE: this is not a RoR-specific question. I only mention it to illustrate a point of view.

I certainly see the benefit of this approach; the largest of which is that one codebase can be identically deployed to multiple servers without changing code or fear that the the app will be using the wrong resource. However, I am wary about jumping on the band wagon.

First, the approach doesn't seem scalable on my development work station (laptop), or on servers. If I am working on 10 different websites, and each are using Amazon S3 (for instance), I need 10 different EVs. Management will be difficult:

naming collisions are a distinct possibility (especially if I am working on legacy projects that I dont have complete control over);

visibility is murky (which EVs exist on the target machine? which have been or can be decommissioned?);

no version control (who changed the EV? when? why?)

Second, one of the main selling-points as I understand it, is that using EVs takes the sensitive data out of the repository where prying eyes could see it. This only seems like it should be an issue for public repositories, which I have none. All my repos are private, often because of contractual issues like NDA or ownership rights.

How does all of this play out in real life scenarios? Is this approach better for some situations than others? Are there other pros that outweigh my concerns here?


答:
the primary reason is that almost universally in GUI designers there is a distinct separation between pure presentation components and dynamic, data-based presentation components.

eg, you may use a Unchangable label in the static layout of a page.  And this label is really a quite distinct component from a 'field' control.

so, although there are good ways to make the labels themselves dynamic, this is often the very, very, very last step that gets skipped because of time and priority constraints.

And the natural flow of most GUI designers is to have this separation beween static and dynamic components, and often  is left that way, unless you specifially go back and QA these kinds of things.


问:
What is the role of a Software Architect in the Test-Driven Development process?
As I understand it, Test-Driven Development is about writing tests to define the program specifications (you can correct me if I'm wrong).

If there is someone responsible for writing the specifications (including a public API) for the software (let's call him the Software Architect), does that mean that the Software Architect must write all of the tests?

Or does the Software Architect write the specifications, and then hand them over to the developers to write tests against?

Or do you allow the specifications to grow organically by allowing all of the developers to write their own tests, and forget about having a Software Architect?

答:
Test-Driven Development is about writing tests to define the program specifications

You don't write tests to define the specification, the test descriptions, user stories, and feature descriptions are the specification, in the 'dead trees' sense.

To review, the TDD process in a nutshell is:

define a project in terms of features

describe the stakeholder, behavior, and goal of each feature using user stories

specify the expected givens, triggering events/conditions, and behaviors/outcomes associated with a user story using test descriptions [and this completes the 'specification']

pick a set of features for each iteration; iterations should be short [i'm omitting the planning and estimation steps for brevity]

code a test for a feature (it will fail, but you had to make API decisions to code the test)

implement enough of the feature so that the test passes

refactor the code if necessary

repeat with the next test until the feature is completed

repeat with the next feature until the iteration is completed

repeat with the next iteration until the project is completed

how much design, architecture, supporting documentation, et al you choose to do is not part of TDD. There are some practical 'best practices' you can read about, but keep in mind that those are the 'best' practices in someone else's workshop, not yours.

note that the point is for the customer and the developer to come up with the features and write the stories and test descriptions together, for mutual understanding

so, with that out of the way, the original question was:

what is the role of a software architect in TDD?

And the short answer is:

Same as it ever was, same as it ever was.
  --David Byrne

EDIT: The long answer is: the architect plays the usual visionary/investigator/irritant/support/backstop roles during the entire process, as necessary.

EDIT 2: sorry I missed the point of the sub-questions! Everyone is responsible for writing the specifications; all of the developers including the architect if/when appropriate plus the customer. The developers also code the tests.

ContentLicense: CC BY-SA 2.5


问:
What would be the optimal way to solve a problem like this?
I have a problem where I have to change all the Xs in a 2D array into 0s, and I have to calculate the minimum steps (where a single step consists of changing an entire row or column) required to do so. For example, in an array like-

```<code>[[X, X, X],

[X, 0, 0],

[X, 0, 0]]
</code>```

The minimum number of steps required here is 2.

I thought of a brute force approach (where I am checking row-wise once and column-wise thence and then comparing them to check which takes minimum number of steps) but that would give me an answer of 3, which is not the desired output.

Any help, or clue, regarding how I should approach this problem would be appreciated, thanks!

答:
That seens to be an interview and/or college exercise question, so I will give you just some directions...

Imagine that each possible matrix (the arrays with X and zeroes) are nodes in a graph. From each node, you can generate another one with the steps that you mentioned (change a line or change a column).

So, with:

```<code>[[X, X, X],
[X, 0, 0],
[X, 0, 0]]
</code>```

You can go to:

```<code>[[0, 0, 0],
[X, 0, 0],
[X, 0, 0]]

or

[[0, X, X],
[0, 0, 0],
[0, 0, 0]]

or

[[X, X, 0],
[X, 0, 0],
[X, 0, 0]]

or

(Goes on...)
</code>```

Now you should, from the initial matrix, try to do a breadth-first search (see this wikipedia link and/or your favorite algorithm book) for a matrix that satisfies your condition: all zeroes.

Body:
That seens to be an interview and/or college exercise question, so I will give you just some directions...

Imagine that each possible matrix (the arrays with X and zeroes) are nodes in a graph. From each node, you can generate another one with the steps that you mentioned (change a line or change a column).

So, with:

[[X, X, X],
[X, 0, 0],
[X, 0, 0]]

You can go to:

[[0, 0, 0],
[X, 0, 0],
[X, 0, 0]]

or

[[0, X, X],
[0, 0, 0],
[0, 0, 0]]

or

[[X, X, 0],
[X, 0, 0],
[X, 0, 0]]

or

(Goes on...)

Now you should, from the initial matrix, try to do a breadth-first search (see this wikipedia link and/or your favorite algorithm book) for a matrix that satisfies your condition: all zeroes.


答:
If a "step" is changing out a row or column, then your goal is to do the change-outs that will affect the most Xes before you do those that cover fewer.

The way to figure that out is to traverse the entire array once and keep track of the number of Xes in each row and column.  For a minor variant on your example, the end result of that calculation would look like this:

```<code>   C C C
   1 2 3
R1 X X X -- 3 Total
R2 0 X 0 -- 1 Total
R3 0 X 0 -- 1 Total
   | | |
   1 3 1 Totals
</code>```

Break that information out into a list (read each item as "3 Xes in Row 1", "1 X in Row 2", etc.):

```<code>3/R1  1/R2  1/R3  1/C1  3/C2  1/C3
</code>```

A descending sort of the counts makes it pretty obvious which one to change out first:

```<code>3/R1  3/C2  1/R2  1/R3  1/C1  1/C3
</code>```

Change out R1, make note of that as your first step and remove it from the list.  When you change out a row with Xes, the columns that contained those Xes (all of them in this case) now contain one less.  This means you have to reduce the count in each column where you found an X:

```<code>0/C1  1/R2  1/R3  2/C2  0/C3
</code>```

That change blows the sort order right out of the water, because now the item that's going to wipe out the most Xes is no longer up front.  A re-sort fixes that and reveals column 2 as the next step:

```<code>2/C2  1/R2  1/R3  0/C1  0/C3
</code>```

After a change-out, decrement and re-sort, you're down to this:

```<code>0/R2  0/R3  0/C1  0/C3
</code>```

A zero first element means you've reached the end because anything following it will also be zero, meaning no more Xes in the array.  Anything else means you repeat the process.

Not only will you get the number of steps out of this, you'll also get a list of what those steps are.

You also don't necessarily have to do a sort, either.  You can simply traverse the list each time, and hold onto the element with the largest count.  If you're using a language that has a sorted collection available, writing this would be a piece of cake.

Title: What would be the optimal way to solve a problem like this?

Body:
I have a problem where I have to change all the Xs in a 2D array into 0s, and I have to calculate the minimum steps (where a single step consists of changing an entire row or column) required to do so. For example, in an array like-

```<code>[[X, X, X],

[X, 0, 0],

[X, 0, 0]]
</code>```

The minimum number of steps required here is 2.

I thought of a brute force approach (where I am checking row-wise once and column-wise thence and then comparing them to check which takes minimum number of steps) but that would give me an answer of 3, which is not the desired output.

Any help, or clue, regarding how I should approach this problem would be appreciated, thanks!

Body:
If a "step" is changing out a row or column, then your goal is to do the change-outs that will affect the most Xes before you do those that cover fewer.

The way to figure that out is to traverse the entire array once and keep track of the number of Xes in each row and column.  For a minor variant on your example, the end result of that calculation would look like this:

   C C C
   1 2 3
R1 X X X -- 3 Total
R2 0 X 0 -- 1 Total
R3 0 X 0 -- 1 Total
   | | |
   1 3 1 Totals

Break that information out into a list (read each item as "3 Xes in Row 1", "1 X in Row 2", etc.):

3/R1  1/R2  1/R3  1/C1  3/C2  1/C3

A descending sort of the counts makes it pretty obvious which one to change out first:

3/R1  3/C2  1/R2  1/R3  1/C1  1/C3

Change out R1, make note of that as your first step and remove it from the list.  When you change out a row with Xes, the columns that contained those Xes (all of them in this case) now contain one less.  This means you have to reduce the count in each column where you found an X:

0/C1  1/R2  1/R3  2/C2  0/C3

That change blows the sort order right out of the water, because now the item that's going to wipe out the most Xes is no longer up front.  A re-sort fixes that and reveals column 2 as the next step:

2/C2  1/R2  1/R3  0/C1  0/C3

After a change-out, decrement and re-sort, you're down to this:

0/R2  0/R3  0/C1  0/C3

A zero first element means you've reached the end because anything following it will also be zero, meaning no more Xes in the array.  Anything else means you repeat the process.

Not only will you get the number of steps out of this, you'll also get a list of what those steps are.

You also don't necessarily have to do a sort, either.  You can simply traverse the list each time, and hold onto the element with the largest count.  If you're using a language that has a sorted collection available, writing this would be a piece of cake.


问:
Does functional programming ignore the benefits gained from the "On the Criteria To Be Used in Decomposing Systems into Modules" (data hiding)?
There's a classic article named On the Criteria To Be Used in Decomposing Systems into Modules that I just read for the first time.  It makes perfect sense to me, and is probably one of those articles that OOP was based on.  Its conclusion:

We have tried to demonstrate by these examples that
  it is almost always incorrect to begin the decomposition
  of a system into modules on the basis of a flowchart.
  ... Each module is then designed to hide
  such a decision from the others

In my uneducated and inexperienced opinion, functional programming takes the exact opposite advice of this article.  My understanding is functional programming makes data flow idiomatic.  Data gets passed from function to function, each function being intimately aware of the data and "changing it" along the way.  And I think I've seen a Rich Hickey talk where he talks about how data hiding is overrated or unnecessary or something, but I can't remember for sure.

First I want to know if my assessment is correct.  Does the FP paradigm and this article philosophically disagree?

Assuming they disagree, how does FP "compensate" for its lack of data hiding?  Perhaps they sacrifice data hiding but gain X, Y and Z.  I'd like to know the reasoning for why X, Y and Z are considered more beneficial than data hiding.

Or, assuming they disagree, perhaps FP feels that data hiding is bad.  If so, why does it think data hiding is bad?

Assuming they agree, I'd like to know what FPs implementation of data hiding is.  It's obvious to see this in OOP.  You can have a private field that nobody outside the class can access.  There's no obvious analogy of this to me in FP.

I feel there are other questions I should be asking but I don't know I should be asking.  Feel free to answer those, too.

Update

I found this Neal Ford talk that has a very relevant slide in it.  I'll embed the screenshot here:

答:
... and is probably one of those articles that OOP was based on.

Not really, but it did added to the discussion, specially to practitioners that, at the time, were trained to decompose systems using the first criteria he describes in the paper.

First I want to know if my assessment is correct. Does the FP paradigm and this article philosophically disagree?

No. Moreover, to my eyes, your description of what an FP program looks like is not different from any other that uses procedures or functions:

Data gets passed from function to function, each function being intimately aware of the data and "changing it" along the way.

...except for the "intimacy" part, since you can (and often do) have functions operating on abstract data, precisely to avoid the intimacy. Thus, you do have some control over that "intimacy" and you can regulate it however you like, by setting up interfaces (ie. functions) for what you want to hide.

So, I see no reason why we wouldn't be able to follow Parnas criteria of information hiding using functional programming and end up with an implementation of a KWIC index with similar pointed benefits as his second implementation.

Assuming they agree, I'd like to know what FPs implementation of data hiding is. It's obvious to see this in OOP. You can have a private field that nobody outside the class can access. There's no obvious analogy of this to me in FP.

As far as data is of concern, you can elaborate data abstractions and data type abstractions using FP. Any of these hide concrete structures and manipulations of these concrete structures using functions as abstractions.

EDIT

There is a growing number of assertions here stating that "hiding data" in the context of FP is not so useful (or OOP-ish (?)). So, let me stamp here a very simple and clear example from SICP:

Suppose your system needs to work with rational numbers. One way you might want to represent them is as a pair or a list of two integers: the numerator and denominator. Thus:

```<code>(define my-rat (cons 1 2)) ; here is my 1/2
</code>```

If you ignore data abstraction, most likely you will get the numerator and denominator using car and cdr:

```<code>(... (car my-rat)) ; do something with the numerator
</code>```

Following this approach, all parts of the system that manipulate rational numbers will know that a rational number is a cons -- they will cons numbers to create rationals and extract them using list operators.

One problem you may face is when you need to have a reduced form of the rational numbers -- changes will be required across the entire system. Also, if you decide to reduce at creation time, you might find later that reducing when accessing one of the rational terms is better, yielding another full scale change.

Another problem is if, hypothetically, an alternative representation for them is preferred and you decide to abandon the cons representation -- full scale change again.

Any sane effort in dealing with these situations will likely start to hide the representation of rationals behind interfaces. At the end, you might end up with something like this:

(make-rat <n> <d>) returns the rational number whose numerator is the integer <n> and whose denominator is the integer <d>.

(numer <x>) returns the numerator of the rational number <x>.

(denom <x>) returns the denominator of the rational number <x>.

and the system will no longer (and should no longer) know of what rationals are made of. This is because cons, car and cdr are not intrinsic to rationals, but make-rat, numer and denom are. Of course, this could easily be an FP system. So, "data hiding" (in this case, better known as data abstraction, or the effort to encapsulate representations and concrete structures) comes as a relevant concept and a technique widely used and explored, whether in the context of OO, functional programming or whatever.

And the point is...though one may try to make distinctions between what "kind of hiding" or encapsulation they are doing (whether they are hiding a design decision, or data structures or algorithms -- in the case of procedural abstractions), all of them have the same theme: they are motivated by one or more points Parnas made explicit. That is:

Changeability: whether required changes can be made locally or are spreaded through the system.

Independent Development: to what degree two parts of the system can be developed in parallel.

Comprehensibility: how much of the system is required to be known to understand one of its parts.

The example above was taken from SICP book so, for the full discussion and presentation of this concepts in the book, I highly recommend checking out chapter 2. I also recommend getting familiar with Abstract Data Types in the context of FP, which brings other issues to the table.

Body:
... and is probably one of those articles that OOP was based on.

Not really, but it did added to the discussion, specially to practitioners that, at the time, were trained to decompose systems using the first criteria he describes in the paper.

First I want to know if my assessment is correct. Does the FP paradigm and this article philosophically disagree?

No. Moreover, to my eyes, your description of what an FP program looks like is not different from any other that uses procedures or functions:

Data gets passed from function to function, each function being intimately aware of the data and "changing it" along the way.

...except for the "intimacy" part, since you can (and often do) have functions operating on abstract data, precisely to avoid the intimacy. Thus, you do have some control over that "intimacy" and you can regulate it however you like, by setting up interfaces (ie. functions) for what you want to hide.

So, I see no reason why we wouldn't be able to follow Parnas criteria of information hiding using functional programming and end up with an implementation of a KWIC index with similar pointed benefits as his second implementation.

Assuming they agree, I'd like to know what FPs implementation of data hiding is. It's obvious to see this in OOP. You can have a private field that nobody outside the class can access. There's no obvious analogy of this to me in FP.

As far as data is of concern, you can elaborate data abstractions and data type abstractions using FP. Any of these hide concrete structures and manipulations of these concrete structures using functions as abstractions.

EDIT

There is a growing number of assertions here stating that "hiding data" in the context of FP is not so useful (or OOP-ish (?)). So, let me stamp here a very simple and clear example from SICP:

Suppose your system needs to work with rational numbers. One way you might want to represent them is as a pair or a list of two integers: the numerator and denominator. Thus:

(define my-rat (cons 1 2)) ; here is my 1/2

If you ignore data abstraction, most likely you will get the numerator and denominator using car and cdr:

(... (car my-rat)) ; do something with the numerator

Following this approach, all parts of the system that manipulate rational numbers will know that a rational number is a cons -- they will cons numbers to create rationals and extract them using list operators.

One problem you may face is when you need to have a reduced form of the rational numbers -- changes will be required across the entire system. Also, if you decide to reduce at creation time, you might find later that reducing when accessing one of the rational terms is better, yielding another full scale change.

Another problem is if, hypothetically, an alternative representation for them is preferred and you decide to abandon the cons representation -- full scale change again.

Any sane effort in dealing with these situations will likely start to hide the representation of rationals behind interfaces. At the end, you might end up with something like this:

(make-rat <n> <d>) returns the rational number whose numerator is the integer <n> and whose denominator is the integer <d>.

(numer <x>) returns the numerator of the rational number <x>.

(denom <x>) returns the denominator of the rational number <x>.

and the system will no longer (and should no longer) know of what rationals are made of. This is because cons, car and cdr are not intrinsic to rationals, but make-rat, numer and denom are. Of course, this could easily be an FP system. So, "data hiding" (in this case, better known as data abstraction, or the effort to encapsulate representations and concrete structures) comes as a relevant concept and a technique widely used and explored, whether in the context of OO, functional programming or whatever.

And the point is...though one may try to make distinctions between what "kind of hiding" or encapsulation they are doing (whether they are hiding a design decision, or data structures or algorithms -- in the case of procedural abstractions), all of them have the same theme: they are motivated by one or more points Parnas made explicit. That is:

Changeability: whether required changes can be made locally or are spreaded through the system.

Independent Development: to what degree two parts of the system can be developed in parallel.

Comprehensibility: how much of the system is required to be known to understand one of its parts.

The example above was taken from SICP book so, for the full discussion and presentation of this concepts in the book, I highly recommend checking out chapter 2. I also recommend getting familiar with Abstract Data Types in the context of FP, which brings other issues to the table.


答:
In TeX you can define macros having an “argument pattern” which basically means that your calling protocol is free. For your specific example, you could use

\def\getTopCustomers#1OfTheYear#2;{%
  The #1 top customers of the year #2.
}
\getTopCustomers 50 OfTheYear 2010;
```

<p>Note that it is also possible to get rid of the <code>;</code> if you agree to play with registers:</p>

<pre class="lang-tex prettyprint-override"><code>\newcount\customers
\newcount\year
\def\getTopCustomers#1OfTheYear{%
  \customers#1\relax
  \afterassignment\reallyGetTopCustomersOfTheYear
  \year
}
\def\reallyGetTopCustomersOfTheYear{%
  The {\the\customers} top customers of the year {\the\year}.
}
\getTopCustomers 50 OfTheYear 2010
</code>```

TeX allows you to reconfigure its lexer, and thanks to the \afterassignment macro I used above, you can use built-in procedures to lex numbers.  It is very useful to define very terse calling protocols.  For instance, it is very plausible to write TeX macros understanding Markdown notation for tables.

Now you ask “how do I access my database where customers are stored from TeX?” but this is another question. :)

In Common lisp, this is definitely possible to define a query macro allowing you to write

(query getTopCustomers 50 OfTheYear 2010)
```

<p>where getCustomers and OfTheYear are interpreted as symbols.  It is then the job of the macro to make sense of it.  Common lisp is excellent in the domain of code readability (yes, I mean it!) because the macro system allows to easily create pseudo-languages tuned for your application. (I think they are called application languages.)</p>

<p>P.S.: It seems that nobody quoted C++. The closest you can get (without the preprocessor) is</p>

```query.getTopCustomers(50).OfTheYear(2010):
```

<p>the trick is to let <code>getTopCustomers</code> returns a reference on <code>query</code> (or anything else) that also implements <code>OfTheYear</code>.  You can build this example up to a small query language but then you have to identify final properties (returning a value) or add a <code>finalise</code> method (performing the lookup and returning the value).  If you feel like it, you can also imitate stream controllers of the STL and be able to write things like</p>

```query << getTopCustomers(50) << OfTheYear(2010) << flush;
```

but this is again going in the direction of application languages.

Edit: I overlooked @han answers, that also quote Common Lisp and C++ (but not TeX!).

Title: I'm writing about language syntax. Is there a language out there in which parameters are placed inside method name?

Body:
in JavaScript:

function getTopCustomersOfTheYear(howManyCustomers, whichYear) {
   // Some code here.
}
getTopCustomersOfTheYear(50, 2010);
```

<p>in C#:</p>

<pre class="lang-cs prettyprint-override"><code>public List<Customer> GetTopCustomersOfTheYear(int howManyCustomers,
 int whichYear)
{
   // Some code here
}
List<Customer> customers = GetTopCustomersOfTheYear(50, 2010);
</code>```

in PHP:

public function getTopCustomersOfTheYear($howManyCustomers, $whichYear)
{
   // Some code here
}
$customers = getTopCustomersOfTheYear(50, 2010);
```

<p>Is there any language out there which support this syntax:</p>

<pre class="lang-c prettyprint-override"><code>function GetTop(x)CustomersOfTheYear(y)
{
    // Some code here
}
returnValue = GetTop(50)CustomersOfTheYear(2010);
</code>```

Isn't it more semantic, more readable form of writing a function?

Update: The reason I'm asking this question is that, I'm writing an article about a new syntax for a new language. However, I thought that having such syntax for declaring methods could be nicer and more friendly to developers and would decrease learning-curve of the language, because of being more closer to natural language. I just wanted to know if this feature has already been contemplated upon or not.

Body:
In TeX you can define macros having an “argument pattern” which basically means that your calling protocol is free. For your specific example, you could use

\def\getTopCustomers#1OfTheYear#2;{%
  The #1 top customers of the year #2.
}
\getTopCustomers 50 OfTheYear 2010;

Note that it is also possible to get rid of the ; if you agree to play with registers:

\newcount\customers
\newcount\year
\def\getTopCustomers#1OfTheYear{%
  \customers#1\relax
  \afterassignment\reallyGetTopCustomersOfTheYear
  \year
}
\def\reallyGetTopCustomersOfTheYear{%
  The {\the\customers} top customers of the year {\the\year}.
}
\getTopCustomers 50 OfTheYear 2010

TeX allows you to reconfigure its lexer, and thanks to the \afterassignment macro I used above, you can use built-in procedures to lex numbers.  It is very useful to define very terse calling protocols.  For instance, it is very plausible to write TeX macros understanding Markdown notation for tables.

Now you ask “how do I access my database where customers are stored from TeX?” but this is another question. :)

In Common lisp, this is definitely possible to define a query macro allowing you to write

(query getTopCustomers 50 OfTheYear 2010)

where getCustomers and OfTheYear are interpreted as symbols.  It is then the job of the macro to make sense of it.  Common lisp is excellent in the domain of code readability (yes, I mean it!) because the macro system allows to easily create pseudo-languages tuned for your application. (I think they are called application languages.)

P.S.: It seems that nobody quoted C++. The closest you can get (without the preprocessor) is

query.getTopCustomers(50).OfTheYear(2010):

the trick is to let getTopCustomers returns a reference on query (or anything else) that also implements OfTheYear.  You can build this example up to a small query language but then you have to identify final properties (returning a value) or add a finalise method (performing the lookup and returning the value).  If you feel like it, you can also imitate stream controllers of the STL and be able to write things like

query << getTopCustomers(50) << OfTheYear(2010) << flush;

but this is again going in the direction of application languages.

Edit: I overlooked @han answers, that also quote Common Lisp and C++ (but not TeX!).


答:
TL;DR: No

Does the FP paradigm and this article philosophically disagree?.

No it doesn't. Functional Programming is declarative which is "a style of building the structure and elements of computer programs, that expresses the logic of a computation without describing its control flow."  It's less about following the flow chart and more like creating the rules that let the flow arise on it's own.

Procedural programming is much closer to a encoding of a flow chart than Functional programming.  It follows that transforms that occurs, and encodes of those transforms into procedures that are executed in order, exactly like the flow in a flow chart describes.

Whereas procedural languages model execution of the program as a sequence of imperative commands that may implicitly alter shared state, functional programming languages model execution as the evaluation of complex expressions that only depend on each other in terms of arguments and return values. For this reason, functional programs can have a freer order of code execution, and the languages may offer little control over the order in which various parts of the program are executed. (For example, the arguments to a procedure invocation in Scheme are executed in an arbitrary order.)

Data Hiding

Functional Programming has it's own methods of data hiding, for example think closures.  That is data hiding by encapsulation in a closure.  It's hard for fields to be any more private data that has been closed over since only the closure has a reference to the data and you cannot refer to it external to the closure.

One of the reasons for data hiding is to stabilize the programming interface by hiding mutating data.  Functional programming doesn't have mutating data, therefore it doesn't need as much data hiding.

Title: Does functional programming ignore the benefits gained from the "On the Criteria To Be Used in Decomposing Systems into Modules" (data hiding)?

Body:
There's a classic article named On the Criteria To Be Used in Decomposing Systems into Modules that I just read for the first time.  It makes perfect sense to me, and is probably one of those articles that OOP was based on.  Its conclusion:

We have tried to demonstrate by these examples that
  it is almost always incorrect to begin the decomposition
  of a system into modules on the basis of a flowchart.
  ... Each module is then designed to hide
  such a decision from the others

In my uneducated and inexperienced opinion, functional programming takes the exact opposite advice of this article.  My understanding is functional programming makes data flow idiomatic.  Data gets passed from function to function, each function being intimately aware of the data and "changing it" along the way.  And I think I've seen a Rich Hickey talk where he talks about how data hiding is overrated or unnecessary or something, but I can't remember for sure.

First I want to know if my assessment is correct.  Does the FP paradigm and this article philosophically disagree?

Assuming they disagree, how does FP "compensate" for its lack of data hiding?  Perhaps they sacrifice data hiding but gain X, Y and Z.  I'd like to know the reasoning for why X, Y and Z are considered more beneficial than data hiding.

Or, assuming they disagree, perhaps FP feels that data hiding is bad.  If so, why does it think data hiding is bad?

Assuming they agree, I'd like to know what FPs implementation of data hiding is.  It's obvious to see this in OOP.  You can have a private field that nobody outside the class can access.  There's no obvious analogy of this to me in FP.

I feel there are other questions I should be asking but I don't know I should be asking.  Feel free to answer those, too.

Update

I found this Neal Ford talk that has a very relevant slide in it.  I'll embed the screenshot here:


问:
What happens if I do not explicitly state "This program comes with absolutely no warranty"?
And lets say, my application is a simple feed reader. Does my app really have to include the no warranty notice?</p>

答: Well, if your application breaks, I know people who would be happy to sue you for your house and shirt too. Don't take legal issues slightly specially if you are in the G7 (may be G7-2) countries.</p>


答:
A "no warranty" clause gives you limited protection from being made liable for any damage caused by your program. How much protection varies from jurisdiction to jurisdiction.

One scenario where a "simple news reader" could cause damage is through a security vulnerability. A malicious newsfeed could exploit a bug in your reader and infect the users machine with malware which deletes important files on their machine or disclose sensitive information to a 3rd party. When the hoster of the newsfeed can not be located, the user might try get compensation for their damage from you.

Another potential scenario could be a bug which causes it to poll the server very frequently. This could be interpreted as a DOS attack on it. The server hoster could decide to ban the user from using its services or even press charges for computer sabotage. The user could then try to make you liable for this mess.

I am not a lawyer, so I can not estimate how likely it is that your users could be successful in court. You should consult one for more information.

Title: What happens if I do not explicitly state "This program comes with absolutely no warranty"?

Body: And lets say, my application is a simple feed reader. Does my app really have to include the no warranty notice?</p>


答:
Unfortunately, it really depends on your exact locality. Some places such a disclaimer is pointless because the law doesn't assume a warranty unless one is offered. In other places, it will make clear that you don't have a warranty, and in still other places, the law includes an automatic warranty of some sort, which you CAN NOT opt out of providing.

So, in order to answer this question, you're gonna need a lawyer familiar with your jurisdiction, and any others where you plan to distribute.

Alternately, you can put the phrase in, ship it, and hope. You'll at least be covered in locations where such a disclaimer is valid.


答:
In Clojure, it is common to use keyword arguments for situations like this, e.g.:

(get-customers :top 50 :year 2010)

Keyword arguments are fairly flexible, they can be optional and have defaults specified etc.


答:
Agda has mixfix notation

```<code>if_then_else x y z = case x of
                     True -> y
                     False -> z

 if cond then x else y
</code>```

Whenever the function is named with an underscore, it can be split into two parts with an argument in between

Body:
Agda has mixfix notation

if_then_else x y z = case x of
                     True -> y
                     False -> z

 if cond then x else y

Whenever the function is named with an underscore, it can be split into two parts with an argument in between


问:
Is it okay to call functions when event occurs, or after that?
So I was not sure how to structure this title, feel free to edit it.

My question is:
When I have a Game Loop, I have 3 main blocks. Handle Events, Update game state, and draw.
Let's say for example I check for keyboard/mouse events, and I want to move my character when buttons are pressed.
Whenever KEYDOWN event occurs, should I immediately call Player.move?
Or should I toggle move_left/move_right bools, and then call Player.move when I'm in the Update game state block.

I was wondering this becouse, for example a function performs a long algorithm and I call it when an event occur's, calling the function will take some time, and meanwhile I might press more button's/events. I think I will lose some of those events becouse in that time the algirthm function was runing.

Or, I can toggle a bool when the event occurs, and after checking for ALL events, I perform functions based on the bools.

PS: Feel free to edit this post in a more constructive question.

答: You must not skip valid user inputs. If your game function is supposed to respond to a single input, then you have no choice but responding to that input immediately. You can queue user inputs and play them in sequence as soon as you can. This would work when you are playing a single player game. Another option is to lock the input device (keyboard, etc.) until the function is processed after indicating that the system is processing the previous input. In all cases, try to optimize the long running function. Chances are with today's computers, you can do that with some work.</p>


问:
The Agile process: how and what should be documented?
A while ago the company I work for had outsourced a development project to a third party. They employed agile practices in developing the solution. However when asked for documentation they would just say it was required as it was incorporated in a wiki or as part of their sprints.

They did leave at the completion of the project, with all but one of the project team. The project wiki site has now been closed down once the yearly subscription was due.

When they left they took most of the knowledge and understanding of what was developed with them.

So I do have 2 main questions;

Is this normal for agile or just an excuse for not wanting to write it?

What are the industry norm for documentation in agile projects to record development
requirements, designs, key decisions and context?

答:
They're just horrible. I don't believe agile means no documentation at all. They should have at least kept track of the application description. Getting an export of their wiki would have been nice or allowed someone else to pick up the service fee.

It may not be as detailed as some attempt. The theory is, when in a time-crunch, the specs no longer match the code anyway. So you have enough documentation to write the code and not try to define it in detail (Sort of like writing the code in some pseudo-verbalized-text/diagram-code and then in the actual code.).


问:
Returning multiple values in Javascript
Often I am writing a function that returns multiple values, such as a pair of coordinates:

```<code>function get_coords() {
  return ???;
}
</code>```

If I was using a language like Python, I would use a tuple:

```<code>return (x, y)
</code>```

Or, in an OOP language like Java, I would create a custom coordinate class:

```<code>class Coordinates {
  public int x;
  public int y;

  public Coordinates(x, y) {
    this.x = x;
    this.y = y;
  }
}
</code>```

Then return like this:

```<code>return new Coordinates(x, y);
</code>```

On to JavaScript.

In JavaScript, we have the option of returning a simple object:

```<code>return {x: x, y: y}
</code>```

or a Java-like approach, with a custom object:

```<code>return new coordinates(x, y)
</code>```

Are there any reasons to use one above the other?

答:
Use the one that matches the meaning of your data.

My overwhelming habit is to use simple object literals like dictionaries/hashes and to use custom-prototyped-objects in an OOP manner.

Are you returning a simple collection of convenient values which will be immediately disassembled by the calling function? Then use a quick object literal.

Is your return value a thing that does and represents important conceptual stuff in your data model? Then take the time to write a constructor and make it a prototyped instance.

Sure, javascript lets us be flexible (sloppy) and clever (cryptically) by blending these ideas, but I find my code is much clearer if I stick to this rule.

Title: Returning multiple values in Javascript


问:
Unit-testing databases: test all possible permutations of read and write to table?
I am testing a resource management class that is interacting with a database or a file system, or a combination of both. I was wandering if it is the norm to test all possible permutations of read and write for all columns of a data-set when a database is involved. What I mean is:

Database table of test case:

```<code>+----------------------+----------------------+----------------------+----------------------+
| users                                                                                |
+----------------------+----------------------+----------------------+----------------------+
|       user_id        |      user_name       |      user_email      |      user_role       |
+----------------------+----------------------+----------------------+----------------------+
|          1           |      A New Name      | email@provider.com   |          1           |
+----------------------+----------------------+----------------------+----------------------+
|          2           |   A different name   | address@domain.com   |          1           |
+----------------------+----------------------+----------------------+----------------------+
</code>```

I could envision something different going wrong in the abstraction layer, updating the first record but no others, updating the second record, but not the fourth, or any of other permutation or combination.

Is it the norm to write tests for all those scenarios (if I am thinking this through correctly it would be 4! = 24 cases, right)?

Now if I want to retrieve columns, I again could imagine something going wrong only retrieving the first and the fourth column, just the third, or all possible permutations of that.

Now what if write and read is mixed, first a read, then a write, then a read. Maybe a write to one column, a read of three columns, then a read of one, or any other permutation. Very soon there are potentially thousands of test cases...

Am I over thinking this and should I just test what I am actually encountering, or is it the norm to do due diligence and test all of this.

I am asking because database access is causing my test suites to balloon in execution time.

Edit:
In case this wasn't clear, I am not trying to test if the database is doing what it should be, but if my abstraction layer behaves as intended.

答:
I think you are over thinking this.  You test for 2 things when unit testing.  Does the code do what it is supposed to, and does it handle errors/bad data without crashing.

If you are able to, or did, design the database, then the proper design should handle bad writes assuming you correctly validate your data before writing it.  If there is something wrong the database will tell you.

As far as reads go, if the data going into the database was properly validated, you should only get correct data back.

You'll never think of all the possible problem.  Make sure your program logs errors that occur.  Then evaluate them, and add a new test case if needed.


问:
What skills (technologies) get outdated slower?
It's a common knowledge that since the IT industry develops very quickly, most of the skills get outdated fairly rapidly: jQuery, .NET, Ruby on Rails, etc. They change all the time so that it is difficult to keep track of them and especially learn them. Once I learn Ruby on Rails 3.2, Ruby on Rails 4 has appeared; the same thing for other frameworks and libraries.

What skills (or rather, technologies) get outdated slower and, at the same time, pretty useful in terms of being able to find a job? I figure these are knowing networks and algorithms. What else?

答:
If you can understand the concepts, you can understand any language.  The computer industry goes in circle with old technology coming around again in a slightly new form.

Even if you spend 100% of your waking time learning everything possible, you will still not know it all, and you will fall behind in some of the technology.

C++ is still around, but Pascal and FORTRAN really are not.

My point is that it is not possible to determine what will go out of style slowly.  You try to find a niche and go with it.  The more you learn, the more you can use to understand the next "thing".


答:
Well at the risk of sounding slightly cheesy: Ideas are timeless. By this I mean that the notion of a depth first search is goodness knows how old, but still totally relevant. Likewise, things that aren't totally platform and technology dependent tend to have a longer lifespan.

If you learn things like

Algorithms

Data structures

Paradigms and Concepts

Common [Coding] Sense

How to Document

A Sparkling Sense of Humor

then no matter what technology you're using, you'll still be a reasonably competent developer.

Depending on what sort of work you do, compilers, webdev, dbs, finance, whatever, their will be a certain amount of domain specific knowledge that will be relevant so long as the field is relevant.

Title: What skills (technologies) get outdated slower?

Body:
It's a common knowledge that since the IT industry develops very quickly, most of the skills get outdated fairly rapidly: jQuery, .NET, Ruby on Rails, etc. They change all the time so that it is difficult to keep track of them and especially learn them. Once I learn Ruby on Rails 3.2, Ruby on Rails 4 has appeared; the same thing for other frameworks and libraries.

What skills (or rather, technologies) get outdated slower and, at the same time, pretty useful in terms of being able to find a job? I figure these are knowing networks and algorithms. What else?


问:
Client-server application design issue
I have a collection of clients on server's side. And there are some objects that need to work with that collection - adding and removing clients, sending message to them, updating connection settings and so on. They should perform these actions simultaneously, so mutex or another synchronization primitive is required. I want to share one instance of collection between these objects, but all of them require access to private fields of collection. I hope that code sample makes it more clear[C++]:

```<code>class Collection
{
    std::vector< Client* > clients;
    Mutex mLock;
    ...
}

class ClientNotifier
{
    void sendMessage()
    {
         mLock.lock();
         // loop over clients and send message to each of them
    }
}

class ConnectionSettingsUpdater
{
    void changeSettings( const std::string& name )
    {
        mLock.lock();
        // if client with this name is inside collection, change its settings
    }
}
</code>```

As you can see, all these classes require direct access to Collection's private fields.

Can you give me an advice about how to implement such behaviour correctly, i.e. keeping Collection's interface simple without it knowing about its users?

答:
You could implement a simple locking function and iteration functions to avoid exposing the private variables.  If you want to reuse it, you could use a mixin pattern.  For example (pseudo code):</p>

```<code>class Collection {
    bool getLock(){};
    bool unlock(){};
    Client* getClient(){};
    Client* getNextClient(){
        // returns null when there are no more clients
     }
 }

A search for mixins will show you how to abstract this idea.
</code>```

Title: Client-server application design issue

Body:
You could implement a simple locking function and iteration functions to avoid exposing the private variables.  If you want to reuse it, you could use a mixin pattern.  For example (pseudo code):

class Collection {
    bool getLock(){};
    bool unlock(){};
    Client* getClient(){};
    Client* getNextClient(){
        // returns null when there are no more clients
     }
 }

A search for mixins will show you how to abstract this idea.


问:
When should I copy a pointer inside a function?
I'm trying to teach myself programming and I'd really appreciate some help with this issue. I've just read a tutorial on pointers but I have a problem with the example. The function copies one string to another. In the original function a copy is being made with ptr. What is the meaning of this? because as far as I can see it's unnecessary. Is there anything wrong with my revised function or am I missing something?

//Tutorial example

```<code>char *my_strcpy(char *destination, const char *source){
    char *ptr = destination;
    while(*source != '\0'){
        *ptr++ = *source++;
    }
    *ptr = '\0';
    return destination;
}
</code>```

My revision

```<code>void my_strcpy2(char *destination, const char *source){

    while(*source != '\0'){
        *destination++ = *source++;
    }
    *destination = '\0';
}
</code>```

Thanks.

答:
From a technical point of view, using an additional variable ptr to make it possible to return the original destination value is unneccessary, since the caller obviously must already have the value of destination in his scope. If you design a strcpy-like function without returning that value, you can create a more comprehensive implementation, as you have shown above. But the original strcpy function from the standard library is defined to return destination, and my_strcpy obviuosly tries to mimic that behaviour/signature.

The reason for this is mainly "syntactic sugar", allowing the use of strcpy in a call chain. Read this SO post to get a better explanation for what it is good for.


问:
What code lays behind C++ exception?
In C and C++ you can return a single variable inside a function. Now in the case that variable is returning data, and not an error code, you can use exceptions. But how is that possible? If you data being returned is the data you tell your function to return, then there is practically no way for the function calling it to know it's success (because the return is used for data, and not an error code). Also, the ability for a exception to literally stop the function in the middle of the code to return the error. How do C++ compilers achieve this?</p>

答:
There are several misconceptions underpinning your question.

First of all, the distinction you make between returning data or an error code is an artificial distinction. The C and C++ languages do not have that distinction. To them you are always returning data. It is only us programmers that attach the meaning of an error code to some of that data.

Secondly, when you leave a function, there is no requirement that you end up back at the point where the function was called. You can end up in some completely different location of the code.

Now, exceptions can be implemented in various ways. I will outline one of those ways. It is not the most efficient one, but it is one of the easiest to understand.

First I will explain how a regular function call works. When you call a function in your C or C++ code, the compiler generates instructions to take several steps. First the (values of) the arguments to the function are pushed onto the stack. Then the address is pushed where to continue processing after the function returns (with a normal return). And lastly, a jump is executed to the first instruction of the function.

For the exception handling, the compiler generates some additional information that gets placed on the stack along with the local variables. This information tells the throw statement how to clean up those local variables and where the catch blocks are located.
When an exception is thrown, the throw statement walks over the stack to search for an appropriate catch block, cleaning up the local variables that it finds along the way. When an appropriate catch block has been found, a jump is performed to continue execution at that point.

As you can see, returning from a function and throwing an exception use completely different information on where to continue execution after the return/throw. For that reason, if a function does not indicate errors with an error code, but uses exceptions, you can safely presume that the function succeeded if it returns from its call. If the function had thrown, the code immediately after the function call would not have been executed.

Title: What code lays behind C++ exception?


问:
Can REST, Ajax and jQuery work well together?
I'm trying to use REST (usign spring MVC) as my Ajax backend but got some problems when using it with jQuery. REST best pratices recommend using HTTP status code, e.g. 200, 403, 401, etc, and I have no problem with a 200 status code, jQuery's ajax method have a done(data) callback that let me read the reponse in json format. But when I need to return some error in json format along with the status code, I got stucked. The fail(jqXHR, textStatus) callback doesn't seem to support json in the response. So if I return JSON from the serverside, it will be put in jqXHR.reponseText and treated as plaintext instead.

So my question is, is REST good for Ajax? Why does jQuery treat the data differently in case of non-200 status code?

答:
It is very common to use REST in combination with Ajax.

This has not really much to do with REST or any other architecture. Using the correct HTTP status code in case of errors should be the recommendation in any case (there may be exceptions I am not aware of, though).

I don't know why the jQuery team decided to handle it this way, but they may have simply decided that in case of success the resturned value is well defined while in case of error it may be anything (a simple text message being one choice).

In any case you can parse the message manually if you decide to return JSON like this:

```<code>var msg = $.parseJSON(err).msg;
</code>```

Body:
It is very common to use REST in combination with Ajax.

This has not really much to do with REST or any other architecture. Using the correct HTTP status code in case of errors should be the recommendation in any case (there may be exceptions I am not aware of, though).

I don't know why the jQuery team decided to handle it this way, but they may have simply decided that in case of success the resturned value is well defined while in case of error it may be anything (a simple text message being one choice).

In any case you can parse the message manually if you decide to return JSON like this:

var msg = $.parseJSON(err).msg;


答:
1) Actually instead of using jQuery parsing you may use the stock Javascript JSON parser simply by var object = JSON.parse(test) in places where you don't get a parsed object already.

2) Ensure your server is returning a proper mimetype application/json in other error codes.

3) It is not wrong to write your own small AJAX lib. jQuery is not doing anything special. Some hints are given in other question. https://stackoverflow.com/a/5165528/403571

Title: Can REST, Ajax and jQuery work well together?

Body:
I'm trying to use REST (usign spring MVC) as my Ajax backend but got some problems when using it with jQuery. REST best pratices recommend using HTTP status code, e.g. 200, 403, 401, etc, and I have no problem with a 200 status code, jQuery's ajax method have a done(data) callback that let me read the reponse in json format. But when I need to return some error in json format along with the status code, I got stucked. The fail(jqXHR, textStatus) callback doesn't seem to support json in the response. So if I return JSON from the serverside, it will be put in jqXHR.reponseText and treated as plaintext instead.

So my question is, is REST good for Ajax? Why does jQuery treat the data differently in case of non-200 status code?


答: To better understand the pointers I find it useful to put asterisk near the type, like char* destination. This way you see that the value you pass has type "pointer to char" and you simply think of it as an integer (usually 32-bit or 64-bit) that in itself you may modify without any consequences. Your understanding is probably already good of this, because this is the reason a local copy is unnecessary. The case when with strcpy it is useful is to return the original value as noted by the other answer.

Title: When should I copy a pointer inside a function?

Body:
I'm trying to teach myself programming and I'd really appreciate some help with this issue. I've just read a tutorial on pointers but I have a problem with the example. The function copies one string to another. In the original function a copy is being made with ptr. What is the meaning of this? because as far as I can see it's unnecessary. Is there anything wrong with my revised function or am I missing something?

//Tutorial example

```<code>char *my_strcpy(char *destination, const char *source){
    char *ptr = destination;
    while(*source != '\0'){
        *ptr++ = *source++;
    }
    *ptr = '\0';
    return destination;
}
</code>```

My revision

```<code>void my_strcpy2(char *destination, const char *source){

    while(*source != '\0'){
        *destination++ = *source++;
    }
    *destination = '\0';
}
</code>```

Thanks.


问:
When developing algorithms, is skipping the pen&paper phase a bad habit?
I heard many people saying that when developing algorithms you should first use pen and paper, flowcharts and what not, so that you can focus on the algorithm itself, not worrying about the implementation of said algorithm (i.e., you deal with one problem at a time).

However, most of the time I find it easier to actually develop my algorithm on the fly. That is, I think a bit about the problem until I know the general direction to take, and then I start writing code and making changes until the algorithm emerges and works.

Is this a bad habit that I should try to change?

答:
1. The amount of preparation needed is typically proportional to the complexity of what you are doing. It makes no sense to pen&paper 2 full days for an algorithm that is used once in a quarter, runs one hour singlethreaded on one machine only. It makes sense to pen&paper three man-weeks (if necessary) to design the new high-performance flux compensator module which will be able to process half a million requests per hour and has to run 24/7/365 without downtime.

2. You can tell if it's a bad habit within 30 seconds if you look at what solutions you are coding. You asked if it is a good or a bad habit. Well, that depends on you. If you are a slow learner at the beginning of your programming career, it is probably a good idea to pen&paper to full detail everything. If you got some years of experience, it will be enough to just think it through for 5 minutes and then just do it. Of course still with respect to 1. above.

Bottom line

Only your code tells the thruth whether you need more or less pen&paper. Don't let anyone else dictate that to you, but find it out on your own. That keeps you learning.

Disclaimer: This may not be what's called mainstream thinking and common sense. That's ok. Just set a bookmark and read it again in five years or so.


问:
PHP developer, how to solve javascript related issues in a program with millions of line
I am expert in PHP. There are some JavaScript related bugs in my
assignment given by my supervisor.  I tried to fix them using Firebug.
It is time consuming.  Is there any other ways?

Are there any good IDE's to tackle this issue?

Are there any other developer tools except Firebug?

答:
In order:

Narrow the scope.

Focus on the frontend, forget the backend and PHP for the time being. If javascript bugs are backend related (like AJAX), try mocking the backend (replacing the AJAX calls with something simpler in the test environment).

Find the module which is buggy. Javascript codebase likes evolving into a code soup when there's no discipline. Debugging is where a clean module separation shines - it's valuable to be able to test a javascript module in isolation.

Write unit tests.

Reproduce your bugs using automated tests to confirm their existence, make sure your fix works and they don't come back in the future.

You could use PhantomJS + CasperJS for frontend testing.

Use a debugger (if you still need to).

Learn what Firebug or Chrome Developer Tools offer you.

Or try something hot like trace.gl.

Don't expect an IDE to be a magic bullet to your problems. When you limit yourself to one tool, you're missing out.


答:
The answer lies in understanding life as a process. Does life change computers or does computers change our life or the way the business is done?

It is basically the usage of software as a product or service that first goes obsolete due changes in business scenarios. The next new level of thinking and rethinking is done to save its death in terms of its usability. When the next level of thinking comes into play, technologies and their components are first analysed, language being a starting point, first comes into change... It needs to reduce the complexity, maintenance and learning curve to build the next wave of applications/software.

Hence, according to my understanding, I feel only those languages go slow in changes that remain above the critical threshold level that determines actual usage by the end users.