答:
I taught introductory programming at the college level.
It was a bread-and-butter course, all the faculty did it, and I think we did it quite well.
We followed a common text and had common exams, but we each had our own classroom method that worked.
It's been a long time since then, but occasionally I get to tutor some kid in programming, and the whole picture is about the same.

The way I do it is to start at the bottom, as concrete as possible.
What students know is a structure.
They already have a lot of concepts.
I am building further concepts on top of those, and I am pruning off concepts they may form which are counter-productive.
At the same time, I make them learn by doing.

I had built a little computer with an Intel 8008 chip, some EPROM, and a few circuits.
I had programmed it to play a little duet when the I/O chip was connected to a couple speakers.
I would explain how the little program worked, with an inner loop to count down a counter.
That would act as a delay.
Then it would toggle the output bit and do it again.
It would do that for a while, and then switch to another delay, giving another pitch, and so on.
The memory chip had a little timer, and if I tucked a capacitor lead under one of the timer inputs, the program would run veeeeery slowly.
The class could hear the speakers going click, click, click...
I wanted the class to understand that the computer was doing very simple things one step at a time.
Then I would un-hook the capacitor lead, and the "music" would burst forth. (applause)

Then I had built a simulator for a very simple decimal computer, having 1000 memory locations, each holding a signed 4-digit decimal number.
It had very simple opcodes like "add to accumulator", "jump if negative", and so on.
I would have them write little programs in this "machine language", like adding two numbers, or adding up a list of numbers.
Then they could watch it work by single-stepping, or holding down the Enter key to watch it run "fast".

The point of this was to put in place the concept that computers can only do a very small number of different basic operations, and they do them one-at-a-time.
This is to counter the impression they have that computers are complicated, and that they do everything all at the same time, and read your mind in the bargain.

From there we went on to programming in a "real" language (BASIC :), starting with very simple but interesting programs, working up through conditionals, loops, arrays, files, merging, and so on.
The object was to put in place a sufficient skill set so they could take on a project of their own choosing, because that's the only thing that makes programming interesting - the use to which you can put it.
I would throw out some ideas for projects, and then they would take it from there.
I would ask for written ideas, and then progress reports, to keep them from postponing it to the last minute and then panicking.
I think the projects were the best part, because they were learning under their own power.

That initial grounding in a very concrete understanding of what computers do made it much easier to teach concepts later on that would otherwise be real speed-bumps, like arrays or (in a later course) pointers.
We tend to glorify the concept of "abstraction" as this wonderful thing, but it needs to be built on a concrete foundation, not on air.

Title: How can I deal with the cargo-cult programming attitude?

Body:
I have some computer science students in a compulsory introductory programming course who see a programming language as a set of magic spells, which must be cast in order to achieve some effect (instead of seeing it as a flexible medium for expressing their idea of solution).

They tend to copy-paste code from previous, similar-looking assignments without considering the essence of the problem.

Are there some exercises or analogies to make these students more confident that they can, and should, understand the structure and meaning of each piece of code they write?


问:
Algorithm for an exact solution to the Travelling Purchaser Problem
do you know of any algorithms which give an exact solution for the Traveling Purchaser Problem. I can only find heuristic and probabilistic approaches.

I do have implemented a genetic algorithm so far, which by its nature does not terminate by itself an does not always yield the optimal result. Thus I'm looking for an exact solution to the problem such that I'm able to compare my solution to an exact / optimal value for a given test data set.

For those of you who haven't heard of the Traveling Purchaser Problem (TPP), this is not the Traveling Salesman Problem (TSP), but a generalization of it. It thus is also NP-hard.

答:
The NP-Hard domain of problems means that, as far as current mathematical knowledge goes, the problem can only be solved by trying every permutation and choosing the correct answer.

If you can solve the problem more efficiently than the brute force method, you will win a Noble Prize in mathematics as a bonus. The best mathematicians have been working on a general answer to this problem for decades.

Perhaps as you are wanting to create a test data-set for your NP-Hard problem solver, your approach may be to design the test data backwards - rather than solve the NP-Hard problem, create an NP-Hard problem with a known answer - I don't even know if that is a NP-Hard problem on it's own.

ContentLicense: CC BY-SA 3.0


问:
Conflicting versions of jQuery in Separate Extensions
I have built a few browser extensions that live in GMail. Since they are larger extensions, they incorporate jQuery 1.6.x.

I am using jQuery as a content script which means it is injected into GMail then my scripts reference jQuery as they are loaded afterwards.

I have found that when other extensions are installed alongside of my extensions and they incorporate earlier versions of jQuery the earlier versions are loaded first and my 1.6.x is ignored. The functionality I have that depends on 1.6.x no longer works, and that's a dealbreaker.

I'm trying to come up with an elegant solution for this. My first instinct is to namespace my version of jQuery, but loading jQuery twice seams clunky. Possibly testing for jQuery and then doing a diff, but that seems tedious.

Any thoughts?

答:
My personal feeling is that you probably shouldn't be injecting a third-party library into the page anyway. Keep in mind, that -- since it's a Chrome extension -- you only need to support a single browser anyway.

So that means things like subscribing to events, Ajax, and all the other stuff that jQuery abstracts are all pretty easy because you don't need to worry about cross-browser compatibility.

You can even use document.querySelector to get much of the functionality of jQuery's selectors (not all, though).

As a bonus, it'll make your extension much more light-weight by not loading 100KB of javascript into every page...


问:
Which questions a Software Developer/Sr. Software Developer (non-DBA, non-Database Enigneer) should be able to answer about databases?
I am a Java developer and most of my experience is on Java. But sometimes I have face some database related questions in the interviews. Hence I wanted to ask that from the interview point of view, which questions a Software Developer/Sr. Software Developer (non-DBA, non-Database Enigneer) should be able to answer about databases?

I know that this is a very subjective question with no definite answer. But I have come across a similar question about J2EE with some really great answers. Hence some constructive suggestions like specific topics, areas, questions, even links to resources will be greatly appreciated.

答:
Each organization have certain expectations from their developers, these expectations depend on the project at hand and the seniority of the developer. Here are some of the topics that cover all developer roles:

0-Build database scheme, tables, procedures and permissions.

1-Index design basics and when to use each type of index.

2-Query performance analysis and tuning - How and what tools/commands to use.

3-SQL and common SQL functions.

4-Database scripting language (T-SQL, PL/SQL) and when to use and when not to use.

5-Primary Keys/Foreign Keys design.

6-At least the first 3 Normal Forms ormalization (pros and cons).

7-Triggers types and when to use and not use.

8-Loading database from files.

9-Database environment parameters that needs to be set and why.

10-Logical database modeling, and some physical database modeling although, DBAs would know about that more. If applying for ETL job, need to know about star schema.

11-Referential Integrity constraint types and their effects.

12-Key design/selection best practices.

13-How to use the database management environment.

14-How to invoke the database commands from console.

15-How to write basic DDL (Create Table, etc.).

16-What is a dead lock and how to avoid it.

17-Views and their usage

18-What is a RDBMS!

Edit-1:

There are several references for the above knoweldge, The following were added to address some of the comments:

Index Types - MSDN

Index Types and Query Optimaization

Database Engine Advisor - MSDN

SQL Server Profiler

Edit-2
FYI - See related question: software-developer-interview-question-fair-or-unfair


问:
What to search/research to learn more about this way of coding Java?
What should I search/research if I'm looking for how to get started with translating database tables to Java code? For instance, if I have a one-many relationship in the database and I want to translate that to java code...what is that process called? </p>

<p>I'm really looking for just plain Java code example and not any tools at the moment. </p>

答:
First, learn about SQL (tables, queries, joins, transactions), then JDBC (statements, cursors, bind variables). Basic SQL is rather simple, as is basic JDBC. This will let you at least implement the simple display / create / update / delete sort of operations.

Distant next, learn about ORMs (such as Hibernate).

By that time you'll be able to ask more specific questions here.


问:
Why "Foo" is so a special word?

Possible Duplicate:

  Using “Foo” and “Bar” in examples

I discovered that in many examples of code i various books/questions/answers/tutorials the word Foo is used to name functions, interfaces, classes, properties, variables etc.

It is a special name, or is simple to name something in 3 letters, and
why Foo?

答:
It's a component of 'FooBar', a commonly used placeholder name and metasyntatic variable.

From the Wikipedia Article:

The terms foobar /ˈfʊːbɑː/, fubar, or foo, bar, baz and qux (alternatively quux) are sometimes used as placeholder names (also referred to as metasyntactic variables) in computer programming or computer-related documentation. They have been used to name entities such as variables, functions, and commands whose purpose is unimportant and serve only to demonstrate a concept. The words themselves have no meaning in this usage. Foobar is sometimes used alone; foo, bar, and baz are sometimes used in that order, when multiple entities are needed.

OwnerDisplayName: croisharp

Title: Why "Foo" is so a special word?


问:
How to drastically improve code coverage?
I'm tasked with getting a legacy application under unit test. First some background about the application: It's a 600k LOC Java RCP code base with these major problems

massive code duplication

no encapsulation, most private data is accessible from outside, some of the business data also made singletons so it's not just changeable from outside but also from everywhere.

no abstractions (e.g. no business model, business data is stored in Object[] and double[][]), so no OO.

There is a good regression test suite and an efficient QA team is testing and finding bugs. I know the techniques how to get it under test from classic books, e.g. Michael Feathers, but that's too slow. As there is a working regression test system I'm not afraid to aggressively refactor the system to allow unit tests to be written.

How should I start to attack the problem to get some coverage quickly, so I'm able to show progress to management (and in fact to start earning from safety net of JUnit tests)? I do not want to employ tools to generate regression test suites, e.g. AgitarOne, because these tests do not test if something is correct.

答:
One way to improve coverage is to write more tests.

