问:
Is it bad interview practice to have candidates write a linked-list implementation?
Reading this site and SO I've seen many stories of interview questions and answers saying a candidate had to implement a linked list from scratch. Usually this is a "gimme" exercise for programming role candidates like writing FizzBuzz. The idea is that if the candidate can't do this, they can't program and should be rejected almost immediately.

However, I can't help but think this could be a poor practice for the following reasons:

Modern higher level languages like C# and Python natively use lists extensively; writing your own linked list object would be only required under unusual circumstances and even then probably ill-advised.

Lower level languages like C++ have standard libraries with iterators/list containers and objects.

In light of the first two points, coders can go years without even thinking about implementing a list (linked, doubly-linked, etc) themselves. Some may not even really see such things since college days.

Computing power also isn't the factor it was years ago, so efficiency via pointers isn't the issue it used to be (in general).

A simple web search of something like "linked list example" would bring up plenty of code examples that could just be memorized and spat back out, not really indicating the true competence of the applicant.

I should say that using a linked list to lead to open-ended questions/discussions of candidates' problem solving/critical thinking abilities is mostly likely a really good interview practice. Any way an interviewer can really see what an applicant is like and how they think is massively beneficial.

I think this binary approach of "no linked list code, no job" for programmers working on a desktop or web application is a bit outdated. It could also be quite harmful; a candidate who can't remember how to properly work with the head of a list could be an otherwise excellent coder and co-worker and be lost in the mix. Thoughts?

EDIT: There are many (good) comments suggesting that whether this is a good or bad question to ask depends on the context of the job. I strongly agree, so let me rephrase this question: Implementing a linked-list is a common interview question for a wide range of coding jobs, similar to questions like FizzBuzz or writing a recursive function for calculating factorials. Does this question have enough utility to be used commonly for evaluating programming candidates across the board? Or should considered a bad question to ask except for "Senior Developer, Embedded Linked Lists Team" positions?

答:
Writing a linked-list implementation is a good interview question, because it will reveal a lot about the candidate's way of coding:

Does he know what an API is? Can he use other people's code? Can he write code so other people can use it?

Does he know what a Linked List is? Does he know Collections, Data Structures, Algorithms?

If he doesn't even know what methods a Linked List should offer, you know he probably never used one, or knows when to use one.

How does he handle the problem? Does he start with an analysis first, a small specification, some tests beforehand? Or does he just start hacking away happily?

Does he handle edge cases? What about removing the last node from the Linked List? What if someone tries to add a reference to the linkedlist itself to the linkedlist, and then deletes the whole thing?

Does he handle exceptions? Each programming language has their own conventions for handling exceptions: in Java, you'll expect a LinkedList to throw a NoSuchElementException when you do a getFirst() on an empty list. Other languages might return undefined, -1 or a constant.


问:
How would Functional Programming proponents answer this statement in Code Complete?
On page 839 of the second edition, Steve McConnell is discussing all the ways that programmers can "conquer complexity" in big programs. His tips culminate with this statement:

"Object-oriented programming provides a level of abstraction that applies to algorithms and data at the same time, a kind of abstraction that functional decomposition alone didn't provide."

Coupled with his conclusion that "reducing complexity is arguably the most important key to being an effective programmer" (same page), this seems to pretty much a challenge to functional programming.

The debate between FP and OO is often framed by FP proponents around the issues of complexity that derives specifically from the challenges of concurrency or parallelization. But concurrency is certainly not the only kind of complexity software programmers need to conquer. Perhaps focusing on reducing one sort of complexity increases it greatly in other dimensions, such that for many cases, the gain is not worth the cost.

If we shifted the terms of the comparison between FP and OO from particular issues like concurrency or reusability to the management of global complexity, how would that debate look?

EDIT

The contrast I wanted to highlight is that OO seems to encapsulate and abstract away from the complexity of both data and algorithms, whereas functional programming seems encourage leaving the implementation details of data structures more "exposed" throughout the program.

See, e.g., Stuart Halloway (a Clojure FP proponent) here saying that "the over-specification of data types" is "negative consequence of idiomatic OO style" and favoring conceptualizing an AddressBook as a simple vector or map instead of a richer OO object with additional (non-vectorish & non-maplike) properties and methods. (Also, OO and Domain-Driven Design proponents may say that exposing an AddressBook as a vector or map overexposes the encapsulated data to methods that are irrelevant or even dangerous from the standpoint of the domain).

答:
"Object-oriented programming provides a level of abstraction that applies to algorithms and data at the same time, a kind of abstraction that functional decomposition alone didn't provide."

Functional decomposition alone isn't enough to make any sort of algorithm or program: you need to represent the data too. I think the statement above implicitly assumes (or at least it can be understood like) that the "data" in the functional case is of the most rudimentary kind: just lists of symbols and nothing else. Programming in such a language is obviously not very convenient. However, many, especially the new and modern, functional (or multiparadigm) languages, such as Clojure, offer rich data structures: not only lists, but also strings, vectors, maps and sets, records, structs - and objects! - with metadata and polymorphism.

The huge practical success of OO abstractions can hardly be disputed. But is it the last word? As you wrote, concurrency issues are already the major pain, and the classical OO contains no idea of concurrency at all. As a result, the de facto OO solutions for dealing with concurrency are just superimposed duct tape: works, but it's easy to screw up, takes considerable amount of brain resources away from the essential task at hand, and it doesn't scale well. Maybe it's possible to take the best of many worlds. That's what modern multiparadigm languages are pursuing.

ContentLicense: CC BY-SA 3.0


问:
How to incrementally update a database when deploying a website?
We use JSF over Tomcat along with a backing proprietary DB.

I want to know how the addition of new database fields or/and stored procedures should be handled when we deploy a new version of the application.

We deploy by sending a WAR file to the hosting Team, as such our WAR should be able to
setup the stored procedure when it starts.

What are the possible appropriate strategies to be able to incrementally update the database?

答:
Jelayn's answer is pretty good, and represents roughly standard practice, esp in the Rails world where a similar solution is baked into the framework. However, the state of the art, as practiced by Facebook, Flickr, Heroku, and IMVU - a pioneer in this - is a bit more advanced.

The problem with the standard practice is that it assumes you can write 2 versions of code, and switch from one to the other with a quick migration as you deploy. There's lots of problems with this:

If you have a lot of data, a migration will take time. It takes months for Facebook to migrate data, but unless you have very little data, it's rare for the migration to be instant. The solution to this is to migrate slowly. IMVU pioneered the strategy here:

instead of migrating the table, make a separate table with the new schema

when a row is read that isn't present in the new table, migrate only that row and save it to the new table. You can then delete the old row.

also run a background job that runs the migrations in batches (watch out for conflicts!)

during a migration, your code needs to support the old schema and the new one. So you should write the code that supports both, then migrate, then remove the old code in a separate deploy.

upon a failed migration, you should decide whether you can migrate in both directions or just forwards. IMVU goes forward only I think - so if they have a bug in their migration, they fix it instead of rolling it back. I personally prefer fixing, but there are good arguments for rolling it back too.

This stuff is all highly related to continuous deployment as well, and a lot of those strategies can help. For example, a common CD technique is selectively enable new code only for a small user base to give it more testing, and only then enable it for larger and larger audiences (typically, you use a DB setting for each feature). This practice allows you gain more confidence in your migrations,  esp when they are more complicated than just adding a field, and without betting all your data on a relatively untested migration.

Source: market research and talking to customers while making my Continuous Integration and Deployment start-up.


问:
Is Javascript a Functional Programming Language

Is Javascript a functional language? I know it has objects & you can do OOP with it also, but is it also a functional language, can it be used in that way?

You know how OOP became/seems like the next evolution in programming, does that mean that 'Functional Programming' is the next evolution(Note: this is NOT a prompt for opinion BUT a prompt for a factual evidence based answer, & this note is more for the moderators than the contributors ;) ).

I learn best through examples, maybe someone could show performing the same task in a OOP way & then in a Functional Programming way for myself to understand & compare what functional programming does/is.

I don't really completely understand 'Functional Programming' to be honest :P So comparing Javascript to functional programming may be totally incorrect.

To put Functional programming in laymans terms: is it simply the benefit of abstration THROUGH using anonymous functions?

Or is that way too simple? In a simple way, OOP is the benefit of abstraction through objects, but I believe thats being a little too simplistic to describe OOP.

Is this a good example of functional programming?...

Javascript OOP Example:

```<code>// sum some numbers
function Number( v )
{
  this.val = v;
}

Number.prototype.add( /*Number*/ n2 )
{
    this.val += n2.val;
}
</code>```

Functional programming example:

```<code>function forEach(array, action)
{
   for (var i = 0; i < array.length; i++)
       action(array[i]);
}

function add(array)
{
    var i=0;
    forEach(array, function(n)
    {
        i += n;
    });
    return i;
}

var res = add([1,9]);
</code>```

答:
No.

JavaScript is an object-oriented language first and foremost.

That is not to say that you can't write JavaScript programs in a functional style, since you can adopt a functional style in any Turing complete language if you try hard enough. You can do functional programming in assembler if you like. But this does not make every language functional. You might equally as well call Haskell imperative, or Java a logic programming language - if you took this approach, the terms would soon become meaningless.

