答:
When you're interactively editing something, I like to think of there being two "models".  There's the "entity model" which is the persisted state, and there's the "edit model" which is the current state of the data during the interactive editing.

These are typically not the same thing.  For instance, there are states that are allowable in the edit model which aren't allowed in the entity model (like having not filled out a required field).

So the edit model and entity model (as far as I'm concerned) should both be part of your business layer, because they both contain business rules.  I know a lot of people using MVVM think that the ViewModel should be the edit model.  I don't think that's a hard and fast rule, and in my current application I'm keeping them separate.

So, Pankaj said:

Controllers process incoming requests, perform operations on the model, and select views to render to the user.

Based on what I've said above, there are two types of actions:

Normal edit actions (changing a selection in a drop-down that has an effect on some other field) would interact with the edit model only.  The controller then creates a new View based on the new edit model state.

"CRUD" operations that commit data should first check the edit model for validity (by calling into the edit model itself), and if valid, should then commit the changes to the entity model by delegating to some kind of "map" method in the models.  Typically this commits your changes to a shared data store like a database.  Other users can then see the changes.

So the controller handles all input requests, but delegates the work to the model.  After the delegation of the work to the model, it then maps the model back onto the View (typically by instantiating a new view and passing in the new state of the edit model).


问:
Can any GPLv2 licensed library be used in a company's internal intranet application?
I am creating an internal application for the company I am contracted to. We wish to use a GPLv2 licensed library in this application. Some points

The application is to be used within the confines of the company and
never be available for public use. It is for internal company use
only.

It will never be sold, ever!!. So no money will be made directly from selling the code. It's not a product.

There are two forms of usage of the application

Its native form which is console based exe (which uses the GPL library); and

Usage via a web interface which calls the executable.

The source code will remain closed source (company use only), and be propriety

I have gone through numerous questions on SO about this (one closed as off-topic and another unmarked from Programmers ), but I have had a hard time in understanding whether my interpretation of the licence is correct.

Based on my understanding thus far, I am permitted to use this library without any concern. I am not modifying the source code nor am I distributing the application or making the application publicly available. The application will not be sold nor will it be distributed to anyone outside the company (It will however be available at our company's offsite DR facility). I am very likely to use the released versions binaries and not re-compile from source.

The following question from the GNU FAQ seems to support my thoughts.

Does the GPL require that source code of modified versions be posted to the public?

The GPL does not require you to release your modified version, or any
  part of it. You are free to make modifications and use them privately,
  without ever releasing them. This applies to organizations (including
  companies), too; an organization can make a modified version and use
  it internally without ever releasing it outside the organization.

But if you release the modified version to the public in some way, the
  GPL requires you to make the modified source code available to the
  program's users, under the GPL.

Thus, the GPL gives permission to release the modified program in
  certain ways, and not in other ways; but the decision of whether to
  release it is up to you.

Can any GPLv2 licensed library be used in a company's internal intranet application?

答:
It's important to remember in all of this "programmer-to-programmer" advice that none of it is legal counsel. As this thread makes clear, there is room for interpretation with GPL.

You've got to weigh the cost of exposing your organization to legal action if you violate the GPL vs. getting a good, sound legal opinion. There are good ideas in this thread, but I wouldn't make a decision on this input alone.

--

For example, here's a wrinkle: What if the the GPL'd code is JavaScript?

When a user accesses a website with GPL'd JavaScript code, technically the "source code" (in this case a JS file) is "distributed" to the end-user. Does that mean your entire website needs to be GPL'd? There's an entire debate about that, too.

While I hate paying lawyers as much as the next hardworking guy, given the risk, this is one area it's generally better not to depend on Internet advice (except for this advice, of course).

ContentLicense: CC BY-SA 3.0


问:
Complexity vs maintainability in modern hardware
Today with the modern hardware and memory coming cheap, how much sense does it make to spend effort to analyze algoriths or data structure complexity?

Wouldn't it be better instead, to focus on clean, maintainable code, readable code than on optimizations for complexity?

Note:I not talking about embedded systems or systems with similar kinds of constraints.

答:
I can't imagine a day when breeders of fine, ever-faster, racehorses will be able to compensate for overweight, ever-fatter, jockeys.

Hardware engineers knock themselves out making finer and finer lithography, faster clocks, levels of caches, multiple CPUs on a chip.
Meanwhile the people who make the software those chips have to execute say "Performance - who cares?"

Performance does matter.
Slowness is like any other kind of bugs.

You should try not to make them.
But you will make them (if you're working) and you should know how to remove them.

Here's my favorite example.


问:
Why no client-side HTML include tag?
I had a question posed to me the other day by another programmer.  I remember (a very long time ago) wondering the very same.  Why was a browser-side include tag never considered?  Or was it?

Specifically with a tag that instructed the browser to include additional HTML from other sources. e.g. <include src="http://server/foo/bar.html">.  Many folks will make javascript calls and fill innerHTML to accomplish the same, when the same outside a the javascript engine could be accomplished by the browser.

It would have been painful to have nested s s (i.e.) but we have to consider that aspect anywhere anyway.

答: Variants on an <include> tag were indeed considered in the early history of HTML, but they never got very far.

ContentLicense: CC BY-SA 2.5

Title: Why no client-side HTML include tag?


问:
What's a good Programming Metaphor?
I am referring to explaining to the non-programmer what programming is. I made sure to search for similar questions before creating this one, but the few ones I did find seemed to dodge the question, and I specifically would like to see some metaphors or analogies. I personally find it easier to explain something technical to someone through the use of metaphors or analogies.

The reason I'm interested in this is because many people encounter the work of a programmer on a daily basis, but if you ask the average person what a programmer is or does, they don't really know. This leads to certain situations of misunderstanding (ex. "[...] but I thought you were good with computers!")

I really would like to find the best one out there. I would like to be able to easily explain to someone what my career choice is about. Of course, at least the general idea.

I personally don't have a solid one, but I have long thought about it and I have usually gravitated towards the 'language' metaphor, where we happen to know a language that computers understand, and therefore we are able to tell computers what to do, or "teach" them, to solve our problems.

For example:

Imagine that in an alternate reality, humanoid robots with artificial intelligence exist, and some people are able to communicate with them through a common language, which is a variation of English. These people who can communicate with the robots are able to teach them how to solve certain problems or do certain tasks, like doing our chores.

Well, although robots like that don't exist yet, programmers of our time are like those people, but instead of communicating with the robots, they communicate with computers. Programmers "teach" the computers how to perform certain tasks or solve certain problems by means of software which they create by using this "common language".

Programmers and this "common language" are what give us things like email, websites, video games, word processors, smart phones (to put it simply), and many other things which we use on a daily basis.

I don't mean to put programming on the throne or anything, it's just the best metaphor I could come up with.

I'm sure someone will find some issue with this one, it's probably a bit contrived, but then again that's why I'm asking this question.

答:
Programming is like building a factory or an assembly line.

Think of software as a machine or assembly line that exists inside the computer. Some raw materials and components are fed into the machine, and it follows a set of procedures to process them into some final product. The procedures are set up to perform a specific operation on some raw material or component to a specific set of parameters (eg, time, temperature, distance, etc) in a particular order. If the details of the operation to be performed were incorrect, or the machine's sensors aren't correctly calibrated, or if some raw material or component wasn't within expected quality standards, it could change the operation's outcome and the product would not turn out as expected.

Such a machine is very rigid in its operation and acceptable inputs. Machines don't question the designers' intelligence nor its current operating environment. It will continue to follow procedures as long as it's directed to. Even if a change in raw materials or components could have a drastic effect on what happened in later operations, the machine would still perform its procedures. The process would need to be reviewed to see what changes to the procedures were necessary to compensate and produce the desired result. A change to the product's design or configuration might also require a significant change to the operations performed or their order. Although those in charge of production quickly learned the importance of isolating operations as much as possible to reduce undesirable effects between them, a lot of assumptions are made of the condition components are in as they undergo processing; assumptions that might not be detected until the final product is in the hands of the user in some different operating environment.

Title: What's a good Programming Metaphor?


问:
Is code like this a "train wreck" (in violation of Law of Demeter)?
Browsing through some code I've written, I came across the following construct which got me thinking. At a first glance, it seems clean enough. Yes, in the actual code the getLocation() method has a slightly more specific name which better describes exactly which location it gets.

```<code>service.setLocation(this.configuration.getLocation().toString());
</code>```

In this case, service is an instance variable of a known type, declared within the method. this.configuration comes from being passed in to the class constructor, and is an instance of a class implementing a specific interface (which mandates a public getLocation() method). Hence, the return type of the expression this.configuration.getLocation() is known; specifically in this case, it is a java.net.URL, whereas service.setLocation() wants a String. Since the two types String and URL are not directly compatible, some sort of conversion is required to fit the square peg in the round hole.

However, according to the Law of Demeter as cited in Clean Code, a method f in class C should only call methods on C, objects created by or passed as arguments to f, and objects held in instance variables of C. Anything beyond that (the final toString() in my particular case above, unless you consider a temporary object created as a result of the method invocation itself, in which case the whole Law seems to be moot) is disallowed.

Is there a valid reasoning why a call like the above, given the constraints listed, should be discouraged or even disallowed? Or am I just being overly nitpicky?

If I were to implement a method URLToString() which simply calls toString() on a URL object (such as that returned by getLocation()) passed to it as a parameter, and returns the result, I could wrap the getLocation() call in it to achieve exactly the same result; effectively, I would just move the conversion one step outward. Would that somehow make it acceptable? (It seems to me, intuitively, that it should not make any difference either way, since all that does is move things around a little. However, going by the letter of the Law of Demeter as cited, it would be acceptable, since I would then be operating directly on a parameter to a function.)

Would it make any difference if this was about something slightly more exotic than calling toString() on a standard type?

When answering, do keep in mind that altering the behavior or API of the type that the service variable is of is not practical. Also, for the sake of argument, let's say that altering the return type of getLocation() is also impractical.

答: The only thing I can think of not writing code like this is what if this.configuration.getLocation() returns null?  It depends on your surrounding code and target audience using this code.  But as Marco say - Demeter's law is a rule of thumb - it's good to follow, but don't break your back doing so unnecessarily.


答:
The problem here is the signature of setLocation. It's stringly typed.

To elaborate: Why would it expect String? A String represents any kind of textual data. It can potentially be anything but a valid location.

In fact, this poses a question: what is a location? How do I know without looking into your code? If it were a URL than I would know a lot more about what this method expects.

Maybe it would make more sense for it to be a custom class Location. Ok, I wouldn't know at first, what that is, but at some point (probably before writing this.configuration.getLocation() I would take a minute to figure out what it is this method returns).

Granted, in both cases I need to look some place else to understand, what is expected. However in the latter case, if I understand, what a Location is, I can use your API, in the former case, if I understand, what a String is (which can be expected), I still don't know what your API expects.

In the unlikely scenario, that a location is any kind of textual data I would reinterpret this to any kind of data, that has a textual representation. Given the fact, that Object has a toString method, you could go with that, although this demands quite a leap of faith from the clients of your code.

Also you should consider, that this is Java you're talking about, which has very few features by design. That's what's forcing you to actually call the toString at the end.

If you take C# for example, which is also statically typed, then you would actually be able to omit that call by defining behavior for an implicit cast.

In dynamically typed languages, such as Objective-C, you don't really need the conversion either, because as long as the value behaves like a string, everybody is happy.

One could argue, that the last call to toString is less a call, than actually just noise generated by Java's demand for explicitness. You're calling a method, that any Java object has, therefore you do not actually encode any knowledge about a "distant unit" and thereby don't violate the Principle of Least Knowledge. There is no way, no matter what getLocation returns, that it doesn't have a toString method.

But please, do not use strings, unless they are really the most natural choice (or unless you're using a language, that doesn't even have enums ... been there).

Title: Is code like this a "train wreck" (in violation of Law of Demeter)?

Body:
Browsing through some code I've written, I came across the following construct which got me thinking. At a first glance, it seems clean enough. Yes, in the actual code the getLocation() method has a slightly more specific name which better describes exactly which location it gets.

```<code>service.setLocation(this.configuration.getLocation().toString());
</code>```

In this case, service is an instance variable of a known type, declared within the method. this.configuration comes from being passed in to the class constructor, and is an instance of a class implementing a specific interface (which mandates a public getLocation() method). Hence, the return type of the expression this.configuration.getLocation() is known; specifically in this case, it is a java.net.URL, whereas service.setLocation() wants a String. Since the two types String and URL are not directly compatible, some sort of conversion is required to fit the square peg in the round hole.

However, according to the Law of Demeter as cited in Clean Code, a method f in class C should only call methods on C, objects created by or passed as arguments to f, and objects held in instance variables of C. Anything beyond that (the final toString() in my particular case above, unless you consider a temporary object created as a result of the method invocation itself, in which case the whole Law seems to be moot) is disallowed.

Is there a valid reasoning why a call like the above, given the constraints listed, should be discouraged or even disallowed? Or am I just being overly nitpicky?

If I were to implement a method URLToString() which simply calls toString() on a URL object (such as that returned by getLocation()) passed to it as a parameter, and returns the result, I could wrap the getLocation() call in it to achieve exactly the same result; effectively, I would just move the conversion one step outward. Would that somehow make it acceptable? (It seems to me, intuitively, that it should not make any difference either way, since all that does is move things around a little. However, going by the letter of the Law of Demeter as cited, it would be acceptable, since I would then be operating directly on a parameter to a function.)

Would it make any difference if this was about something slightly more exotic than calling toString() on a standard type?

When answering, do keep in mind that altering the behavior or API of the type that the service variable is of is not practical. Also, for the sake of argument, let's say that altering the return type of getLocation() is also impractical.


问:
Is it worth it for a developer to be a scrum master? Is it an official designation or?
Is it beneficial for a developer to become a 'scrum master'?

Is this an official certification or just someone who specializes?

What are the steps towards becoming one?

答:
There are official Scrum training courses as well as assessments and certifications that cover various roles in scrum - Scrum Master, Product Owner, development team member. For these, it's simply a matter of optionally taking a course, reading the recommended material, working through the assessments, and then paying to take a certification exam.

I'm not sure how beneficial formal training is. There are plenty of resources out there for Scrum, including the Scrum Guide and countless books on the subject. Also, these certifications and training is only useful for as long as you are in an environment that uses Scrum. I would recommend learning about Scrum and how to function in various roles in a Scrum team, but I think you could do that very well with self-study, asking the appropriate questions to the right people, and spending time working on a Scrum team.

I personally believe it's far more valuable to understand a variety of process models and methodologies, their strengths and weaknesses, and process improvement methods/techniques rather than to focus on one particular model or method. The ability to tailor processes to meet the needs of your organization, project, and team is far more important than spending a significant amount of time learning a single methodology. After all, if all you have is a hammer, everything looks like a nail.


答:
Speaking as a developer who was trained up as a scrum master I'd say that if you are serious about using agile, and the people around you are too, then it's well worth training up.  A scrum master should know how the agile process works, which meetings are required, what peoples' responsibilities are etc  It's your job to make sure the agile process flows smoothly and to correct it when it doesn't.  I couldn't have done my job without some guidance, but equally you may find that online resources are good enough.

I was lucky in that my company paid for me to be trained and certified by the Scrum Alliance, but I believe there are numerous places you can be trained.  My training consisted of a two day seminar with a exam afterwards - it wasn't taxing, and you'll have to reread a lot of the training material as there's a fair amount to take in.

Title: Is it worth it for a developer to be a scrum master? Is it an official designation or?

Body:
Is it beneficial for a developer to become a 'scrum master'?

Is this an official certification or just someone who specializes?

What are the steps towards becoming one?


答:
Strictly following the Law of Demeter would mean you should implement a method in the configuration object like:

```<code>function getLocationAsString() {
  return getLocation().toString();
}
</code>```

but personally I wouldn't bother because this is such a small situation, and anyway your hands are kinda tied because of the API you can't change. Programming rules are about what you should do when you have a choice, but sometimes you don't have a choice.

Body:
Strictly following the Law of Demeter would mean you should implement a method in the configuration object like:

function getLocationAsString() {
  return getLocation().toString();
}

but personally I wouldn't bother because this is such a small situation, and anyway your hands are kinda tied because of the API you can't change. Programming rules are about what you should do when you have a choice, but sometimes you don't have a choice.


答:
I'd agree with Thomas on the generalities, but focusing on the scrum master role itself there's an important point to note. It is not a technical role. We discussed this a little on the scrum master training I attended recently, If you want to write code then on paper 'being a scrum master' probably not for you.

That said, in practice It seems people wear many hats. I'm a defacto scrum master on my team but I'm still involved with the actual product delivery.

Also worth noting The basic scrum master certification is a minimal effort affair, a short training course/series of workshops and on online 'exam'. So it may be worth doing just for an understanding of the framework itself.


问:
How to Avoid Fragile Unit Tests?
We have written close to 3,000 tests -- data has been hard coded, very little reuse of code. This methodology has began to bite us. As the system changes we find ourselves spending more time fixing broken tests. We have unit, integration and functional tests.

What I'm looking for is a definitive way to write manageable and maintainable tests.

Frameworks

FakeItEasy

nUnit

AutoFixture

答:
You should definitely have a look at Gerard Meszaros's XUnit test patterns. It has a great section with many recipes to reuse your test code and avoid duplication.

If your tests are brittle, it could also be that you don't resort enough to test doubles. Especially, if you recreate whole graphs of objects at the beginning of each unit test, the Arrange sections in your tests might become oversized and you might often find yourself in situations where you have to rewrite the Arrange sections in a considerable number of tests just because one of your most commonly used classes has changed. Mocks and stubs can help you here by cutting down on the number of objects you have to rehydrate to have a relevant test context.

Taking the unimportant details out of your test setups via mocks and stubs and applying test patterns to reuse code should reduce their fragility significantly.

OwnerDisplayName: Chuck Conway

ContentLicense: CC BY-SA 4.0

Title: How to Avoid Fragile Unit Tests?


问:
Applications Architecture - fewer big systems vs more smaller systems
re: Applications Architecture, that is, "the science and art of ensuring the suite of applications being used by an organization to create the composite application is scalable, reliable, available and manageable."

When looking at a range of applications in an organisation, I can see various reasons for merging apps together, but sometimes also good reasons for keeping them separate.

In general, what are the pros and cons of having fewer big systems versus more smaller systems (bearing in mind that many of the systems will exchange information).

I'm thinking things like: fewer, bigger apps means less plumbing between apps, but more smaller apps means more flexibility for individual departments.

Is there any literature on this, or has anyone got a list of pros and cons that they've discovered?

edit: In my scenario, a lot of the apps might be customisable off-the-shelf ones rather than in-house developed, but feel free to consider more general scenarios.

答:
Just off the top of my head

Smaller Systems

Pro - Scale up on commodity hardware, or cheaper virtualized environments.

Pro - Can implement on demand scaling in a Cloud.

Pro - Fewer intra-system dependencies, ie. 1 service per server.

Pro - HA/DR (High Availability/Disaster Recovery) is typically easier to implement

Con - Has to be horizontally scalable

Con - The more systems, the more interconnects the more complicated management is

Larger Systems

Pro - Fewer interconnects which usually mean it's less complicated

Pro - Responds faster to high peak usage if it's within the tolerance.

Pro - Fewer resources to manage

Pro - More efficient resource usage (assuming relatively constant usage)

Con - More complicated intra-system dependencies, ie. N services per server

Con - HA/DR is typically harder/more complicated


问:
Is OOP hard because it is not natural?
One can often hear that OOP naturally corresponds to the way people think about the world. But I would strongly disagree with this statement: We (or at least I) conceptualize the world in terms of relationships between things we encounter, but the focus of OOP is designing individual classes and their hierarchies.

Note that, in everyday life, relationships and actions exist mostly between objects that would have been instances of unrelated classes in OOP. Examples of such relationships are: "my screen is on top of the table"; "I (a human being) am sitting on a chair"; "a car is on the road"; "I am typing on the keyboard"; "the coffee machine boils water", "the text is shown in the terminal window."

We think in terms of bivalent (sometimes trivalent, as, for example in, "I gave you flowers") verbs where the verb is the action (relation) that operates on two objects to produce some result/action. The focus is on action, and the two (or three) [grammatical] objects have equal importance.

Contrast that with OOP where you first have to find one object (noun) and tell it to perform some action on another object. The way of thinking is shifted from actions/verbs operating on nouns to nouns operating on nouns -- it is as if everything is being said in passive or reflexive voice, e.g., "the text is being shown by the terminal window". Or maybe "the text draws itself on the terminal window".

Not only is the focus shifted to nouns, but one of the nouns (let's call it grammatical subject) is given higher "importance" than the other (grammatical object). Thus one must decide whether one will say terminalWindow.show(someText) or someText.show(terminalWindow). But why burden people with such trivial decisions with no operational consequences when one really means show(terminalWindow, someText)? [Consequences are operationally insignificant -- in both cases the text is shown on the terminal window -- but can be very serious in the design of class hierarchies and a "wrong" choice can lead to convoluted and hard to maintain code.]

I would therefore argue that the mainstream way of doing OOP (class-based, single-dispatch) is hard because it IS UNNATURAL and does not correspond to how humans think about the world. Generic methods from CLOS are closer to my way of thinking, but, alas, this is not widespread approach.

Given these problems, how/why did it happen that the currently mainstream way of doing OOP became so popular? And what, if anything, can be done to dethrone it?

答:
EDITED

First of all I would like to say that I never found OOP hard, or harder than other programming paradigms. Programming is inherently hard because it tries to solve problems from the real world and the real world is extremely complex. On the other hand, when I read this question I asked myself: Is OOP "more natural" than other paradigms? And therefore more effective?

I once found an article (I wish I could find it again so I could post it as a reference) about a comparative study between imperative programming (IP) and object-oriented programming (OOP). They had basically measured the productivity of professional programmers using IP and OOP in different projects, and the result was that they had not seen big differences. So, the claim was that there was no big difference in productivity between the two groups, and that what really counts is experience.

On the other hand, proponents of object-orientation claim that, while during the early development of a system OOP may even take more time than imperative, in the long run the code is easier to maintain and extend due to the tight integration between data and operations.

I have worked mainly with OOP languages (C++, Java) but I often have the feeling that I could be as productive using Pascal or Ada even though I never tried them out for large projects.

Contrast that with OOP where you first have to find one object (noun)
  and tell it to perform some action on another object.

[cut]

I would therefore argue that the mainstream way of doing OOP
  (class-based, single-dispatch) is hard because it IS UNNATURAL and
  does not correspond to how humans think about the world. Generic
  methods from CLOS are closer to my way of thinking, but, alas, this is
  not widespread approach.

When I read this last paragraph more carefully I finally understood the main point of your question and I had to rewrite my answer from scratch. :-)

I know of other OO proposals where multiple objects receive a message instead of only one, i.e. several objects play a symmetric role when receiving a message. YES, this seems a more general and maybe more natural (less restrictive) OOP approach to me.

On the other hand, "multiple dispatch" can be easily simulated using "single dispatch" and "single dispatch" is easier to implement. Maybe this is one reason why "multiple dispatch" hasn't become mainstream.

Title: Is OOP hard because it is not natural?


答: OOP is not hard. What makes it difficult to use well is a shallow understanding of what it's good for, where programmers hear random maxims, and repeat them to themselves under their breath in order to receive the blessings of the divine Gang of Four, the blessed Martin Fowler, or whoever else they've been reading.</p>

Title: Is OOP hard because it is not natural?

Body:
One can often hear that OOP naturally corresponds to the way people think about the world. But I would strongly disagree with this statement: We (or at least I) conceptualize the world in terms of relationships between things we encounter, but the focus of OOP is designing individual classes and their hierarchies.

Note that, in everyday life, relationships and actions exist mostly between objects that would have been instances of unrelated classes in OOP. Examples of such relationships are: "my screen is on top of the table"; "I (a human being) am sitting on a chair"; "a car is on the road"; "I am typing on the keyboard"; "the coffee machine boils water", "the text is shown in the terminal window."

We think in terms of bivalent (sometimes trivalent, as, for example in, "I gave you flowers") verbs where the verb is the action (relation) that operates on two objects to produce some result/action. The focus is on action, and the two (or three) [grammatical] objects have equal importance.

Contrast that with OOP where you first have to find one object (noun) and tell it to perform some action on another object. The way of thinking is shifted from actions/verbs operating on nouns to nouns operating on nouns -- it is as if everything is being said in passive or reflexive voice, e.g., "the text is being shown by the terminal window". Or maybe "the text draws itself on the terminal window".

Not only is the focus shifted to nouns, but one of the nouns (let's call it grammatical subject) is given higher "importance" than the other (grammatical object). Thus one must decide whether one will say terminalWindow.show(someText) or someText.show(terminalWindow). But why burden people with such trivial decisions with no operational consequences when one really means show(terminalWindow, someText)? [Consequences are operationally insignificant -- in both cases the text is shown on the terminal window -- but can be very serious in the design of class hierarchies and a "wrong" choice can lead to convoluted and hard to maintain code.]

I would therefore argue that the mainstream way of doing OOP (class-based, single-dispatch) is hard because it IS UNNATURAL and does not correspond to how humans think about the world. Generic methods from CLOS are closer to my way of thinking, but, alas, this is not widespread approach.

Given these problems, how/why did it happen that the currently mainstream way of doing OOP became so popular? And what, if anything, can be done to dethrone it?


答:
In a larger system, it is much easier to:

Share features and code. You will reinvent the wheel a little less. For example, if you have ten applications which must have an access to the database, you have to specify the connection string in all of them, i.e. ten times. Or you have to create a separate library and reference it ten times again.

Consolidate workflows, including the deployment process.

Manage the system: less applications to manage is generally easier.

Unify the user experience. When an employee has to deal with ten different applications, he may easily be lost: what application to run to do A? In what application is available the option B? But don't overunify. No one will appreciate Word, PowerPoint, Outlook, Publisher, Visio, Project and Groove as a single monolithic application.

In a bunch of small systems, on the other hand, you'll find that:

You can abandon a whole system if you don't need it any longer. Or start from scratch if the codebase becomes unusable over time. This is of course only true if other systems do not rely on this one, or if the interface is light enough to be easily rewritten in a new version.

You can form a team of fresh developers and expect from them to understand the existent codebase in less time. If it's a part of a large project, chances are they will require more time, unless the overall large codebase is done extremely professionally and refactored very well (I haven't seen such codebases in my life).

The system administrators will be able to relocate the applications easier. The larger system, on the other hand, either scale well on multiple servers, or not.

The developers can migrate the codebase to new standards easier. Migrating a large codebase is always scaring. Instead, when you have to deal with a small codebase, then another, then another, and so on, it becomes less scary.

This being said, such comparisons work only in general cases, but your decision must be taken not from pools, but from your company assets. How is it organized? Are there many small developer teams or a few large ones? Are there strict guidelines about coding style and similar things?

It also depends on the application itself. For example, it would be absurd to ship all Microsoft Office applications as a single app. But it would also hurt productivity to, for example, separate Adobe Photoshop in an application for drawing and another one for photos retouching. IMO, the decision to unify or separate a product must be a business decision, not a purely technical one.

Finally, I also want to answer to the second comment of the original question:

I'm kindof assuming that linking data within an app is less effort than linking data between apps

It is not always true. If you're dealing for example with .NET, it is not unusual to ship a single application where different components are exchanging through WCF. In this case, this is comparable to a set of separate applications communicating through WCF.

Of course, when you have to deal with multiple applications, you have to establish some way for them to communicate, whereas having a single monolithic application does not force you to do that. But would you really be able to write a large monolithic application?

Title: Applications Architecture - fewer big systems vs more smaller systems

Body:
re: Applications Architecture, that is, "the science and art of ensuring the suite of applications being used by an organization to create the composite application is scalable, reliable, available and manageable."

When looking at a range of applications in an organisation, I can see various reasons for merging apps together, but sometimes also good reasons for keeping them separate.

In general, what are the pros and cons of having fewer big systems versus more smaller systems (bearing in mind that many of the systems will exchange information).

I'm thinking things like: fewer, bigger apps means less plumbing between apps, but more smaller apps means more flexibility for individual departments.

Is there any literature on this, or has anyone got a list of pros and cons that they've discovered?

edit: In my scenario, a lot of the apps might be customisable off-the-shelf ones rather than in-house developed, but feel free to consider more general scenarios.


问:
How can I organize my implementation notes to use as a future reference?
How should I document my designing of the app better so that I avoid programming by coincidence? How can I structure notes so that it is clear how an app works so that when I refer to it a year later I'm not lost for the first 3 days?</p>

答: If you're not good at note taking (and it sounds like you're not) then I would try prototyping. Sketch out a rough plan then spend a couple of hours to see if it's a good idea. You can then use the prototype as a plan of how your production should work. (do a rewrite)</p>


答:
Applications consist of at least two major sets of requirements:  Business and Technical.  Business Requirements come first and should describe what the application needs to do and the business goals it will solve.  Having a good set of Business Requirements often requires not only understanding what the user asks for, but also what the user really wants.  I mean, a non-technical person often cannot express bus. req's clearly and fully without the help of a qualified BA (one that understands the particular Business at hand).

Assuming you are a qualified BA and you have a complete set of Bus. Req's.  Then you need to drawup a plan to build the product, technical requirements.  There are many paradigms and approaches to managing a project.  You should pick one that works for you and the team, say Agile.

I recommend drawing out the Entities required to solve the Business Requirements.  Then, take a divide and conquer approach to implementation.  Red-Green refactor works quite well for division of labor.

For example, an Employee is an Entity in your product.  The Employee needs CRUD operations.  Create an CRUD interface, and a unit test for each of the 4 CRUD elements.  The unit tests all fail at the start.  Then, delegate a programmer to implement the CRUD operations of the Employee entity until they all pass.

Rinse and repeat.  Assuming you have properly identified all entities, this will bring you well into the last phases of back-end development.  Add helper classes and a common library, keep unit tests updated and over time the products will improve and development will be faster.

Finally, decouple front end work from backend by using Inversion of Control. Do up your CSS and all that jazz with mock data until complete.  Then, plugin the backend.

That's how I like to do things at least.  Keep in mind, there are no "right ways to build a bridge" in software.  Each team is unique.  Each project is unique.  Paradigms and standards are guidelines set by developers who solved particular problems in a particular way and said solutions stood the test of time.

Good luck.

Title: How can I organize my implementation notes to use as a future reference?

Body: How should I document my designing of the app better so that I avoid programming by coincidence? How can I structure notes so that it is clear how an app works so that when I refer to it a year later I'm not lost for the first 3 days?</p>


答:
Separate the Analysis from the Design.  Don't let architectural issues intrude on the requirements.  Take your notes from an outsider's perspective, what will they see and where does that data come from?

You should spend more time on your notes, not less.  You can't create the architecture to fit partial notes, that's like designing clothes for a mannequin missing both legs and an arm, sure it's fast but (as you've noticed) it's hardly functional ;-)

Read up a little on UML, even if you don't use it to sketch out your app the methodologies that use UML will provide you with inspiration.


答:
Bear in mind that my answer reflects my strengths and weaknesses, which may not be yours.

I divide programming into three parts 1) syntax (defining variables, read-write operations, etc.), 2) computations, and 3) logic.