Another way is to reduce the redundancy in your code, in such a way that existing tests in effect cover redundant code not presently covered.

Imagine you have 3 code blocks, a, b, and b', where b' is a duplicate (exact or near miss copy) of B, and that you have coverage on a and b but not b' with test T.

If refactor the code base to eliminate b' by extracting the commonality from b and b' as B, the code base now looks like a, b0, B, b'0, with b0 containing the nonshared code with b'0 and vice-versa, and both b0 and b'0 being much smaller than B, and invoking/using B.

Now the functionality of the program hasn't changed, and neither has test T, so we can run T again and expect it to pass.  The code now covered is a, b0, and B, but not b'0.
The code base has gotten smaller (b'0 is smaller than b'!) and we still cover what we originally covered.  Our coverage ratio has gone up.

To do this, you need to find b, b' and ideally B to enable your refactoring.
Our CloneDR tool can do this for many languages, especially including Java.  You say your code base has lots of duplicated code; this might be a good way to tackle it to your benefit.

Oddly, the act of find b and b' often increases your vocabulary about the abstract ideas the program implements.  While the tool has no idea what b and b' do, the very act of isolating them from the code, allowing simple focus on the content of b and b', often gives programmers an very good idea of what abstraction B_abstract the cloned code implements. So this improves your understanding of the code, too.   Make sure you give B a good name when you abstact it out, and you'll get better test coverage, and a more maintainable program.


答:
It is a form of code generation. You can get the information from the database using SQL queries. For instance, to get the column names from table "person" you would do this:

```<code>SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'person'
</code>```

That would give you the column names which you can then generate getters and setters based on each column name and type (which you can also get from the INFORMATION_SCHEMA).

Title: What to search/research to learn more about this way of coding Java?

Body:
What should I search/research if I'm looking for how to get started with translating database tables to Java code? For instance, if I have a one-many relationship in the database and I want to translate that to java code...what is that process called? </p>

<p>I'm really looking for just plain Java code example and not any tools at the moment. </p>

Body:
It is a form of code generation. You can get the information from the database using SQL queries. For instance, to get the column names from table "person" you would do this:

SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'person'

That would give you the column names which you can then generate getters and setters based on each column name and type (which you can also get from the INFORMATION_SCHEMA).


答:
Pardon my french, but you asked.....

foo is the first part of foobar.

foobar = FUBAR = Fucked up beyond all recognition.

Yes. That's what it means. The foobar spelling is based on the sound based phonics. How did it become popular in programming examples??? That I don't know.

Title: Why "Foo" is so a special word?

Body:
Possible Duplicate:

  Using “Foo” and “Bar” in examples

I discovered that in many examples of code i various books/questions/answers/tutorials the word Foo is used to name functions, interfaces, classes, properties, variables etc.

It is a special name, or is simple to name something in 3 letters, and
why Foo?


问:
Automatic programming: write code that writes code
After reading the book The Pragmatic Programmer, one of the arguments I found most interesting was "write code that writes code".

I tried searching over the net for some more explanations or articles about it, and while I found some good articles on the subject, I still haven't found any specific code implementation or good examples.

I feel it's still not a so common argument, something that lacks documentation or it's not embraced by so many people, and I would like to know more about it.

What do you think about the subject? Is it something that will really increase your productivity? What are some good resources on the subject, among books, blogs, slideshows, etc?

Some code examples would be greatly appreciated to allow me to better understand its implementation.

Here's the wiki page on the subject with various relevant programming techniques, like Meta Programming, Generative Programming and Code Generation.

答:
OP asks for resources.

You might found our DMS Software Reengineering Toolkit interesting.  It is a pure metaprogramming tool, intended to let one build custom program analysis and transformation tools.

