答:
No matter how restrictive a language is, some programmers will still find ways to screw things up. Imagine the following piece of code:

var price = this.ApplyVAT(basePrice);
if (this.acceptsRebate)
{
    return new RebateCalculator(RebateType.Default).Transform(price);
}

return price;
```

<p>Let's screw it:</p>

<pre class="lang-cs prettyprint-override"><code>// Rebats calculator became variable cal.
var cal = new RebateCalculator(RebateType.Default);

// stylecop complain if i dont put comment here and leave line empty. don't know why??
//
// don't know price now so later maybe!!!
Price pp = null;

// Func is transforms price to price!
Func<Price, Price> tar = cal.Do;
var g = Tax(bPR);

// changed by MAG 02/08/2013
// if arebt2 is true, the condition should match.....
if (arebt2)
{
    // assign g to g2
    var g2 = g;

    // don't remember what tar mean but its very important!!! don't remove!!!
    pp = tar(g);
}
else
{
    // it's the same!
    pp = g;
}

// i can return now because i know price!!!
return pp;
</code>```

The code still complies to the same IL, and doesn't violate any StyleCop or Code analysis rules (while StyleCop is damn strict forcing you to write code in a very precise way). But it's now a piece of crap, completely impossible to work with. How would you possibly design a language which tells that those comments are useless and annoying, that my naming conventions is among the poorest and that intermediary variables add more harm than good?

Using Unicode in names is a good example. In the code above, I haven't even used Unicode in the names of variables. [A-Za-z0-9_] is enough to give meaningless names. On the other hand, Unicode may be very helpful in improving code. This piece of code:

```<code>const numeric Pi = 3.1415926535897932384626433832795;
numeric firstAlpha = deltaY / deltaX + Pi;
numeric secondAlpha = this.Compute(firstAlpha);
Assert.Equals(math.Infinity, secondAlpha);
</code>```