My big weakness is in the math/computation part, so I try to get help on that from others. Specifically, I will try to get the user, typically an engineer, to write out all the relevant equations and computational formulas for me. Absent such help, I may consult a textbook, or use a programming library.

My strength is in languages, so I tackle the syntactical issues on my own: variable definition, formatting, layout, etc. This is much easier, if I've followed step 1 and had the engineer define the problem for me.

The last area is logic: branching, loops, links, test conditions etc. This is my area of intermediate difficulty, which is why I tackle it last.

This advice may not work for you in its exact form. But the idea is to identify your strengths and weaknesses, and get any help you need in the latter area.


问:
What non-programming books should a programmer read to help develop programming/thinking skills?
There are a lot of questions about what programming books should be on the programmer's bookshelf. How about non-programming related books that can help you become a better programmer or developer? It would also be interesting to know why they would help.

My first choice would be Sun Tzu's "Art of War" (however cliché), because it made it obvious that the success of any project depends on the strength of its weakest link (and warfare is a big project).

答:
Gödel, Escher, Bach: An Eternal Golden Braid by Douglas Hofstadter.

If you haven't read this, put it on your list. It's still breathtaking over 30 years later. While I am a Strange Loop contains a more complete and convincing argument about where consciousness comes from, GEB explores the realms of symmetry, intelligence and logic systems through the music of Bach, the mathematics of Gödel and the art of Escher. It's as infuriating and entertaining as it sounds.