[To follow a comment to OP's question, when used to build a specific transformation tool, DMS is a product line that writes code, that writes code :]

DMS achieves this by being agnostic (but not independent) of target programming lanuages. DMS provide the standard services needed by a wide variety of metaprogramming tasks, much as an OS provide a wide variety of services for standard programming tasks. These services include strong parsing, automatic construction of abstact syntax trees, pattern-matching and rewriting on trees, symbol table libraries that easily manage langauges with nasty scoping rules such as multiple inheritance, control-flow, data-flow, points-to and call graph analysis.  None of this is meaninful in the absence of specific langauges to process, so DMS accepts language definitions that are tied to these general pieces of machinery, yielding language-specific parsing, AST construction, target language-specific pattern matching/rewriting using the target-language syntax, target-langauge specific analyzers, etc.

And like an OS, DMS is designed to have very few opinions or constraints on what (meta)programs you wish to write, which means it can be used for wide variety of purposes: extracting metrics, finding dead code, implementing aspect weavers, translating langauges, generating codes from DSLs, rearchitecting large applications.  (DMS has already been used for all of these tasks).

One needs robust language definitions if you don't want to spend your time encoding everything in the langauge reference manual (think about what this means for Java and C++).  DMS solves this problem by having a library of complete langauge definitions available.  The analog here is kind of like having a database avaialbe for your OS; you don't have to implement one of them to get on with writing your database-centric application.


问:
How easy should a language development framework be to use?

This is part of a series of questions which focuses on a project called the Abstraction Project, which aims to abstract the concepts used in language design in the form of a framework.

Another page associated to it related to structural typing can be viewed here.  The meta-topic associated to an inquiry about the framework and the proper place to post can be found here.

How easy should it be to use a Language Development Framework?

I've written large scale code generation frameworks which also included the ability to send the result to the language-specific compiler. The topic of ease of use comes up from one such framework example: CodeDOM, or the Code Document Object Model.

It is a framework written by Microsoft that describes common code structures, but generally left a lot out (expression coercions) and tended to be a bit abstract in its representation of certain constructs, to downright emitting bad code based upon what you were doing: earlier CodeDOM poorly handled emitting PrivateImplementationType on CodeMemberMethod, when the type used was a generic interface.  CodeDOM was my original reason for writing my first code generator.

One thing I'm trying to do, to simplify the framework, is reduce the amount of work you need to do something, and focusing on actions versus the specific types that make up those actions.

Here's a side by side comparison of how the framework I'm writing works:

```<code>//Truncated...
/* *
 * From a project that generates a lexer, this is the
 * state->state transition character range selection logic.
 * */
var nextChar = nextMethod.Parameters.Add(new TypedName("currentChar", typeof(char).GetTypeReference()));
//...
char start = rangeElement.B.Value.Start;
char end = rangeElement.B.Value.End;
/* *
 * 'start' <= nextChar && nextChar <= 'end'
 * */
currentExpression = start.LessThanOrEqualTo(nextChar).LogicalAnd(nextChar.LessThanOrEqualTo(end));
</code>```

Versus CodeDOM:

```<code>//Truncated...
var nextChar = new CodeVariableReferenceExpression("nextChar");
//...
var start = new CodePrimitiveExpression(rangeElement.B.Value.Start);
var end = new CodePrimitiveExpression(rangeElement.B.Value.End);
currentExpression = new CodeBinaryOperatorExpression(new CodeBinaryOperatorExpression(start, CodeBinaryOperatorType.LessThanOrEqual, nextChar), CodeBinaryOperatorType.BooleanAnd, new CodeBinaryOperatorExpression(nextChar, CodeBinaryOperatorType.LessThanOrEqual, end));
</code>```

The focus of the framework is language enthusiasts, as well as those interested in generating code or applications. Given its focus on compilation, code generation, and language development, should the framework focus on ease of use or raw power?

My primary goal is to increase the availability of such tools, so those interested in the domain don't require a lot of experience in the language theory domain before they can start to work on their own language-centric projects.

Given that I'm the author of the framework, my view of "usability" is biased.  Thus, I must ask another if the focus and goal make sense to others who aren't associated to the project.

答:
Its tough to build a language-development framework. You have to decide what kinds of things you'd like it to support, then you have to decide which of those you sort of know how to do, and how to integrate those together into a coherent whole.  Finally, you have make enough investment so it works with real languages (e.g., typical computer languages as well as DSLs), and actually does something useful.   My hat is off to you for trying.

You might compare you effort with the one I started 15 years ago, the DMS Software Reengineering Toolkit.  DMS is intended to provide general purpose parsing, analysis, and transformation of code.  Given an explicit langauge specification, it will parse code, build ASTs, regenerate code from ASTs (prettyprint), transform code using patterns written in the targeted programming language, build symbol tables, compute control and data flow, etc.   By adding custom code, one make DMS carry off a wide variety of effects.
(See the tools at the site; they're all DMS in one form or another).

Here's a technical paper on DMS as is was several years ago. (We keep improving it)

While DMS itself has been hard to build, we found that it took a correspondingly large chunk of engineering to define real langauges to DMS, including IBM COBOL, C# 4.0, Java 1.7, C++11 (and many others).

What we think it does (reasonably well): lower the cost of building tools by 1-2 orders of magnitude. What this means is that tasks that might otherwise take 1-10 years can be contemplated by mere mortals as 1 month-1 year projects.  What still isn't easy:

Defining new langauges

Handling all the idiocies of current languages

Making it easy to write the custom code specific to your task

Defining new, complex analyses

Handling partial programs, or programs containing errors

(To your initial point) Make it easy for nonexperts to use these tools

So, there's lots of room for improvement.  Let many flowers bloom.


问:
What is the best unit test framework for .NET and why?
It seems to me that everyone uses NUnit without even considering the other options. I think this is because:

Everyone is familiar with it already so they won't have to learn a new API.

It is already set up with their continuous integration server to work with NUnit.

Am I wrong about this?

I decided to use xUnit on one of my own projects recently and I love it! It makes so much more sense to me and conceptually it seems like a definite step forward from NUnit.

I'd like to hear opinions on which framework is actually the best - not taking into consideration having to learn it or reconfigure your automated testing.

答:
The one reason is NUNIT become more industry standard than xUnit.
But personally, i love xunit.</p>

ContentLicense: CC BY-SA 2.5


答:
Excerpted from the Jargon File:

When ‘foo’ is used in connection with ‘bar’ it has generally traced to
  the WWII-era Army slang acronym FUBAR (‘Fucked Up Beyond All Repair’
  or ‘Fucked Up Beyond All Recognition’), later modified to foobar.
  Early versions of the Jargon File interpreted this change as a
  post-war bowdlerization, but it it now seems more likely that FUBAR
  was itself a derivative of ‘foo’ perhaps influenced by German
  furchtbar (terrible) — ‘foobar’ may actually have been the original
  form.

For, it seems, the word ‘foo’ itself had an immediate prewar history
  in comic strips and cartoons. The earliest documented uses were in the
  Smokey Stover comic strip published from about 1930 to about 1952.
  Bill Holman, the author of the strip, filled it with odd jokes and
  personal contrivances, including other nonsense phrases such as
  “Notary Sojac” and “1506 nix nix”. The word “foo” frequently appeared
  on license plates of cars, in nonsense sayings in the background of
  some frames (such as “He who foos last foos best” or “Many smoke but
  foo men chew”), and Holman had Smokey say “Where there's foo, there's
  fire”.

If this sort of etymological study is of interest to you, there's a vast wellspring more of it at the link.

But what's known for certain is that the modern usage of foo (and bar, and much other modern computer nonsense jargon) is first documented as appearing at MIT in the late 1950s.  Which bits of jargon the MIT engineers/students picked up from elsewhere (say, from a popular comic strip from six or seven years earlier), and which they invented themselves is much less well-documented.  Hints about a history pre-dating the MIT Tech Model Railroad Club are intriguing, but are also mostly supposition and anecdotes.

Title: Why "Foo" is so a special word?


问:
Would this be an effective use of the Subject/Observer pattern, or is there a better way?
TBH:  I've never used an observer pattern.  But it looks pretty useful for this situation:

I'm developing a very simple strategy game.  It involves two combatants who simultaneously bludgeon each other over a short period of time, the winner being the combatant with the most health remaining in the end.

Now, there's a lot of configurable strategies for the combatants, different pieces of equipment that can change how often they attack, etc.  I'm also planning on including some "outside" factors like weather that will affect the combatants.

So....    I could create a Fight object that is the subject.  It keeps track of the time and notifies the observers every "tick" of the clock.

The observers are two instances of a Combatant object and one Weather object.

It seems like a good idea, but where are the pitfalls?  Actually, as I'm typing this I think one problem is that observers are probably ignorant of each others' parameters.  Or must they be?

Has anyone used an effective design pattern to do something like this?

答:
If the two Combatant instances and Weather object are notified as the result of the clock tick count being updated, and not by direct intervention by the Fight object, then it's the Observer pattern.

If your Fight object triggers the notifications directly you can use the Command pattern to encapsulate the receivers or have the Fight object send messages directly to the Combatants and Weather objects individually.


问:
How can I deal with the cargo-cult programming attitude?
I have some computer science students in a compulsory introductory programming course who see a programming language as a set of magic spells, which must be cast in order to achieve some effect (instead of seeing it as a flexible medium for expressing their idea of solution).

They tend to copy-paste code from previous, similar-looking assignments without considering the essence of the problem.

Are there some exercises or analogies to make these students more confident that they can, and should, understand the structure and meaning of each piece of code they write?

答: When I was in an introductory programming course, the instructor required everyone to write an algorithm in English and print it out and turn it in before we started writing code. Then we would have to put plenty of comments such as Create variables, Get Input from user, Perform calculations, Print output, etc. I was docked a couple of times for not having enough comments when I thought there were plenty, so I started adding more. This forced me to think about what I was doing and write the solutions and keep translating back and forth between English and Java.</p>


问:
How relevant are Brainbench scores when evaluating candidates?
I've seen many companies using certification services such as Brainbench when evaluating candidates. Most times they use it as a secondary screen prior to interview or as a validation to choose between candidates.

What is your experience with Brainbench scores? Did you try the tests yourself, and if so do you feel the score is meaningful enough to be used as part of a hiring process?

Difficult choice.

Consensus seems to be that BB cert are not very good as a certification.  The biggest argument was around the fact that some of the questions are too precise to form a good evaluation.  This view can probably be tempered somewhat but still, to hold someone's future solely on the results of this evaluation would be irresponsible.

That said, I still think it is possible to use them properly to gain additional objective knowledge on a candidate's level of expertise provided the test is done in a controlled environment ensuring that all taking it stand on equal footing.

Thus I went with the answer that best reflected this view keeping in mind that it is still just an hour long 50ish multiple choice question to evaluate skills and knowledge that take years to acquire.  To be taken with a grain of salt !

In short, the tests have value but whether or not they are worth the money is another debate.

Thanks all for your time.

答:
I took the Brainbench Java and XML tests in 2003.  I thought they were kind of hokey.  But in a lot of job interviews, the homebrewed 20 multiple choice questions tests are even worse.  They're invariably composed and edited in Word, and the auto-capitalization "feature" makes "string" into "String" and "boolean" into "Boolean".  The latter can really make a difference in Java code, and turning "int" into "Int" can render C code where you're supposed to pick out the error into a confusing maze.

As an interviewee, I take those tests with a grain of salt. The goofier the test is the less I want to work there. So: testers beware.  You're giving away information, and unless you've formatted extraordinarily carefully, your candidate may find out something undesirable about your company.


问:
How to encourage creative user interface design?
When I picture a really well functioning software team in my mind, one of the visions I have is of a developer showing off to a small group of devs some cool, clever UI that they just came up with based on something that they were just playing with.

I'm afraid that while we're doing great at being creative writing expressive, well architected, high quality code - we aren't pushing any creative boundaries when it comes to effective user interface.

What's an effective strategy for encouraging developers to push their boundaries with user interface?

Edit:

I'm looking for something "lab oriented", like for instance pair programming sessions focused on some problem or other.

答:
A key component that enables creativity is having a base understanding of what is possible. You need to know what the boundaries are before you can push them. It sounds like your team has this covered when it comes to programming and development. This is understandable as your are a team of developers with a strong knowledge of that area.

Learn about interfaces and what sits on both sides of them. That is, learn about UI toolkits and graphics packages but more importantly learn about people and psychology. I'd highly recommend checking out Designing Interactive Systems I as well as part II. It's an amazingly well put together lecture series that covers both the psychology and technology side of interface design. Also, have a look at resources like Little Big Details.

Learn about the boundaries, seek out what others are doing to use and distort them and challenge yourselves to do better.


答:
I don't think there are any definite answers, but here are some things that I've seen work:

Programmers usually aren't user interface designers. If you feel that your UI needs improvement, you'd do well to work with someone who was actually trained in design. It's easy to appreciate good design, but not always so easy to create it.

Use data to identify problems and to quantify them. That might mean doing some usability studies first, observing real users to find out what works well for them and what doesn't. Or it might mean sorting all the UI-related complaints you've received from users over the last n months into categories and using that data to determine what users like and don't like. That should give you some real, specific problems to work on. Set some goal, like: "minimize the number of clicks required to set up a new document" or "make the effect of the undo and redo commands more obvious." Once you've made improvements, keep collecting data to make sure that your changes really do solve the problem.

Hold some no-holds-barred brainstorming sessions in which developers (and others) are encouraged to rethink a product. You're not designing the next version of your product here; it's probably not the right way to develop a clear design. Instead, you want people to practice thinking outside their current box, and to gather creative ideas from people who spend a lot of time thinking about every detail of your product.

Taste your dog food. Sometimes, developers who work on a product don't have a lot of time to really dig in and use the product beyond testing the specific functions that they're working on. Set aside some time for the whole development team to use the product, if possible. Turning the developers into users for a while can help identify a lot of problems.

Training. Send some (or all) of your developers to classes or seminars to learn about UI design, data presentation, etc. For example, Edward Tufte does a one-day seminar that's very interesting.

Title: How to encourage creative user interface design?

Body:
When I picture a really well functioning software team in my mind, one of the visions I have is of a developer showing off to a small group of devs some cool, clever UI that they just came up with based on something that they were just playing with.

I'm afraid that while we're doing great at being creative writing expressive, well architected, high quality code - we aren't pushing any creative boundaries when it comes to effective user interface.

What's an effective strategy for encouraging developers to push their boundaries with user interface?

Edit:

I'm looking for something "lab oriented", like for instance pair programming sessions focused on some problem or other.


问:
Should controls on a form be prepared in a separate class?
I have a form with several controls on it. Every control has to be declared in the class, formatted in the constructor (-size, location, event subscription etc), and its event-handlers declared, again, in the class.

This is getting a bit unorganized, so I was thinking of refactoring this. For every control: Preparing a class which derives from that control-type (which will include location, event-subscription and event-handlers, etc.), and then using an instance of it.

Am I going to run into any trouble doing this?

答:
I think what you might want is a Mediator, as per MVC. It sounds like you are hitting the wall on your WYSIWYG form builder and need to transfer part or all of what is going on into some automated code.

A good example of this is a keyboard I was emulating on a form, so instead of manually placing the size and location of each key, I make an algorithm do it.

If you look into MVC, particularly pureMVC, you will see that a mediator is responsible for driving and responding to controls -- so there is a bit of wiring up to do. I am not saying you have to use MVC, but just the concept of a mediator. Subclassing each control seems like overkill from the information given.

There can be more than one mediator per form too. When I do MVC I will make a mediator for ALMOST every control, excepting menus, which there will be a mediator for each, and each submenu -- and toolbar (buttons) will all be managed as a group.

Mediators are a good way isolate responsibilities, for instance, you can have one mediator in charge of the background color of treelists, or have a mediator that keeps track of focus issues.

Looking at your post again, I think you should probably look into pureMVC, there is a C#  version out on the web. If you are really clever you can get Reflection to wire things up automatically based on the names of your handlers. MVC is a good way to go because it loosens the coupling of your code, so instead of directly calling functions you just send a notification up and whoever 'cares' will receive it. This way you don't have to remember at the event point all the things you need to do, and everyone out there doesn't have to be present.

The downside is, you can no longer follow your code around by jumping from function to function in all cases.

Think of it this way, every class instance is isolated and needs to know very little about the outside world -- only the message conventions. How much faster can you program a class when all it has to worry about is itself :)

Psuedo-code:

```<code>/////////////////////////////////
// I mediate a form called AppsFm
C AppsFmMed
   = NAME         //="AppsFmMed"
   //
   /////////////////////////////////
   // published message
   = ___P_LOAD  //="AppsFmMed_LOAD"
   //
   /////////////////////////////////
   // interested in messages;
   = ___I_DATAPROXYNAME_DATACHANGED //="DataProxyName_DATACHANGED"
   //
   /////////////////////////////////
   // my controls
   p it         // the form
     get{return ViewForm as AppsFm;}
   //
   p form         // the same form
   p okBU         // a button
     get{return GetControl("okBU") as SimpleButton;}
   p cancelBU     // a button
   p appsTL     // a treelist
  //
  //////////////////////////////////
  //ctors
  Cn AppsFmMed()
  Cn AppsFmMed(string mediator_name_)
  Cn AppsFmMed(string mediator_name_, object view_component_)
  Cn AppsFmMed(string mediator_name_, object view_component_, object view_form_)
  //
  //////////////////////////////////
  // notifications come here and I respond to them
  Fn HandleNotification(INotification notification_){
    switch notification_.Name
     case:___I_DATAPROXYNAME_DATACHANGED
  }
  //
  //////////////////////////////////
  // initialization code, wire up events
  Fn hookEvents()   {
      assignFormEvent("FormClosed");
      assignFormEvent("Load");
      assignControlEvent(okBU.Name, "Click", "evtClick");
      assignControlEvent(cancelBU.Name, "Click", "evtClick");
  }
  //
  //////////////////////////////////
  // utility fns
  Fn initLabels()
  Fn saveValues()
  Fn loadValues()
  Fn initForm()
  //
  //////////////////////////////////
  // I am born and registered to recieve "interests",
  Fn OnRegister()
  Fn OnRemove()
  //
  //////////////////////////////////
  // the control events are wired to these
  Fn evtClick(object sender_, EventArgs e_)
  Fn EvtLoad(object sender_, EventArgs e_)
  Fn EvtFormClosed(object sender_, FormClosedEventArgs e_)
</code>```

Body:
I think what you might want is a Mediator, as per MVC. It sounds like you are hitting the wall on your WYSIWYG form builder and need to transfer part or all of what is going on into some automated code.

A good example of this is a keyboard I was emulating on a form, so instead of manually placing the size and location of each key, I make an algorithm do it.

If you look into MVC, particularly pureMVC, you will see that a mediator is responsible for driving and responding to controls -- so there is a bit of wiring up to do. I am not saying you have to use MVC, but just the concept of a mediator. Subclassing each control seems like overkill from the information given.

There can be more than one mediator per form too. When I do MVC I will make a mediator for ALMOST every control, excepting menus, which there will be a mediator for each, and each submenu -- and toolbar (buttons) will all be managed as a group.

Mediators are a good way isolate responsibilities, for instance, you can have one mediator in charge of the background color of treelists, or have a mediator that keeps track of focus issues.

Looking at your post again, I think you should probably look into pureMVC, there is a C#  version out on the web. If you are really clever you can get Reflection to wire things up automatically based on the names of your handlers. MVC is a good way to go because it loosens the coupling of your code, so instead of directly calling functions you just send a notification up and whoever 'cares' will receive it. This way you don't have to remember at the event point all the things you need to do, and everyone out there doesn't have to be present.

The downside is, you can no longer follow your code around by jumping from function to function in all cases.

Think of it this way, every class instance is isolated and needs to know very little about the outside world -- only the message conventions. How much faster can you program a class when all it has to worry about is itself :)