is readable enough, but allowing Unicode in names can empower the programmer to write this instead (the problem being that you won't be able to type variable names on a non-Greek keyword):

```<code>const numeric π = 3.1415926535897932384626433832795;
numeric α₁ = Δy / Δx + π;
numeric α₂ = this.Compute(α₁);
Assert.Equals(math.∞, α₂);
</code>```

Some developers will consider that the second variant pushes naming too far, but it may be an excellent readability boost for some projects (such as a project written by a team of scientists).

Talking about naming conventions, I haven't seen a single rule which actually prevents giving bad names to variables. An example such as the code above can be prevented by a rule similar to:

The names of private variables should contain at least four characters. The names of public variables should contain at least six characters.

But this won't prevent renaming pp into ppppppp just to get rid of the warning. An additional rule:

The names can't contain a character consecutively repeated more than two times. For example, feed is a valid name, while feeed is not.

may also be circumvented by renaming the variable to ppabcde.

The actual goal

What's more important is that a well designed programming language should help avoiding errors. For example:

```<code>if (this.isEnabled)
    this.PlayVideo();
    this.PlaySubtitles();
</code>```

is a sign that something went wrong. When I see that in a C# code, I blame:

The programmer, because it's so simple to always insert curly brackets, instead of taking a risk of losing thousands of dollars because of a stupid bug, hard to detect during code reviews and hard to find later,

The programmer, again, because he should have used proper tools (StyleCop in this case),

The language, because such syntax could have been forbidden,

The IDE, because it didn't reacted to the fact that the programmer screwed up indentation.

Conclusion

Be restrictive when it helps avoiding bugs and when the syntax flexibility is not particularly useful.

Don't be restrictive just to help beginners: they'll find ways to make their code unreadable anyway.

Add syntactic sugar when it helps readability most of the time, without being misused most of the time.

Example of Python

If you know Python, this is a good example of useful strictness. Persons who just started learning it are usually negatively surprised by its strictness:

What? I can't indent the code like I want? This is annoying!

or:

There are no switch statements in Python? Are you serious?! Are you telling that I have to use if-elif-else every time I need a switch?

A few years later, the person would confirm that:

Having meaningful indentation is an excellent idea, because it prevents subtle errors (like the one with the if above) and reduces the effort of writing code (instead of putting semicolons and indenting code, you deal only with indentation).

They don't need a switch, because they replace conditional by polymorphism anyway and when they actually need a mechanism similar to a switch, a dictionary is a perfect choice.

Title: Should sanity be a property of a programmer or a program?

Body:
I design and implement languages, that can range from object notations to markup languages. In many cases I have considered restrictions in favor of sanity (common knowledge), like in the case of control characters in identifiers. There are two consequences to consider before doing this:

It takes extra computation

It narrows liberty

I'm interested to learn how developers think of decisions like this. As you may know Microsoft C# is very open on the contrary. If you really want to prefix your integer as Long with 'l' instead of 'L' and so risk other developers of confusing '1' and 'l', no problem. If you want to name your variables in non-latin script so they will contrast with C#'s latin keywords, no problem. Or if you want to distribute a string over multiple lines and so break a series of indentation, no problem.

It is cheap to ensure consistency with restrictions and this makes it tempting to implement. But in the case of disallowing non-latin characters (concerning the second example), it means a discredit to Unicode, because one would not take full advantage of its capacity.

Body:
No matter how restrictive a language is, some programmers will still find ways to screw things up. Imagine the following piece of code:

var price = this.ApplyVAT(basePrice);
if (this.acceptsRebate)
{
    return new RebateCalculator(RebateType.Default).Transform(price);
}

return price;

Let's screw it:

// Rebats calculator became variable cal.
var cal = new RebateCalculator(RebateType.Default);

// stylecop complain if i dont put comment here and leave line empty. don't know why??
//
// don't know price now so later maybe!!!
Price pp = null;

// Func is transforms price to price!
Func<Price, Price> tar = cal.Do;
var g = Tax(bPR);

// changed by MAG 02/08/2013
// if arebt2 is true, the condition should match.....
if (arebt2)
{
    // assign g to g2
    var g2 = g;

    // don't remember what tar mean but its very important!!! don't remove!!!
    pp = tar(g);
}
else
{
    // it's the same!
    pp = g;
}

// i can return now because i know price!!!
return pp;

The code still complies to the same IL, and doesn't violate any StyleCop or Code analysis rules (while StyleCop is damn strict forcing you to write code in a very precise way). But it's now a piece of crap, completely impossible to work with. How would you possibly design a language which tells that those comments are useless and annoying, that my naming conventions is among the poorest and that intermediary variables add more harm than good?

Using Unicode in names is a good example. In the code above, I haven't even used Unicode in the names of variables. [A-Za-z0-9_] is enough to give meaningless names. On the other hand, Unicode may be very helpful in improving code. This piece of code:

const numeric Pi = 3.1415926535897932384626433832795;
numeric firstAlpha = deltaY / deltaX + Pi;
numeric secondAlpha = this.Compute(firstAlpha);
Assert.Equals(math.Infinity, secondAlpha);

is readable enough, but allowing Unicode in names can empower the programmer to write this instead (the problem being that you won't be able to type variable names on a non-Greek keyword):

const numeric π = 3.1415926535897932384626433832795;
numeric α₁ = Δy / Δx + π;
numeric α₂ = this.Compute(α₁);
Assert.Equals(math.∞, α₂);

Some developers will consider that the second variant pushes naming too far, but it may be an excellent readability boost for some projects (such as a project written by a team of scientists).

Talking about naming conventions, I haven't seen a single rule which actually prevents giving bad names to variables. An example such as the code above can be prevented by a rule similar to:

The names of private variables should contain at least four characters. The names of public variables should contain at least six characters.

But this won't prevent renaming pp into ppppppp just to get rid of the warning. An additional rule:

The names can't contain a character consecutively repeated more than two times. For example, feed is a valid name, while feeed is not.

may also be circumvented by renaming the variable to ppabcde.

The actual goal

What's more important is that a well designed programming language should help avoiding errors. For example:

if (this.isEnabled)
    this.PlayVideo();
    this.PlaySubtitles();

is a sign that something went wrong. When I see that in a C# code, I blame:

The programmer, because it's so simple to always insert curly brackets, instead of taking a risk of losing thousands of dollars because of a stupid bug, hard to detect during code reviews and hard to find later,

The programmer, again, because he should have used proper tools (StyleCop in this case),

The language, because such syntax could have been forbidden,

The IDE, because it didn't reacted to the fact that the programmer screwed up indentation.

Conclusion

Be restrictive when it helps avoiding bugs and when the syntax flexibility is not particularly useful.

Don't be restrictive just to help beginners: they'll find ways to make their code unreadable anyway.

Add syntactic sugar when it helps readability most of the time, without being misused most of the time.

Example of Python

If you know Python, this is a good example of useful strictness. Persons who just started learning it are usually negatively surprised by its strictness:

What? I can't indent the code like I want? This is annoying!

or:

There are no switch statements in Python? Are you serious?! Are you telling that I have to use if-elif-else every time I need a switch?

A few years later, the person would confirm that:

Having meaningful indentation is an excellent idea, because it prevents subtle errors (like the one with the if above) and reduces the effort of writing code (instead of putting semicolons and indenting code, you deal only with indentation).

They don't need a switch, because they replace conditional by polymorphism anyway and when they actually need a mechanism similar to a switch, a dictionary is a perfect choice.


问:
How to process document state transition?
Imagine there is an application (ASP.NET MVC) that processes some documents. The document must be revised several times by different group of users.

state/role rules:

simple user can only publish document; (priority: low)

userGroup1 can switch it to next state or reject it; (priority: higher)

userGroup2 can confirm previous state and switch it to next gradual state or reject it; (priority: highest)

How to implement such a workflow in ASP.NET MVC? How to impelement UI, views so that group with lower priority can both visually/technically perform only allowed transitions? Can I somehow extend that system: link?

Do I need extras like service bus, event sourcing for that?

答:
I did something similar

Created a class user

And an enumeration role

HashSet of the roles the user is in

Create a public property for each authority

```<code>public bool CanPublish
{
    get { return roles.Contains(role.simple) || roles.Contains(role.Group1) ...; }
}
</code>```

This gives you the freedom to add or remove roles and what roles have have what authority

The UI is not in the business of deciding what role can do what

ContentLicense: CC BY-SA 3.0

Body:
I did something similar

Created a class user

And an enumeration role

HashSet of the roles the user is in

Create a public property for each authority

public bool CanPublish
{
    get { return roles.Contains(role.simple) || roles.Contains(role.Group1) ...; }
}

This gives you the freedom to add or remove roles and what roles have have what authority

The UI is not in the business of deciding what role can do what


问:
Is this simple XOR encrypted communication absolutely secure?
Say Alice and Peter each have a 4GB USB flash memory stick. They meet and save on both sticks two files named alice_to_peter.key (2GB) and peter_to_alice.key (2GB) which contain randomly generated bits. They never meet again, but communicate electronically. Alice also maintains a variable called alice_pointer and Peter maintains variable called peter_pointer, both of which are initially set to zero.

When Alice needs to send a message to Peter, she does (where n is the nth byte of the message):

```<code>encrypted_message_to_peter[n] = message_to_peter[n] XOR alice_to_peter.key[alice_pointer + n]
encrypted_payload_to_peter = alice_pointer + encrypted_message_to_peter
alice_pointer += length(encrypted_message_to_peter)
</code>```

(and for maximum security, the used part of the key can be erased)

Peter receives encrypted_payload_to_peter, reads alice_pointer stored at the beginning of message and does:

```<code>message_to_peter[n] = encrypted_message_to_peter[n] XOR alice_to_peter.key[alice_pointer + n]
</code>```

And for maximum security, after reading of message also erase the used part of the key.
- EDIT: In fact this step with this simple algorithm (without integrity check and authentication) decreases security, see Paŭlo Ebermann post below.

When Peter needs to send a message to Alice they do the reverse, this time with peter_to_alice.key and peter_pointer.

With this trivial schema they can send each day for the next 50 years 2GB / (50 * 365) = ~115kB of encrypted data in both directions. If they need more data to send, they could use larger keys, for example with today's 2TB HDs (1TB keys) it would be possible to exchange 60MB/day for the next 50 years! That's a lot of data in practice; for example, using compression it's more than hour of high quality voice communication.

It seems to me that there is no way for an attacker to read the encrypted messages without the keys, because even if they have an infinitely fast computer, with brute force they can get every possible message under the limit, but this is an astronomical number of messages and the attacker doesn't know which of them is the actual message.

Am I right? Is this communication scheme really absolutely secure? And if it is secure, does it have its own name? XOR encryption is well-known, but I'm looking for the name of this concrete practical application using large keys on both sides? I am humbly expecting that this application has been invented someone before me. :-)

Note: If it's absolutely secure then it's amazing, because with today's low cost large storage devices, it would be much cheaper to do secure communication than with expensive quantum cryptography, and this has equivalent security!

EDIT:
I think this will be more practical in the future as storage costs decrease. It can solve secure communication forever. Today you have no certainty if someone successfully attacks existing ciphers even a year later and makes its often expensive implementations insecure. In many cases before communication occurs, when both sides meet personally, that's the time to generate the keys. I think it's perfect for military communication, for example between submarines which can have HDs with large keys, and military central can have a HD for each submarine. It could also be practical in everyday life, for example to control your bank account, because when you create your account you meet with the bank etc.

答:
Yes, this is a One-time pad. If the key material is never re-used, it is theoretically secure.

The downsides are that you would need one key per communicating pair of principals and you would need a secure way of exchanging the key material in advance of communicating.


问:
Preferred way for dealing with customer-defined data in enterprise application
Let's say that we have a small enterprise web (intranet) application for managing data for car dealers. It has screens for managing customers, inventory, orders, warranties and workshops.

This application is installed at 10 customer sites for different car dealers.

First version of this application was created without any way to provide for customer-specific data. For example, if dealer A wanted to be able to attach a photo to a customer, dealer B wanted to add e-mail contact to each workshop, and dealer C wanted to attach multiple PDF reports to a warranty, each and every feature like this was added to the application, so all of the customers received everything on new update.

However, this will inevitably lead to conflicts as the number of customers grow as their usage patterns are unique, and if, for instance, a specific dealer requested to have an ability to attach (for some reason) a color of inventory item (and be able to search by this color) as a required item, others really wouldn't need this feature, and definitely will not want it to be a required item. Or, one dealer would like to manage e-mail contacts for their employees on a separate screen of the application.

I imagine that a solution for this is to use a kind of plugin system, where we would have a core of the application that provides for standard features like customers, inventory, etc, and all of the customer's installed plugins.

There would be different kinds of plugins - standalone screens like e-mail contacts for employees, with their own logic, and customer plugin which would extend or decorate inventory items (like photo or color).

Inventory (customer,order,...) plugins would require to have installation procedure, hooks for plugging into the item editor, item displayer, item filtering for searching, backup hook and such.

Is this the right way to solve this problem?

答: Looks like you need to put authorization in your system. Develop all functionality but put client ids against each services /UI and based on the current client id fetch the specific feature.</p>


问:
Server side C# MVC with AngularJS
I like using .NET MVC and have used it quite a bit in the past.  I have also built SPA's using AngularJS with no page loads other than the initial one.  I think I want to use a blend of the two in many cases.  Set up the application initially using .NET MVC and set up routing server side.  Then set up each page as a mini-SPA.  These pages can be quite complex with a lot of client side functionality.

My confusion comes in how to handle the model-view binding using both .NET MVC and the AngularJS scope.  Do I avoid the use of razor Html helpers?  The Html helpers create the markup behind the scene so it could get messy trying to add angularjs tags using the helpers.  So how to add ng-model for example to @Html.TextBoxFor(x => x.Name).  Also ng-repeat wouldn't work because I'm not loading my model into the scope, right?  I'd still want to use a c# foreach loop?

Where do I draw the lines of separation?  Has anyone gotten .NET MVC and AngularJS to play nicely together and what are your architectural suggestions to do so?

答:
We built an app that is a combination of AngularJS and MVC

The best practices say while using both MVC and angularJS, we should use MVC web api at server side to get data from server
And at client side we should use Angularjs framework for binding JSON data with html controls.

OwnerDisplayName: Ryan Langton

Title: Server side C# MVC with AngularJS


问:
How can I team up two MVC frameworks without having them fight each other?
I'm creating a CRUD-based web project, and am thinking about using a server side MVC framework (such as CodeIgniter or Laravel) in tandem with a client side MVC framework (such as AngularJS). Is this a fairly common approach? After all, it's clear that I need something on the server, and that doing MVC on the client as well can enhance my application. But I feel that two MVC frameworks on the same project would just get in the way of each other and lead to disproportionate complexity and repetition.

What kind of approach or architecture would help me get the best out of both MVC frameworks when using one on the client, the other on the server?

答:
The best practices say while using both MVC and angularJS, we should use MVC web api at server side to get data from server
And at client side we should use Angularjs framework for binding JSON data with html controls.

On the client:
On the client, I used AngularJS to handle everything from calling the web api's to local validation. It gives the user the "immediate" response that is being pushed by the latest push on the web. You can make your page dynamic or relatively static. By using an architecture that is using a separation of concerns, I can replace the back end with anything that supports a RESTful api.

On the Server :
I found the easiest thing to do was to build a bunch of RESTful web api's to provide data services to the client. I also perform validation on the server to make sure that no one cheats (sending data using a client other than the web page). I also assemble the web page (though a controller and minimal view) to load all of the libraries it needs. Since I am building the web page with almost no changes from the view to the final HTML, I should be able to replace AngularJS with something else.


答:
As Vatine's answer indicates, your algorithm is basically a one-time-pad.

However, to comment on one of your notes:

Note: If its absolutely secure then its amazing because with today low cost large memories it is practicaly much cheeper way of secure communication than expensive quantum cryptography and with equivalent security!

My response is no, it is not amazing. The devil is always in the details, and the devil here is in the exchange of keys. Your method depends on a flawless, face-to-face key exchange. I can't afford to send James Bond carrying a 4GB flash disk for me to every merchant on the internet every time I want to buy something or have other secure connections.

And lastly, the XOR aspect of your algorithm is not important. A simple substitution cipher is just fine with a OTP. The strength of the OTP is that the key is never reused, and it assumes James Bond is flawlessly exchanging the keys for both parties (i.e. prior secure key exchange)

Title: Is this simple XOR encrypted communication absolutely secure?

Body:
Say Alice and Peter each have a 4GB USB flash memory stick. They meet and save on both sticks two files named alice_to_peter.key (2GB) and peter_to_alice.key (2GB) which contain randomly generated bits. They never meet again, but communicate electronically. Alice also maintains a variable called alice_pointer and Peter maintains variable called peter_pointer, both of which are initially set to zero.

When Alice needs to send a message to Peter, she does (where n is the nth byte of the message):

```<code>encrypted_message_to_peter[n] = message_to_peter[n] XOR alice_to_peter.key[alice_pointer + n]
encrypted_payload_to_peter = alice_pointer + encrypted_message_to_peter
alice_pointer += length(encrypted_message_to_peter)
</code>```

(and for maximum security, the used part of the key can be erased)

Peter receives encrypted_payload_to_peter, reads alice_pointer stored at the beginning of message and does:

```<code>message_to_peter[n] = encrypted_message_to_peter[n] XOR alice_to_peter.key[alice_pointer + n]
</code>```

And for maximum security, after reading of message also erase the used part of the key.
- EDIT: In fact this step with this simple algorithm (without integrity check and authentication) decreases security, see Paŭlo Ebermann post below.

When Peter needs to send a message to Alice they do the reverse, this time with peter_to_alice.key and peter_pointer.

With this trivial schema they can send each day for the next 50 years 2GB / (50 * 365) = ~115kB of encrypted data in both directions. If they need more data to send, they could use larger keys, for example with today's 2TB HDs (1TB keys) it would be possible to exchange 60MB/day for the next 50 years! That's a lot of data in practice; for example, using compression it's more than hour of high quality voice communication.

It seems to me that there is no way for an attacker to read the encrypted messages without the keys, because even if they have an infinitely fast computer, with brute force they can get every possible message under the limit, but this is an astronomical number of messages and the attacker doesn't know which of them is the actual message.

Am I right? Is this communication scheme really absolutely secure? And if it is secure, does it have its own name? XOR encryption is well-known, but I'm looking for the name of this concrete practical application using large keys on both sides? I am humbly expecting that this application has been invented someone before me. :-)

Note: If it's absolutely secure then it's amazing, because with today's low cost large storage devices, it would be much cheaper to do secure communication than with expensive quantum cryptography, and this has equivalent security!

EDIT:
I think this will be more practical in the future as storage costs decrease. It can solve secure communication forever. Today you have no certainty if someone successfully attacks existing ciphers even a year later and makes its often expensive implementations insecure. In many cases before communication occurs, when both sides meet personally, that's the time to generate the keys. I think it's perfect for military communication, for example between submarines which can have HDs with large keys, and military central can have a HD for each submarine. It could also be practical in everyday life, for example to control your bank account, because when you create your account you meet with the bank etc.


问:
On a queue, which end is the "head"?
I had always thought that the "head" of a queue as the next element to be read, and never really questioned that usage. So a linked-list library I wrote, which is used for maintaining queues, codified that terminology: we have a list1_head macro that retrieves the first element; when using this library in a queue, this will be the first element to be removed.

But a new developer on the team was used to having queues implemented the other way around. He described a queue as behaving like a dog: you insert at the head, and remove at the tail. This is a clever enough description that I feel like his usage must be more widespread, and I don't have a similarly evocative description of my preferred usage.

So, I guess, there are two related questions: 1, what does the "head" of a queue mean to you? and 2, why do we use the word "head" to describe that concept?

答:
Both conventions are in common use. In my experience, when talking about queues in general, the head element is the next one to come out of the queue, and the tail is where elements enter the queue. This is consistent with everyday English usage—we get in line at the back, and the next to be served is at the front, or head. (And if you cut, it's to the back of the line for you!)

However, when a queue (aka FIFO) is implemented as a ring buffer, the terms are typically reversed, because the used portion of the ring buffer resembles a snake going around in a circle. Assuming the snake is moving forward, the head is naturally the end that leading the movement, which is also the end at which incoming items are inserted.

Title: On a queue, which end is the "head"?


问:
Session management in a Service Oriented Architecture
Where should you manage a users session in a SOA? Should you manage it in the Web Service or in the client and why?

My application is SPA
(Considering that this will be the stacked that will be used
Apache CXF for Web Services
AngularJS for making REST calls)

答: Session should be managed at client side, as services mainly for server side processing and not for maintaining user session. But if we are managing user session at client side we need take care of security pitfall at client side, as user data is prone to get changed.</p>


答:
Surely... if you have a SPA that describes the page and only requires data provided to it, then you need a RESTful server that fetches and returns the required data. Nothing more.

If you're trying to mix the two, then I think you might be making things very complicated. Sure using MVC to generate the initial pages is a decent idea, but once done - you still want the AngularJS calls to be making REST requests for data. Combining the two seems easiest when you keep the 2 technologies separate.

Title: Server side C# MVC with AngularJS

Body:
I like using .NET MVC and have used it quite a bit in the past.  I have also built SPA's using AngularJS with no page loads other than the initial one.  I think I want to use a blend of the two in many cases.  Set up the application initially using .NET MVC and set up routing server side.  Then set up each page as a mini-SPA.  These pages can be quite complex with a lot of client side functionality.

My confusion comes in how to handle the model-view binding using both .NET MVC and the AngularJS scope.  Do I avoid the use of razor Html helpers?  The Html helpers create the markup behind the scene so it could get messy trying to add angularjs tags using the helpers.  So how to add ng-model for example to @Html.TextBoxFor(x => x.Name).  Also ng-repeat wouldn't work because I'm not loading my model into the scope, right?  I'd still want to use a c# foreach loop?

Where do I draw the lines of separation?  Has anyone gotten .NET MVC and AngularJS to play nicely together and what are your architectural suggestions to do so?


问:
Condition to use polymorphism
is polymorphism only possible when there is a scenario of inheritance or is the implementation of polymorphism not dependent on inheritance.

Or is polymorphism mainly usefull when there is inheritance ?

答:
Polymorphism in computer science is a broader term than your question suggests:

adhoc polymorphism, supported as function overloading;

parametric polymorphism, as realized in generic containers like List<T>;

dynamic polymorphism, or subtyping, which relies on the Liskov substitution principle.

Only the last form is based on inheritance. See http://en.wikipedia.org/wiki/Polymorphism_%28computer_science%29

Title: Condition to use polymorphism


答:
If you haven't heard of Dependency Injection - I think it's worth taking a look at.  Implementing DI really helped me get a better feel for polymorphism, constructing / testing instances or objects, etc.  Here are a few good tutorials:

DI For Beginners

Basic structure / surface concepts

Title: Condition to use polymorphism

Body:
is polymorphism only possible when there is a scenario of inheritance or is the implementation of polymorphism not dependent on inheritance.

Or is polymorphism mainly usefull when there is inheritance ?


答:
While the one-time-pad has an unconditional (mathematically proven) privacy guarantee against an attacker who only can read messages, it has some weaknesses.

An intercepting attacker who guesses correctly the plain text can manipulate the ciphertext to whatever she wants (with the same length).

If an attacker inserts or deletes some message (or part thereof), Alice's and Bob's pointers get out-of-sync and every future communication is broken.

Update: This assumed that both parties keep track of both pointers. If you send the current pointer value, you are vulnerable to two-time-pad attacks (if you allow the same range of key to be used more than once) or DOS-attacks (if you don't allow the same range of key to be used more than once, e.g. by deleting them).

Both of those problems are caused by missing integrity and authentication protection – you have a perfect cipher, but no MAC.

Add a MAC to your one-time-pad protocol to make it actually secure. Each message should get a "checksum" which ensures that it was actually sent by the supposed sender, and was not modified in between. Also, you should sent some sequence number so the receiver knows which part of the key to use when a previous message got lost (or to reject the message if it is duplicated) – include this in the checksum calculation.

A usual MAC algorithm would do here, but I suppose you might want to use some one-time polynomial MAC to have matching security to your one-time pad. (Take the MAC key from the bits before or after your encryption key, i.e. don't reuse one key for both goals.)


答:
Polymorphism is unrelated to inheritance.

There are different kinds of polymorphism:

Parametric Polymorphism: here, a subroutine is parameterized over a type, meaning it doesn't know anything about the type. If it doesn't know anything, then it obviously also doesn't know about any inheritance relationship. Examples are a subroutine to compute the length of a list, it doesn't need to know anything about the types of the contents of the list. (Another common name for this kind of polymorphism is Generics.)

Ad-Hoc Polymorphism: contrary to parametric polymorphism, where the subroutine doesn't care about the type and behaves identical for every type, with ad-hoc polymorphism, there are ad-hoc implementations of the subroutine for every type, so that the subroutine behaves differently for each type. (Another common name for this kind of polymorphism is Overloading.)

Inclusion Polymorphism: this implies some kind of subtype relationship. (Note: subtyping is not the same as inheritance, even though languages like Java and C# confuse the two. In OCaml, for example, they both exist but are different and distinct concepts.) Inclusion polymorphism means that an instance of a subtype can be treated as an instance of a supertype. (The Liskov Substitution Principle tells us how to make sure that is safe.) (Another common name for this kind of polymorphism is Subtype Polymorphism.)

Inheritance can be used in ad-hoc polymorphism to share code between different implementations of subroutines to avoid code duplication. But it is purely a method for reducing code duplication, it is neither necessary nor sufficient for ad-hoc polymorphism.

Title: Condition to use polymorphism


问:
Creating an object that is ready to be used & unset properties - with IoC
I have a question regarding the specifics of object creation and the usage of properties.  A best practice is to put all the properties into a state such that the object is useful when its created.  Object constructors help ensure that required dependencies are created.

I've found myself following a pattern lately, and then questioning its appropriateness.

The pattern looks like this...

```<code> public class ThingProcesser
  {
    public List<Thing> CalculatedThings { get; set; }

    public ThingProcesser()
    {
        CalculatedThings = new List<Thing>();
    }

    public double FindCertainThing()
    {
        CheckForException();
        foreach (var thing in CalculatedThings)
        {
            //do some stuff with things...
        }
    }

    public double FindOtherThing()
    {
        CheckForException();
        foreach (var thing in CalculatedThings)
        {
            //do some stuff with things...
        }
    }

    private void CheckForException()
    {
        if (CalculatedThings.Count < 2) throw new InvalidOperationException("Calculated things must have more than 2 items");
    }
  }
</code>```

The list of items is not being changed, just looked through by the methods.  There are several methods on the class, and to avoid having to pass the list of things to each function as a method parameter, I set it once on the class.  While this works, does it violate the principle of least astonishment?

Since starting to use IoC I find myself not sticking things into the constructor, to avoid having to use a factory pattern.  For example, I can argue with myself and say well the ThingProcessor really needs a List to work, so the object should be constructed like this.

```<code> public class ThingProcesser
    {
        public List<Thing> CalculatedThings { get; set; }

        public ThingProcesser(List<Thing> calculatedThings)
        {
            CalculatedThings = calculatedThings;
        }
    }
</code>```

However, if I did this, it would complicate things for IoC, and this scenario hardly seems appropriate for something like the factory pattern.

So in summary, are there some good guidelines for when something should be part of the object state, vs. passed as a method parameter?  When using IoC, is the factory pattern the best way to deal with objects that need created with state?  If something has to be passed to multiple methods in a class, does that render it a good candidate to be part of the objects state?

答:
While this works, does it violate the principle of least astonishment?

I suppose. More importantly, it tightly couples a bunch of stuff to these methods that not all of them (individually) need, and presents a too loose contract with the outside world.

Since starting to use IoC I find myself not sticking things into the constructor, to avoid having to use a factory pattern.

What? I fail to see how those things are in any way related. If something needs IFoo, then let it take an IFoo. If you also want to use IoC containers to provide you a concrete implementation of IFoo then go right ahead. Your constructor doesn't need to know that.

So in summary, are there some good guidelines for when something should be part of the object state, vs. passed as a method parameter?

Who owns the state? If it's an intrinsic part of your class, used across multiple functions on the class, then your class owns the state. Otherwise, pass it in.

If something has to be passed to multiple methods in a class, does that render it a good candidate to be part of the objects state?

Possibly, but it's not a candidate for including something in your class, it's a code smell. It means that this other odd class needs this data to work, but the data isn't part of it.

It's a bit subtle, but "oh, I'll tack this on in the constructor" is a good way to violate the Single Responsibility Principle and otherways make a sucky class. "Hrmm, this doesn't quite work, what if I did XYZ instead?" is a good way to refactor multiple classes so that they have a nice single responsibility and interact in a clean decoupled way.


问:
How to design console application with good seperation of UI from Logic

Is it considered an overkill for console application to be design like MVC , MVP or N tier architecture?  If not which is more common and if you can link me to simple example of it.

I want to implement a tic tac toe game in console application.

I have a solution which hold two projects: TicTacToeBusinessLogic (Class library project) and
TicTacToeConsoleApplication (Console application project) to represent the view logic.
In the TicTacToeConsoleApplication I've Program.cs class which holds the main entry point (public static void Main).

Now I face a problem.

I want the game to handle its own game flow so I can:
Create new GameManager class (from BL) but this causing the view to directly know the BL part.

So I'm a little confused how to write it in an acceptable way.
Should I use delegates? Please show me a simple example.

答:
The choice to use MVC or alike depends to my opinion on the size of your application and not on the kind of UI.

The bigger the complexity and size, the more you want to work in a structured way, using a design pattern. Of course, the used method should not give more overhead than benefits. But keep in mind thad code tends to grow in size and complexity very fast.


问:
Is there a common programming term for the problems of adding features to an already-featureful program?
I'm looking for a commonly used programming term to describe a software-engineering phenomenon, which (for lack of a better way to describe it) I'll illustrate first with a couple of examples-by-analogy:

Scenario 1:  We want to build/extend a subway system on the outskirts of a small town in Wyoming.  There are the usual subway-problems to solve, of course (hiring the right construction company, choosing the best route, buying the subway cars), but other than that it's pretty straightforward to implement the system because there aren't a huge number of constraints to satisfy.

Scenario 2:  Same as above, except now we need to build/extend the subway system in downtown Los Angeles.  Here we face all of the problems we did in case (1), but also additional problems -- most of the applicable space is already in use, and has a vocal constituency which will protest loudly if we inconvenience them by repurposing, redesigning, or otherwise modifying the infrastructure that they rely on.  Because of this, extensions to the system happen either very slowly and expensively, or they don't happen at all.

I sometimes see a similar pattern with software development -- adding a new feature to a small/simple program is straightforward, but as the program grows, adding further new features becomes more and more difficult, if only because it is difficult to integrate the new feature without adversely affecting any of the large number of existing use-cases or user-constituencies.  (even with a robust, adaptable program design, you run into the problem of the user interface becoming so elaborate that the program becomes difficult to learn or use)

Is there a term for this phenomenon?

答:
Feature creep or creeping featurism:

Describes a systematic tendency to load more chrome and features onto systems at the expense of whatever elegance they may have possessed when originally designed. See also feeping creaturism. “You know, the main problem with BSD Unix has always been creeping featurism.”

More generally, the tendency for anything complicated to become even more complicated because people keep saying “Gee, it would be even better if it had this feature too”. (See feature.) The result is usually a patchwork because it grew one ad-hoc step at a time, rather than being planned. Planning is a lot of work, but it's easy to add just one extra little feature to help someone ... and then another ... and another.... When creeping featurism gets out of hand, it's like a cancer. The GNU hello program, intended to illustrate GNU command-line switch and coding conventions, is also a wonderful parody of creeping featurism; the distribution changelog is particularly funny. Usually this term is used to describe computer programs, but it could also be said of the federal government, the IRS 1040 form, and new cars. A similar phenomenon sometimes afflicts conscious redesigns; see second-system effect. See also creeping elegance.

-- From the Jargon File, a compendium of the (originally) 1970s MIT and Stanford hacker subculture. So yeah, you could say that it's an established term...


问:
Modelling highly specific business requirements
How can one go about modelling highly specific business requirements, which have no precedent in the system? Take for example the following requirement:

When a purchase order contains N lines, is over X value in total and is being recorded against project Y, an email needs to be sent to persons A and B with the details

This requirement supplements other requirements surrounding purchase orders, but comes in at a much later date in response to some ongoing problem elsewhere in the business.

Persons A and B are not part of any role or group in the system, and don't hold any specific responsibility; they are simply the two people the business has appointed to receive these emails in this very specific case. Projects are also data driven, so project Y has no special properties to distinguish it from any other project. The only way to identify it is to compare its identifier to a magic number.

How can one go about modelling this kind of case without introducing too much additional complexity? That I can think of right now, there are a couple of options.

Perform the checks and actions inline with the existing code. Here we find the correct spot in the code, check the conditions in the requirement and send the emails to hardcoded addresses. Of course this is fraught with issues. At the very least it stops working if one of these people leaves or changes their email address. At worst you have to ensure that any tests and test data are aware that additional actions are taken for a specific set of criteria.

Introduce some form of events system. Here we introduce an eventing system, so that we might react to some event, and fulfil the requirement outside of the usual path of execution. This sounds like a cleaner solution than option 1, but the work involved is ultimately probably slightly overkill for this one small requirement. That said, having it in place does allow the system to handle these kinds of specific requirements consistently and easily in the future.

Are there any other (good/better) ways of handling highly specific requirements? I mean other than telling the other parts of the business no!

答:
This requirement supplements other requirements surrounding purchase orders, but comes in at a much later date in response to some ongoing problem elsewhere in the business.

You seem to think that, once this issue is solved, your customer will have no more ongoing problem elsewhere in the bussiness. Experience shows that they will have.

And you should plan accordingly some system that is extensible. In fact, IM(ns)HO it should have been done from the beginning; thinking that the rules of validation of a Purchase may change over time is not something, and would have helped in implementing the rules that you knew beforehand (by making them more modular).

Anyway for me it is not a programming question but a project management question. Since it was not contemplated in the initial project because nobody asked about that possibility, it mingt be the moment to call the stakeholders and let them decide: a fast, dirty fix that will require modifications to the code for every change, or a more flexible solution that will be delivered later (and probably with some additional costs).

It is the stakeholders who really know what is in the balance (how many of these changes are likely to happen, which are the costs of deploying late the project, even if that check is really so important that it cannot be done by having someone review the data in a report).

You can make an educated guess of the importance of such changes, but really cannot be sure. Also, by involving stakeholders and make them decide, you can hope to educate them into realizing the costs of incomplete/late specifications so that in the next project they do a better job at it.


问:
Follow the deadlines vs Do it right
I have been given a huge task of migrating few functionalities from jQuery to AngularJS. I have been pretty good at Angular by now. But I want to dive deep and create futuristic, sound architecture. BAs are seating on my neck, wanting to get my tasks as quickly as possible. I prefer doing something once and right vs keeping on patching existing functionalities. And with this attitude, I always keep working more than necessary. Am I missing something? Am I having right approach or am just not convincing enough BAs my point. What's the best approach, in your opinion

Thank You :)

答:
As a developer you should give estimates about the time it will take to do something along with fully explaining the consequences of the various choices in terms of technical debt.

However, if you are supposed to get something done in a week and that is possible (with the associated addition of more technical debt) that is not something you, as a developer, make the call on.  The managers, architects, business analysts, and clients are the ones that decide which path to follow.  If they are ok with adding to the technical debt of the project, thats fine.

Yes, it is wonderful to sit down and craft some beautiful code that fits an ideal framework and will be beautiful.  However, if that doesn't fit within the timeframe for the project, thats not what you should be coding.  You are wishing to be a painter painting the Sistine Chapel, and instead being paid to paint a fence... thats ok, fences need to be painted too... but don't paint a fresco in the fence.

Joycoding is a fun thing to do, but it doesn't always align to business objectives.

Title: Follow the deadlines vs Do it right


答:
Gold-plating: from wikipedia continuing to work on a project or task well past the point where the extra effort is worth the value it adds (if any).

http://en.wikipedia.org/wiki/Gold_plating_(software_engineering)

Most of the gold-plating I've seen/heard about isn't an exact fit for the scenario you give (extending a simple subway to LA), but is a good definition.

Title: Is there a common programming term for the problems of adding features to an already-featureful program?

Body:
I'm looking for a commonly used programming term to describe a software-engineering phenomenon, which (for lack of a better way to describe it) I'll illustrate first with a couple of examples-by-analogy:

Scenario 1:  We want to build/extend a subway system on the outskirts of a small town in Wyoming.  There are the usual subway-problems to solve, of course (hiring the right construction company, choosing the best route, buying the subway cars), but other than that it's pretty straightforward to implement the system because there aren't a huge number of constraints to satisfy.

Scenario 2:  Same as above, except now we need to build/extend the subway system in downtown Los Angeles.  Here we face all of the problems we did in case (1), but also additional problems -- most of the applicable space is already in use, and has a vocal constituency which will protest loudly if we inconvenience them by repurposing, redesigning, or otherwise modifying the infrastructure that they rely on.  Because of this, extensions to the system happen either very slowly and expensively, or they don't happen at all.

I sometimes see a similar pattern with software development -- adding a new feature to a small/simple program is straightforward, but as the program grows, adding further new features becomes more and more difficult, if only because it is difficult to integrate the new feature without adversely affecting any of the large number of existing use-cases or user-constituencies.  (even with a robust, adaptable program design, you run into the problem of the user interface becoming so elaborate that the program becomes difficult to learn or use)

Is there a term for this phenomenon?


问:
Architecture for dashboard showing aggregated stats
I'd like to know what are common architectural pattern for the following problem.

Web application A has information on sales, users, responsiveness score, etc. Some of this information are computationally intensive and or have a complex business logic (e.g. responsiveness score).

I'm building a separate application (B) for internal admin tasks that modifies data in web application A and report on data from web application A.

For writing I'm planning to use a restful api. E.g. create a new entity, update entity, etc.

In application B I'd like to show some graphs and other aggregate data for the previous 12 months. I'm planning to store the aggregate data for each month in redis.

Some data should update more often, e.g every 10 minutes.

I can think of 3 ways of doing this.

A scheduled task in app B that connects to an api of app A that provides some aggregated data. Then app B stores it in Redis and use that to visualise pages. Cons: it makes complex calculation within a web request, requires lot's of work e.g. api server and client, storing, etc., pros: business logic still lives in app A.

A scheduled task in app A that aggregates data in an non-web process and stores it directly in Redis to be accessed by app B.

A scheduled task in app A that aggregates data in a non-web process and uses an api in app B to save it.

I'd like to know if there is a well known architectural solution to this type of problems and if not what are other pros/cons for the solution I've suggested?

答:
As I mentioned in comment, I'd use ETL tool to extract data from app A database and maybe from the logs too. At the same time, I'd transform the raw data into data cube, I'm guessing for dashboard you will need to mix them with time dimension.

The output from ETL process should be a more structured data that will help you build dashboard or feed them to OLAP tools for analysis.

In operation, the tool would be scheduled to run different tasks depending on your needs, some could be hourly, daily or every 10 mins. If you're concern about the impact on production database, you can setup a database replica to read from.

ps.
Even if you still want to create an API, ETL tool can do that for you too, that is read data and present it as API with output in xml/json.


答:
" BAs are seating on my neck, wanting to get my tasks as quickly as possible."

So what? What happens when you don't deliver when they want? Are they setting the schedule or do you. Hopefully, you have some control over determining the quality of a feature and get some consensus on what it means to be done.

Give an estimate and keep them informed when you will not be able to deliver. Let them know the more they interrupt you asking when things will be done, will only make the project take longer.

They should have some idea of the complexity and length of time it took to create this functionality the first time. Not that they can come up with specific times, but you will need to explain if you do not deliver in a "relative" time frame. Example:  If feature A took twice as long as feature B in the old language, you would need to explain why it may take you 3 times as long to build B in the new language as you did with feature A.

Title: Follow the deadlines vs Do it right

Body:
I have been given a huge task of migrating few functionalities from jQuery to AngularJS. I have been pretty good at Angular by now. But I want to dive deep and create futuristic, sound architecture. BAs are seating on my neck, wanting to get my tasks as quickly as possible. I prefer doing something once and right vs keeping on patching existing functionalities. And with this attitude, I always keep working more than necessary. Am I missing something? Am I having right approach or am just not convincing enough BAs my point. What's the best approach, in your opinion

Thank You :)


问:
How to safely copy an object?
This question is going to be a little long. Please bear with me.

Something that happened in a project of mine made me think about how to safely copy objects. I'll present the situation I had and then ask a question.

There was a class SomeClass:

class SomeClass {
    private Thing[] things;

    public SomeClass(Thing[] things){
        this.things = things;
    }

    // irrelevant stuff omitted

    public SomeClass copy(){
        return new SomeClass(things);
    }
}
```

<p>There was another class <code>Processor</code> that takes <code>SomeClass</code> objects, copies them (via <code>someClassInstance.copy()</code>), manipulates the copy's state, and returns the copy. Here it is:</p>

<pre class="lang-java prettyprint-override"><code>class Processor{
    public SomeClass processObject(SomeClass object){
        SomeClass copy = object.copy();
        manipulateTheCopy(copy);
        return copy;
    }

    // irrelevant stuff omitted
}
</code>```

I ran this, and it had bugs. I looked into these bugs, and it turned out that the manipulations Processor does on copy actually affect not only the copy, but also the original SomeClass object that was passed into processObject.

I found out that it was because the original and the copy shared state - because the original passed it's field things into the copy when creating it.

This made me realize that copying objects is harder than simply instantiating them with the same fields as the original.

For the two objects to be completely disconnected, without any shared state, each of the fields passed to the copy also has to be copied. And if that object contains other objects - they have to be copied too. And so on.

So basically, in order to be able to actually copy an object, each class in the system must have a copy() method, that also invokes copy() on all of it's fields, and so on.

So for example, for copy() in SomeClass to work, it needs to look like this:

public SomeClass copy() {
    Thing[] copyThings = new Thing[things.length];
    for(int i = 0; i < things.length; i++)
        copyThings[i] = things[i].copy();
    return new SomeClass(copyThings);
}
```

<p>And if <code>Thing</code> has object fields of it's own, than it's own <code>copy()</code> method must be appropriate:</p>

<pre class="lang-java prettyprint-override"><code>class Thing {
    private Apple apple;
    private Pencil pencil;
    private int number;

    public Thing(Apple apple, Pencil pencil, int number){
        this.apple = apple;
        this.pencil = pencil;
        this.number = number;
    }

    public Thing copy(){
        // 'number' is a primitve.
        return new Thing(apple.getCopy(), pencil.getCopy(), number);
    }
}
</code>```

And so on.

Of course, instead of all classes having a copy() method, the copying mechanism can happen in all of the getters and the constructors of classes (unless places where it isn't suitable, for example when the field points to an external object, not to an object that 'is part' of this object).

Still, that means that in order to be able to safely copy an object - most classes would have to have copying mechanisms in their getters.

My question is divided into two parts:

How frequently do you need to get a copy of an object? Is this a regular issue?

Is the technique described common and/or reasonable? Or is there a better way to make safe copies of objects?

答:
1) I think it depends on the language, but yes, I copy things quite a bit. That said, I think it depends on the type of object immensely. Things I tend to copy a lot: plain-old-data structures, things like date/time or other objects that in my particular program are building blocks for everything else. If you think of object relationships as a tree, I typically copy only leaf nodes. (Think structs or blittable objects, in the old meaning of "blit"). Note that in many cases these leaf nodes are also good candidates for immutability (with a nod to @SJuan76). Things I don't copy: controllers or services, anything with references to other objects that don't fall into the leaf-node category. Your mileage may vary.

2) So then we get into why you copy. Unfortunately, the purpose of a copied object can be quite different from program to program or even within two parts of a program. The point is that it is quite hard to get a one-size-fits all solution because you wouldn't be programming if one size fit all. There are at least two main approaches to this: shallow vs. deep cloning. @gnat brought up a great point about Java clone. In the same vein I would do some digging around .NET's memberwise clone and find out its pros and cons. The only real rule I've found in programming using copies is that if you choose to copy something other than a leaf node, you run a greater risk of confusion about what the copy does - just like you found from your assignment.

Title: How to safely copy an object?


答:
Based on your two examples - this is simple program extension - and that's all it is - it doesn't matter if your program is simple (Wyoming) or complex (LA), in both cases you've identified a business need for new features and are going to design them in. Feature creep would involve features of questionable value - or possibly involve features better implemented by separate software.

I don't know if there's a specific phrasing to describe extending an already complex software - but this would be where documentation (blueprints) and code/project management will start to be really useful. Regression testing (no real analogue to subway construction) would be extremely useful here, too.


答:
This is an interesting question because it touches on some very important concepts which are often confused by novice and even intermediate programmers.  Java tends to exacerbate this confusion somewhat due to the design of the language.

The big problem here is that you initially confused copying a reference with copying a value.  What you thought you were going to do was copy the values, what you ended up doing was copying the references.

To explain the difference, imagine you have a tv set.  You are watching a DVD on that TV.  Someone else wants to watch the same program as you.  When you copy by reference, you are giving them a tv and hooking that tv up to the DVD player.  Whenever you decide to watch a different DVD, they get to see what you're watching.  If they change the DVD, you see what they're watching.

When you are copying by value, you are giving them a TV, DVD player and a copy of the DVD.  They can change the DVD to whatever they like and you don't see it.  Similarly, if you change the DVD they won't see what you're watching.

There are many times when you want to copy by value and there are many times where you want to copy by reference.

To work out what type of copying you want to do, you need to ask yourself the following questions:

Why am I copying this object?

For each of the properties of the object, do I want my copies to refer to the original property or a copy of the original copy?

How will my program behave if I am copying by reference/value?

The answers to these questions will tell you how deeply you need to copy your objects.

Title: How to safely copy an object?

Body:
This question is going to be a little long. Please bear with me.

Something that happened in a project of mine made me think about how to safely copy objects. I'll present the situation I had and then ask a question.

There was a class SomeClass:

class SomeClass {
    private Thing[] things;

    public SomeClass(Thing[] things){
        this.things = things;
    }

    // irrelevant stuff omitted

    public SomeClass copy(){
        return new SomeClass(things);
    }
}
```

<p>There was another class <code>Processor</code> that takes <code>SomeClass</code> objects, copies them (via <code>someClassInstance.copy()</code>), manipulates the copy's state, and returns the copy. Here it is:</p>

<pre class="lang-java prettyprint-override"><code>class Processor{
    public SomeClass processObject(SomeClass object){
        SomeClass copy = object.copy();
        manipulateTheCopy(copy);
        return copy;
    }

    // irrelevant stuff omitted
}
</code>```

I ran this, and it had bugs. I looked into these bugs, and it turned out that the manipulations Processor does on copy actually affect not only the copy, but also the original SomeClass object that was passed into processObject.

I found out that it was because the original and the copy shared state - because the original passed it's field things into the copy when creating it.

This made me realize that copying objects is harder than simply instantiating them with the same fields as the original.

For the two objects to be completely disconnected, without any shared state, each of the fields passed to the copy also has to be copied. And if that object contains other objects - they have to be copied too. And so on.

So basically, in order to be able to actually copy an object, each class in the system must have a copy() method, that also invokes copy() on all of it's fields, and so on.

So for example, for copy() in SomeClass to work, it needs to look like this:

public SomeClass copy() {
    Thing[] copyThings = new Thing[things.length];
    for(int i = 0; i < things.length; i++)
        copyThings[i] = things[i].copy();
    return new SomeClass(copyThings);
}
```

<p>And if <code>Thing</code> has object fields of it's own, than it's own <code>copy()</code> method must be appropriate:</p>

<pre class="lang-java prettyprint-override"><code>class Thing {
    private Apple apple;
    private Pencil pencil;
    private int number;

    public Thing(Apple apple, Pencil pencil, int number){
        this.apple = apple;
        this.pencil = pencil;
        this.number = number;
    }

    public Thing copy(){
        // 'number' is a primitve.
        return new Thing(apple.getCopy(), pencil.getCopy(), number);
    }
}
</code>```

And so on.

Of course, instead of all classes having a copy() method, the copying mechanism can happen in all of the getters and the constructors of classes (unless places where it isn't suitable, for example when the field points to an external object, not to an object that 'is part' of this object).

Still, that means that in order to be able to safely copy an object - most classes would have to have copying mechanisms in their getters.

My question is divided into two parts:

How frequently do you need to get a copy of an object? Is this a regular issue?

Is the technique described common and/or reasonable? Or is there a better way to make safe copies of objects?


问:
If Scheme is untyped, how can it have numbers and lists?
Scheme is said to be just an extension of the Untyped Lambda Calculus (correct me if I am wrong). If that is the case, how can it have Lists and Numbers? Those, to me, look like 2 base types. So I'd say Racket is actually an extension of the Simply Typed Lambda Calculus. No?

Question:

Is Scheme's type system actually based or more similar to Simply Typed or Untyped Lambda Calculus?

In what ways does it differ from Untyped and or Simply Typed Lambda Calculus?

(The same question is valid for "untyped" languages such as Python and JavaScript - all of which look like they have base types to me.)

答:
The simple answer is that Scheme is not untyped: as you noticed, Scheme programs can use values of several useful types. Still, people do mean something when they say Scheme is untyped, they mean something that is better expressed by saying that Scheme has a dynamic type system. Let me (eventually) explain.

When people say "the untyped lambda calculus", they call it untyped because all the values it deals with are of the same type: combinators (you may have heard them called "functions", too). Programming in such a language feels dangerous because you have to keep straight in your head what kind of thing you wanted to represent with each value. The system has no built in help to catch your errors.

Languages people actually program in tend[^1] to have more help telling different sort of values apart, this extra help is in the form of (1) a richer collection of types for the values the language lets you talk about and (2) error messages you get when you attempt to apply an operation to a value of a type for which the operation is not defined.

In some language implementations, programs can be compiled or preprocessed in some way prior to being run. If you get error messages about using values of the wrong type during this compilation phase, before running your program, the implementation is said to use static typing.

If either (1) there is no compilation or preprocessing phase or (2) there is but you still only get error messages about using values of the wrong type during the running of your program, then the implementation is said to use dynamic typing.

Most (all?) Scheme implementations use a dynamic typing system. There are languages fairly similar to Scheme which have an implementation using static typing, such as Typed Racket.

[^1]: There are languages that people have actually used to make software where all values are essentially of the same type, such as most computer's native machine languages, assembly languages and BCPL.

OwnerDisplayName: Dokkat


答:
What you are describing is a well known and very basic issue in computer languages that have objects. It really isn't very surprising. The ending was fairly obvious by about halfway through the story. It's the difference between shallow copy and deep copy.

Objects tend to fall into two categories: those that represent values and those that have identity. Value objects are things like points and vectors, and they really need to be copied accurately. If they contain references to mutable objects you need a deep copy, but be wary. You may be digging a hole.

Identity objects are things like widgets, business objects and other complex entities. They usually don't need to be copied. To be safe, it's best to use language features to enforce that. [In C++ we use a private copy constructor.]

In answer to your questions:

How frequently do you need to get a copy of an object? Is this a regular issue?

Value objects commonly; identity objects rarely. It's an issue you often have to think about, but not so often do anything special. If you are copying identity objects, could be a smell.

Is the technique described common and/or reasonable? Or is there a better way to make safe copies of objects?

Depends on the language, but in most languages it looks like overkill. Make sure your value objects copy safely, make sure your identity objects cannot be copied and handle any others on a case-by-case basis.

Value objects rarely contain references to other objects, and if they do it will only be a reference to either an immutable object (like a string) or to another value object. For example, a Rectangle object could contain two Point objects. This is one case where it makes sense to handle a copy of one object (Rectangle) by a nested call to the copy method of another object (Point). It is very much the exception.

Note that C# is quite helpful in that it has real value types. In Java and other languages where all objects are references, life is not so simple.

You may find yourself in a situation where you seem to need to copy an object that has identity, although it should not be common. You need to consider carefully the issues of identity for the copy (same or different), mutability (setters etc), whether the copy may replace the original, etc. It's all case by case unfortunately.

Note also that value objects will normally calculate their hash value from their contents, where identity objects will normally calculate their hash value from a unique feature such as their address. That means they may not play well with hash-based collections like dictionaries.

Title: How to safely copy an object?


问:
Future of a ServiceStack based Solution in the Context of Licensing
I just want someone to clarify the following questions as Demis Bellot had announced a couple of weeks ago that ServiceStack would go commercial. Refer link below.

https://plus.google.com/app/basic/stream/z12tfvoackvnx1xzd04cfrirpvybu1nje54

(Please note that when I say ServiceStack or SS I refer to all associated SS libraries such as ServiceStack.Text, etc.)

If I have a solution already developed using ServiceStack today will I have to purchase a license once SS goes commercial even if I don't upgrade the SS binaries to the commercial release version?

Will previous versions of SS (prior to commercial licensing) always be opensource and use the same license as before?

If I fork SS today (prior to commercial licensing) on Github, would it be illegal to maintain that after SS goes commercial?

If the answer to question 2 is yes, then would I still be able to fork a previous version after SS goes commercial without worrying about the commercial license (all the while maintaining and releasing the source to the public)?

答:
No, you do not have to purchase a license to keep using your existing version of ServiceStack (version 3) once a commercial version 4 is released.

Yes, you can still use existing versions of ServiceStack under the permissive BSD licenses with which they were released.

No, it is not illegal to fork Version 3 of SS (and maintain that fork), because the license under which it was released allows you to do so.

Yes, you may fork previous versions of SS (version 3) even after commercial versions (version 4+) are released.  However, as another answer mentions, SS is under no obligation to provide the world with old versions.  (It may be in their interest to remove it from the web.) However, rather than creating your own fork, may I suggest considering getting behind one of the community forks:

a) NServiceKit - "a forever free, open source fork of ServiceStack V3"

b) NuStack - "Providing a public, non commercial, user maintained version of Service Stack libraries."


问:
Storing editable site content?
We have a Django-based website for which we wanted to make some of the content (text, and business logic such as pricing plans) easily editable in-house, and so we decided to store it outside the codebase. Usually the reason is one of the following:

It's something that non-technical people want to edit. One example is copywriting for a website - the programmers prepare a template with text that defaults to "Lorem ipsum...", and the real content is inserted later to the database.

It's something that we want to be able to change quickly, without the need to deploy new code (which we currently do twice a week). An example would be features currently available to the customers at different tiers of pricing. Instead of hardcoding these, we read them from database.

The described solution is flexible but there are some reasons why I don't like it.

Because the content has to be read from the database, there is a performance overhead.

We mitigate that by using a caching scheme, but this also adds some complexity to the system.

Developers who run the code locally see the system in a significantly different state compared to how it runs on production. Automated tests also exercise the system in a different state. Situations like testing new features on a staging server also get trickier - if the staging server doesn't have a recent copy of the database, it can be unexpectedly different from production.

We could mitigate that by committing the new state to the repository occasionally (e.g. by adding data migrations), but it seems like a wrong approach. Is it?

Any ideas how best to solve these problems? Is there a better approach for handling the content that I'm overlooking?

答:
You should think about editable content as a full feature.

Some added complexity is obviously needed. Maybe you could store the static resource after editing in order to avoid performance harm.

Content is data, so it's part of system state. Developers must deal with it thinking users can do pretty much everything your UI allows them to.

If automated tests rely on database state, the tests must also set database state (TestDataBuilders, fixtures...) before running, or make them unit tests (maybe through mocking).

But, instead of making content editable, you could make that technical people part of your development flow. Instead of develop --> deploy --> alter data, you could do alter data --> develop --> deploy. Maybe you could borrow some ideas from static blogging platforms like Octopress.

Title: Storing editable site content?


问:
Handling Types for Real and Complex Matrices in a BLAS Wrapper
I come from a C background and I'm now learning OOP with C++. As an exercise (so please don't just say "this already exists"), I want to implement a wrapper for BLAS that will let the user write matrix algebra in an intuitive way (e.g. similar to MATLAB) e.g.:

A = B*C*D.Inverse() + E.Transpose();

My problem is how to go about dealing with real (R) and complex (C) matrices, because of C++'s "curse" of letting you do the same thing in N different ways.

I do have a clear idea of what it should look like to the user: s/he should be able to define the two separately, but operations would return a type depending on the types of the operands (R*R = R, C*C = C, R*C = C*R = C). Additionally R can be cast into C and vice versa (just by setting the imaginary parts to 0).

I have considered the following options:

As a real number is a special case of a complex number, inherit CMatrix from RMatrix. I quickly dismissed this as the two would have to return different types for the same getter function.

Inherit RMatrix and CMatrix from Matrix. However, I can't really think of any common code that would go into Matrix (because of the different return types).

Templates. Declare Matrix<T> and declare the getter function as T Get(int i, int j), and operator functions as Matrix *(Matrix RHS). Then specialize Matrix<double> and Matrix<complex>, and overload the functions.

Then I couldn't really see what I would gain with templates, so why not just define RMatrix and CMatrix separately from each other, and then overload functions as necessary?

Although this last option makes sense to me, there's an annoying voice inside my head saying this is not elegant, because the two are clearly related. Perhaps I'm missing an appropriate design pattern?

So I guess what I'm looking for is either absolution for doing this, or advice on how to do better.

答:
Although this last option makes sense to me, there's an annoying voice inside my head saying this is not elegant, because the two are clearly related.

Your difficulty comes from your conception that the two are clearly related.  You are probably right, but in this pretty vague form, this statement is only puzzling you instead of helping you.  What you have to do is to turn that clearly into a specific statement about the relations you expect within your implementation, and what they do imply for the library client and maybe the end-user of the application using that library.  Once you have this specific statement, you can use it to evaluate the merits and demerits of your various designs.

I do have a clear idea of what it should look like to the user: s/he should be able to define the two separately, but operations would return a type depending on the types of the operands (R*R = R, C*C = C, R*C = C*R = C)

First of all, defining such an interface has little practical interest—but you warned everybody: this is a toy-example.  In numerical computations, where one typically uses BLAS, matrices are huge and sometimes really huge so that one actually wants to avoid implicit or automatic allocations of memory and one would use a register-like interfaces pretty similar to the one you will find in the original library.

If you want to type formulas as in a math book you could make evaluation be an extra step, i.e. R*R returns a formula, which, when evaluated, returns an actual matrix, e.g.

```<code> C.eval(R*R)
</code>```

would set C to the product of R and R.

I have considered the following options: […]

Trying to model the world as we understand it (your first attempt with RMatrix ← CMatrix) is often wrong in OO-programming because what we actually need, is to model the world in a way that makes the treatments we want to make easy to describe.

Body:
Although this last option makes sense to me, there's an annoying voice inside my head saying this is not elegant, because the two are clearly related.

Your difficulty comes from your conception that the two are clearly related.  You are probably right, but in this pretty vague form, this statement is only puzzling you instead of helping you.  What you have to do is to turn that clearly into a specific statement about the relations you expect within your implementation, and what they do imply for the library client and maybe the end-user of the application using that library.  Once you have this specific statement, you can use it to evaluate the merits and demerits of your various designs.

I do have a clear idea of what it should look like to the user: s/he should be able to define the two separately, but operations would return a type depending on the types of the operands (R*R = R, C*C = C, R*C = C*R = C)

First of all, defining such an interface has little practical interest—but you warned everybody: this is a toy-example.  In numerical computations, where one typically uses BLAS, matrices are huge and sometimes really huge so that one actually wants to avoid implicit or automatic allocations of memory and one would use a register-like interfaces pretty similar to the one you will find in the original library.

If you want to type formulas as in a math book you could make evaluation be an extra step, i.e. R*R returns a formula, which, when evaluated, returns an actual matrix, e.g.

 C.eval(R*R)

would set C to the product of R and R.

I have considered the following options: […]

Trying to model the world as we understand it (your first attempt with RMatrix ← CMatrix) is often wrong in OO-programming because what we actually need, is to model the world in a way that makes the treatments we want to make easy to describe.


问:
Should sanity be a property of a programmer or a program?
I design and implement languages, that can range from object notations to markup languages. In many cases I have considered restrictions in favor of sanity (common knowledge), like in the case of control characters in identifiers. There are two consequences to consider before doing this:

It takes extra computation

It narrows liberty

I'm interested to learn how developers think of decisions like this. As you may know Microsoft C# is very open on the contrary. If you really want to prefix your integer as Long with 'l' instead of 'L' and so risk other developers of confusing '1' and 'l', no problem. If you want to name your variables in non-latin script so they will contrast with C#'s latin keywords, no problem. Or if you want to distribute a string over multiple lines and so break a series of indentation, no problem.

It is cheap to ensure consistency with restrictions and this makes it tempting to implement. But in the case of disallowing non-latin characters (concerning the second example), it means a discredit to Unicode, because one would not take full advantage of its capacity.

答:
I don't think you can make a language "idiot proof". At most, you can make it "mistake proof" for those that have good intentions.

So I wouldn't invest computertime and developer (compile time) or user (runtime) frustration  in checking every little detail. Of course, errors will be made, and of course bugs will be shipped, but is it worth restricting everything and everyone in the hope that you can prevent (for the full 100%) fools from being fools, or humans from making mistakes?


问:
Do input template languages exist?
When I have to create some textual representation of data, I can use a template language, so that my code does not have to worry about the structure of the output file - I can sometimes even write code that's independent of whether the output is XML, LaTeX or any other plain text. A simple example:

Template (in separate file):

```<code><someXmlTag>
$variableName
</someXmlTag>
</code>```

Code:

```<code>Template(temstring).substitute(variableName="value")
</code>```

Result (written to output file):

```<code><someXmlTag>
value
</someXmlTag>
</code>```

I want to do the same, but in the opposite direction. I have XML or plain text or whatever files to input. I want to describe the input structure in a separate file that looks like the input but has these variable declarations in it, and I want to handle it with code that's independent of the structure.

Has this been done before? What approach was used and how did it work out?

(We usually handle XML input by using an XML parser library to describe the input structure in program code, handle plaintext input by writing regexes in code, and don't handle LaTeX input because LaTeX can't really be parsed.)

答:
Simple templating doesn't really work in the reverse direction.  The reverse direction is (effectively) parsing.  The problem with parsing based on just templates is that a typical template or set of templates can be applied to a typical input string in lots of ways ... resulting in ambiguous parses.

This is not to say that reverse templating is impossible.  But I think that you can only make it practical in the context of a grammar and/or schema.  For example, to handle XML templates your reverse templating engine would need at least an understanding of core XML syntax, and possible also an XML schema or DTD as well.

Has it been done?  Well I used a system called Refine in the 1990s that did something rather like this.  (It was designed as a framework for program language engineering / reverse engineering, and it allowed you to do funky things like defining a custom grammar and define parse-tree patterns in the context of that grammar.)  I recall it being quite powerful ... but the system was really expensive, and never took off.

Title: Do input template languages exist?


问:
If you had to go back and re-learn your skill set, how would you do it?
My younger brother is looking to start programming. He's 14, and technically-inclined, but no real experience programming. He's looking to me for guidance, and I don't feel as if my experience is enough, so I figured I'd ask here.

He's more interested in web programming, but also has an interest in desktop/mobile/server applications.

What would be a good learning path for him to take? I'm going to buy him a bunch of books for Christmas to get him started; the question is, what should he learn, and in which order?

The way I see it, he needs to learn theory and code. I'd like to start him off with Python or Ruby or PHP. If he wants to get in to web, he's also going to need to learn HTML, CSS, Javascript, etc.

Out of those three domains (Languages, Theory, Markup/Etc.), what is the best order do you think to learn in? Also, am I missing anything?

Thanks!

答:
I really like the way that I came into programming; the only thing I can imagine changing is my access to books.  My family didn't have the money for all the books I could devour, and our small rural library didn't exactly stock tech manuals.  In the grand scheme of things, this is a small nitpick.

I wholeheartedly disagree with those who say you can't learn theory at 14.  The earlier you learn the theory, the better.  I read The Art of Computer Programming at 14, though I'd already been coding a while.

The best thing you can do for your brother is to give him the tools to pursue his interests, and include him in the hacker/coder community whenever possible, so he can learn the mindset of a great coder.

Nudge him away from proprietary tools wherever possible.  There's so much more available to him in the open source world.  I got as good as I am largely due to the guidance I received from more experienced folks in the open source community.

If you can afford to, get him a Safari account, or help him buy books when needed.  Even lending what you already own can help.

Make sure he has access to a decent desktop or laptop and a server or VPS to experiment on.  If mobile apps are his thing, make sure he has a phone or demo device to work on.

Show him how to find IRC channels, mailing lists, etc. for the things he is interested in working with/on.

Make sure he knows how to ask smart questions and, conversely, the particulars of a support leech so he knows what not to do.

His first programming language isn't the most important factor.  The totality of programming languages he learns is extremely important.  One-language coders never pass a certain (relatively low) level of coding-foo.

ContentLicense: CC BY-SA 2.5


问:
Looking for a certain datatype if it exists
I'm looking for the kind of a certain datatypes.

The main idea of this datatype is to describe a productionline containing several steps. Each step should be represented as a "vertex" containing an object of any type. Then for every "vertex" there are possible "subproductionlines" joining the line.

So it could look something like:

```<code>                  O   ->   O   ->   |                    #   subproductionline
                                    |                    #   joiningpoint
O   ->   O   ->   O   ->   O   ->   O   ->   O   ->   O  # main productionline
                                    |                    #   joiningpoint
         O   ->   O   ->   O   ->   |                    #   subproductionline
                           |                             #   joiningpoint
                  O   ->   |                             #subsubproductionline
</code>```

Does anyone of you know such a datatype?

If I were to code such a datatype... I see there two options of doing this:

A datatype as an Array (main productionline) containing Arrays (containing as first element the containing data of each vertex) and the rest of elements containing subproductionlines as recursive this datatype

or

A datatype as an Array containing the data stored in the vertex. Last element is either the element, where this subproductionline is joining, or a specific element representing the end of a main productionline, if it is one.

What do yout think is the better solution?

The programming language I think of using for is c / c++.

答:
What you have drawn is a Directed Graph. It is most likely a Directed Tree, but it could be a Directed Acyclic Graph. The diagram provided and my understanding of the process would not be compatible with cycles, but I'm not clear whether there is only fan-in or there is also fan-out.

Graphs of this kind are a well known and thoroughly analysed data structures. There are numerous algorithms for doing interesting things like finding paths, pruning, reordering, weighting and so on.

In C++ you could implement this as a Node with a collection of pointers to other Nodes. If it is a tree, and if you need to navigate in only one direction, you need only one 'down' pointer per node.

There are functions provided in the standard libraries to make implementing structures like these very straightforward. You could say C++ was designed to solve this problem (and those like it).


问:
Is it good to review programs with seniors and boss even if it is working fine?
In my company, before delivery of any project, my boss asks my seniors to review programs written by me or other team members or sometimes boss also sits with us for review.

I think it is a good way of getting knowledge, but sometimes when programs are working fine, they don't work same after review and I need to look again into my program.

They says that review helps to optimize program and query execution, but can we prefer optimization over actual functioning of program?

答:
I interpreted your question as "Can my functioning code be butchered in a review to a point where it doesn't even compile anymore?".

Yes, it can. Generally, during a review you look at how your code does what it does. When you want to hand in your code, you say you have finished a certain part of the program.

You say it works. Testing is then done to verify this. A module passing tests does not mean that module should not be touched again.

A module appearing functional can still be a disaster waiting to happen, either at runtime or in a few months when you or someone else has to perform maintenance on it. By changing your code in a review and pointing out what was wrong with it, your reviewer is (hopefully) trying to actually teach you something.


问:
How can I handle this string concatenation in C in a reusable way
I've been writing a small C application that operates on files, and I've found that I have been copy+pasting this code around my functions:

```<code>char fullpath[PATH_MAX];
fullpath[0] = '\0';
strcat(fullpath, BASE_PATH);
strcat(fullpath, subdir);
strcat(fullpath, "/");
strcat(fullpath, filename);

// do something with fullpath...
</code>```

Is there a better way? The first thought that comes to mind is to create a macro but I'm sure this is a common problem in C, and I'm wondering how others have solve it.

答:
In my opinion, as a professional programmer, you must not write code like that. You must either write your own path concatenation function, or use the one provided by the platform.

If it's Windows you should use the _makepath function. For greater safety, use the _makepath_s function. It will be more careful than you are. I'm sure Posix has something similar.

If you must write your own, simple concatenation is just not good enough. You need to check for proper handling of delimiters, trailing slash on directories, leading period on extensions, null arguments and all that stuff. The good news is that if you do it once it's done.

In the more general case of concatenating strings, you are very hampered by your apparent decision to stick with C rather than C++. I would again recommend writing your own function with variable arguments (vararg) and using strcat_s() for security. Something like:

```<code>bool strcat_multi_s(char *destination, size_t maxlength, ...); // return false on overflow
</code>```

I leave the coding as an exercise for the reader.

Body:
In my opinion, as a professional programmer, you must not write code like that. You must either write your own path concatenation function, or use the one provided by the platform.

If it's Windows you should use the _makepath function. For greater safety, use the _makepath_s function. It will be more careful than you are. I'm sure Posix has something similar.

If you must write your own, simple concatenation is just not good enough. You need to check for proper handling of delimiters, trailing slash on directories, leading period on extensions, null arguments and all that stuff. The good news is that if you do it once it's done.

In the more general case of concatenating strings, you are very hampered by your apparent decision to stick with C rather than C++. I would again recommend writing your own function with variable arguments (vararg) and using strcat_s() for security. Something like:

bool strcat_multi_s(char *destination, size_t maxlength, ...); // return false on overflow

I leave the coding as an exercise for the reader.


答:
"Working fine" is indeed a great metric, but if you are the only one in the team able to decipher what you wrote, and thus maintain it, the code is close to worthless for the company for the mid or long-term.

A good code is at least :

working as intended

human-readable / clear

easily maintainable

easily extensible for future changes

safe

without unneeded dependencies

handling correctly non nominal cases

etc

(Some of these requirements are actually overlapping but are good to consider individually...)

Code reviews serve the purpose beyond the "working" part, which can be done through automatic tests.

I personally know this is annoying to have something working being teared apart, and having to rebuild it from the ground up. But, often, this is due to a miscommunication from the senior/tech lead. So, if you think you have to rewrite too often, next time, go to the reviewer before writing a single line and try to get as much information as possible on what he is expecting, in every detail. It could also be great if the team of code reviewers summarize their expectation in a formal document that every dev can refer to.

On a more positive side, a session could also be an occasion to share great practices/designs.

Title: Is it good to review programs with seniors and boss even if it is working fine?

Body:
In my company, before delivery of any project, my boss asks my seniors to review programs written by me or other team members or sometimes boss also sits with us for review.

I think it is a good way of getting knowledge, but sometimes when programs are working fine, they don't work same after review and I need to look again into my program.

They says that review helps to optimize program and query execution, but can we prefer optimization over actual functioning of program?


答:
Peer reviews are no doubt a great way of learning. Someone may see something different, they have different experience to you and should be able to contribute improvements. This shouldn't be disparaging, I'd expect any developer to be able to comment and constructively criticize anyone's code!

It sounds to me like some of these "improvements" are actually making breaking changes because (as you'd expect) the reviewing developer has less experience with the software than the author.

This trend is it's self feedback, perhaps your code is difficult to follow or maintain? Are your reviews valuable? Absolutely! I can see how it can be frustrating, to have working code which your peers then appear to break, you shouldn't be disheartened - you should work to protect your code against these changes.

The question then becomes how to protect the functionality of your programs so you know the functionality is still working after you've completed your reviews. My suggestion would be to ensure you have decent unit test coverage. That way whenever you/your reviewer/your successor changes the code they can be confident that the changes they've made are safe.

ETA: I've just spotted one of your comments, I'm sure this goes without saying but code reviews should be done before the test team get their hands on it. Otherwise they're not testing the final product.