问:
What did Linus Torvalds mean by his quotation about portability?
In a debate with Andrew Tanenbaum over microkernel vs. monolithic operating system architecture, Linus Torvalds said,

Portability is for people who cannot write new programs.

What did he mean by that?

答:
I think it means that each program should be written specifically for the hardware and operating system it runs on.

I think what he's driving as is that general purpose code that can run on several platforms is less efficient or more error prone than code written specifically for and tailored to one platform. It does, however, mean that when you develop like this you have to maintain several different code lines.


答:
Read this.  It's the "many small programs" philosophy of Unix.  Linux uses it, also.  The immense endurance of this philosophy (from the late 1960's to today) suggests that it's the right thing to do.

http://en.wikipedia.org/wiki/Unix_philosophy#Eric_Raymond

http://en.wikipedia.org/wiki/Unix_philosophy#Mike_Gancarz:_The_UNIX_Philosophy

http://159.93.17.14/usoft/WWW/LJ/Articles/unixtenets.html

http://www.linuxjournal.com/article/2877


答:
As Linus writes in the debate, it's with tongue in cheek (i.e. not to be taken too seriously).

Then, he goes on to explain that while portability is good thing, it's also a trade-off; unportable code can be much simpler. That is, instead of making the code perfectly portable, just make it simple and portable enough ("adhere to a portable API"), and then if it needs to be ported, rewrite it as needed. Making code perfectly portable can also seen as a form of premature optimization - often more harm than good.