Psuedo-code:

/////////////////////////////////
// I mediate a form called AppsFm
C AppsFmMed
   = NAME         //="AppsFmMed"
   //
   /////////////////////////////////
   // published message
   = ___P_LOAD  //="AppsFmMed_LOAD"
   //
   /////////////////////////////////
   // interested in messages;
   = ___I_DATAPROXYNAME_DATACHANGED //="DataProxyName_DATACHANGED"
   //
   /////////////////////////////////
   // my controls
   p it         // the form
     get{return ViewForm as AppsFm;}
   //
   p form         // the same form
   p okBU         // a button
     get{return GetControl("okBU") as SimpleButton;}
   p cancelBU     // a button
   p appsTL     // a treelist
  //
  //////////////////////////////////
  //ctors
  Cn AppsFmMed()
  Cn AppsFmMed(string mediator_name_)
  Cn AppsFmMed(string mediator_name_, object view_component_)
  Cn AppsFmMed(string mediator_name_, object view_component_, object view_form_)
  //
  //////////////////////////////////
  // notifications come here and I respond to them
  Fn HandleNotification(INotification notification_){
    switch notification_.Name
     case:___I_DATAPROXYNAME_DATACHANGED
  }
  //
  //////////////////////////////////
  // initialization code, wire up events
  Fn hookEvents()   {
      assignFormEvent("FormClosed");
      assignFormEvent("Load");
      assignControlEvent(okBU.Name, "Click", "evtClick");
      assignControlEvent(cancelBU.Name, "Click", "evtClick");
  }
  //
  //////////////////////////////////
  // utility fns
  Fn initLabels()
  Fn saveValues()
  Fn loadValues()
  Fn initForm()
  //
  //////////////////////////////////
  // I am born and registered to recieve "interests",
  Fn OnRegister()
  Fn OnRemove()
  //
  //////////////////////////////////
  // the control events are wired to these
  Fn evtClick(object sender_, EventArgs e_)
  Fn EvtLoad(object sender_, EventArgs e_)
  Fn EvtFormClosed(object sender_, FormClosedEventArgs e_)


问:
Using bug-tracking / issue-tracking software to discuss design questions, new tools etc
Does anybody have experience with using a bug-tracking / issue-tracking software like bugzilla, mantis or JIRA not only for bugs or tasks, but to initiate and maintain discussions that in the end lead to a decision?

For example, a developer thinks that all protected fields should be abolished and changed to private fields with protected methods that access them. It is not his call, and he would like to discuss it. Normally he brings up the point in the next developer meeting at the end of which a decision is made. Instead, my idea was for him to open an issue of a certain type "decision" and describe his intent like normally one would describe a bug or task.

Other developers can make their comments if they feel like it, and in the end, the issue is closed as "accepted" or "denied".

The advantages I see in this:

Asynchronous communication: no one is forced to voice his opinion in a meeting when they didn't have time yet to oversee all ramifications of said decision.

Written log of considerations that lead to a decision. If one later raises that question again he can be referred to it.

Relations to other issues can be made, e.g. a task can be followed back to a decision.

Integration with version control software, e.g. a commit can be traced back to a decision.

Disadvantages:

Heavy smell of a golden hammer: issue tracking software normally is used to track actionable items

Organizational overhead may be disproportionate: instead of a small informal talk one has to communicate his ideas in written form

答:
Correct me if i am wrong; but i think what you are talking about it is - "Can/How to use Bug tracking/Issue Tracking systems to also do 'Decision Tracking'. Is it or am i missing something?

At the outset i would say this is indeed a great idea. Though we don't use it in the exact said manner, it makes sense that we use it for the purpose of tracking. In our case, a long thread of email - more as a forum/mailing list is followed.

However, your question in a broader sense is about how to make (and manage) decisions effectively and connect the implications of work back to decisions taken that brings better insights.

As i said, it can be great a idea if that helps people. Nothing wrong about it. But for effectively making/manging decisions needs few concrete things.

It is true that most decisions should be broad based inclusive effort so that all important aspects are covered and weighed appropriately before decisions are based. So whatever tool you use must have enabled transparent access to information to all concerned. You are right that Asynchronous mode of conveying and collecting information helps because people can put in time before putting suggestions. If asked for upfront answers - typically in the meetings, the judgment might not be equally sound compared to the same person with enough homework.

However, this doesn't necessarily mean "pure democracy" where every vote is equal. In general, the decision making person should be one or few - and while they have taken all opinions, they must be individually responsible for the decisions and not all people who provided their opinions.

Most decisions must be actionable. This might find hard to avoid contradictions; but the fact that decisions are not actionable and only subjective means there possibilities for future (mis)interpretations.

It is important to classify the level and scope of the decision. Most importantly we must identify whether are we discussing specific design problem or specific aspect of code, aspect of processes or are these project planning and tracking related issues? Quite often when issues strike from a production code - all of these are applicable, but we must be able to distinguish all different aspects and independently to be able to manage these decisions effectively.

Sometimes the decisions could be of whether we use certain systems or roles and responsibilities for individuals; it might be harsh to put these decisions along side with coding specific decisions on a notice-board-type forum.

Just an additional anecdotes; every team must put code reviews and design reviews as a process by itself - which will exhaustively cover many issues the likes of example you quoted. They are must whether or not decisions tracking deals with other things or not.

A good decision making practices involve a lot of discipline on how we pull the information together and ensuring that decisions are followed through with the implementations with the right spirit.

A tool can only help to make information more presentable not beyond that; but that might be good help if it works for you.


问:
Commented short fancy code vs. uncommented longer easy-to-understand code - which is preferred?
Sometimes an algorithm can be written in two ways:

The short, fancy way; or

The longer, easy-to-understand way.

For example, here is a longer, easier way of copying a string source to dest in C:

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