IMO the way to classify a language into the appropriate paradigm is to consider:

What is the dominant style enabled by the language constructs (clearly OOP for JavaScript, functional languages instead emphasise functions and immutable data values)

What paradigm is supported in the language's core libraries (again clearly OOP for JavaScript)

What features are disabled or discouraged in the language (functional languages discourage or forbid mutable variables, which is not the case for JavaScript)

What development style is prevalent in the community of developers using the language (again, OOP is clearly prevalent in the JavaScript world)

Personally I find it rather amusing that lots of people like to claim a language is "functional" just because it is a trendy term at the moment :-)

If you want a slightly long but entertaining perspective on programming paradigms through the years, it's worth watching Uncle Bob Martin's video "The Last Programming Language". For me the great insight from this talk was that programming paradigms are defined by what features they take away, not what features they put in......


答:
In my about 10 years so far programming professionally (and around another ten years as a hobby), I don't think I have ever needed to implement a linked list. If someone asked me to do it during an interview, I might counter by asking if that's something I will be doing regularly on the job.

For sure, there almost certainly are jobs out there where you will need to write more-or-less-cleanroom implementations of commonly known algorithms - like implement a linked list from scratch. But for most programming jobs, what specific value does it have for the company that a candidate can do it during an interview? Is it really so important in such a setting that the candidate provides a perfect implementation which handles edge cases correctly, reports failures according to common practice in the language or framework, and so on? Or can you overlook that and instead focus on how they actually approach a problem that they perhaps haven't been faced with in 10-20 years?

When I interviewed for my current job, I had very little experience with the technology stack in use at the company. Now, a few years later, I regularly have colleagues come to me and ask questions not just about the products, the implementation of them, and the standards implemented by them, but also about much more general programming problems (just yesterday I was asked what the implications were of a circular dependency in a default constraint in SQL Server in the context of a particular table and its usage in our case - reasoning through it, it turned out that there were no implications in that particular case). I didn't need a brand new linked list implementation for that, either.