Of course that's not possible if you can't write new programs and have to stick with the original one :)

Title: What did Linus Torvalds mean by his quotation about portability?

Body:
In a debate with Andrew Tanenbaum over microkernel vs. monolithic operating system architecture, Linus Torvalds said,

Portability is for people who cannot write new programs.

What did he mean by that?


答:
I make notes but they're not very useful, how should I organize my notes[...]?

You need a bug tracker.

If you want to start a project, report it's Elevator Pitch as a bug! Attach each important feature to support that goal as another bug.

If you've got written notes, either ideas you've brainstormed, or minutes you've taken from a meeting with a customer, those need to make it into the bug tracker as soon as possible.

The value of organizing your project plan in this way is that you can easily search and organize each task according to how it relates to other items, how urgent it is, how much you've completed.  It also allows you to link the changes in the source code back to the factors that influenced them; this change fixes that bug or implements that feature.


问:
Difference between complexity and performance guarantee
I'm a bit confused with the performance guarantee and complexity of selection sort.

I checked through internet and the complexity of selection sort is O(n^2). This O(n^2) is in terms of time complexity, am i right?

So how about performance guarantee? Is the performance guarantee in my case measured in terms of swapping or in time complexity as well? If the performance guarantee is in terms of swapping, so best case of swapping is zero swaps (the array is already sorted) and the worst case of swapping is n-1 step? The performance guarantee is then equal to (n-1)/0=undefined, am I correct?

Please correct me if im wrong...or is the performance guarantee is in terms of running time? Then performance guarantee will be (n-1)/(n-1) = 1?

Can someone please clear my doubts?

答:
Sometimes there is a difference between the big O of the average time vs. the big O of the worst case.  For example, quicksort averages N*Log(N), but in theory you could get unlucky on the partition every time and end up with N**2.

In the case of selection sort both average and worst case are N**2, but it's still possible that "performance guarantee" was referring to the worst case performance.


问:
How do I move a client from UI mockups to a set of real requirements?
Say you are given a mock-up of 25 screens of the visual states of your application. The expectation is that this is enough for us to be confident we can develop and hand it to the original stakeholder or customer as a finished application, and they will be satisfied. Naturally, you're going to end up asking the stakeholders many questions over again that were used to come up with the UI, which is wasteful.

However, I have many many times found that this is very much not enough, in the course of developing the application the requirements become blurred by the fact that we are replicating an interface and in the end the customer is not as happy as they first seemed when we asked them for all the info to create the UI.