And here is a short, fancy way.

```<code>// Copy string source to dest
while (*dest++ = *source++);
</code>```

I've always heard and read that fancy code should be avoided, and I tend to agree. But what if we take comments into account? Assume that, as in the examples above, we have an uncommented, longer and supposedly easier-to-understand code, and a well-commented, short, fancy code? Is the non-fancy code still preferred?

EDIT: Many have commented on variable names, so I've modified the example code as to not make that a factor when preferring on over the other. I tried to remove the double assignment in the first example, but that only made the code less readable.

Perhaps this wasn't the best of examples because many find the 'fancy' code more readable and understandable than the longer code. The idea was to have one longer code which was much easier to understand than a very short but complicated code.

EDIT2: Here's a new examle I got from SO:

Commented fancy version:

```<code>//direct formula for xoring all numbers from 1 to N
int Sum = (N & (N % 2 ? 0 : ~0) | ( ((N & 2)>>1) ^ (N & 1) ) );
</code>```

Non-commented long version:

```<code>int Sum = 0;
for (int i = 1; i < N; ++i)
{
   Sum ^= i; //or Sum = Sum ^ i;
}
</code>```

答:
I'm starting to never trust comments. All too often, comments don't get updated when code gets updated and are vastly out of date or represent rules from clients/management that no-longer are relevant.

It has gotten to the point in some cases where the comments don't even match the code that they're describing anymore.

If I have to choose between short/fancy and longer/easier to understand then I always choose the latter unless there is a really good reason.


问:
How can I gather client's data on Google App Engine without using Datastore/Backend Instances too much?
One of the projects I'm working on is online survey engine. It's my first big commercial project on Google App Engine.

I need your advice on how to collect stats and efficiently record them in DataStore without bankrupting me. Initial requirements are:

After user finishes survey client sends list of pairs [ID (int) + PercentHit (double)]. This list shows how close answers of this user match predefined answers of reference answerers (which identified by IDs). I call them "target IDs".

Creator of the survey wants to see aggregated % for given IDs for last hour, particular timeframe or from the beginning of the survey.

Some surveys may have thousands of target/reference answerers.

So I created entity

```<code>public class HitsStatsDO implements Serializable
{
    @Id
    transient private Long id;
    transient private Long version = (long) 0;

    transient private Long startDate;

    @Parent transient private Key parent;   // fake parent which contains target id
    @Transient int targetId;

    private double avgPercent;
    private long hitCount;
}
</code>```

But writing HitsStatsDO for each target from each user would give a lot of data. For instance I had a survey with 3000 targets which was answered by ~4 million people within one week with 300K people taking survey in first day. Even if we assume they were answering it evenly for 24 hours it would give us ~1040 writes/second. Obviously it hits concurrent writes limit of Datastore.

I decided I'll collect data for one hour and save that, that's why there are avgPercent and hitCount in HitsStatsDO. GAE instances are stateless so I had to use dynamic backend instance.

There I have something like this:

```<code>// Contains stats for one hour
private class Shard
{
    ReadWriteLock lock = new ReentrantReadWriteLock();
    Map<Integer, HitsStatsDO> map = new HashMap<Integer, HitsStatsDO>(); // Key is target ID

    public void saveToDatastore();
    public void updateStats(Long startDate, Map<Integer, Double> hits);
}
</code>```

and map with shard for current hour and previous hour (which doesn't stay here for long)

```<code>private HashMap<Long, Shard> shards = new HashMap<Long, Shard>();   // Key is HitsStatsDO.startDate
</code>```

So once per hour I dump Shard for previous hour to Datastore.

Plus I have class LifetimeStats which keeps Map<Integer, HitsStatsDO> in memcached where map-key is target ID.

Also in my backend shutdown hook method I dump stats for unfinished hour to Datastore.

There is only one major issue here - I have only ONE backend instance :) It raises following questions on which I'd like to hear your opinion:

Can I do this without using backend instance ?

What if one instance is not enough ?

How can I split data between multiple dynamic backend instances? It hard because I don't know how many I have because Google creates new one as load increases.

I know I can launch exact number of resident backend instances. But how many ? 2, 5, 10 ? What if I have no load at all for a week. Constantly running 10 backend instances is too expensive.

What do I do with data from clients while backend instance is dead/restarting?

One thing to note is that I can't change client much. Currently it's JavaScript embedded into web-pages of customers. I can change RPC in some way but architecturally I cannot replace client with Google Docs forms for example.

答:
My service went live and I want to share how I implemented it.

So instead of gathering data in memory of single backend instance for an hour I decided to gather it in multiple dynamic backend instances and update shard for current hour in Datastore every 10 mins from each instance. Class Shard stays the same with the exception of saveToDatastore() where I now update HitsStatsDOs in transaction loop to make sure it's updated even if another backend instance changes shard at the moment.

In order to fetch HitsStatsDO really fast I decided to put target ID in fake parent key and timestamp if this hard to primary ID like this

```<code>public class HitsStatsDO implements Serializable
{
    @Id
    transient private Long id;  // always equals to "startDate"
    @Unindexed
    transient private Long version = (long) 0;

    transient private Long startDate;

    @Parent
    transient private Key targetIdKey;   // fake parent which contains target id

    @Unindexed
    private double avgPercent;
    @Unindexed
    private long hitCount;

    public Key<HitsStatsDO> createKey()
    {
        return new Key<HitsStatsDO>(targetIdKey, HitsStatsDO.class, startDate);
    }

    public HitsStatsDO(Long startDate, long targetId)
    {
        this.id = this.startDate = startDate;
        this.targetIdKey = new Key(Long.class, targetId);
    }
}
</code>```

This entity takes only 2 writes to be stored. Amount of writes is never more than ([amount of backend instances] * 2 * 6) per hour which is not bad. Also I can pre-create keys in my code and do batch-get from Datastore.

Similarly I changed HitsStatsTotalDO which contains stats from the beginning of survey. It looks like this

```<code>public class HitsStatsTotalDO implements Serializable
{
    @Id
    private Long targetId;
    @Unindexed
    transient private Long version = (long) 0;

    @Unindexed
    private double avgPercent;
    @Unindexed
    private long hitCount;
}
</code>```

Same thing - 2 writes to store/update.

Service went live 3 days ago. Maximum load so far was 230 QPS. I'm using dynamic B1 type instances. In config I set maximum of 4 instances for now but to my pleasure GAE never instantiated more than one. And surprisingly I haven't had concurrency exceptions yet.

Let me know if you have any questions or think I missed something.

And thank you everyone for your help. StackExchange is really awesome community.

Body:
My service went live and I want to share how I implemented it.

So instead of gathering data in memory of single backend instance for an hour I decided to gather it in multiple dynamic backend instances and update shard for current hour in Datastore every 10 mins from each instance. Class Shard stays the same with the exception of saveToDatastore() where I now update HitsStatsDOs in transaction loop to make sure it's updated even if another backend instance changes shard at the moment.

In order to fetch HitsStatsDO really fast I decided to put target ID in fake parent key and timestamp if this hard to primary ID like this

public class HitsStatsDO implements Serializable
{
    @Id
    transient private Long id;  // always equals to "startDate"
    @Unindexed
    transient private Long version = (long) 0;

    transient private Long startDate;

    @Parent
    transient private Key targetIdKey;   // fake parent which contains target id

    @Unindexed
    private double avgPercent;
    @Unindexed
    private long hitCount;

    public Key<HitsStatsDO> createKey()
    {
        return new Key<HitsStatsDO>(targetIdKey, HitsStatsDO.class, startDate);
    }

    public HitsStatsDO(Long startDate, long targetId)
    {
        this.id = this.startDate = startDate;
        this.targetIdKey = new Key(Long.class, targetId);
    }
}

This entity takes only 2 writes to be stored. Amount of writes is never more than ([amount of backend instances] * 2 * 6) per hour which is not bad. Also I can pre-create keys in my code and do batch-get from Datastore.

Similarly I changed HitsStatsTotalDO which contains stats from the beginning of survey. It looks like this

public class HitsStatsTotalDO implements Serializable
{
    @Id
    private Long targetId;
    @Unindexed
    transient private Long version = (long) 0;

    @Unindexed
    private double avgPercent;
    @Unindexed
    private long hitCount;
}

Same thing - 2 writes to store/update.

Service went live 3 days ago. Maximum load so far was 230 QPS. I'm using dynamic B1 type instances. In config I set maximum of 4 instances for now but to my pleasure GAE never instantiated more than one. And surprisingly I haven't had concurrency exceptions yet.

Let me know if you have any questions or think I missed something.

And thank you everyone for your help. StackExchange is really awesome community.


答:
I'm reminded of that saying about not worrying about the barn door when the horse has already bolted.

The reality is that there really isn't a cost effective way to get good test coverage for a legacy system, certainly not in a short time frame. As MattNz mentioned, it's going to be a very time consuming process, and ultimately costly in the extreme.  My gut tells me that if you attempt to do something to impress management, you'll likely create a new maintenance nightmare because of trying to show too much too quickly, without fully understanding the requirements that you are attempting to test for.

Realistically, once you have already written the code, it's almost to late to write the tests effectively without the risk of missing something vital.  On the other hand, you could say that some tests are better than no tests, but if that's the case, the tests themselves need to show that they add value to the system as a whole.

My suggestion would be to look at those key areas where you feel something is "broken".  By that I mean it could be terribly inefficient code, or that you can demonstrate has been previously costly to maintain. Document the problems, then use this as a starting point to introduce a level of testing that helps you to improve the system, without embarking on a massive re-engineering effort.  The idea here is to avoid playing catch-up with the tests, and instead introduce tests to help you solve specific problems. After a period of time, see if you can measure and distinguish between the previous cost of maintaining that section of code, and the current efforts with the fixes you have applied with their supporting tests.