Ask questions that are relevant for the work that the candidate is likely to be assigned, and try to get an idea of how they feel about picking up new knowledge. How would they go about figuring out the meaning of some obscure syntax they have never seen? (If you are a C shop, for example, then you might try a question involving trigraphs.) For a programming position, do they regularly read or contribute to forums such as Stack Overflow? If they were asked to perform some task in a programming language or framework they have little or no experience with (say, if you are primarily a Java shop, what about Clojure or .NET?), then how would they approach the problem? Maybe take a real bug out of your bug tracker (might even be one that's long since resolved) and ask them how they in general terms would approach solving it, and be ready to explain the relevant parts of the product in question.

If the candidate can handle business-case-relevant types of problems and has a good attitude toward learning new things, that's probably a much better indicator of fit for that particular position than being able to provide canned responses to well-known questions, whether those questions are about FizzBuzz, linked lists, or something else. Throw in how well the candidate fits with the team and I would think that you are on fairly safe ground.

Title: Is it bad interview practice to have candidates write a linked-list implementation?

Body:
Reading this site and SO I've seen many stories of interview questions and answers saying a candidate had to implement a linked list from scratch. Usually this is a "gimme" exercise for programming role candidates like writing FizzBuzz. The idea is that if the candidate can't do this, they can't program and should be rejected almost immediately.

However, I can't help but think this could be a poor practice for the following reasons:

Modern higher level languages like C# and Python natively use lists extensively; writing your own linked list object would be only required under unusual circumstances and even then probably ill-advised.

Lower level languages like C++ have standard libraries with iterators/list containers and objects.

In light of the first two points, coders can go years without even thinking about implementing a list (linked, doubly-linked, etc) themselves. Some may not even really see such things since college days.

Computing power also isn't the factor it was years ago, so efficiency via pointers isn't the issue it used to be (in general).

A simple web search of something like "linked list example" would bring up plenty of code examples that could just be memorized and spat back out, not really indicating the true competence of the applicant.

I should say that using a linked list to lead to open-ended questions/discussions of candidates' problem solving/critical thinking abilities is mostly likely a really good interview practice. Any way an interviewer can really see what an applicant is like and how they think is massively beneficial.

I think this binary approach of "no linked list code, no job" for programmers working on a desktop or web application is a bit outdated. It could also be quite harmful; a candidate who can't remember how to properly work with the head of a list could be an otherwise excellent coder and co-worker and be lost in the mix. Thoughts?

EDIT: There are many (good) comments suggesting that whether this is a good or bad question to ask depends on the context of the job. I strongly agree, so let me rephrase this question: Implementing a linked-list is a common interview question for a wide range of coding jobs, similar to questions like FizzBuzz or writing a recursive function for calculating factorials. Does this question have enough utility to be used commonly for evaluating programming candidates across the board? Or should considered a bad question to ask except for "Senior Developer, Embedded Linked Lists Team" positions?


答:
I dont think for a regular programming job should be a question that eliminates a candidate. But its a good one to see if you are dealing with a really senior programmer or someone who just has been monkey coding forms for a lot of years. And even so, it shouldnt be a fundamental criteria for choosing a programmer. Maybe is a great programmer with bad memory and hasnt read the words "linked list" on years (or doesnt remember the name) but still can do good apps.

So, as some said, if is going to be a job that need to work with linked list and a lot of fancy algorithms, etc.. then ok. Is if for the usual input data on a form, validate and show is kinda useless and unfair.


问:
How to manage github issues for (priority, etc)?
I'm new to github, and am looking for advice on how to manage issues.  I'm used to having priority and other ordering options but see that none exist.

How do others manages issues during the lifecycle of a bug/feature?

Thanks in advance.

答:
The GitHub issue tracker is quite flexible. There is indeed no priority, nor ordering. It revolves around three major pillars: Assignments, labels and milestones.

You can "tag" issues with labels you create (in a similar way than Gmail labels). For instance: "bug", "feature-request", "todo", "question", ... One issue can be tagged with different labels.

You can "package" several issues into a milestone. A milestone is made of a title (a version number for instance) and an optional delivery date.

Each issue can be assigned to a collaborator (contributor or organization member) of the repository. You can even summon a collaborator in a comment using a @ followed by its GitHub login.

Eventually, thanks to the sidebar, you can "filter" the list of issues to help you manage it.

A full blog post "Issues 2.0" on this subject will give you a more detailed view of the features.

OwnerDisplayName: djf

OwnerDisplayName: nulltoken


问:
How do I approach a coworker about his or her code quality?
I work on a new venture at a large enterprise software company (3000+ programmers). In my group, we have a bunch of projects and people usually work on several projects over the course of a year.

I just started work on a project that has been previously maintained by a buddy of mine (consultant who's been with us for 3+ years) to add some features. I got into the code, and the quality was really quite poor. Whether it was on the UI frontend or the services backend, the code simply wasn't indented, there were hundreds of lines commented out for no apparent reason, documentation was basically non-existent, coding standards weren't applied consistently (e.g. mixing camelCase and under_scored_variables), variable names were unintelligible, datatype choices were wrong, etc. etc.

I'm very much a non-confrontational person, so I don't want to attack my coworker, but I also don't just wanto to go to my boss and complain about his performance. What are the kinds of things I could say to politely mention that the code is poorly structured?

EDIT:

I want to clarify that while I understand there is an element of "Everyone else's code sucks" to all programmers, when I see something like this (names are chosen on purpose and some details left out/changed in this example):

```<code>public void doCalculate(Object argument) {
  if (argument instanceof String) {
    String argument2 = (String) argument;
    if (argument2 == "DataBase") {
      // do something
    } else {
      long argument3;
      try {
        argument3 = Long.parseLong(argument2);
      } catch (Exception e) {
        argument3 = -1;
      }
      // do something completely unrelated
    }
  }
}
</code>```

I think it's objectively fair to say that this is not a good idea. Furthermore, I'm not dealing with a newbie here (I'm only coding 3 years now). He's got maybe 20 years of experience on me. The advice you guys have given so far is great; just wanna make sure that we're not talking about a "fine line" here.

答: Suggest you boss that you have been seeing some crazy code and ask him to put all possible staff on some programming courses. I think he should be aware that his apps are being filled with crappy code.</p>


问:
Automatic sorting of class/module members and its possible impact on productivity and code quality
Recently I saw some possibilities of some IDEs (via plugins) to sort members of their classes/modules based on some criteria, sou you could have everything sorted automaticaly no matter where you would put the elements in time of writing it to editor.

Do you think that this kind of sorting in class/module may have positive impacts on productivity, readability, comprehensibility etc?

答:
I do not think it would have a positive impact. We tend to group class members according to their purpose and function, and this is something that cannot be communicated by means of any simple criteria: it requires an understanding of what these things actually do.

For example, in hand-written code, a public method which manipulates some kind of elements and contains a call to a standard library routine to sort said elements might be immediately followed by the private callback method which compares said elements, so that the programmer can regard the two methods as a whole, since they work very closely together. I do not see any kind of criteria that could be used by an automated tool to figure out that these two methods should be grouped together.


答: No, it will not have a positive impact in kind of class I develop or have seen. I cant think of any criterion that can be used to group class elements. Self assumption from tool will mostly be bad assumption. </p>

Title: Automatic sorting of class/module members and its possible impact on productivity and code quality

Body:
Recently I saw some possibilities of some IDEs (via plugins) to sort members of their classes/modules based on some criteria, sou you could have everything sorted automaticaly no matter where you would put the elements in time of writing it to editor.

Do you think that this kind of sorting in class/module may have positive impacts on productivity, readability, comprehensibility etc?


问:
Make a big deal out of == true?
There is a colleague of mine who constantly writes:

```<code>if (someBool == true)
</code>```

It drives me up the wall!  Should I make a big deal of it or just drop it?

答:
This may get some of your nickers in a wad.

We have extension methods for .IsTrue and .IsFalse for the bool type.

So we write

if(someBool.IsTrue())

-or-

if(someBool.IsFalse())

Yep! And I love them. When reading code it just becomes more obvious to me.

ContentLicense: CC BY-SA 2.5

Title: Make a big deal out of == true?


问:
Software design for procedural programming
Right now, I'm trying to learn a well documented software engineering. I knew that if we code using Object Oriented concept, we can do software design concept using UML. But what if we code using procedural programming, how we do software design? as my understanding, UML is for OOP.

And do you have any references in internet? Please advices and correct me if I'm wrong about UML.

答:
The design technique I made the best experiences with regarding 6+ years procedural programming (and 10+ years OO/UML) leading to clean and easy to test code is Flow Design:

Link

And its "translation" to methods:

Link

ContentLicense: CC BY-SA 4.0


答:
Some of the concepts such as generalization and realization in a class diagram might not make sense, but a "class" module could be used to represent another unit of compilation. Object diagrams as a whole might not make sense. But deployment, component, activity, state, use case, sequence, and timing diagrams would make sense outside of an object-oriented environment.

UML provides you with a common language and set of symbols for modeling. As long as there is a mapping between your target language and the set of symbols used, UML can be used, and I'd support it since it would make communicating your design much easier. If a certain concept (and therefore a certain symbol) doesn't make sense in your language, make sure you don't use it.

Title: Software design for procedural programming

Body:
Right now, I'm trying to learn a well documented software engineering. I knew that if we code using Object Oriented concept, we can do software design concept using UML. But what if we code using procedural programming, how we do software design? as my understanding, UML is for OOP.

And do you have any references in internet? Please advices and correct me if I'm wrong about UML.


答:
The answer depends on the language. Lisps, for example, have the really neat properly that code is data--the algorithms you write are actually just Lisp lists! You store data the same way you write the program. This abstraction is simultaneously simpler and more thorough than OOP and lets you do some really neat things (check out macros).

Haskell (and similar language, I imagine) have a completely different answer: algebraic data types. An algebraic data type is like a C struct, but with more options. These data types provide the abstraction needed to model data; functions provide the abstraction needed to model algorithms. Type classes and other advanced features provide an even higher level of abstraction over both.

For example, I am working on a programming language called TPL for fun. Algebraic data types make it really easy to represent values:

```<code>data TPLValue = Null
              | Number Integer
              | String String
              | List [TPLValue]
              | Function [TPLValue] TPLValue
              -- There's more in the real code...
</code>```

What this says--in a very visual way--is that a TPLValue (any value in my language) can be a Null or a Number with an Integer value or even a Function with a list of values (the parameters) and a final value (the body).

Next I can use type classes to encode some common behavior. For example, I could make TPLValue and instance of Show which means it can be converted to a string.

Additionally, I can use my own type classes when I need to specify behavior of certain types (including ones I did not implement myself). For example, I have a Extractable type class which lets me write a function that takes a TPLValue and returns an appropriate normal value. Thus extract can convert a Number to an Integer or a String to a String as long as Integer and String are instances of Extractable.

Finally, the main logic of my program is in several functions like eval and apply. These are really the core--they take TPLValues and turn them into more TPLValues, as well as handling state and errors.

Overall, the abstractions I'm using in my Haskell code are actually more powerful than what I would have used in an OOP language.

Title: How would Functional Programming proponents answer this statement in Code Complete?

Body:
On page 839 of the second edition, Steve McConnell is discussing all the ways that programmers can "conquer complexity" in big programs. His tips culminate with this statement:

"Object-oriented programming provides a level of abstraction that applies to algorithms and data at the same time, a kind of abstraction that functional decomposition alone didn't provide."

Coupled with his conclusion that "reducing complexity is arguably the most important key to being an effective programmer" (same page), this seems to pretty much a challenge to functional programming.

The debate between FP and OO is often framed by FP proponents around the issues of complexity that derives specifically from the challenges of concurrency or parallelization. But concurrency is certainly not the only kind of complexity software programmers need to conquer. Perhaps focusing on reducing one sort of complexity increases it greatly in other dimensions, such that for many cases, the gain is not worth the cost.

If we shifted the terms of the comparison between FP and OO from particular issues like concurrency or reusability to the management of global complexity, how would that debate look?

EDIT

The contrast I wanted to highlight is that OO seems to encapsulate and abstract away from the complexity of both data and algorithms, whereas functional programming seems encourage leaving the implementation details of data structures more "exposed" throughout the program.

See, e.g., Stuart Halloway (a Clojure FP proponent) here saying that "the over-specification of data types" is "negative consequence of idiomatic OO style" and favoring conceptualizing an AddressBook as a simple vector or map instead of a richer OO object with additional (non-vectorish & non-maplike) properties and methods. (Also, OO and Domain-Driven Design proponents may say that exposing an AddressBook as a vector or map overexposes the encapsulated data to methods that are irrelevant or even dangerous from the standpoint of the domain).

Body:
The answer depends on the language. Lisps, for example, have the really neat properly that code is data--the algorithms you write are actually just Lisp lists! You store data the same way you write the program. This abstraction is simultaneously simpler and more thorough than OOP and lets you do some really neat things (check out macros).

Haskell (and similar language, I imagine) have a completely different answer: algebraic data types. An algebraic data type is like a C struct, but with more options. These data types provide the abstraction needed to model data; functions provide the abstraction needed to model algorithms. Type classes and other advanced features provide an even higher level of abstraction over both.

For example, I am working on a programming language called TPL for fun. Algebraic data types make it really easy to represent values:

data TPLValue = Null
              | Number Integer
              | String String
              | List [TPLValue]
              | Function [TPLValue] TPLValue
              -- There's more in the real code...

What this says--in a very visual way--is that a TPLValue (any value in my language) can be a Null or a Number with an Integer value or even a Function with a list of values (the parameters) and a final value (the body).

Next I can use type classes to encode some common behavior. For example, I could make TPLValue and instance of Show which means it can be converted to a string.

Additionally, I can use my own type classes when I need to specify behavior of certain types (including ones I did not implement myself). For example, I have a Extractable type class which lets me write a function that takes a TPLValue and returns an appropriate normal value. Thus extract can convert a Number to an Integer or a String to a String as long as Integer and String are instances of Extractable.

Finally, the main logic of my program is in several functions like eval and apply. These are really the core--they take TPLValues and turn them into more TPLValues, as well as handling state and errors.

Overall, the abstractions I'm using in my Haskell code are actually more powerful than what I would have used in an OOP language.


问:
Is it possible to write application-level logic in an XML or plain text format?
For example, a system where the developer does not need to write source code any more, instead they can using XML or some defined text to construct the application-level logic.</p>

答:
Yes, you can of course, but at the end of the day that would become the source code. One can just replicate the tree structure of the source code (expressions that call subexpressions and so on) and write it as XML.

And if you take the care of adjusting the syntax to remove unneeded cruft, you may end with Scheme :-)


问:
Write Unit test for heavily-database application?
I'm currently developing a Spring-based web-application, in which almost every operation create/update/delete something in the database. The logic mostly about checking condition so as to we should create/update records in the database or not.

The reason I want to try unit test is that we often meets regression errors when request changes or refactor. Most the bugs comes from Database changes, when I doesn't fully reflect those changes in the code. I have some experience in web-development now, but it seems that's not enough to stop them appear.

My controller/service is actually not too complex. I just take the binding object submited from the HttpRequest, check the condition & record in DB. Sometimes the system must read the Database, take out some records & manipulate them, then update some other records.Much of the coding effort lies on the interface(HTML/CSS/Javascript) too.

I'm investigating unit test, and I heard that when it comes to database operation, it's no longer unit test, since the test will be slow. Is that true? So that if my project is heavily database-operation, I shouldn't use unit test?

I also heard about DBUnit & some in-memory database which can quicken the test. Should I use them? And how I can write good unit test for database operation?

答:
I also heard about DBUnit & some in-memory database which can quicken the test. Should I use them?

Yes.

And how I can write good unit test for database operation?

Same way you write any other unit test.

You look at the defined interface for your class (or method) and write a test that demonstrates that it works when it's supposed to work and breaks when it's supposed to break.

Your setup may be somewhat complex because you have to put rows into the database that match the requirements of your unit test.


答:
While you can surely write programs in XML (after all, XML's just a way of serializing a labelled tree structure with embedded strings) it's not going to help you out with programming. The hard part of programming is not writing it down, it's comprehending what exact assembly of concepts need to be told to the computer to make it do what you want to happen.

I have written IDEs. I have written visual programming languages. (It's a heck of a lot of work.) Any time you want something complex, you're going to end up with a complicated description. I happen to think that the easiest way to manage the complexity is with plain text in a structured language spread across multiple files, and there are excellent tools to help with such things.

Title: Is it possible to write application-level logic in an XML or plain text format?

Body: For example, a system where the developer does not need to write source code any more, instead they can using XML or some defined text to construct the application-level logic.</p>


答:
First of all, what you are going to define will be simply a new programming language. You will have to define the language, its semantics, and implement a compiler or interpreters for the language. So, you are not going to take away the task of programming from developers.

Maybe you can make a very simple language if you have a very restricted context where programmers only have to specify certain options in an XML file and you have a framework that takes care of the rest. This would look more like customization of an existing application. However, as soon as you have some non-trivial application your language will grow very fast into a more traditional programming language (with data structures, control structures, variables, libraries, and so on).

If your issue is only about the syntax: XML is easier to parse but (IMHO) less readable.


问:
Which part of the source base should users be testing?
I'm using SVN and I'm wondering about which part of the code base the users should test.  The trunk (after the new feature branch has been merged in) or the branch?

If using the branch, how do you deal with the scenario where two developers are working on two different feature sets (so two branches), and need to release for testing to the users?

We've had a scenario where users are testing the wrong version (branch) and obviously cannot see their fixes.  I'd appreciate some experience / advice about dealing with this.

Update:

Branches are used for new features / bug fixing and eventually merged back into the trunk.  Testing involves testing the entire application (for site-effects) but will realistically users will have only tested their feature.

答:
You mention users, so that could mean this is some sort of a Beta test. I would then assume this is a major release of some sort. So it was a branch from the trunk.

Or are they internal testers so they would be testing something prior to it being added to the branch or trunk.

In any case the users should be testing what they are given, or granted access to. Prior to testing starting a specific build is given to them to test.


答:
In our project, branches are created for specific releases, upon code freeze. So there is no regular development on a branch anymore, only bug fixes (for bugs found during release testing). So any features/bugfixes requested by users and included in that specific version are already on the branch.

This is the version which then gets deployed for UAT / staging, thus users can test it. It is also possible to deploy a development (trunk) version in the UAT environment for users to test, but we very rarely do this in practice. Usually only our own testers get access to the development (trunk) version of our app. This is deployed on separate development servers, which are physically not accessible for end users.

We use JIRA for issue tracking, which makes release management easy, so we (almost) always know (almost) precisely what features/bugfixes a specific release includes. In case you have no issue tracker, I recommend taking one into use. JIRA is commercial, but there are free alternatives too.

Title: Which part of the source base should users be testing?

Body:
I'm using SVN and I'm wondering about which part of the code base the users should test.  The trunk (after the new feature branch has been merged in) or the branch?

If using the branch, how do you deal with the scenario where two developers are working on two different feature sets (so two branches), and need to release for testing to the users?

We've had a scenario where users are testing the wrong version (branch) and obviously cannot see their fixes.  I'd appreciate some experience / advice about dealing with this.

Update:

Branches are used for new features / bug fixing and eventually merged back into the trunk.  Testing involves testing the entire application (for site-effects) but will realistically users will have only tested their feature.


答: Since it's possible for errors to creep in after a feature branch has been merged into either trunk or a release branch, I would never do UAT based on a build from a feature branch.  Make a build from your trunk, or your release branch if you use them; and have the users UATing that build.</p>


答:
Mutable state is the root of most complexities and problems related to programming and software/system design.

OO embraces mutable state. FP abhors mutable state.

Both OO and FP have their uses & sweet spots. Choose wisely. And remember the adage: "Closures are poor man's objects. Objects are poor man's closure."


答:
There is no well marked line between OOP and procedural. Just saying, there's a number of people (GTK APIs used to, IIRC) that map OOP over procedural languages.

And then there's a silent majority that develops incrementally by starting from a main(), adding objects as they seem fit, using them as tools and not like Platonic Ideas. When things are getting too big to handle, they write classes and  diagrams like everybody does.

Then again, there's still some big design before finalizing contract in software engineering, so you may wonder how procedural-first firms could handle this. First of all there are not many of those firms, as it's harder to split tasks without objects.

Then, you know, there where many. They used control flow diagrams. With diamonds and rectangles and stuff. Nowadays they could use statecharts, and, in protocol interactions over network or inter-process, sequence diagrams.


答:
The problem with these type of solutions for the general case is that "end-users" tend to think and write in terms of "what I want", which can be extremely wooly, whereas computers work in terms of "what you said".

For example, if a user says "delete all the unimportant stuff", the computer can't handle concepts like "unimportant" and "stuff" unless the user specifically describes that to them (e.g. "Every file and folder that I've marked as unimportant".

You end up having to define stuff more and more specifically, and at some point you find you've got variables and functions, and basically a prototype scripting language, which no non-developer would want to touch because it's too complicated.

However, in any SPECIFIC case, your scripting language can take advantage of the limited scope of the user's interest to limit the language to the set of rules that they're actually interested in writing. Note that's the kind of task that entire companies and university theses are built around.

For example, if your client wants to be able to compare balance sheets according to user-defined rules, you could provide them with a client that handles all the things at computer level, but allow them to define the fields that they want to compare, and use a specific syntax for setting up rules on how to compare them. You may recognise this as the basic use-case of Microsoft Excel.

To give another example, Spiderweb Software has several "Blades of Exile/Avernum" Editors to allow users to create their own levels & scenarios for games. All the AI and UI is handled for the user. What the user sets up are the event flags that occur when you move to a particular space, what monsters will be in a particular room, etc. What was originally handled by the game creator carefully setting up position variables and trigger events in the source code, is now generalised and with a clean UI over the top of it, which generates the kind of scripts that you're talking about, which are then read by the game engine.


答:
It depends on your branching/merging model, what put in your trunk, and how big your feature branches are. It depends also on your release model, if your users get a special "testing" version of your product before the final release is made, or if there is always just one software release in production, which always contains the latest (maybe unstable) features.

From what you wrote I assume a feature is merged back into the trunk when the developer in place thinks the feature is fully implemented. Letting the user test only the trunk version thus has pros and cons:

Pro:

you will get feedback from your testers not only if a feature is ok, but also when there is a bug caused by integration into the trunk

if you apply bug fixes directly in the trunk, you will be sure your users will get them also

Con:

if you need several days or weeks for developing a feature before you reintegrate it into the trunk, you will get no feedback from users in this period, since they cannot see the feature during this time.

The solution to this seems pretty simple: try to break down features into small feature slices which can be developed in only a few days, and merge them early and often. If you fear that your will get too many "half-baked" things into production using this model, I would suggest to implement something like a testing-mode into your application. In this mode, those "unstable" new features can be switched on at run time and tested from your testing-users, without having the need of delivering / developing two different branches of your program.


答:
Not only is it theoretically possible, there is already a language defined and implemented -- it's called XML Plus Plus.  It hasn't been developed in a while, though, but seeing as it is apparently open source, you should be able to continue developing it if you want to.

However, as has already been said and as you can see from the code samples you can find of XML Plus Plus, the language is not particularly pleasant to program in, and requires all the same mental effort (plus a lot of extra typing).


问:
Do paint programs also need database?
I was thinking about how would a paint software works. Firstly I thought that it might not use any database but when I started thinking about the undo function I realized that it might be that the data is somehow stored in the database. Can anyone please help me out by telling me how the images are stored in a normal paint program(say MS-PAINT of Windows).</p>

答: If I name the filesystem as non-relational database - then probably - yes, else - depends what and how do you painting and how do your paintings organized.</p>

Title: Do paint programs also need database?


答:
Images aren't usually stored in a database (assuming you mean something like an SQL database) as the format isn't suited to image data.

Images are usually stored as files in folders - just as Word, Excel, OpenOffice documents are.

When you manipulate the data the program keeps a record of your changes in memory (usually) so that you can undo and redo modifications. Sometimes when you save the file the undo stack is cleared so you can only undo to last version on the hard drive.

Some file formats allow revision information to be stored in the file itself - but this isn't usually the case for images. What you have on disk is the only version of the file. If you want to keep a revision history then you need to either keep manual backups or store the file in a version control system, unless the underlying file system supports this natively.  An example of the latter is ZFS under OpenSolaris, which allow for a "look back in time" functionality with Time Slider - http://java.dzone.com/news/killer-feature-opensolaris-200.  Unfortunately, Solaris is heading in a different direction these days.

Title: Do paint programs also need database?

Body: I was thinking about how would a paint software works. Firstly I thought that it might not use any database but when I started thinking about the undo function I realized that it might be that the data is somehow stored in the database. Can anyone please help me out by telling me how the images are stored in a normal paint program(say MS-PAINT of Windows).</p>


答: You could look at the implementations of the undo functionality in some open source programs. Perhaps the The GIMP or Version 3.36 or earlier of Paint.NET (when it was still open source) might provide you with some inspiration. However, the Command and Memento design patterns are commonly cited as good ways to implement the undo/redo functionality.</p>

Title: Do paint programs also need database?


问:
planning the same app for both OSX and iOS
I would like to ask which is the best strategy for creating an application that will be developed both on Mac and iPad, so to make minumum effort to port it from one platform to the other, starting from iPad, for example, but rather trying to make both at the same time. The application, in fact, would be an iPad-style one on the Mac too. How should I have to plan the project? Which are the main tricks to easily get the goal?</p>

答:
I can't really answer your question but I may suggest a new route.

Have a look at Chameleon Project:

If you're an iOS developer, you're already familiar with UIKit, the framework used to create apps for the iPhone, iPod and iPad. Chameleon is a drop in replacement for UIKit that runs on Mac OS X. In many cases, your iOS code doesn't need to change at all in order to run on a Mac.

This new framework is a clean room implementation of the work done by Apple for iOS. The only thing Chameleon has in common with UIKit are the public class and method names. The code is based on Apple's documentation and does not use any private APIs or other techniques disallowed by the Mac App Store.

It is used to develop Twitterrific.


问:
Do people in non-English-speaking countries code in English?
I've heard it said (by coworkers) that everyone "codes in English" regardless of where they're from. I find that difficult to believe, however I wouldn't be surprised if, for most programming languages, the supported character set is relatively narrow.

Have you ever worked in a country where English is not the primary language?

If so, what did their code look like?

答:
I'm swedish and pretty much all my code is in english.

An intresting concept in this regard is Domain Driven Design, in that process it is a major point to not translate words and concepts:

Direct translation to and from the existing domain models may not be a good solution. Those models may be overly complex or poorly factored. They are probably undocumented. If one is used as a data interchange language, it essentially becomes frozen and cannot respond to new development needs.

Therefore:

Use a well-documented shared language that can express the necessary domain information as a common medium of communication, translating as necessary into and out of that language.

So if domain specific terms are in the local language and not translated along with the rest of the code, a domain expert but non-programmer can get a grasp of what the code does.


答:
...the code simply wasn't indented, there were hundreds of lines commented out for no apparent reason, documentation was basically non-existent, coding standards weren't applied consistently (e.g. mixing camelCase and under_scored_variables), variable names were unintelligible, datatype choices were wrong...

As far as I can tell, above matches #12, #9, #5, #2 and probably #7 of Top 12 things likely to be overheard if you had a Klingon Programmer (archive) [original link]:

12. Specifications are for the weak and timid!

  11. This machine is a piece of GAGH! I need dual Pentium processors if I am to do battle with this code!

  10. You cannot really appreciate Dilbert unless you've read it in the original Klingon.

  9. Indentation?! - I will show you how to indent when I indent your skull!

  8. What is this talk of 'release'? Klingons do not make software 'releases.' Our software 'escapes,' leaving a bloody trail of designers and quality assurance people in its wake.

  7. Klingon function calls do not have 'parameters' - they have 'arguments' - and they ALWAYS WIN THEM.

  6. Debugging? Klingons do not debug. Our software does not coddle the weak.

  5. I have challenged the entire quality assurance team to a Bat-Leth contest. They will not concern us again.

  4. A TRUE Klingon Warrior does not comment his code!

  3. By filing this PTR you have challenged the honor of my family. Prepare to die!

  2. You question the worthiness of my code? I should kill you where you stand!

  1. Our users will know fear and cower before our software! Ship it! Ship it and let them flee like the dogs they are!

It is quite likely that the only way to avoid confrontation is a warp drive into another space quadrant.

Title: How do I approach a coworker about his or her code quality?

Body:
I work on a new venture at a large enterprise software company (3000+ programmers). In my group, we have a bunch of projects and people usually work on several projects over the course of a year.

I just started work on a project that has been previously maintained by a buddy of mine (consultant who's been with us for 3+ years) to add some features. I got into the code, and the quality was really quite poor. Whether it was on the UI frontend or the services backend, the code simply wasn't indented, there were hundreds of lines commented out for no apparent reason, documentation was basically non-existent, coding standards weren't applied consistently (e.g. mixing camelCase and under_scored_variables), variable names were unintelligible, datatype choices were wrong, etc. etc.

I'm very much a non-confrontational person, so I don't want to attack my coworker, but I also don't just wanto to go to my boss and complain about his performance. What are the kinds of things I could say to politely mention that the code is poorly structured?

EDIT:

I want to clarify that while I understand there is an element of "Everyone else's code sucks" to all programmers, when I see something like this (names are chosen on purpose and some details left out/changed in this example):

```<code>public void doCalculate(Object argument) {
  if (argument instanceof String) {
    String argument2 = (String) argument;
    if (argument2 == "DataBase") {
      // do something
    } else {
      long argument3;
      try {
        argument3 = Long.parseLong(argument2);
      } catch (Exception e) {
        argument3 = -1;
      }
      // do something completely unrelated
    }
  }
}
</code>```

I think it's objectively fair to say that this is not a good idea. Furthermore, I'm not dealing with a newbie here (I'm only coding 3 years now). He's got maybe 20 years of experience on me. The advice you guys have given so far is great; just wanna make sure that we're not talking about a "fine line" here.


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

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

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

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

答:
You might want to check Netty.

Netty is a NIO client server framework which enables quick and easy development of network applications such as protocol servers and clients. It greatly simplifies and streamlines network programming such as TCP and UDP socket server.


问:
What issues do I need to consider when setting up a User Support group for a large enterprise system?
I have been tasked with becoming the Administrator for a large enterprise software system that consists of several shrink wrapped applications and some home grown 'glue' and has a couple of hundered users across three continents.

What do you think are the aspects / points I need to address?

At the moment the best I can come up with is a quote from Kathy Sierra's Creating Passionate Users blog post:

How does this help the users kick ass?

which seems helpful as a mantra, but not very concrete.

答:
What is your level of expertise with the shrink wrapped and glue programs?
Is/was somebody already in that position?

You will have to become an expert in the applications. You will also have to become an expert in the service the applications are supposed to provide.

What role will you play in the glue applications, especially regarding the continued development of these applications?

Will your relationship with the users be public or anonymous? Are you expected to be proactive and reach out to users to see what they need? Or, will you be asked only to handle the trouble tickets as they come in?


答: A lot of people organize themselves spatially.  If the IDE is moving things around on you to enforce alphabetical order of member names, it will be disconcerting to a lot of people.  Also, many IDEs provide direct access to the members of a class through a drop down list, which is sorted alphabetically.  This ought to be enough to help people who need to scan for a class member.</p>


答: I find it funny that everybody seems to immediately say "No" to having the IDE automatically sort the members of a class.  Working in C# quite a bit and abiding by StyleCop's default rules, I personally find it nice to have consistency in my code to have all fields, constructors, properties, and methods grouped together and within each group it's sorted by scope (public, protected, protected internal, private).  Back before development stopped on it I made use of Regionerate to automatically group the code for me and make sure the members were in alphabetical order.  I really wish my current team would view the benefits of this because for a number of base classes that we all have to modify (sometimes at the same time) having the tools to consistently structure where new members are placed would make merging a ton easier.</p>


问:
How do I encrypt the source code on the webserver?
I have a web application developed using Python, HTML, CSS & JavaScript.

The customer installs it in any of their own Machine and uses it through their LAN.
In short the customer sets up the webserver in any of their own machine.

Since its a web application, all the source code is open for the customer in the document root directory of webserver. I want to encrypt the whole source code in the document root directory in such a way that it should not effect the working of the web application.

Is there is any way to encrypt the Python, HTML, CSS & JavaScript for this purpose.

答:
Once your customer has a program they can run, they will be able to reverse engineer it given sufficient time & skill. That is just a fact of life.

If you really want to stop it, you should host and run the software yourself (SaaS)

Having said that, something like Python will be easier than C. Let's split this into the 3 parts you asked about (and then some more)

HTML

No matter what you do here, it will be decrypted in the browser (even in the SaaS model), so encrypting it on the server is pointless. Even minifying is pointless as modern browsers like Firefox and Chrome will neatly format it for them.

CSS

See above - don't waste your time

Javascript

Yahoo has a tool that can obfuscate it for you. Try YUI Compressor. Not, don't both encrypting this on the server-side as it must be served to the client unecrypted*, which would defeat the purpose.

Python

This is the only place you really want to spend your time - protecting your business logic. There are several methods you will find on google such as encrypting on disk and then decrypting at run-time. All these methods have problems, such as performance hits and having to supply the decrypter (hence enabling them to decrypt it anyone).

Your best beat to stop those not hellbent on stealing your code would be to use an obfuscate your Python code.

Summary

The only code you can stop someone from getting is the code you don't give them. HTML, CSS & Javascript will always end up on your users machine in a manner they can use, so assume they be able to steal it if they want, tough luck.

To protect your server code, the only sure-fire method is to NOT give it to them, running it in something like a SaaS model.

If that isn't possible, the best you can do is make it harder for them.

Testing

Always make sure you test on the production version you will be supplying your customers. This ensures any special build steps (such as obfuscation & minification) do not break your software.

Boring Business Stuff

So all of the above (and your question) has addressed this issue from the technical side. The other side of the coin is from the business/legal side.

If you have a small number of clients you can provide different "watermarked" versions of your software to each client. By doing this, you increase the possibility being able to track stolen software back to the source and take whatever legal action is appropriate.

Don't forgot, if you are in a serious business, you would be best to consult a lawyer on how you can prove and enforce the ownership of your software, should things go wrong.

* not strictly true, you could serve it encrypted and have other Javascript decrypt it on the fly, but this would be near pointless as it adds a performance hit and you will have to supply the attacker with the decrypter anyway...


答:
No.

HTMl, CSS, and JavaScript Cannot be encryption as the Browser needs to read it as Plain text. The best you can do is Obfuscate it.

For Python you could compile it into a DLL, so you are not outright giving the client the source code. But is can still be De-compiled.

For Arguments Sake, lets say provided a Custom Web server for your clients to use this Custom Web server reads Encrypted Python files then compiles and runs them. A hacker could still De-compiled the Custom Web server and get full access to the decryption module and the Encryption keys.

If you Code (or data) in any form, is on someone else hardware, The code can be stolen.

My proof of this : Just look at all the warez sites, everything gets hacked.

Title: How do I encrypt the source code on the webserver?

Body:
I have a web application developed using Python, HTML, CSS & JavaScript.

The customer installs it in any of their own Machine and uses it through their LAN.
In short the customer sets up the webserver in any of their own machine.

Since its a web application, all the source code is open for the customer in the document root directory of webserver. I want to encrypt the whole source code in the document root directory in such a way that it should not effect the working of the web application.

Is there is any way to encrypt the Python, HTML, CSS & JavaScript for this purpose.


问:
Should one use pseudocode before actual coding?
Pseudocode helps us understand tasks in a language-agnostic manner. Is it best practice or suggested approach to have pseudocode creation as part of the development lifecycle? For instance:

Identify and split the coding tasks

Write pseudocode

Get it approved [by PL or TL]

Start Coding based on Pseudocode

Is this a suggested approach? Is it practiced in the industry?

答:
If you're writing COBOL or C, pseudocode may be helpful because writing the actual code will take much longer, and if you can verify your algorithm/requirements from the pseudocode, you can save some time. </p>

<p>In more modern languages, pseudocode doesn't make as much sense. What would work better is writing method stubs, and filling out the top level logic, and as much detail as necessary to verify the algorithm and requirements, all of this in actual code. You can then show that code to the Team Lead for approval, and have your real code already started. </p>

Body:
If you're writing COBOL or C, pseudocode may be helpful because writing the actual code will take much longer, and if you can verify your algorithm/requirements from the pseudocode, you can save some time.

In more modern languages, pseudocode doesn't make as much sense. What would work better is writing method stubs, and filling out the top level logic, and as much detail as necessary to verify the algorithm and requirements, all of this in actual code. You can then show that code to the Team Lead for approval, and have your real code already started.


答: From what I have seen, alot of testing of new software packages in many companies is done among IT personnel, because our fellow IT folks are close by, and we are more comfortable dealing with them.  In almost all of our new product roll-outs, we bring in a handful of average Joe users to try out the app, and give feedback.  As far as I am concerned, this should be customer service 101, to take a select group of people that actually use a product, (and not their bosses) and gain feedback from them.  Even at an early stage, if a product isn't ready to test, just put together a presentation on the product, and submit to testers, and get feedback on what they are thinking, and how they feel.  This will be invaluable to find out what they need to know about, and what sort of questions to expect.  A major pitfall in professional IT is that many assume the end user thinks and acts like we do.  This is not this case in 99% of situations.</p>

Title: What issues do I need to consider when setting up a User Support group for a large enterprise system?

Body:
I have been tasked with becoming the Administrator for a large enterprise software system that consists of several shrink wrapped applications and some home grown 'glue' and has a couple of hundered users across three continents.

What do you think are the aspects / points I need to address?

At the moment the best I can come up with is a quote from Kathy Sierra's Creating Passionate Users blog post:

How does this help the users kick ass?

which seems helpful as a mantra, but not very concrete.


问:
T-SQL stored procs orders of magnitude faster than LINQ
According to answers I've seen on stackoverflow, stored procedures (and to a lesser extent db functions) tend to perform better vs. LINQ + ORM frameworks (e.g. Entity Framework).

I want to determine if the performance difference is large enough to justify an increase in development time, assuming it takes more time to write equivalent, reasonably complex query operations in T-SQL vs. LINQ.

In which scenarios is there an order-of-magnitude (or at least a very large constant factor) difference in running time, between a performance-optimized stored proc  and its equivalent, performance-optimized LINQ counterpart? Or for scalar- or table- valued functions vs. the LINQ equivalent?

Hopefully, it is not too difficult to see that this question follows the guidelines per the FAQ. It's not asking a subjective question like, "which is better, T-SQL or LINQ?". It's asking for a few specific scenarios  (can give abstract or concrete examples)  where there is a significant difference in performance. If that still doesn't make sense to you, and you still think this question is not constructive and should be closed, please leave an explanation why if you can.

答:
My suggestion:

1. Do development with LINQ to get a product to market faster.

2. Optimize performance of the whole system by using cache and alike.

3. Optimize performance of those few queries where it really matters.

In the order listed.


答:
I worked with Tango/WiTango/TerraScript that is basically an XML-encoded language (with a really nice drag/drop tree-based IDE). It compiles to J2EE or can be executed with its own run-time as well. It has been XML-based for about 12 years now.

http://www.witango.com/


问:
Rule of thumb for cost vs. savings for code re-use
Is it a good rule of thumb to always write code for the intent of re-using it somewhere down the road?  Or, depending on the size of the component you are writing, is it better practice to design it for re-use when it makes sense with regards to time spent on it.  What is a good rule of thumb for spending extra time on analysis and design on project components that have "some probability" of being needed later down the road for other things that may or may need this part.

For example, if I have the need for project X to do things A, and B.  A definitely needs to be written for re-use because it just makes sense to do so.  B is very project specific at the moment, and I can hack it all together in a couple days to finish the project on time and give everyone kudos for being a great team, etc.  Or if we say, lets spend a whole friggin' 2 weeks figuring out what project Y/Z might need this thing for and spend a load of extra time on on part B because someday we might need to use it on project Y/Z (where the savings will be realized).

I'd imagine a perfect world situation would be a nicely crafted combination of project specific vs. re-use architected components given the project.  However some code shops might feel it would be a great idea to write everything for the intention of using it at some point down the road.

答:
YAGNI. Keep it simple, clear, and well-covered by unit tests.

If it turns out you DO need to re-use it, refactor it as needed. If you have good unit tests in place, the refactoring is fairly low-risk. Besides, in my experience, code that is testable is pretty close to being re-usable anyway. You might need to add in an extension point or two, but if your code is clean to begin with, it shouldn't be a huge deal.


答: I think you are making an incorrect assumption that it will take longer to create a stored procedure than an equivalent LINQ query. The extra speed can be a huge benefit though here is an article talking about studies by Google and Amazon where load time increases of less than .5 secs had huge impacts on revenue. Given the long life of most applications it seems foolish to worry about an extra few hours of developer time for what could work out to days of time not wasted by users and/or significant increases to revenue. Another thing to consider is MS is dropping L2S in favor of EF.</p>

Title: T-SQL stored procs orders of magnitude faster than LINQ

Body:
According to answers I've seen on stackoverflow, stored procedures (and to a lesser extent db functions) tend to perform better vs. LINQ + ORM frameworks (e.g. Entity Framework).

I want to determine if the performance difference is large enough to justify an increase in development time, assuming it takes more time to write equivalent, reasonably complex query operations in T-SQL vs. LINQ.

In which scenarios is there an order-of-magnitude (or at least a very large constant factor) difference in running time, between a performance-optimized stored proc  and its equivalent, performance-optimized LINQ counterpart? Or for scalar- or table- valued functions vs. the LINQ equivalent?

Hopefully, it is not too difficult to see that this question follows the guidelines per the FAQ. It's not asking a subjective question like, "which is better, T-SQL or LINQ?". It's asking for a few specific scenarios  (can give abstract or concrete examples)  where there is a significant difference in performance. If that still doesn't make sense to you, and you still think this question is not constructive and should be closed, please leave an explanation why if you can.


问:
Is Microsoft's Entity Framework a proprietary variant of NHibernate?
I have no knowledge of Entity Framework and NHibernate but definitely want to learn. I want to know how to start. Whether to first read documentation of NHibernate or the default Visual Studio Entity Framework?

Is Microsoft's Entity Framework a variant of NHibernate?

答:
Pick up Julia Lermans book "Entity Framework" and read it.

No, EF is not connected to nhibernate in any other way than that the two frameworks cover about the same business domain.


问:
How do you name your private variables in C#?
What is the best practice, most commonly accepted naming conventions for private variables in C#?

private int myInteger;

private int MyInteger;

private int mMyInteger;

private int _myInteger;

private int _MyInteger;

Mysterious other option

Which do you use and why?  (My company is fairly new to C# and I would like to pick the most "industry accepted" method to try and get into our coding standard.)

答:
I go by option 5: private int _MyFoo

I don't see any real competitive advantage over _myFoo though.


问:
Is Entity Framework Code First a bit meaningless/useless in production and what is a good EF strategy for production?
I have been programming recently with Entity Framework 4.1 Code First and am loving it for development, but with only an end plan and a rapidly changing feature list, I am constantly modifying the Class/Database to meet the applications needs.

In development, there is no live data and I can easily just delete the entire database so it is recreated with the new schema however, obviously, when live - this is very bad!

The only solutions I can see are to either drop the metadata table and manually keep the database in sync or basically drop and reseed.

I personally prefer the first method as I think it will be a lot easier to add a column/table than to recreate and migrate data, but, unless I have missed something, this is completely moving away from Code First.

So the question really is, is Code First just about the initial development and what is a good strategy for managing EF for a production environment?

答:
The question is somehow flawed in that it makes connections between the programming model and the runtime environment where there is none.

Code first is primarily a development speed driver and is not really connected to the runtime system.

In production you will properly have a configuration setting that denies the runtime the possibility of deleting/updating the db model.


问:
Is Entity Framework ready for production?
I'm looking into Entity Framework for a new project that I'm going to be taking on and as part of my research into it I'm asking some industry professionals if it's stable and ready for 'real world' implementation.

In the running is:

EF

NHibernate

DevExpress XPO

I already have a great deal of experience with XPO, but I'm not particularly happy with it.

答: Yes it is, however you should allocate resources for updating and retesting your application when updates comes out (as with any other framework).</p>


问:
Is CodeFirst intended for large scale applications?
I've been reading up on Entity Framework, in particular, EF 4.1 and following this link ( http://weblogs.asp.net/scottgu/archive/2010/07/16/code-first-development-with-entity-framework-4.aspx) and it's guide on Code First.

I find it neat but I was wondering, is Code First supposed to be just a solution for rapid development where you can just jump right in without much planning or is it actually intended to be used for large scale applications?

答: Code first is viable for even large systems: Just examine the model after creation and remap using the fluent api until you reach a db model you like.</p>


问:
How best to prevent having to revisit a change after check in
Normally what happens is that I work on something for a while and then when I am done I check it in(After the test/review process of course).  Sometimes I have to go back and fix something that I got wrong the first time due to me not understanding the problem enough, lack of testing, etc..

What is an acceptable rate for this?  Ideally you would hope that you never have to go back but sometimes you do.  What rate does the average programmer have and what is the expert programmers rate?  Do people track this?  Lastly what kind of checks are best at preventing this?

PS: I am not counting the cases where the requirements have changed and you have to go back in.

I know that there is no real answer to this so let me change the actual question to: "What general checks could be implemented, before code is sent for review or checked in, that would help prevent the need to revisit the change later?"

答:
There is a set of practices which helps to raise quality of code:

Unit testing is a must.

Continuous integration will help to run unit-tests automatically and provide convenient reporting.

Static analysis (inspections) helps detecting source code vulnerabilities and frequent coding errors which cannot be caught on the compile time.

Dynamic analysis - autotests, performance analyzers, memory & leaks analysis, etc.

Personally I have several types of branches (in version control system) with different commit and code quality policies.

experimental branches have no control over code at all. One exception is that code should compile before commit.

trunk & maintenance branches have also unit-tests and continuous integration enabled.

release branches have all of the aforementioned enabled: unit-tests, continuous integration, static analysis, dynamic analysis and even copy-paste detectors.

So, the recommendation is very simple: use different policies and tools for different types of source code repository branches.


答: When I was at university in Switzerland I worked on a Modula-2 project, where everything (variables, comments, messages, etc) was in French, except for the keywords of the programming language.  They also told me there were preprocessors available that would allow you to write the keywords in French as well, so "si" = "if", "alors" = "then", "sinon" = "else", etc.</p>

Title: Do people in non-English-speaking countries code in English?

Body:
I've heard it said (by coworkers) that everyone "codes in English" regardless of where they're from. I find that difficult to believe, however I wouldn't be surprised if, for most programming languages, the supported character set is relatively narrow.

Have you ever worked in a country where English is not the primary language?

If so, what did their code look like?


答:
CSLA for .NET serializes a copy of the object that you wish to save undo-history on and stores it in a stack of undo's... so you can keep popping back through history (Might be a little off on how it's stored, but fairly confident in the overall method)...

No database needed, infact, it's overkill to have a database to save "undo" information.  Just find a way to store "instances" of your data (paint info) and be able to recall them.

Title: Do paint programs also need database?


问:
What are the complexities of memory-unmanaged programming?
Or in other words, what specific problems did automated garbage collection solve? I've never done low-level programming, so I don't know how complicated can freeing resources get.

The kind of bugs that GC addresses seem (at least to an external observer) the kind of things that a programmer that knows well his language, libraries, concepts, idioms, etc, wouldn't do. But I could be wrong: is manual memory handling intrinsically complicated?

答:
Here's a list of problems faced by C++ programmers when dealing with memory:

Scoping problem occurs in stack allocated memory: it's lifetime do not extend outside of the function where it was allocated in. There are three main solutions to this problem: heap memory, and moving the allocation point upwards in the call stack or allocating from inside objects.

Sizeof problem is in stack allocated and allocating from inside object and partly heap allocated memory: The memory block's size cannot change on the runtime. Solutions are heap memory arrays, pointers and libraries and containers.

Order of definition problem is when allocating from inside objects: the classes inside the program need to be in correct order. Solutions are restricting dependencies to a tree and reordering the classes and not using forward declarations, and pointers and heap memory and using forward declarations.

Inside-Outside problem is in object allocated memory. Memory access inside objects is divided to two parts, some memory is inside an object and other memory is outside of it, and programmers need to correctly choose to use either composition or references based on this decision. Solutions are doing the decision correctly, or pointers and heap memory.

Recursive objects problem is in object allocated memory. Size of objects becomes infinite if same object is placed inside itself, and solutions are references, heap memory and pointers.

Ownership tracking problem is in heap allocated memory, the pointer containing address of the heap allocated memory has to be passed from allocation point to deallocation point. Solutions are stack allocated memory, object-alloated memory, auto_ptr, shared_ptr, unique_ptr, stdlib containers.

Ownership duplication problem is in heap allocated memory: the deallocation can only be done once. Solutions are stack allocated memory, object-allocated memory, auto_ptr, shared_ptr, unique_ptr, stdlib containers.

Null pointer problem is in heap allocated memory: the pointers are allowed to be NULL making many of the operations crash on runtime. Solutions are stack memory, object-allocated memory and careful analysis of heap areas and references.

Memory leak problem is in heap allocated memory: Forgetting to call delete for every allocated memory block. Solutions are tools like valgrind.

Stack overflow problem is for recursive function calls which are using stack memory. Normally size of stack is completely determined on compile time, except for the case of recursive algorithms. Defining OS's stack size wrong also often causes this problem since there is no way to measure the required size of stack space.

As you can see, the heap memory is solving very many existing problems, but it causes additional complexity. GC is designed to handle part of that complexity. (sorry if some problem names are not the correct names for these problems -- sometimes it's difficult to figure out the correct name)


问:
How to teach basic principles to programmers
In order to get experience as a team lead, I was recently given the task of supervising a programmer.

What I found out is that he is having a problem in writing a simple if condition. He has issues with string. And he doesn't know how to pass a variable in the addClass function of jQuery with an if condition.

And he doesn't know when to use a for loop. Or even what a for loop is used for.

How to make him understand these basic concepts quickly?

I told him to Google for how to use if condition for addClass variable. But he didn't find it, then I told him to do it quickly in the early morning, when discussing he was giving reasons that it is what that, then I told him I show you how to do that,
then he told me, you should have done it before.

What should I reply to him? He is telling me that you should tell me everything or Should I do it and show him every time? It may take lot of time, and every time I have to do a task. I want him to be independent.

答:
Disclaimer : you may want to check with you manager and/or your Human Ressources Department before following my advice.

Plain and simple : Fire him from your team.

He does not have the basic skills needed to be a programmer. Your company is certainly not a programming school, and you cannot be a full time team leader and a school teacher at the same time.

In the future, you should get involved in the recruitment process of your company to select the people you will have in your team, and help implement best practices for programmers' recruitment. If you don't, you will have a hard time achieving your goals as a team leader. If team leaders are not involved in the recruitment process at your company, the best you can do is to remain a programmer or find a new company that gives you the responsabilities that come with your role.

If you, as a team leader, don't act by telling your manager : "This person is not a good fit for my team", you will be held responsible of losing time in unnecessary hand-holding, instead of getting involved in more constructive tasks for the company. Whatever your manager's answer is, you will have done your due diligence.

I've seen enough team leaders failing their first assignement because of this specific case.


答:
I don't have a rule of thumb in terms of time/effort/cost, but the line I like to use is "reusable code isn't part of a project, it is a project." This is because truly reusable code needs to have its own very well defined set of requirements that take into account everything that's going to be using it and may be using it in the future.

Of course, you can take any given component that's being written as part of a project and make it reusable. But the difference between something that's "reusable" (in quotes) and something that truly does have the potential to be reused is whether or not it can meet the needs of multiple real consumers in all aspects - flexibility, deployment considerations, performance, behavior, configurability, etc. The level of design required to get all that essentially makes a piece of reusable code a project unto itself.

Title: Rule of thumb for cost vs. savings for code re-use

Body:
Is it a good rule of thumb to always write code for the intent of re-using it somewhere down the road?  Or, depending on the size of the component you are writing, is it better practice to design it for re-use when it makes sense with regards to time spent on it.  What is a good rule of thumb for spending extra time on analysis and design on project components that have "some probability" of being needed later down the road for other things that may or may need this part.

For example, if I have the need for project X to do things A, and B.  A definitely needs to be written for re-use because it just makes sense to do so.  B is very project specific at the moment, and I can hack it all together in a couple days to finish the project on time and give everyone kudos for being a great team, etc.  Or if we say, lets spend a whole friggin' 2 weeks figuring out what project Y/Z might need this thing for and spend a load of extra time on on part B because someday we might need to use it on project Y/Z (where the savings will be realized).

I'd imagine a perfect world situation would be a nicely crafted combination of project specific vs. re-use architected components given the project.  However some code shops might feel it would be a great idea to write everything for the intention of using it at some point down the road.


问:
How to determine the effectiveness of a code review process?
We've introduced a code review process within our organisation and it seems to be working well. However, I would like to be able to measure the effectiveness of the process over time, i.e. are we not finding bugs because the code is clean or are people just not picking up on bugs?

Currently, we don't have an effective fully-automated test process. We primarily employ manual testing, so we can't rely on defects found at this stage to ensure that the code review process is working.

Has anyone come across this issue before or has any thoughts on what works well in measuring code reviews?

答:
There are a number of metrics that can be gathered from code reviews, some even extending throughout the lifecycle of the project.

The first metric that I would recommend gathering is defect removal effectiveness (DRE). For every defect, you identify what phase the defect was introduced in and what phase it was removed in. The various defect detection techniques that you use are all assessed simultaneously, so it applies equally to requirements reviews, design reviews, code reviews, unit tests, and so on. You would be particularly interested in the number of defects caught in the code phase, since this would probably encompass your unit tests as well as code reviews. If many defects from the code phase are making it through to the integration test phase or even the field, you know that you post-coding practices should be evaluated.

Various meeting metrics would also be relevant. These include the time to prepare, time in meeting, lines of code read, defects found in the review, and so on. Some observations can be made from this data. As an example would be if your reviewers are spending a large amount of time reading the code in preparation for the review, but finding very few problems. Coupled with the DRE data, you can draw the conclusion that if defects are being tested in integration testing or the field, then your team needs to focus on their review techniques to be able to find problems. Another interesting note would be the lines of code (or some other size measurement) read in a meeting compared to the time of the meeting. Research has found that the speed of a typical code review is 150 lines of code per hour.

With any of these metrics, it's then important to understand their impact on the process. Root cause analysis, using techniques such as why-because, Five Whys, or Ishikawa diagrams can be used to identify the reasons why code reviews (or any other quality improvement technique) are (in)effective.

You might also be interested in this article about inspections from The Ganssle Group and an article by Capers Jones in Crosstalk about Defect Potentials and DRE.


问:
Data Serialization to process business logic
Going by the general principle of data abstraction, I normally abstract data in a serialized format(JSON) and pass it as a parameter to the Business Logic(BL) modules such that the BL module always see a consistent format of the data irrespective of the underlying data storage layer. Even if I use a ORM, I use the serialized format of that ORM. I feel I have the following advantages.

By serializing data, there would be better control over data and parameters

Any developer can write BL without thinking too much about the underlying data storage

Wrappers can be written for new databases (There are a lot of ready-made wrappers to convert data into JSON)

Testing could be done ruthlessly and without a database (since the data format is serialized)

Functionally easier to understand and better OLAP, OLTP integration

I also notice the following drawbacks

A new layer to be added between the database and the BL module (most ORM's nowadays come with a predetermined JSON format)

Extra function calls slow down the application (but I think this trade-off is OK when compared to better testing and easy maintenance)

Increased level of abstractions may confuse the developer

I make the above observations mostly in the context of business applications
To follow this discussion, lets have an example so that things could be discussed in its context.
Assume a product database having the columns: Product,Rate,Taxes and we need to create a invoice

Code without database abstraction

```<code>GET rate,taxes for product X from database
multiply qty with rate and add taxes
display invoice
</code>```

Code with database abstraction

```<code>  GET rate,taxes for product X from database
  Convert it into JSON
  call create_invoice function //This does all the calculations
  display invoice
</code>```

In the second example, I would pass arguments in the form (Product=X, Qty=5, Rate=5, Taxes=0.05). If taxes are to be split into more that one category (State Tax=0.03, Central Tax=0.02) or a discount factor to be added  I would just increase the number of parameters in the BL functions such that the database fields, the JSON keys and the function parameters match (this is done automatically during serialization and most ORM's do it). This makes it easy, in my approach, to extend functions and also make modules independent of data since the modules always know the data they can receive and even if they receive a new parameter, they can adapt it provide the underlying code is intelligent.

My general questions are

Is this a good pattern and what's it called (Data abstraction comes to my mind)?

Pros/Cons of this pattern(apart from those mentioned above) in the context of business application, apps for embedded devices, big data

Is there a difference between this pattern and ORM (I believe so since ORM is mostly a class wrapper to get data from a database while this pattern is more oriented towards data structure)

If this is good, can this be easily understood by a new developer?

答:
A lot depends on your intention. Data serialization in this manner just to pass on to the business logic of a single application, seems wasteful, when you should be passing a native object from the ORM to the object encapsulating BL which will modify state and return the object to the ORM for persistence.

On the other hand, if you have multiple, distributed applications that handle different aspects of of the domain, then wrapping your DB in an API to provide serialized (JSON or XML) data is a good idea.

For instance: I have to deal with a rather insane vendor-supplied legacy database in which a major constraint is inability to modify the DB schema other than adding the occasional view. I have this DB (as well as a couple of our other 'enterprise' data stores) wrapped in a REST API. Most of our user-facing applications, as well as daemons that monitor the DB for certain events, communicate with the API. In this way I can have the following workflow:

OR/M classes each wrap a single table in the DB. One object == one record.

Decorator classes handle presentation, including composition of more complex objects from simple model objects.

Controller classes respond to requests with a JSON representation of the object appropriate to the client application.

Clent processes data, POSTs or PUTs JSON object back to the API

Controller requests to save object, which is decomposed back to model objects and persisted by the O/RM.

This adds significant complexity.

If you have to deal with heterogeneous data stores, distributed applications, etc., this is an excellent solution. But unless you have those requirements, the rule of thumb is You Ain't Gonna Need It.


问:
How Do You Estimate Project Hours Using Pivotal Tracker If You Are a Services Firm?
I am new to Pivotal Tracker and trying to learn how best to use it for our business. We are an app development consulting services firm. As you guys know, clients want to have an idea of total time and cost before they sign any contract.

How are you guys mapping your project on Pivotal to total hours and timelines? Any best practices? Pointers?

Right now my team and I have broke the project into stories (love how Pivotal gets us thinking on a much lower level) and have roughly mapped out points to hours.

1 - 1 hour

2 - 2 hours

3 - 6 hours

5 - 10 hours

Then we are basically thinking of 2 as a quarter day, 3 as 3/4 a day, and 5 as a full day or a bit longer.

I then calculate how many 1s, 2s, 3s and 5s we have to get a rough estimate of total hours. Pivotal gives me an estimated completion date based on default velocity (I know this can change). I then report the rough total hours, cost, and due date to my client. I do understand that this is agile and iterative where things change, but when people hire you as a consultant they want costs up front.

答:
You're attempting to repurpose an agile project planning tool into a waterfall one.

I'm no expert, but this is the very problem that Agile intends to address i.e: "Responding to change over following a plan". "Going Agile" involves something of a tradeoff - exhanging concrete costs and deadlines for flexibility and responsiveness of development. In a nutshell, the customer has to be (delicately) asked the following question:

Which of these is more important to your business, the features or the
  delivery/cost?

NB: This is an abbreviation of a commonly accepted rule of thumb, see Thomas Owens comment below re: project management triangle. I chose to present a slightly more cynical slant on it...

Inevitably, clients want both, but armies of burnt out developers/agencies shows that up front estimation rarely matches the reality of execution and generally this leads to hideous overtime or "late" delivery and angry clients.

The whole point of Agile is that it is an attempt to bring an element of empiricism to delivery dates, measuring performance in terms of velocity relative to "task complexity". IMO the problem is that you've equated story size with hourly estimates. The meaning of story size is entirely dependent on how you break them up, which is why 1-5 is not already presented as a unit of time (unlike typical estimation tools).

If they absolutely need a concrete estimate, then they are not ready for an Agile relationship, so use the time honoured method of padding out of your schedule, and hope that the competition is putting in more padding in than you.

As I said, I'm no expert, but I've been through a experience to the one you're describing, and I asked a similar question then too: Funding Agile Projects

EDIT: JFTR - I heartily endorse Pivotal Tracker, we used it extensively on the last project I worked on, but it was something of a paradigm shift for the management/sales team to get their head round...as illustrated by the thread above, Agile is not such an easy sell outside of the dev/enterprise community