I am just not sure what else to ask for, I have tried to be specific and ask for requirements and an understanding of the overall goal, but I don't know what I should ask for. If I just start now, lots of time is going to be wasted re-hashing all the info that lead up to the UI and during this phase many important reasons the customer originally had will be lost.

How can I get people to understand that we cannot lock down requirements based on UI mock-ups by asking for something actionable they can create for me?

What would you ideally start with in order to properly execute the task of developing an application for end users?

答: Personally, I would ask for a half-day to day-long meeting with the client to walk through their UI design and their goals and make sure everything aligned.</p>


答:
Some other things you may need are:

Usecases or Workflow descriptions: Just because you know what a screen looks like, do you know how bad input is handled? Do you know how to transition between screens in ALL cases? You could include error handling here as well.

High-level system description: Something the explains what the whole system that these 25 screens are for, and what they do.

Data model: Is it possible to infer a data model from these screens? Is there a data model that must be used or are you free to design your own to get the job done?

Technical requirements: Are the specific technoligies that must be used because of licencing or for integration reasons?

Performance requirements: If there's a search screen, is there an expectation of what can be searched and how fast the response should be? What about responses for other types of actions? Can or should some of them be asynchronous (user submits job and comes back later)?

Security requirements: Does the application store potentially sensitive/personal data and if so, what kinds of data and what must be done to keep it secure? Do you need to meet some level of compliance (like PCI compliance for doing credit card payments)?

Also, is there any special business domain knowledge that you may need them to assist you on? Some industries such as insurance, banking, medical health records, etc... have all sorts of complex business logic. Such projects shouldn't be attempted without the help of a business analyst who knows that domain. But if it's just a shopping cart/info site for generic widgets, then you may not need such a team member.

Title: How do I move a client from UI mockups to a set of real requirements?

Body:
Say you are given a mock-up of 25 screens of the visual states of your application. The expectation is that this is enough for us to be confident we can develop and hand it to the original stakeholder or customer as a finished application, and they will be satisfied. Naturally, you're going to end up asking the stakeholders many questions over again that were used to come up with the UI, which is wasteful.

However, I have many many times found that this is very much not enough, in the course of developing the application the requirements become blurred by the fact that we are replicating an interface and in the end the customer is not as happy as they first seemed when we asked them for all the info to create the UI.

I am just not sure what else to ask for, I have tried to be specific and ask for requirements and an understanding of the overall goal, but I don't know what I should ask for. If I just start now, lots of time is going to be wasted re-hashing all the info that lead up to the UI and during this phase many important reasons the customer originally had will be lost.

How can I get people to understand that we cannot lock down requirements based on UI mock-ups by asking for something actionable they can create for me?

What would you ideally start with in order to properly execute the task of developing an application for end users?


问:
How can I handle chat messages asynchronously?
I'm working on a program where part of it will be working as a chat between different people. I'm trying to figure out the best way to send and receive messages.

A PrintWriter or something similar won't work because the process will stop at the read() method while waiting for a message to be sent to it. I'd like to check to see if there is a new message, and if not, continue the execution.

I've seen some stuff about JMS, but I haven't done enough research to determine if it's up for this job.

Is JMS the best option for this, or is there a better way?

答:
You'll want to read up on Java's networking I/O but if you can't use Java 7 then you might want to look into this question/answer

HTH


答: Start simple. Get them to understand that with the information you've been given, none of those screens would do anything. No details about use cases, bad input behaviour and so on. It just won't work. Explaining a blunt generalisation is easier than explaining details, because the point can't get lost. Trying to give them a more complicated justification for why screen mockups isn't enough gives them the opportunity to quibble your definitions instead of acknowledging the problem. Ask them to imagine that the back-end developer didn't speak English (or whatever language the screens are presented in). Then ask how different this situation is to a developer who has no knowledge at all of their business processes. Then build up to the more realistic example of yourselves, who have some knowledge, but are justified in believing that it isn't appropriate to decide their business logic for them.


答:
Well, this is an embarrassingly obvious starting reference, but Wikipedia might be a place for you and the users to start out.  The fact that there is an entry about this stuff might help convince them that this is a real issue, not you being a pain.

More specifically, are you just baffled about what the application does, even after going over the mock-ups?  If so, admit it, and try to explain that you have no idea what data each form should display, or where it would come from, is it from other screens or external data?

If you have some idea, try to come up with examples of things that you don't know how to do ("will the list of templates to select be one global list or are any of them by User, or something else?  If it's not by User should I let two people edit it at once?  What should the UI show if someone else is editing it?  Is there a screen for that?  Once someone has used a template for whatever templates are used for and then the template gets edited should that change be propagated to the thing they made with the template?").

Make it clear that with your present level of knowledge you will need to have questions answered approximately every 90 seconds for the remainder of the development cycle, and that much of the time you will be unable to keep working until you get an answer.  The goal should be to make it clear why having some kind of process will make it all easier.  Also mention that Q.A. is going to need the same information you do, so it will be easier to write it all down so it's available for everyone and nobody forgets anything.

It might help to mention that some of the code you write affects more than one screen at a time, so if you got as many answers up front as possible it might make it easier to write that code appropriately and not have to change it later.

If you still can't get requirements and you really don't know how to proceed, send out emails every time you need more information (i.e., requirements), and if you can't continue working without that information, state clearly that you are, unfortunately, unable to continue working, because the code you need to write will be very different depending on the answer(s) to your question(s).  Don't complain, just very professionally let them know that you can't write the program until you know what it should do.


问:
Java/C# - When should AOT be considered if reverse engineering is a concern?
Long and short is really in the question title.  For a language which compiles to an intermediate language like MSIL or Java byte-code, if there's concern about something like reverse engineering or hacking to disable security features, should AOT (ahead of time) compilation be considered rather than just obfuscation?  Obviously, there's a bit of wiggle room in this question as there's no one answer I wouldn't imagine, but when would you start looking at performing an AOT compilation before distributing something versus sending it out obfuscated?

For anyone that stumbles across this and isn't familiar:

Wikipedia Entry on AOT Compilers:  http://en.wikipedia.org/wiki/AOT_compiler

Mono AOT Compiler feature:  http://www.mono-project.com/AOT

答: It'll be a lot harder to maintain different versions. You should either use a language like C++ or if you're stuck with Java, you can use a custom class loader instead of just obfuscating. All code can be RE'd with time; I'd just trust the law to do your work for you and obfuscate.</p>


答:
How to get people to understand that UI mocks aren't enough to create a working program:

I would handle this with an analogy.  Since I'm a bit of a car nut, I'm going that route.

"Pretend I know nothing about cars.  You hand me a few photos of a Ferrari.  A couple from the outside and one from inside the car (taken from the driver seat so I can see the controls for the car).  Now you ask me to build you a Ferrari.  I come back with a thing that looks like the pictures and has all the controls.  Unfortunately, those controls aren't hooked up to anything because (since I know nothing about cars) I don't know what those controls should do.  I can't even make a guess because I don't even know what cars are supposed to do.  So then we have a conversation like this:

"So what does a Ferrari do?"
"It allows me to move myself from one point to another quickly."
"OK. so what does this circle thing do?"
"Oh, that's the steering wheel.  By turning it, you can change which way the wheels on the outside of the car point.  This will change which way the car moves."
"OK, and what about this pedal thing?"
"That's the gas pedal.  It makes the engine go faster which makes the car go faster."
... a few minutes later ...
"Ok, so what kind of engine does it need?  I've done some research and I've found engines for golf carts and some for sports cars.  Which should I use?"
... etc. ..."

Then you can explain the analogy.  Handing the developers mocks of screens only tells them what it looks like, not what it does.  Developers need to know what problem the program solves or how it will be used (like knowing what a car does makes it easier to design the car and take educated guesses about what things should do).  They need to know what kinds of things they are expected to use (ie. the golf cart engine vs. the sports car engine) and what other non-UI requirements there are (car should go fast).

Things I would ask for:

General / High level problem description

Use cases / user stories

Performance Requirements

Required technologies / platform (Windows, Linux, Web)

Everything FrustratedWithForms has in his answer


答:
One thing that people seem to forget to ask, is what is the data going to be used for after it is input? Do you need reports? Do you need to generate a packing slip and send to the warehouse for shipping, etc. If data is used to make managment decision and reporting is needed, then that can change the database design. It can also add a serious amount of time to development depending on the complexity of reports.

You also need to make sure there is a path for each possible decision. So if something requires managment approval - then what do you do if is disapproved as well as what do you do if it is approved. If it is not approved or disapproved  in X amount of time, then what happens to it? If they select a product and it is out of stock, what happens to the order? Those kinds of questions.

You also need to know if there are specific limits on what data should be put into each field. Are there required values. Where are you goign to get them from? How will they be updated? You need to know how to handle errors. You need to know if the database needs to have auditing or if you need to be able to recreate data from a historical perpective (back to those pesky reports).

Another thing I see happening is that applications may be designed just get to the release with no consideration of how the data will be maintained afterwards. Do you need an admin page to make sure that they can update their lists of required values? Do you need to send data back and forth to other systems. How are you going to get the initial data into the database?


问:
Website development from scratch v/s web framework
Do people develop websites from scratch when there are no particular requirements or they just pick up an existing web framework like Drupal, Joomla, WordPress, etc.