The thing to remember is that management are more interested in the cost/benefit and how that directly affects their customers, and ultimately their budget.  They are never interested in doing something simply because it is the best thing to do unless you can prove that it will provide them with a benefit that is of interest to them. If you're able to show that you are improving the system and getting good test coverage for the work you are presently doing, management are more likely to see this as an efficient application of your efforts.  This could possibly allow you to argue the case for extending your efforts to other key areas, without demanding either a complete freeze of the product's development, or even worse the nearly impossible to argue for rewrite!

Title: How to drastically improve code coverage?

Body:
I'm tasked with getting a legacy application under unit test. First some background about the application: It's a 600k LOC Java RCP code base with these major problems

massive code duplication

no encapsulation, most private data is accessible from outside, some of the business data also made singletons so it's not just changeable from outside but also from everywhere.

no abstractions (e.g. no business model, business data is stored in Object[] and double[][]), so no OO.

There is a good regression test suite and an efficient QA team is testing and finding bugs. I know the techniques how to get it under test from classic books, e.g. Michael Feathers, but that's too slow. As there is a working regression test system I'm not afraid to aggressively refactor the system to allow unit tests to be written.

How should I start to attack the problem to get some coverage quickly, so I'm able to show progress to management (and in fact to start earning from safety net of JUnit tests)? I do not want to employ tools to generate regression test suites, e.g. AgitarOne, because these tests do not test if something is correct.


问:
What hurts maintainability?
For someone who doesn't have much real world experience yet, the notion of maintainable code is a bit vague, even though it follows from typical good practice rules. Intuitively I can tell that code can be well written, but not maintainable if for example it hard-wires information that is subject to constant change, but I still have a hard time looking at code and deciding if it's maintainable or not.

So the question is: what hurts maintainability? What should I look for?

答:
There are many aspects to maintainability, but IMO the most important are loose coupling and high cohesion. Essentially, when you're working with good code, you're able to make small changes here and there without having to keep the whole codebase in your head. With bad code, you would have to take more things into account: fix here, and it breaks elsewhere.

When you have 100+ kLOC of code in front of you, this is crucial. Oft-mentioned "good practice" rules like code formatting, commenting, variable naming, etc. are superficial compared to coupling/cohesion issues.

The trouble with coupling/cohesion is that it's not easy to measure or see quickly. There are some academic attempts to do that, and maybe some static code analysis tools, but not anything I know of that would immediately give a reliable estimate of how hard time you're going to have with the code.

Title: What hurts maintainability?


答:
Duplicated code :

Copy Paste is most probably the single most expensive operation when it comes to maintenance costs of programs.

Why bother move this code to a common component, i'll just copy it over and be done with it  Yes... the programmer probably saved an hour of work or so doing things this way.  However later comes a bug and... yes of course it gets fixed in only half of the running code.  Which means that later still a regression will be logged resulting in yet another fix OF THE SAME THING.

This one sounds obvious but in the grand scheme of things it is insidious.  Programmers look good cause they get more done.  Dev team manager look good cause they delivered on time.  And since the problem is found only much later blame never befalls on the real culprit.

I lost count on how many times I had to halt a release because of such "regressions"  Just now I lost one full day tracking a fix that was already done, get it fixed again and pushing the new build through the hoops.  So yes, one hour time for one dev six months ago (approx CAD 40$) just costed one full day for 1 senior dev + half day for one junior dev + one full day delay in a project already late....

you do the math....

so next one that pulls this on me I swear he'd better run fast caus'i'll be right behind him !!!

Title: What hurts maintainability?

Body:
For someone who doesn't have much real world experience yet, the notion of maintainable code is a bit vague, even though it follows from typical good practice rules. Intuitively I can tell that code can be well written, but not maintainable if for example it hard-wires information that is subject to constant change, but I still have a hard time looking at code and deciding if it's maintainable or not.

So the question is: what hurts maintainability? What should I look for?


答:
While code which breaks the rules in the other answers is certainly worse to maintain, all code is hard to maintain, therefore the less of it you have the better. Defects correlate strongly with amount of code, so the more code you have the more bugs you have. Once code get over a certain size you can't keep your whole design in your head anymore and things get much harder. Lastly more code eventually means more engineers, which means more cost, more communication problems and more management problems.

Though keep in mind that one should not write more complex, but shorter code. The most maintainable code is simple and simply contains no redundancy to keep it as short as possible. Delegating tasks to other programs or API can also be a viable solution as long as the API calls are simple enough.

so in a nutshell, any superfluous code is a maintainability problem

Title: What hurts maintainability?

ContentLicense: CC BY-SA 4.0


问:
Mobile: Native vs. web - Input for discussion on top management level
I have been given the task of producing a compilation of pros, cons and key points on the issue of mobile native applications versus mobile web applications. It will be input for a discussion on top management level.

What are some valid and maybe overlooked topics here?

答:
Obviously (see below) web apps are somewhat easier to implement and you just need one implementation for all types of devices, while native programming requires some changes for different plaforms. However, there are couple of reasons why users might prefer a native application over a web one:

Native application works where coverage is poor.

Users may not want on-line application when roaming; the roaming prices are still absurdly high in much of the world.

In some parts of the world, mobile internet access is still not exactly cheap even in home network, though that's getting better rapidly.

Web applications can't be shown in applications menu on Android and perhaps other platforms as well (bookmark on home-screen is possible).

Web applications can't run in background providing e.g. notifications nor wake up on timer.

There are however lots of problems if you want to have native application on the various platforms. From my first-hand experience:

Android is probably most useful to have. Core can be implemented in C or C++ and we could get all libraries we needed to compile there, but some Java glue is needed. Both Qt and SDL can be used to reduce the amount of platform-specific code. It does not support MIDP (Java ME), but it does support Java, so Java core with Java ME and Android UI is also an option.

iOS (iPhone) is programmed in Objective C, but almost any C++ compiles there just fine. There are Qt and SDL ports that can reduce the amount of platform-specific code. We use SDL there and had to work around some bugs in there. Still saves some work in porting. Java is not supported.

Windows Phone 7. Forget this platform. It's not possible to get C nor C++ code there, only .NET and that is not supported anywhere else. We even tried asking Microsoft for hints how to port to Windows Phone 7 (we have the application running on Windows Mobile currently), but got no useful answer. With the minimal market share this currently has, I'd not bother with it.

Bada is programmed in C++, but the toolchain is a bit flaky, the API is not similar to anything else and we are really struggling to workaround all it's deficiencies. There is a Qt port, but I don't know how far they are; I didn't hear about SDL port yet. We have some specific customer interested in it, otherwise I am not sure whether it would be worth the effort.

Symbian S60. It's still common, but it's not clear what future it has. Nokia's strategy is currently unclear. They still sell phones with S60, but also sell some with MeeGo and announced they will start using Windows Phone 7. It's one of the last platforms still supporting MIDP. It's also officially supported by Qt (Nokia ported it there when they bought it).

MIDP/Java ME. Most new platforms don't support it anyway, platform integration is minimal (i.e. can't run on background, provide notifications etc.) and the UI options are abysmal.

We spent about 6 man-months to get our application running on each new platform. Granted, it's pretty complex application, but on the other hand it has custom GUI, so we only need to display a framebuffer and don't redo all dialogs. So don't count with less than 3 man-months for anything non-trivial. You might get below that with Qt (we don't use it (we do custom GUI, so there is not that much point) and started to use SDL too late, so we don't use it on some platforms where we could), but some of the ports are still beta and some don't yet exist. I don't expect working around quirks of the various mobile browsers to take that much.

Last, many platforms support developing in Flash, but I have no experience with that. I do have experience with Flash on some custom embedded device and it was not too pleasant (but it had custom OpenGL-only display driver and they had some trouble porting the player at all, so we ended up doing quite a lot of performance tuning). Might be an option for something simple though.

In the end, you should first define your requirements, have somebody look at the options and make estimates (means to spend a few weeks on it!) and only than discuss it at top management layer. Top management can't do reasonable decision without numbers that are at least in the right ballpark.


答:
The only true way of learning what is maintainable code is to get involved in maintaining a large codebase (both bug fixes and feature requests).

You will learn about:

loose coupling and high cohesion

duplicated code

regression tests and refactoring: with an efficient regression test suite, you feel more confident in changing things.

observability and error logging: if the software traces what is going wrong, the bug is more easily located.

accurate documentation: not the kind that is written once at the beginning of the project and never modified.

undocumented obfuscated code taking the form of a supposedly brilliant design idea or optimizations ala Fast inverse square root.

oral tradition transmitted from one generation of developers/maintainers to the next one.

Title: What hurts maintainability?


问:
As a software engineer, who should I be following on Twitter?
Who in the software engineering and software development fields uses Twitter to tweet about relevant happenings in the field?</p>

答:
A few others no-one has mentioned yet

Alan Cooper

Roy Osherove

Mike Cohn

WardCunningham

Elisabeth Hendrickson


答:
I believe that code that isn't Unit Tested hurts maintainability. When code is covered by unit tests, then you can be confident that when you change it you know what you are breaking because the associated unit tests will fail.

Having unit tests along with the other suggestions here makes your code robust and you make sure you know that when you change, exactly what impacts you're having.

Title: What hurts maintainability?


问:
What to search/research to learn more about this way of coding Java?
What should I search/research if I'm looking for how to get started with translating database tables to Java code? For instance, if I have a one-many relationship in the database and I want to translate that to java code...what is that process called? </p>

<p>I'm really looking for just plain Java code example and not any tools at the moment. </p>

答: If I understand your question correctly I think you are looking for the basic object/relational mapping patterns. They will tell you about tested and proven ways of mapping different types relationships between OO code and relation models, as well just basically handling the mismatch between an object in the application code and a row in the DB. The best place to start learning about these patterns is Martin Fowler's book Pattern of Enterprise Application Architecture, or if don't want a book his web site: http://martinfowler.com/eaaCatalog/</p>


问:
Is it misguided to label mobile web applications as cross platform?
Yes, you can access the mobile web site from a range different mobile devices, but the platform, I suppose, is still the web server and the client browser (the latter ideally being the "same" on any device).

When talking mobile and cross platform I am thinking frameworks such as PhoneGap and Appcelerator Titanium, but still with a reluctance to call it cross platform as the deployed products are not the same. I guess I am hung up on the idea that it has to be directly equivalent to the Java virtual machine to call anything cross platform, but maybe I am the one who is misguided.

What is the general opinion?

答:
There is no such thing as true or lesser cross platform. Any application that is essentially the same in more than one platform (or devices or browsers) can be considered cross platform. It doesn't really matter if the platforms are two or n, or if the applications are exactly the same, cross platform is a technical attribute, not a measurement of quality.

But if there's an actual need to evaluate a technical attribute, such as when comparing solutions, you should limit the evaluation to the target domain. PhoneGap and Titanium are currently the most cross platform solutions for native mobile applications, as the JVM is for other domains.


答: In my experience, a major factor in maintainability is consistency. Even if the program works in strange and absurd ways, it's still easier to maintain if it does it the same way everywhere. Working with code that uses different naming schemes, design patterns, algorithms etc. for similar tasks, depending on who wrote it when, is a major PITA.

Title: What hurts maintainability?


答:
I think that maintainability is also tightly coupled with problem complexity, which can be a subjective matter. I've seen situations where the sole developer was able to successfully maintain and consistently grow a large code base, but when others step into his place, it appears an unmaintainable mess -- just because they have quite different mental models.

Patterns and practices really help (see other answers for great advice). However, their abuse can lead to even more problems when the original solution is lost behind facades, adapters and unnecessary abstractions.

In general, understanding comes with experience. A great way to learn is to analyze how others have solved similar problems, trying to find strong and weak points in their implementation.

Title: What hurts maintainability?


答:
Demands from those paying for the software can go a long way or a visionary leader. Management will see it as important and not frivilous. UI design should be at the front of development and not something left at the end. It takes time, a lot of trial and error, and a willingness to allow it to change. This is true of all creative tasks.

Not all developers are going to be good at it. They may need some training. The easiest way to accomplish it is to hire people who are good at it in the first place and stay out of their way.


问:
Organizing large Javascript applications - The view layer
Today Javascript application of a relevant size become more and more common, and as the need arises, certain patterns are identified to manage the code complexity.

I try to follow good advice, but I have some trouble in organizing the view layer of an application I am writing. While the other layers are nicely decoupled, I have a big blob for the UI that I would like to avoid. To make things clear, I am not talking of application the size Osmani (see the link above) considers - like Gmail - but still big enough to deserve a slightly better architecture.

My problem is that I have a lot of UI elements that I have to place. All these elements can have margins, paddings and so on, and I need to explicitly set their size, as the UI has a lot of constraint that are not expressible by CSS (for instance, some images have to be sized to that an integer number of them appears in a row, without blank space at the end). As if this was not enough, the size of some elements depends on how much space their container allows, and this may depend on the size of other elements and so on.

What I am doing right now is to compute the size of all elements every time the window size changes. I start from the first one, which I can compute freely. As soon as this is placed, I fire an event which trigger the computation of the second one and so on.

This approach more or less works, but is ugly as hell. Every function is full of code like

```<code>function resizeFoo() {
    var parent = $('#foo').parent(),
        parentWidth = parent.width(),
        availableWidth = parentWidth - parseInt(parent.css('padding-left'), 10);

    $('#foo').width(availableWidth);
}
</code>```

only much longer. As soon as I add some right padding to #foo's parent, I have to update this. Of course, I could subtract the padding from both sides right from the start, making it event longer.

Are there any useful patterns to handle complex UI sizing and positioning requirements, so that I can reorganize all of the above mess into something meaningful?

答:
I'm posting this as an answer instead of a comment, because it's somewhat big for a comment, even though it's not a true answer.

As I said in my comment, component frameworks like ExtJS and Dojo solve this problem. They can serve as inspiration. I'm personally familiar with ExtJS, so I'll give some pointers on where to find what you need for ExtJS.

Essentially everything in the UI of an ExtJS app is a subclass of Ext.Component (= box on screen), and Ext.Container (component subclass that can contain components). The Ext.Container lays out its child components using a layout (subclass of Ext.layout.Layout). Layouts use a combination of CSS, event-driven javascript, and structural markup (e.g. table tags) to achieve their goal. You always use the layout system, direct positioning with CSS is not "the ExtJS way".

To find out how they implement this:

Explanation about the component model and lifecycle: http://www.sencha.com/learn/components/

An explanation about the layout system: http://www.slideshare.net/senchainc/layouts-5971880

The ExtJS API docs: http://docs.sencha.com/ext-js/4-0/#!/api

In the API docs you can click on the title of a component's API page to see its source code.

If you read your way through all that, you'll get some insight into how ExtJS solves this problem. It's not a simple mechanism, but it's a very scalable system.


答:
Almost everything which violates some good software development principles hurts maintainability. If you look at some code and want to assess how maintainable it is, you can choose some specific principles and check how much it violates them.

The DRY principle is a good starting point: How much information is repeated in the code? YAGNI is also very helpful: How much functionality is there which is not needed?

If you do some research on DRY and YAGNI you will find other principles, which are applicable as general software development principles. If you are using some object-oriented programming language and want to be more specific, the SOLID principles give some good guidelines for good object-oriented design.

Code which violates any of those principles tends to be less maintainable. I put an emphasis on tend here, because – generally spoken – there are situations where it is legit to (mildly) violate any kind of principle, especially if it was made for the sake of maintainability.

What also helps is to look for code smells. Take a look in Refactoring - Improving the Design of Existing Code from Martin Fowler. There you can find examples for code smells, which sharpens your sense for less maintainable code.

Title: What hurts maintainability?


答:
Lack of proper unit-tests

Lack of proper integration tests

Lack of proper benchmarking performance tests

YAGNI