The requirements are almost similar in most cases; if personal, it will be a blog or image gallery; if corporate, it will be information pages that can be updated dynamically along with news section.

And similarly, there are other requirements which can be fulfilled by WordPress, Joomla or Drupal.

So, Is it advisable to develop a website from scratch and why ?

Update:

to explain more as got commentt from @Raynos (thanks for comment and helping me clearify the question), the question is about:

Should web sites be developed and designed fully from scratch?

Should they be done by using framework like Spring, Zend, CakePHP?

Should they be done using CMS like Joomla, WordPress, Drupal (people in east are using these as frameworks)?

答:
Build From Scratch

At my last job (3 years ago) we built every website (all 300+) from scratch. We owned the servers. We knew exactly what was happening to our servers. We were a small shop 6 people. Our customers did not want to look like they came from a template.

Today, I see a ton of BLOAT that is caused by these web toolkits. View the source on some of the newer websites and look how much JS code is being imported/called. If you rely on all these external libraries to pull off the "Web Magic" then you better know how to tweak or fix it if it doesn't perform as expected.

For example: A customer wants "Futura" font which is not readily available on all machines. So, instead of telling the customer that "Futura" is a poor choice for a website font, you find a JavaScript library that embeds the font directly into the page. After the page loads then "Poof" the font changes from Times New Roman to the embedded "Futura" just like magic. If you can't fully support it don't use it.

We didn't build every thing from scratch. When ever a customer asked for a new widget  would often ask ourselves... "Is this a Build or Buy" widget. If we could interface the widget into our existing code without too much trouble we'd buy it. We rarely bought widgets that we couldn't brand to be our own. We never bought widgets that did not include source code.

If you only build websites as a hobby or just do 2-3 a year then perhaps it's not worth it for you to build it from scratch... just be careful where you get code from. Ultimately it's your reputation.


答:
You need to know the limits and ranges for each field in the application. For example, if the field is phone number, do they expect you to handle +1? Which fields are required? What do they want the application to do if the user types "abc" in the phone # field? Are all 25 screens in the order that all users must proceed?

Otherwise, just create everything as text fields and you are done! Wanna bet that will go over like a lead balloon?


答:
Something to the effect of 80% of development effort goes towards 20% of fringe use cases.  Screenshots will not tell you about use cases thus you will be in the dark for 80% of your active development.

It is good that you are trying to figure out more and trying to communicate how important it is for the client to be more involved in the project requirements, however if they don't do this then they are setting up the project for failure, and that isn't your fault.

The majority of software projects fail because the client is not involved enough in the software development process.  This isn't a new problem and it certainly isn't a mystery to why software projects fail but it continually happens over and over in the industry because of situations like this.

You can't just toss a trickle of information over a wall and expect to get back all of your hopes and dreams in the form of a software package.  Software development just doesn't work this way.  Whether you are an Agile or Waterfall shop, solid client direction is necessary to the success or failure of a project.


问:
Why should you prevent a search engine from indexing your development server?
I've heard that you shouldn't let search engines index your development server.  The reasons given were:

Duplicate content penalties

Customers making purchases from an unsecured domain (if eCommerce)

These issues may seem relatively minor and I'm not sure it would be enough to convince someone to put in the effort to lock down the server.  Aren't there broader security concerns?  What should be secured and why?

答:
The most glaring and obvious problem with this is the fact that your development server is even publicly accessible.

Search engine penalties and other related issues aside, there are a plethora of problems with having your dev server unsecured.

While there's nothing wrong with having your dev server on the Internet, it should at the very least be password-protected so as to prevent unauthorized access of what may be insecure and and otherwise immature code.

Password-protecting Apache can be accomplished through use of .htpasswd. For IIS you modify the Authentication and Access Control settings.


答:
People who haven't developed software don't know what software developers need to know. They can't be expected to produce requirements specifications and use cases on their own. You need to apply requirements elicitation techniques to get the information that you need to know. Work with the client (and hopefully a sample of users from various roles) to determine what they need or want. Common techniques for this are interviews and/or user observation, identifying use cases and user stories, and prototyping.

I would highly recommend applying iterative and incremental development techniques in this instance, since you have vague, incomplete, or poorly understood requirements. Look at the various agile methodologies along with the Spiral Model for addressing lifecycle planning.