3 and 4 are, in my experience, the most common offenders in real-life systems. Not having a proper performance/loadtesting suite makes it impossible to benchmark the impact future changes will have on performance and stability and it will cause degradation much quicker and force expensive refactorings more often. YAGNI (what's called "waste" in the Lean vocabulary) will make a system much harder to refactor and maintain as a lot of time will be wasted (pun intended) on maintaining code and backwards compatibility for features that aren't even used.

Title: What hurts maintainability?


答:
We are taking a mobile web app approach, and making use of jquery-mobile.

It simply halves the development for us as we won't have to develop to the two major platforms separately (android and iOS). This means we do not need to care about "browser quirks" as the jquery team handles them.

Also, we are already proficient with javascript and jquery.

We may also create a very basic app for each platform that simply opens the mobile website.

Title: Mobile: Native vs. web - Input for discussion on top management level

Body:
I have been given the task of producing a compilation of pros, cons and key points on the issue of mobile native applications versus mobile web applications. It will be input for a discussion on top management level.

What are some valid and maybe overlooked topics here?


问:
Why isn't rich code formatting more common?
I was reading Code Complete and in the chapter on layout and style, he was predicting that code editors would use some sort of rich text formatting. That means, instead of code looking like this

```<code>Procedure ResolveCollisions
{ Performs a posteriori collision resolution through spatial partitioning algoritm }
(
  CurrentMap : SpriteContext,
  PotentialColliders: SpriteList
)
var Collider  : Sprite,
    Collidee  : Sprite,
    Collision : SpriteCollision
begin
  DoStuff();
end.
</code>```

it could look something like this:

Procedure ResolveCollisions

Performs a posteriori collision resolution through spatial partitioning algorithm

Parameters

CurrentMap : SpriteContext

PotentialColliders : SpriteList

Local Variables

Collider  : Sprite

Collidee  : Sprite

Collision : SpriteCollision

```<code>    DoStuff();
</code>```

I've seen syntax coloring and highlighting and even parentheses coloring, but nothing that looked like this in actual code. I was wondering if this sort of thing actually ever existed, or perhaps if it was decided that it didn't have enough benefit or that it was an entirely bad idea.

Have any of you seen richly-formatted code like this before, or know if the idea was ever considered and eventually rejected?

答:
Tools such as Doxygen or JavaDoc already perfom rich text code formatting. They add code hypertext as well for browsing purpose. You don't need to insert special tags for basic formatting.

This is not WYSIWYG though.


答:
I have a couple of "nightmares" that although I'd never put them on the top of this list, they have definitely caused some struggle.

The mega object/page/function: (The so called "God Object" anti-pattern): Putting everything in one object's method (mostly Java world), page (mostly php and asp), method (mostly VB6).

I had to maintain code from a programmer who had in one php script: html code, business logic, calls to mysql all messed up.
Something like:

```<code>foeach( item in sql_query("Select * from Items")) {
<a href="/go/to/item['id']">item['name']</a>
}
</code>```

Relying on obscure features of the language that might not be well known or are about to become obsolete.

It had happened again with php and preset variables. Short story: for some settings of php v4 a request parameter was auto assigned to a variable.
so http://mysite.com?id=42
would "magically" generate varaible $id with value '42'.

This was a maintenance nightmare not only because you could not possibly know where data came from but also because php v5 completly removed it (+1), so people trained after that version, would not even understand what was going on and why.

Title: What hurts maintainability?

Body:
I have a couple of "nightmares" that although I'd never put them on the top of this list, they have definitely caused some struggle.

The mega object/page/function: (The so called "God Object" anti-pattern): Putting everything in one object's method (mostly Java world), page (mostly php and asp), method (mostly VB6).

I had to maintain code from a programmer who had in one php script: html code, business logic, calls to mysql all messed up.
Something like:

foeach( item in sql_query("Select * from Items")) {
<a href="/go/to/item['id']">item['name']</a>
}

Relying on obscure features of the language that might not be well known or are about to become obsolete.

It had happened again with php and preset variables. Short story: for some settings of php v4 a request parameter was auto assigned to a variable.
so http://mysite.com?id=42
would "magically" generate varaible $id with value '42'.

This was a maintenance nightmare not only because you could not possibly know where data came from but also because php v5 completly removed it (+1), so people trained after that version, would not even understand what was going on and why.


答:
"pushing any creative boundaries" means a long string of failures.  That's the way creativity works.  Creative people build lots of things that get thrown away, cut up, deleted, smashed or otherwise ignored.  A few things, however, are quite cool and novel.  They're novel because they're a singular success after a long string of failures.

The only effective strategy for encouraging developers to push their boundaries is to permit lots of failures.

That means a generous "research" budget to cover all those failures.  It means reworking and reworking solutions so they turn into that "cool, clever UI".

The idea that "they just came up with based on something that they were just playing with" is misleading.  It doesn't work that way.  It's patience, hard work and a sense of perspective.  It's 99% perspiration and 1% inspiration.

http://en.wikiquote.org/wiki/Thomas_Edison

"Genius is one percent inspiration, ninety-nine percent perspiration."


问:
What is the difference between the "lib" and "vendor" folders?
Regarding source folder hierarchy, there are always some common features, such as the src, doc or test folders, which have rather easy-to-understand contents.

However, I realized that big projects have both a lib and vendor folders, while I had always thought they were the same, as their names hint at including “third-party libraries from external vendors”. Though, seeing both in the same project means there is a difference.

I couldn't find any information nor on Google nor on sources such as the Filesystem Hierarchy Standard, even though this is actually a somehow common practice.

Here is a more detailed example with Symfony: once you create a project, you get a lib folder at the root of your project. In this folder, the following structure is found:

```<code>lib
+--filter
+--form
+--…
+--vendor
    +--simpletest
    +--symfony
</code>```

Here, the symfony folder contains all Symfony's core.

答:
When I see a lib or libraries directory, I think of:

Libraries, not plugins, modules, etc.

OOP instead of procedural, where that's applicable (i.e. PHP)

When I see a vendor directory, I think of:

Libraries, plugins, modules, components, etc. Not just libraries, but anything that's provided by a third party.

And stuff that's not code, like an icon set.

When I see lib and vendor directories, I think of a few distinctions:

lib holds only libraries, vendor may hold anything really,

lib is where I should put my libraries, vendor where I should put anything third party (including code by the original author),

lib is where libraries by the original author of the project are located (if that's not me), whereas vendor is where the original author put third party anything.

You can safely assume that whatever is in lib is licensed under the same license as the rest of the project.

Whichever one of the above applies, is reason enough to have different folders. AFAIK there is no generally accepted practice. Some communities have community wide common practices, but that's just about it.

As for the specific Symfony example: Symfony is a framework and I think what the developers are trying to say is that in a Symfony application the framework's core libraries are vendor code, i.e. coming from a third party and not from the original author of the application (you).


答:
Ironically, explicit attempts to "future-proof" a system often make it harder to maintain.

Not hardcoding magic numbers or strings is one thing, but take it further and you start putting logic into configuration files. Which means you're adding a parser and an interpreter for an obscure new (and probably badly-designed) programming language to your maintenance burden.

Layers of abstraction and indirection added for no other reason that some component might be changed in the future and you don't want to depend on it directly are pure maintenance poison and a prime example for YAGNI. The SLF4J FAQ explains the problems with this all-too-common idea:

Given that writing a logging wrapper does not seem that hard, some
  developers will be tempted to wrap SLF4J and link with it only if it
  is already present on the classpath, making SLF4J an optional
  dependency of Wombat. In addition to solving the dependency problem,
  the wrapper will isolate Wombat from SLF4J's API ensuring that logging
  in Wombat is future-proof.

On the other hand, any SLF4J-wrapper by definition depends on SLF4J.
  It is bound to have the same general API. If in the future a new and
  significantly different logging API comes along, code that uses the
  wrapper will be equally difficult to migrate to the new API as code
  that used SLF4J directly. Thus, the wrapper is not likely to
  future-proof your code, but to make it more complex by adding an
  additional indirection on top of SLF4J, which is an indirection in
  itself.

The last half-sentence hints at the sweet irony that SLF4J itself is a logging wrapper to which this argument applies just as well (except it's making a credible attempt to be the only wrapper you need that can sit on top of and beneath all other common Java logging APIs).

Title: What hurts maintainability?


答:
I'm afraid to say that this does exist.

In the past I've worked on some Centura (also known as Gupta or SQL/Windows - an old "4GL") code. It wasn't really possible to edit Centura code in a standard editor like notepad do to the extreme level of formatting required.

Although it may seem like it would be a good idea to have a source file formatted like this, I found developing to be quite restrictive and painful.

Additionally, the formatting often caused problems when merging in source control.

Title: Why isn't rich code formatting more common?

Body:
I was reading Code Complete and in the chapter on layout and style, he was predicting that code editors would use some sort of rich text formatting. That means, instead of code looking like this

```<code>Procedure ResolveCollisions
{ Performs a posteriori collision resolution through spatial partitioning algoritm }
(
  CurrentMap : SpriteContext,
  PotentialColliders: SpriteList
)
var Collider  : Sprite,
    Collidee  : Sprite,
    Collision : SpriteCollision
begin
  DoStuff();
end.
</code>```

it could look something like this:

Procedure ResolveCollisions

Performs a posteriori collision resolution through spatial partitioning algorithm

Parameters

CurrentMap : SpriteContext

PotentialColliders : SpriteList

Local Variables

Collider  : Sprite

Collidee  : Sprite

Collision : SpriteCollision

```<code>    DoStuff();
</code>```

I've seen syntax coloring and highlighting and even parentheses coloring, but nothing that looked like this in actual code. I was wondering if this sort of thing actually ever existed, or perhaps if it was decided that it didn't have enough benefit or that it was an entirely bad idea.

Have any of you seen richly-formatted code like this before, or know if the idea was ever considered and eventually rejected?


问:
Should we bind view to a model property or ViewModel should have it's own..?
I am starting a project with following technical environment :
.Net 4.0, Entity Framework 4.0, WPF with MVVM Architecture

I saw lots of examples on the net, some books with this environment. In some of the examples authors had this Idea :

Viemodel will have an instance of Model class (Entity Framework Entity e.g. Person)

Bind the WPF view controls to the properties of Model

While some authors did :

Viemodel will expose all the properties of the model.

Bind the WPF view controls to the properties of ViewModel rather than to the model
directly.

So is it a good idea to let the view bind properties from model rather than viewmodel exposing its own? Or which is more preferred?

答:
The point of a ViewModel is that it is a model of the View.

You should be binding the ViewModel to the View, not any Model properties (not directly, anyways).


答:
Where Jan Hudec gives a rather detailed/operational overview on the matter, I'm wondering if this is what you are looking for at the top management level, regardless of the requirements?

Maybe other factors come in to play, like time to market (web apps should be alot quicker as opposed to developing for a number of platforms), required skill set (standard web tech vs java objective c etc.), maintenance cost and so on.


答:
I think what you are seeing is a concept called bind through, that is if your model has a property called name and your view-model exposes this property with no additional editing or converting then you can bind through to the model so it would be.

Pseudo Code:

```<code> {Binding: MyViewModel.MyModel.Name}
</code>```

This is done to reduce the amount of 'Fluff' properties on the view model, unfortunately it is also a bad idea in the long term. The concept of a view model is to ensure that the view does not take a dependency to the model. By binding through you now must ensure that your model contains a property called name otherwise your implementation will break.

If you only bind as far as the view-model however, you can change out the model and the view would never know as it will only ever see the property named Name on the view-model.

Now this can be mitigated in certain circumstances were your model is based off an interface. So if the interface had a IBaseDetails which exposed the property ModuleName then you could:

Pseudo Code:

```<code> {Binding: MyViewModel.MyModel.ModuleName}
</code>```

As long as any of the Models you make satisfy the IBaseDetails interface, your golden, be aware however that this is an edge case and in general you are 90% always better to wrap your view-model around any models it covers.

Title: Should we bind view to a model property or ViewModel should have it's own..?

Body:
I am starting a project with following technical environment :
.Net 4.0, Entity Framework 4.0, WPF with MVVM Architecture

I saw lots of examples on the net, some books with this environment. In some of the examples authors had this Idea :

Viemodel will have an instance of Model class (Entity Framework Entity e.g. Person)

Bind the WPF view controls to the properties of Model

While some authors did :

Viemodel will expose all the properties of the model.

Bind the WPF view controls to the properties of ViewModel rather than to the model
directly.

So is it a good idea to let the view bind properties from model rather than viewmodel exposing its own? Or which is more preferred?

Body:
I think what you are seeing is a concept called bind through, that is if your model has a property called name and your view-model exposes this property with no additional editing or converting then you can bind through to the model so it would be.

Pseudo Code:

 {Binding: MyViewModel.MyModel.Name}

This is done to reduce the amount of 'Fluff' properties on the view model, unfortunately it is also a bad idea in the long term. The concept of a view model is to ensure that the view does not take a dependency to the model. By binding through you now must ensure that your model contains a property called name otherwise your implementation will break.

If you only bind as far as the view-model however, you can change out the model and the view would never know as it will only ever see the property named Name on the view-model.

Now this can be mitigated in certain circumstances were your model is based off an interface. So if the interface had a IBaseDetails which exposed the property ModuleName then you could:

Pseudo Code:

 {Binding: MyViewModel.MyModel.ModuleName}

As long as any of the Models you make satisfy the IBaseDetails interface, your golden, be aware however that this is an edge case and in general you are 90% always better to wrap your view-model around any models it covers.