Start by obtaining the business objective driving the development of this software. Interview the client and users, and if you can, watch them at work. Try to determine what problem they are trying to solve. See what tools they are currently using and how they use them so that you can improve on their current way of doing things. Use this opportunity to learn the domain and its language - it will become infinitely easier to communicate if the software developers and client/users all speak the same language (and don't expect the client/users to speak in software terms).

Once you understand what the objectives are, you can begin to work with the UI design mockups that you have and "reverse engineer" use cases and user stories from them based on how various screens fit together. The user story format would probably work out well to deal with a non-technical audience. The format of As a <user type>, I want to <action> so that <reason> works out in terms of getting developers and clients/users speaking the same language. Once you can get a start on the user stories, I would adopt a prototyping approach to development.

I think that I would approach this with the use of prototyping. You could approach this from either an evolutionary prototyping or throwaway prototyping perspective, but I would consider an evolutionary prototyping approach first. Start with the user stories that you are most comfortable with and have validated, and begin to implement them. As you implement them, get feedback from the customer and develop new user stories, use cases, and resolve misunderstandings.

Also, don't think about this as "implementing a user interface with features under it". Instead, think of it as thin vertical slices. Don't implement all of the user interface at once and then worry about features. Instead, use the user interface mockups to identify features and other requirements, and then implement a vertical slice from the UI down to the business logic and data storage. Repeat this for every vertical slice. You should also feel free to make suggestions to improve the UI based on the requirements and usability principles.

I would recommend reading two books by Karl Wiegers - Software Requirements and More About Software Requirements. I think these will help you out with requirements engineering and best practices in this area.


答: What about having information enter the public domain that may not be intended?  Some companies may want to protect who can see upcoming products and services which could be an issue if the development site can be found on Google.  The other thought is that the dummy content on the page may harm a company's brand as "Lorem ipsem" content isn't usually considered professional.  TheDailyWTF will have posts of such content that I'm not sure if companies would want their name associated with such stuff.  Security issues can also be a bit of a problem as development environments may not always be as locked down as production so passwords may be easier to crack.</p>

Title: Why should you prevent a search engine from indexing your development server?

Body:
I've heard that you shouldn't let search engines index your development server.  The reasons given were:

Duplicate content penalties

Customers making purchases from an unsecured domain (if eCommerce)

These issues may seem relatively minor and I'm not sure it would be enough to convince someone to put in the effort to lock down the server.  Aren't there broader security concerns?  What should be secured and why?


问:
What is a manifest and when is it appropriate to use one?
I hear the usage of manifests in various ways but never have had the need—to my knowledge—to use one. What are they and how are they used?

EDIT: I'm curious about manifests in general with any language.

答:
A manifest is a blob of metadata that describes the assembly itself (name, version, required external assemblies, etc.).

An assembly must contain an associated manifest (also referred to as assembly metadata). The manifest documents each module within the assembly, establishes the version of the assembly, and also documents any external assemblies referenced by the current assembly


答: If your project is a web project (like gwt or jsf), you can use reverse ajax to receive the messages in client side. </p>

Title: How can I handle chat messages asynchronously?

Body:
I'm working on a program where part of it will be working as a chat between different people. I'm trying to figure out the best way to send and receive messages.

A PrintWriter or something similar won't work because the process will stop at the read() method while waiting for a message to be sent to it. I'd like to check to see if there is a new message, and if not, continue the execution.

I've seen some stuff about JMS, but I haven't done enough research to determine if it's up for this job.

Is JMS the best option for this, or is there a better way?


问:
What naming conventions do you use for php classes?
I really like using ClassNames and memberNames as convention but I am not sure how I would name the file containing a class.

I like making my classes defined in a file with the exact same name as the class. But I also like making php files all lowercase. So I am conflicted.

If I have a class called ProductGroup should that be defined in ProductGroup.php, productgroup.php, or product_group.php?

I know there is no right answer, so I am looking for what is most common or your opinion of which to use.. which do you use?

答:
I have class files that span applications ("libraries"), and class files specific to applications. The libraries get a prefix to minimize the potential for conflicts with any third-party code we might include, ie. at "My Sweet Company" we might use the class name "MSCPerson" rather than "Person."

We use CamelCase class names, and class files are named CamelCase.class.php. Most class files have the single class and any class-specific exceptions, but this rule is not set in stone. It's nice to have single-class files for vim's gf feature.


答:
The manifest is a special file that can contain information about the
  files packaged in a JAR file. By tailoring this "meta" information
  that the manifest contains, you enable the JAR file to serve a variety
  of purposes.

http://download.oracle.com/javase/tutorial/deployment/jar/manifestindex.html

Title: What is a manifest and when is it appropriate to use one?

Body:
I hear the usage of manifests in various ways but never have had the need—to my knowledge—to use one. What are they and how are they used?

EDIT: I'm curious about manifests in general with any language.


问:
Combining getters and setters
JavaScript libraries such as jQuery, combine 'getters' and 'setters' in the programming interface for example:

```<code> $('element').css({'color','blue'});
</code>```

will set the color or

```<code> $('element').css();
</code>```

will get the css for an element.

Is there a name for such a pattern and is it a good practice to use in applications?

答: I think you're looking for properties

Title: Combining getters and setters

Body: I think you're looking for properties


答:
Martin Fowler recently named it Overloaded getter and setter in this article:

I've been poking around in Javascript recently and one thing that's struck me is the habit of using the same function name for a getter and a setter. So if you want to find out the height of your banner in jQuery you would use $("#banner").height() and if you want to change the height you would use $("#banner").height(100).

This convention is familiar to me, as it was used by Smalltalk. You might get a value with banner height and change it with banner height: 100. Knowing it was a smalltalk convention is enough to expect me to like it, since I have an distant but abiding love for that language. But even the best things have flaws, and I can't hide my dislike for this coding style...

Despite this preference, you do have to follow the conventions of the language you're dealing with. If I were writing Smalltalk again I'd still use height:100 in order retain consistency with the conventions of the language. Javascript, however, isn't noted for having strong conventions, so here I'd prefer to avoid this convention, even if it is used by jQuery...

Title: Combining getters and setters

Body:
JavaScript libraries such as jQuery, combine 'getters' and 'setters' in the programming interface for example:

```<code> $('element').css({'color','blue'});
</code>```

will set the color or

```<code> $('element').css();
</code>```

will get the css for an element.

Is there a name for such a pattern and is it a good practice to use in applications?


问:
Do you know of any encryption techniques used to validate url redirection
I'm adding a click-tracking feature on my website to track click-thrus for my advertisers.

So, on my site, instead of having a direct link, I link to my re-direct page passing the destination url as an argument. This re-direct page then tracks the click thru and then 301 re-directs the user to the correct external url.

I want to prevent 3rd partys from harnessing this system to make it re-direct to arbitrary urls.

I'd like the code that creates the links to:

Create special token using ( destination url + secret )

Then, pass the destination url + special token arguments as query string parameters to my re-direct page in public.

Upon receiving the arguments the re-direct page will do a check:

Given ( destination url + special token + secret ), destination url is either:

good - re-direct it to destination

bad  - do not re-direct it to destination

and it should not be possible for Doctor Evil to:

Create secret using ( known valid destination url + its special token )

Ideally the re-direct page would not have to do any url-specific look-ups on data to validate the parameters - it should just be able to tell from 'the two params given + the secret + the known algorithm'.

I'm not very knowledgeable about encryption so was wondering what kind of method one would use to create and validate the parameters given the shared secret.

I'm sure this is a common technique but I have no idea what its called - thus its difficult to learn more about it.

Any help is appreciated.

答:
The obvious way would be to use a Message Authentication Code (MAC -- a heavily overloaded TLA if ever there was one). A MAC is basically a keyed hash algorithm. You keep the key private, and when you add a URL to your system, you give the owner of that URL the hash of their URL using your key. They pass the authentication back along with the URL. When you get it, you re-hash the URL using your key, and verify that it matches what they passed. If it doesn't match, you reject it.

If you don't have code for a MAC easily available, one easy way to produce one from typical primitives is to do an unkeyed hash (e.g. SHA-256) then encrypt the result of that with a normal encryption algorithm (e.g., AES).

You may want to preprocess the URL to allow some minor variations. Just for example, in a typical case where capitalization doesn't matter, you don't want to start rejecting a URL just because somebody changed something like "MyUrl" to "MyURL". As such, you may want (for one possibility) to convert the entire URL to lower case first.


问:
Command handlers and DDD
I have an ASP.NET MVC application, that uses a query service to get data and a command service to send commands. My question is about the command part.

If a request comes in, the command service uses a command dispatcher that will route the command to its designated command handler. This command handler validates the comand first and if everything is acceptable, it executes the command.

Concrete example: the AddCommentToArticleCommandHandler receives an AddCommentToArticleCommand, which has an ArticleId, CommentText and EmailAddress.

First; validation has to occur, like:
- check if article exists
- check if article is not closed
- check if comment text is filled in and between 20 and 500 characters
- check if email address is filled in and has a valid format.

I'm wondering where to put this validation?

1/ in the command handler itself. But then, it cannot be reused in other command handlers.

2/ in the domain entity. But as a domain entity doesn't know about repositories or services, it cannot do the needed validation (cannot check whether an article exists). But on the other hand, if the entity doesn't contain logic, than it becomes a simple data container, which is not following DDD principles.

3/ the command handler uses validators, so that validation can be reused in other command handlers.

4/ Other mechanisms?

I'm looking for the chain of responsibilities for this particular example and what objects (entities, repositories, ...) play a role in it.

Do you have ideas on how you would implement this, starting from the command handler up to the repositories?

答:
I think you need to separate two types of validation in this case; domain validation and application validation.

Application validation is what you have when you verify that the command property 'text' is between 20 and 200 characters; so you validate this with the GUI and with a view-model-validator that also executes at the server after a POST. The same goes for e-mail (btw, I hope you realize that an e-mail such as `32.d+"Hello World .42"@mindomän.local" is a valid according to the RFC).

Then you have another validation; check that article exists - you have to ask yourself the question why the article should not exist if there is indeed a command sent from the GUI that is about attaching a comment to it. Was your GUI eventually consistent and you have an aggregate root, the article, that can be physically deleted from the data store? In that case you just move the command to the error queue because the command handler fails to load the aggregate root.

In the above case, you would have infrastructure that handles poison messages - they would for example retry the message 1-5 times and then move it to a poision queue where you could manually inspect the collection of messages and re-dispatch those relevant. It's a good thing to monitor.

So now we've discussed:

Application validation

With javascript in the GUI

With MVC-validation at the web server

Missing aggregate root + poison queues

What about commands that are out of sync with the domain? Perhaps you have a rule in your domain logic saying that after 5 comments to an article, only comments below 400 characters are allowed, but one guy was too late with the 5th comment and got to be the 6th - GUI didn't catch it because it was not consistent with the domain at the point of him sending his command - in this case you have a 'validation failure' as a part of your domain logic and you would return the corresponding failure event.

The event could be in the form of a message onto a message broker or your custom dispatcher. The web server, if the application is monolithic, could synchronously listen for both a success event and the failure event mentioned and display the appropriate view/partial.

Often you have custom event that means failure for many types of commands, and it is this event that you subscribe to from the web server's perspective.

In the system that we are working on, we're doing request-response with commands/events over a MassTransit+RabbitMQ message bus+broker and we have an event in this particular domain (modelling a workflow in part) that is named InvalidStateTransitionError. Most commands that try to move along an edge in the state graph may cause this event to happen. In our case, we're modelling the GUI after an eventually consistent paradigm, and so we send the user to a 'command accepted' page and thereafter let the web server's views update passively through event subscriptions. It should be mentioned that we are also doing event-sourcing in the aggregate roots (and will be doing for sagas as well).

So you see, a lot of the validation you are talking about are actually application-type validations, not actual domain logic. There's no problem in having a simple domain model if your domain is simple but you are doing DDD. As you continue modelling your domain, however, you'll discover that the domain might not be as simple as it first turned out. In many cases the aggregate root/entity might just accept a method invocation caused by a command and change some of its state without even performing any validation - especially if you trust your commands like you'd do if you validate them in the web server that you control.

I can recommand watching the two presentations on DDD from Norwegian Developer Conference 2011 and also Greg's presentation at Öredev 2010.

Cheers,
Henke

Title: Command handlers and DDD


答:
Since JavaScript doesn't have actual properties (where setting a value can actually execute code), the patter is one that implements the property idiom.  (Even if you call it something else.)

So, in languages implementing real properties, you would do this instead:

```<code>element.css = ...
x = element.css
</code>```

If you were to use the JavaScript pattern in a language that handles properties, you would be doing something abnormal.  That would likely not be a good idea.  Handle properties the way the language is meant to handle them, so you don't confuse the other people working with you.

Title: Combining getters and setters

Body:
Since JavaScript doesn't have actual properties (where setting a value can actually execute code), the patter is one that implements the property idiom.  (Even if you call it something else.)

So, in languages implementing real properties, you would do this instead:

element.css = ...
x = element.css

If you were to use the JavaScript pattern in a language that handles properties, you would be doing something abnormal.  That would likely not be a good idea.  Handle properties the way the language is meant to handle them, so you don't confuse the other people working with you.


问:
Best practices for generating new identifiers for persistent objects?
In a typical scenario, an object that needs to be persisted in the database will be created in application code without an identifier, and later saved to a table in the database.  Some database construct, such as an identity column, will generate a new identifier, typically an integer that's unique for all of the rows of that table.  This identifier can then be returned to application code and then treated as a key.

```<code>CREATE TABLE Users (
    UserId int IDENTITY(1,1) NOT NULL, DisplayName nvarchar(max),
    UserName nvarchar(50), [Password] nvarchar(50))
GO

INSERT INTO Users (DisplayName, UserName, [Password])
    VALUES ('Joe Shmo', 'jshmo', 'pw1')
SELECT @@IDENTITY
</code>```

Another common scenario is for the identifier to be GUID:

```<code>CREATE TABLE Users (
    UserId uniqueidentifier NOT NULL, DisplayName nvarchar(max),
    UserName nvarchar(50), [Password] nvarchar(50))
GO

DECLARE @id uniqueidentifier = NEWID()
INSERT INTO Users (UserId, DisplayName, UserName, [Password])
    VALUES (@id, 'Joe Shmo', 'jshmo', 'pw1')
SELECT @id
</code>```

This second way provides the following advantage: the GUID can be generated in application code, which can then be used as a key for application caching/referencing purposes before the object is ever saved.  However, there is a cost associated with using GUIDs in size and, especially look-up costs.  These may be trivial when the table is small, but can become a major factor when the table is massive.

Are there any best practices, or techniques for the cases where an identifier unique to the object type needs to be generated in application code, but cannot be a GUID for whatever reason?

One thought was to have a another table generating identifier wrapped by an identifier service which application code could call.

答:
both approaches are valid

if only one database server generates the keys, a sequence ID is fine, and is (as you noted) somewhat more efficient (and a heck of a lot easier to read) than a GUID

if multiple servers generate the keys then go with a GUID

another option is to let the database generate a sequence key for internal relationships, and use a GUID as a unique secondary key

as usual, it depends on how you create and use the data


答:
It's called "method overloading" in OO languages or "function overloading" in non-OO languages.

Whether or not it's good practice is a topic of almost as much debate as getters/setters vs. public members.  Those on the pro and con sides probably cut their teeth on languages that had this feature or didn't and are set in their ways.  I use it and like the practice for a number of reasons:

The context in which it's used pretty well separates one from the other.

Prepending get or set to the method name adds verbosity.

If there are multiple getters (e.g., one for int and one for double), changing the type in the LHS of an assignment (int x = foo.bar() vs. double x = foo.bar()) doesn't require a code change (barAsInteger() vs. barAsDouble()) to the right side if the class provides both.  The down side to this is that sometime it can be difficult to know exactly which method is being called just by looking at the code.

Title: Combining getters and setters


答:
I know of a technique called Guid.Comb (see NHibernate) which has the advantages of a GUID but has a few tweaks to avoid database problems. The problem with GUIDs is that database indexes get fragmented due to their random nature. This is a severe problem, especially as GUIDs are often used as primary keys. But be aware that not every GUID algorithm suffers from that problem, as the database vendors are already aware of it. Not all GUIDs are inherently bad to look up.

What you basically do is creating an identifier that eliminates some of the randomness to get an ordering into the GUIDs. Look at this article here to get an idea of how it can be done.

I can see no reason for not using GUIDs if you won't run into space problems. For large data volumes this can be a very, very serious problem with huge impacts.

When you really can't have a GUID as PK, you can use a GUID as a secondary key, as Steven A. Lowe already stated.

Title: Best practices for generating new identifiers for persistent objects?

Body:
In a typical scenario, an object that needs to be persisted in the database will be created in application code without an identifier, and later saved to a table in the database.  Some database construct, such as an identity column, will generate a new identifier, typically an integer that's unique for all of the rows of that table.  This identifier can then be returned to application code and then treated as a key.

```<code>CREATE TABLE Users (
    UserId int IDENTITY(1,1) NOT NULL, DisplayName nvarchar(max),
    UserName nvarchar(50), [Password] nvarchar(50))
GO

INSERT INTO Users (DisplayName, UserName, [Password])
    VALUES ('Joe Shmo', 'jshmo', 'pw1')
SELECT @@IDENTITY
</code>```

Another common scenario is for the identifier to be GUID:

```<code>CREATE TABLE Users (
    UserId uniqueidentifier NOT NULL, DisplayName nvarchar(max),
    UserName nvarchar(50), [Password] nvarchar(50))
GO

DECLARE @id uniqueidentifier = NEWID()
INSERT INTO Users (UserId, DisplayName, UserName, [Password])
    VALUES (@id, 'Joe Shmo', 'jshmo', 'pw1')
SELECT @id
</code>```

This second way provides the following advantage: the GUID can be generated in application code, which can then be used as a key for application caching/referencing purposes before the object is ever saved.  However, there is a cost associated with using GUIDs in size and, especially look-up costs.  These may be trivial when the table is small, but can become a major factor when the table is massive.

Are there any best practices, or techniques for the cases where an identifier unique to the object type needs to be generated in application code, but cannot be a GUID for whatever reason?

One thought was to have a another table generating identifier wrapped by an identifier service which application code could call.


答:
Either one is OK depending on your requirements.  With an integer identity column there is value little maintenance that will need to be done with the column over time because the data on the index is sequential.  You can insert 1000s and 1000s of row and the index on the column will hardly fragment.

With a GUID, the index will fragment over time and periodic maintenance (rebuilding the index, etc.) will have to be done to maintain the index on the key column.  So, as long as you are aware of this, I beleive either are OK.

The integers take up less space but are easier to guess, guids take up more and are harder to guess.  As you said GUIDs can be generated in code, although SQL Server can do an identity column or  newID() column as well.  I also believe there is something called a sequential guid which helps in the fragmentation department.

If you ever had to merge two databases together, guids would be better as row IDs would probably collide between the two databases.


问:
How do I deal with the need to know multiple programming languages?
I am a relatively young programmer. I am 23 and I have been programming professionally for about 5 years.

As most programmers I started with C, learned some x86 assembly for fun and then I found C++ which turned out to be my greatest passion in the programming world. Programming with C and C++ forces you to learn platform specific APIs, libs and frameworks all of each requires constant study and experimentation.
After some time I had to move on to Java and C# as the demand on my region is basically for these languages. With these languages I entered the world of web development and then I had to learn javascript.
Developing for the .NET Framework was exciting at first but I constantly felt as I was getting tied up by Microsoft (and of course the .NET Framework was driving me away from Linux).
For desktop development I could do pretty much everything I did with .NET using C++ with Qt but for web development I had to look for an alternative. Quickly I found Django and then I proceeded to learn Python so I could use Django.
Nowadays I am learning iOS development with Objective-C.

So far it was pretty much easy to learn all these languages (C++ trained me well) but I am worried that someday I won't be able to keep track of them all.
Just to clarify. The only languages I learned cause I had to were C# and Java. All of the others I learned for fun, because I love programming and learning new things. Also I like to keep my skills sharp on desktop, web and mobile development.

My question is: How do you keep track of multiple programming languages? (I mean, keep track of changes to these languages and keep your skills sharp) and: Is there such a thing as enough programming languages?

答:
I'm kind of at the opposite side of the spectrum. I hate learning multiple languages, because you learn simple things and never get good at deeper problems this way. At the same time you learn bad practices from other languages.

Ever seen a hardcore Java developer coding in C++, it's a mess waiting to explode...

The problem is that all languages have their gotchas where the abstraction starts to leak, or play against you. You can learn syntax in 1 day, but it will take 5 years to know how to code efficiently and bug free. Do you use at() or []? Why malloc will make your long running process run out of memory?

And learning paradigms is also an interesting proposition. Because using Java guidelines in C, or Perl guidelines in C# is probably turn into an awesome demonstration of how to write obfuscated code.

Learning few new languages might help you broaden your horizons, but they shouldn't make you feel smarter, they should make you feel dumber with every new one you learn.


答:
A primary key is implemented via a unique index. For best performance, you should choose the smallest possible column length and if possible use numeric value. This has a performance effect in sorting and finding data.

The datatype int is usually large enough for most applications, but it may not be in your case.

A disadvantages identity fields is that if you use strictly sequential numbers, the indexes don't get built in an efficient way, however, this is really a minor issue. The other silly thing, is that you can't display the key value before you have completed the insert. This may sometime add some complexity to your GUI design. Also, you need to use SCOPE_IDENTITY() to capture the last inserted id which is an extra bit of work for the developer.

GUID is almost universally unique, so they are more generic than identity columns. With GUID, the key is text and its larger than the int type.
It is difficult to test with and difficult to provide to end user as part of a business application. For example, when used for customer number, invoice number, etc. it becomes impractical and causes problems for the end user. Also GUIDs are not 100% unique. I don't know the exact probability of duplication. The only nice thing about them is that they can be generated at the client without the round-trip to the server.

NewID() and NewSequentialId() function makes use of GUID.

You can take a look at this for some insight:
http://www.codinghorror.com/blog/2007/03/primary-keys-ids-versus-guids.html

If you are considering a cluser index, you may want to check this:
http://randommadness.blogspot.com/2008/07/guids-and-clustered-indexes.html
http://databases.aspfaq.com/database/what-should-i-choose-for-my-primary-key.html


问:
How to define complex business rules using User Stories?
A quick and dirty definition of User Story:

```<code>"As a <role>, I want <goal/desire> so that <benefit>"
</code>```

In this commonly accepted definition there is little space for defining business rules, constraints or user input.

Trivial example just to illustrate:

```<code>"As a <librarian>, I want to <register new books> so that
<students can find their availability online>"
</code>```

In this silly example, where would one define the fields needed when registering a book? Should it be written anywhere? Or should the required business rules be passed as word of mouth by the Product Owner?

答:
The fields are part of the conversation that should be had.  They may be written down if that is useful but that is a judgment call.  Keeping the documentation up to date may be challenging whereas the working software could be seen as documentation to some extent.

User Story - A Promise to have a conversation would be a blog entry about this.

Your trivial example has a couple of points that I don't know how well you'd notice this.  What does it mean to "register new books?"  What is "Find their availability online?"  Those are where the conversation begins and once the story is done there may be new stories as perhaps those registrations have to be kept on file or reports have to be generated periodically.