问:
When should JavaScript generate HTML?
I try to generate as little HTML from JavaScript as possible. Instead, I prefer to manipulate existing markup whenever I can and only generate HTML when I need to dynamically insert an element that isn't a good candidate for using Ajax. This, I believe, makes it far easier to maintain the code and quickly make changes to it because the markup is easier to read and trace. My rule of thumb is: HTML is for document structure, CSS is for presentation, JavaScript is for behavior.

However, I've seen a lot of JS code that generates mounds of HTML, including entire forms and content-heavy modal dialogs. In general, which method is considered best practice? In what circumstances should JavaScript be used to generate HTML and when should it not?

答:
Regarding dynamic page loading, one should realize that behind all the "JQuery AJAX Cloud!" magic, only two possible things are happening:

An element's code is being injected in a div (bad), or

Content is being loaded in an iframe (better, but it's just not the same...)

Regarding the original question, I only create HTML content via Javascript when I'm creating a web app of some kind that reads XML or JSON data stored on the server, and it gets changed a lot.

It wouldn't make much sense to load static content on a page with Javascript, as there's always the possibility that it won't load right, or the client will have it disabled ("take that pesky ads!"). In addition, it makes it really hard to change HTML content when it's smushed inside an ugly document.write() or a chain of document.createElement()'s.

So, you are right; either type up the raw HTML, or if dynamic-ish content is necessary, use a server-sided script to output what's necessary. Use Javascript to inject HTML only if the site is meant to work without an Internet connection, or a similar case.

One last note, if you do want to implement xmlhttprequests, er, AJAX, into a website, probably the best/safest way to do it is to store the data in a data format (like XML), load it, and output it accordingly on the client. document.write and element.innerHTML really isn't the best way to go about manipulating content, and is bound to cause potential headaches in the future (why isn't this script running? My broken  tag is italicizing everything! etc.).

Title: When should JavaScript generate HTML?

Body:
Regarding dynamic page loading, one should realize that behind all the "JQuery AJAX Cloud!" magic, only two possible things are happening:

An element's code is being injected in a div (bad), or

Content is being loaded in an iframe (better, but it's just not the same...)

Regarding the original question, I only create HTML content via Javascript when I'm creating a web app of some kind that reads XML or JSON data stored on the server, and it gets changed a lot.

It wouldn't make much sense to load static content on a page with Javascript, as there's always the possibility that it won't load right, or the client will have it disabled ("take that pesky ads!"). In addition, it makes it really hard to change HTML content when it's smushed inside an ugly document.write() or a chain of document.createElement()'s.

So, you are right; either type up the raw HTML, or if dynamic-ish content is necessary, use a server-sided script to output what's necessary. Use Javascript to inject HTML only if the site is meant to work without an Internet connection, or a similar case.

One last note, if you do want to implement xmlhttprequests, er, AJAX, into a website, probably the best/safest way to do it is to store the data in a data format (like XML), load it, and output it accordingly on the client. document.write and element.innerHTML really isn't the best way to go about manipulating content, and is bound to cause potential headaches in the future (why isn't this script running? My broken <i> tag is italicizing everything! etc.).


问:
Is there such a thing as a super programmer?
Have you come across a super programmer? What identifies him or her as such, compared to "normal" experienced/great programmers?

Also. how do you deal with a person in your team who believes he is a super programmer? Both in case he actually is or if he isn't?

Edit: Interesting inputs all round, thanks. A few things can be gleaned:

A few definitions emerged. Disregarding too localised definitions (that identified the authors or their acquaintance as super programmers), I liked a couple definitions:

Thorbjørn's definition: a person who does the equivalent of a good team consistently for a long time.

Free Electron, linked from Henry's answer. A very productive person, of exceptional abilities. The explanation is a good read.

A Free Electron can do anything when it comes to code. They can write a complete application from scratch, learn a language in a weekend, and, most importantly, they can dive into a tremendous pile of spaghetti code, make sense of it, and actually getting it working. You can build an entire businesses around a Free Electron. They’re that good.

Contrasting with the last definition, is the point linked to by James about the myth of the genius programmer (video). The same idea is expressed as egoless programming in rwong's comment. They present opposite opinions as whether to optimise for such a unique programmer or for a team.

These definitions are definitely different, so I would appreciate it if you have an input as to which is better. Or add your own if you want of course, though it would help to say why it is different from those.

答:
There are those who can produce more output than others.

There are those who can produce output with a lower defect rate than others.

Those who can CONSISTENTLY produce more output, with lower than normal defect rates, might be worthy of being called as Super-Programmer.

Being known of or thought of as such is usually only apparent to an enlightened manager with the benefit of hind sight.

Somebody who things they ARE a super-programmer probably has a big ego and thinks they are good. That does not make them good.

Attitude <> Ability.

ContentLicense: CC BY-SA 2.5


答:
Whenever I have encountered heavy HTML generation in javascript, it was almost solely in a stand-alone UI plugin. It makes sense, as it allows to encapsulate the entire plugin in a single .js file (+ a .css to customize styles), thus making it easily reusable, distribuable, and independent from the framework used in the application.

So if you're writing a stand-alone javascript plugin or a generic UI component which you would like to use across different applications, such an approach has its upsides. Otherwise, I think it's both cleaner, easier to write and easier to maintain when you keep html generation away from javascript and on the server side.

ContentLicense: CC BY-SA 3.0

Title: When should JavaScript generate HTML?

Body:
I try to generate as little HTML from JavaScript as possible. Instead, I prefer to manipulate existing markup whenever I can and only generate HTML when I need to dynamically insert an element that isn't a good candidate for using Ajax. This, I believe, makes it far easier to maintain the code and quickly make changes to it because the markup is easier to read and trace. My rule of thumb is: HTML is for document structure, CSS is for presentation, JavaScript is for behavior.

However, I've seen a lot of JS code that generates mounds of HTML, including entire forms and content-heavy modal dialogs. In general, which method is considered best practice? In what circumstances should JavaScript be used to generate HTML and when should it not?


问:
Using an AGPL 3.0-licensed library for extra functionality in an iOS app
I am building an iOS application, and I am planning to incorporate an AGPL 3.0-licensed library to it to provide some extra (non-essential) functionality. I’ve got a couple of questions regarding this:

Do I understand it right that this still obliges me to publish the source of my app open? If yes, does it have to be open to the general public, or only to those who have downloaded the app?

Does this allow me to distribute the app for a fee?

答:
Yes, you are obliged to make the source code available, under the same terms as the AGPL - which are almost equivalent to the GPL, by design.

Technically, the GPL requires that source is distributed only to people who ask for it, and who have received a copy of the binary.  You are not obliged to go beyond that, although you cant stop, eg, me from giving the binary to Mary, and Mary asking for the source through me.

The additional nature of the AGPL is that if you put the AGPL component into a service that is never distributed, but is used by others, you are also obliged to make it available to them.

Since the AGPLv3 and the GPLv3 are almost identical, "Does the GPL allow me to sell copies of the program for money?" applies to you also.  In other words, "yes, totally, go right ahead".

You can't stop me buying a copy, getting the source, and distributing both free of charge - but you can totally put it, eg, in the iOS market and charge anything you want.  (You can't stop me doing the same, and pricing it one cent lower than you do, though, so the model can be ... risky.)


问:
How can a computer render a CLI/console along with a GUI?
I'm confused when looking into graphics - specifically with operating systems.

I mean, how can a computer render a CLI/console along with a GUI?

GUI's are completely different from text. And how can we have GUI windows that display text interfaces, ie how can we have CLI in modern Graphics Operating system - that's what I'm mainly trying to grip on to.

How does graphics get rendered to display? Is there some sort of memory address that a GPU access which holds all pixel data, and there system's within OS's that gather the pixel position of windows and widgets, along with the Z Index and rasterize them to that memory address, which then the GPU loads to the screen?

How about the CLI's integrated with Graphics? How does the OS tell the GPU that a certain part of the screen wants to display text while the rest wants to display pixel data?

答:
It seems like your main question is how GUIs and CLIs can exist together at the same time, such as the Windows command console (cmd.exe).

It's actually not as complicated as you might think.  First, remember that even a GUI needs to be able to render text, so you can read filenames, labels on controls, or work with text inside of programs.  It does this by having font files that contain descriptions of how to turn various characters into glyphs (shapes) on-screen or in a printout.

Once you understand that basic principle, the answer is obvious: you can make a console program on top of a GUI by having an emulation layer that renders the text the way a CLI would and a font file that looks like console text.  (Note: I'm not actually claiming that that's the way Windows does it.  I don't know how it works under the hood.  But it could easily be done that way.)

As for the second part of your question, as to how graphics get rendered, yes, there's a special memory location somewhere that holds pixel data.  That's called a frame buffer.  Back in the old days, you could get direct access to the frame buffer and play around with its pixels directly.  Nowadays, that's highly discouraged if not impossible, for various reasons. Instead, you go through higher-level graphic-drawing APIs, where you describe to the system what you want to do and it takes care of the details.

This has several advantages.  First, it means that you don't need to know where the framebuffer is in memory or how exactly its data is formatted.  Second, and closely related to the first point, different video card manufacturers can set up their framebuffers in different ways, and you don't need to know how to write specific graphics code for each version.  You let the graphics APIs take care of that.  And third, (and closely related to the second point,) it means that things can change in the future without breaking existing code.

For example, there was a major change in the way Windows handles forms ("windows") when they introduced Vista, that you probably never noticed unless you do graphics programming.  It used to be that every form got drawn directly to the screen.  This meant, among other things, that if you dragged a second form over a visible form and then away again, the form on the bottom would have to repaint itself because that image data was lost.

But Vista introduced a compositing window manager, which basically means that each form gets its own virtual framebuffer somewhere in memory, and it just draws everything to the screen based on position and Z-order.  Now you can drag one form in front of another all you want and it won't invalidate the other form's pixel data; forms only need to be repainted when their own content changes.  And they were able to implement that and make it work just fine on existing programs because the existing programs all use predefined drawing APIs.


问:
How do you achieve a numeric versioning scheme with Git?
My organization is considering moving from SVN to Git. One argument against moving is as follows:

How do we do versioning?

We have an SDK distribution based on the NetBeans Platform. As the SVN revisions are simple numbers we can use them to extend the version numbers of our plugins and SDK builds. How do we handle this when we move to Git?

Possible solutions:

Using the build number from Hudson (Problem: you have to check Hudson to correlate that to an actual Git version)

Manually upping the version for nightly and stable (Problem: Learning curve, human error)

If someone else has encountered a similar problem and solved it, we'd love to hear how.

答:
This might be a bit overkill, but I'll let you know how we do it.

We use a branching structure very similar to this.

Hudson builds off our "develop" branches and increments build numbers starting from 0.
The build number is unique to each project and gets tagged in version control. The reason is so that you can tell exactly which develop branch build 42 came from, for example (each project can have several develop branches in parallel, because each project can have several teams working on different aspects of the project).

When we decide that a particular build is good enough to be released, the commit that triggered that build gets tagged with a release version number, which is decided by marketing. This means that the dev teams don't care about what the final version number is and marketing is free to shuffle around version numbers as it sees fit. The final version number and build number are both present in the released product.

Example: 2.1.0 build 1337

This means, for a specific product release, you can tell which was the last team to have worked on it and you can query git for all the commits leading up to release to diagnose a problem if you need to.


答:
I think the problem is that you are comparing cleanly written server side templating to badly written ad-hoc client side HTML generation.  Of course the cleanly written code is easier to read, maintain, and trace.

You call the client side code "mounds of HTML", but of course it's the same HTML wherever it's generated.  The "mound" is really the big lump of code.

There are lots of client side templating libraries out there.  They work similarly to the server side ones.  As for which you should prefer, the performance tradeoff is complicated, but JSON is usually more compact than the HTML it becomes and having the template on the client may eliminate some server calls.  On the other hand, the client may have JS disabled, or be too slow to be practical, so it depends on your target audience as well.  Overall I think the approaches are pretty comparable, with the biggest factor being your target audience's browser capabilities.

But it depends on exactly what you are doing, whether you prefer JS to your server environment, which templating solution you prefer, etc.

Title: When should JavaScript generate HTML?


问:
Design patterns - do you use them?
Being an IT student, I was recently given some overview about design patterns by one of our teachers. I understood what they are for, but some aspects still keep bugging me.

Are they really used by the majority of programmers?

Speaking of experience, I've had some troubles while programming, things I could not solve for a while, but Google and some hours of research solved my problem. If somewhere in the web I find a way to solve my problem, is this a design pattern? Am I using it?

And also, do you (programmers) find yourself looking for patterns (where am I supposed to look, by the way?) when you start the development? If so, this is certainly a habit that I must start to embrace.

UPDATE: I think when I ask if programmers do use them, I'm asking if when you have a problem to solve you think "Oh, I should use that pattern".

答:
Design Patterns were not taught when I was in school.  And, for most of my programming career, I've worked with legacy, non-object oriented code.  In recent years, I've tried to learn them because they sound like such a good idea.  However, I must confess that every time I've ever picked up a book or tried to read a tutorial on the subject, my eyes have glazed over and I've not really learned anything practical about them at all.

I can't believe I just admitted that in public.  I think I've probably just lost any geek cred I may have established over the years.

Title: Design patterns - do you use them?


问:
Does making source code available affect your ability to generate revenue?
We’re working on a .Net framework which ultimately amounts to a single DLL.  We intend to charge for commercial use of the framework, but make it free for open source/non-commercial use.  The rough plan at the moment is to administer this through some form of fairly simple licence which will be issued whether you’re using it for free or paying.

We’re debating whether to make the source code available.  It’s our perception (and our own preference) that it’s far more appealing to use something where you have access to the source code.

I’m interested in whether people think making the source code available will damage our ability to make money from the framework, or whether it will encourage more usage and enough “good” people will arrange to pay for the correct licence if using it commercially.

My feeling is that, generally, commercial operations don’t mess about on the licencing front and so making the source code available will only encourage usage and therefore ultimately generate more revenue, but I’d be interested in others views/experience.

答:
Making a $ from something where the source is given away is kinda hard.

The idea of selling licenses which include the source is more sensible, especially on the context of this being a library. People will have to poke into the internals now and again and that needs to be easy for them to do.

Just putting up everything, source and all, and expecting revenue? Might get a few who pay, but there will be a large number who won't.


问:
Why are statements in many programming languages terminated by semicolons?
Is there a reason that a semi-colon was chosen as a line terminator instead of a different symbol?

I want to know the history behind this decision, and hope the answers will lead to insights that may influence future decisions.

答:
It's largely an arbitrary choice.  Some languages have made other choices.  COBOL terminates statements with the . character.  FORTRAN, BASIC, and Python generally terminate statements with newlines (with special syntax for multi-line statements).  And Lisp brackets its statements with parentheses.

The main reason ; is so popular as a statement separator/terminator is that most of today's popular languages are based on ALGOL, which used that convention.

instead of a different symbol?

What other symbol could you pick?

The ASCII characters #$@[]^_`{|}~ weren't always present in early character encodings like ISO 646.

The characters ()*+-/<=> are typically used as mathematical operators and would create parsing ambiguities if used as statement terminators.

```<code>product = a * b *  // If '*' were a statement terminator,
c * d *            // Are there two factors, or four?
</code>```

Similar problems would apply to ' and ", which are typically used as string delimiters; ,, which is typically used to separate function arguments, and ., which is typically used as a decimal point (or as a delimiter in constructs like some_struct.some_field).

That leaves !%&:;?.

Choosing ! or ? probably wouldn't cause technical difficulties, but their English meanings would give the wrong mood to the program.

```<code>print(x)?  # Yes, you should.
           # It's an IMPERATIVE language; stop questioning my commands.
print(x)!  # OK!  You don't have to shout!
</code>```

The & would be a more sensible choice as a statement separator (not terminator), because

```<code>do_thing_a() &
do_thing_b()
</code>```

can be read as a command to do thing A and then do thing B.  But most languages with an & operator use it as a logical or bitwise AND instead.

The % sign might cause confusion in statements like interest_rate = 2.99% (which would set the variable to 2.99 instead of the expected 0.0299).  Of course, the well-known mathematical meaning of % didn't stop C from using it as the remainder operator.

So that leaves : and ;.

: is a sensible choice, and indeed is used as the intra-line statement separator in most dialects of BASIC.

But ; has English grammar on its side; it can be used to separate clauses within a sentence.

Body:
It's largely an arbitrary choice.  Some languages have made other choices.  COBOL terminates statements with the . character.  FORTRAN, BASIC, and Python generally terminate statements with newlines (with special syntax for multi-line statements).  And Lisp brackets its statements with parentheses.

The main reason ; is so popular as a statement separator/terminator is that most of today's popular languages are based on ALGOL, which used that convention.

instead of a different symbol?

What other symbol could you pick?

The ASCII characters #$@[]^_`{|}~ weren't always present in early character encodings like ISO 646.

The characters ()*+-/<=> are typically used as mathematical operators and would create parsing ambiguities if used as statement terminators.

product = a * b *  // If '*' were a statement terminator,
c * d *            // Are there two factors, or four?

Similar problems would apply to ' and ", which are typically used as string delimiters; ,, which is typically used to separate function arguments, and ., which is typically used as a decimal point (or as a delimiter in constructs like some_struct.some_field).

That leaves !%&:;?.

Choosing ! or ? probably wouldn't cause technical difficulties, but their English meanings would give the wrong mood to the program.

print(x)?  # Yes, you should.
           # It's an IMPERATIVE language; stop questioning my commands.
print(x)!  # OK!  You don't have to shout!

The & would be a more sensible choice as a statement separator (not terminator), because

do_thing_a() &
do_thing_b()

can be read as a command to do thing A and then do thing B.  But most languages with an & operator use it as a logical or bitwise AND instead.

The % sign might cause confusion in statements like interest_rate = 2.99% (which would set the variable to 2.99 instead of the expected 0.0299).  Of course, the well-known mathematical meaning of % didn't stop C from using it as the remainder operator.

So that leaves : and ;.

: is a sensible choice, and indeed is used as the intra-line statement separator in most dialects of BASIC.

But ; has English grammar on its side; it can be used to separate clauses within a sentence.


问:
Differences between software testing processes and techniques?
I get confused between these terms. For example, should unit testing be listed as a software testing process or technique? I think unit testing is a software testing technique. And how about Test driven development? Can you give me some examples for software testing processes and techniques?

In my opinion, software testing process is a part of the software development life cycle. For example, if we use V-Model, the software testing process will be System test, Acceptance test, Integration Test.

答:
A process is a series of actions or operations leading towards a particular result.  A technique is a practical method, skill, or art applied to a particular task.

Unit testing is both a process and a set of techniques.  You employ the process to achieve your particular aim, which is to obtain a level of confidence that the software works as it should.  But you apply a set of techniques to execute that process, which are the skills you developed to implement your unit tests.


问:
Storage of value types and reference types in .net
In .net, the value types are stored on stack where as reference types are stored on managed heap. What is the reason for this one? Is it not possible to exchange their storage locations?

答:
The stack is an implementation detail.  The important thing is the reference/value distinction.

Is it not possible to exchange their storage locations?

It's very easy to store value types on the heap.

```<code>class ReferenceInt
{
    public int Field;
}

ReferenceInt n = new ReferenceInt();
// n.Field is now stored on the heap.
</code>```

Body:
The stack is an implementation detail.  The important thing is the reference/value distinction.

Is it not possible to exchange their storage locations?

It's very easy to store value types on the heap.

class ReferenceInt
{
    public int Field;
}

ReferenceInt n = new ReferenceInt();
// n.Field is now stored on the heap.

ContentLicense: CC BY-SA 4.0


答: These brilliant articles by Eric Lippert should tell you what you need to know. To sum up: don't worry about it.</p>

Title: Storage of value types and reference types in .net

Body: In .net, the value types are stored on stack where as reference types are stored on managed heap. What is the reason for this one? Is it not possible to exchange their storage locations?


问:
Thick models Vs. Business Logic, Where do you draw the distinction?
Today I got into a heated debate with another developer at my organization about where and how to add methods to database mapped classes.  We use sqlalchemy, and a major part of the existing code base in our database models is little more than a bag of mapped properties with a class name, a nearly mechanical translation from database tables to python objects.

In the argument, my position was that that the primary value of using an ORM was that you can attach low level behaviors and algorithms to the mapped classes.  Models are classes first, and secondarily persistent (they could be persistent using xml in a filesystem, you don't need to care).  His view was that any behavior at all is "business logic", and necessarily belongs anywhere but in the persistent model, which are to be used for database persistence only.

I certainly do think that there is a distinction between what is business logic, and should be separated, since it has some isolation from the lower level of how that gets implemented, and domain logic, which I believe is the abstraction provided by the model classes argued about in the previous paragraph, but I'm having a hard time putting my finger on what that is.  I have a better sense of what might be the API (which, in our case, is HTTP "ReSTful"), in that users invoke the API with what they want to do, distinct from what they are allowed to do, and how it gets done.

tl;dr: What kinds of things can or should go in a method in a mapped class when using an ORM, and what should be left out, to live in another layer of abstraction?

答:
This is a judgement call that really depends your anticipated size and scale of what you are developing. The most rigid approach is to limit the ORM types to a data access component and use POCOs in a common library as types referenced and used by all layers. This would allow for future physical separation as well as logical separation. You could also decide that an additional layer should exist between the UI and the business logic layer. This is usually called a Facade or Business Interface layer. This additional layer is where your "use-case code" lives. The individual loosely coupled code is called by the Facade/BI layer (e.g. Facade has a ProcessOrder() function which calls into the business logic 1:M times to perform all of the steps necessary to actually process the order).

However, all of that being said: many times this amount of architecting is simply unnecessary overkill. For example, code specifically for a simple Web site where you have no intention of packaging its components for re-use. It is perfectly valid to create an MVC Web site and use EF objects for this type of solution. If the site needs to scale out later, you can look into clustering or a process often lost fray called "refactoring."


问:
GitHub: Are there external tools for managing issues list vs. project backlog
Recently I posted one of my the projects1 on GitHub and as I was exploring capabilities of the site, I noticed they have a rather decent issue tracking section.

I want to use that section as a) other people can report bugs if they'd like and b) other people can see which bugs I'm aware of. However, as others have noted, issues list cannot be prioritized in order to create a project backlog. For now my backlog has been a text file, but I'd like to be able to have it integrated so the same information isn't maintained in different places.

Having a fully ordered list, which is something we also practice at work, has been very useful as I can open one file, start with line 1 and fire off 2 or 3 items in one sitting without having to go back to a full issues/stories bucket. GitHub doesn't offer this.

What GitHub does offer is a very nice and clean API so issues can easily be exported into anything else. I've searched to see if there are other websites (like Trello) that integrate with GitHub issues, but did not find anything.

Does anyone know of such a product, service or offline tool? Those that use GitHub, what is your experience in managing backlog? I kinda hate the idea of manually managing two disconnected lists like some people seem to be doing with Wiki project pages.

1 - are shameless plugs allowed no this site? Searched but didn't find a definite answer. If it's bad practice, STOP and don't read further

As a developer I got sick and tired of navigating to same set of folders 30 times a day, so I wrote a little, auto-collapsible utility that gets stuck to the desktop and allows easy access to the folders you constantly use.

答:
I did a little digging around and didn't quite find what I was looking for.  So then I looked at GitHub and Trello Web Service APIs and asked myself, how bad can it be to just write a synchronizer utility that would take issues from one place and synchronize it with the other one.

I started another project on GitHub, TrackerSync.  It is in rather rough form at the moment, but so far it got me exactly what I was looking for. I can use GitHub's Issues list to have myself or others report issues.  When the utility is executed, those issues automagically show up in Trello, where I can add them to a prioritized backlog. When I move the issue in Trello from the backlog into "completed" list, next utility run will go back to GitHub and close the corresponding issue.

If there's any interest in this utility, I'll be more than happy to continue refining it.


问:
Practical considerations for HTML / CSS naming conventions (syntax)
Question: what are the practical considerations for the syntax in class and id values?

Note that I'm not asking about the semantics, i.e. the actual words that are being used, as for example described in this blogpost. There are a lot of resources on that side of naming conventions already, in fact obscuring my search for practical information on the various syntactical bits: casing, use of interpunction (specifically the - dash), specific characters to use or avoid, etc.

To sum up the reasons I'm asking this question:

The naming restrictions on id and class don't naturally lead to any conventions

The abundance of resources on the semantic side of naming conventions obscure searches on the syntactic considerations

I couldn't find any authorative source on this

There wasn't any question on SE Programmers yet on this topic :)

Some of the conventions I've considered using:

UpperCamelCase, mainly as a cross-over habit from server side coding

lowerCamelCase, for consistency with JavaScript naming conventions

css-style-classes, which is consistent with naming of css properties (but can be annoying when Ctrl+Shift+ArrowKey selection of text)

with_under_scores, which I personally haven't seen used much

alllowercase, simple to remember but can be hard to read for longer names

UPPERCASEFTW, as a great way to annoy your fellow programmers (perhaps combined with option 4 for readability)

And probably I've left out some important options or combinations as well.  So: what considerations are there for naming conventions, and to which convention do they lead?

答:
It's mostly a matter of preference; there is no established standard, let alone an authoritative source, on the matter. Use whatever you feel most comfortable with; just be consistent.

Personally, I use css-style-with-dashes, but I try to avoid multi-word class names and use multiple classes wherever possible (so button important default rather than button-important-default). From my experience, this also seems to be the most popular choice among high-quality web sites and frameworks.

Lowercase with dashes is also easier to type than the other options (excluding the hard-to-read nowordseparatorswhatsoever convention), at least on US keyboards, because it doesn't require using the Shift key.

For id's, there is the additional practical consideration that if you want to reference elements by their ID directly in javascript (e.g. document.forms[0].btn_ok), dashes won't work so well - but then, if you're using jQuery, you're probably going to use them through $() anyway, so then you can just have $('#btn-ok'), which makes this point mostly moot.

For the record, another convention I come across regularly uses Hungarian warts in ID's to indicate the element type, especially for form controls - so you'd have #lblUsername, #tbUsername, #valUsername for the username label, input, and validator.


答:
Just remind your colleague that you don't need to overarchitect the models as if this was a Java project. I mean, comparing two persisted objects is behavior, but it's none specified by the persistence layer. So the 6 beer question is: why have completely unrelated classes describing something about the same thing? Sure, persistance is a big aspect enough of a model to be treated separately, but not enough to warrant for it to be treated distinct of everything else. If you drive your car, wash it or bust it, your manipulating your car the whole time.

So why not just compose all these different aspects into a single model class? You need a bunch of class methods dealing with persisted objects--put them in one class; you have a bunch of instance methods dealing with validation--put them in another one. Finally, mix the two in and voila! You got yourself a smart, self-aware and fully contained model representation right there.

Title: Thick models Vs. Business Logic, Where do you draw the distinction?

Body:
Today I got into a heated debate with another developer at my organization about where and how to add methods to database mapped classes.  We use sqlalchemy, and a major part of the existing code base in our database models is little more than a bag of mapped properties with a class name, a nearly mechanical translation from database tables to python objects.

In the argument, my position was that that the primary value of using an ORM was that you can attach low level behaviors and algorithms to the mapped classes.  Models are classes first, and secondarily persistent (they could be persistent using xml in a filesystem, you don't need to care).  His view was that any behavior at all is "business logic", and necessarily belongs anywhere but in the persistent model, which are to be used for database persistence only.

I certainly do think that there is a distinction between what is business logic, and should be separated, since it has some isolation from the lower level of how that gets implemented, and domain logic, which I believe is the abstraction provided by the model classes argued about in the previous paragraph, but I'm having a hard time putting my finger on what that is.  I have a better sense of what might be the API (which, in our case, is HTTP "ReSTful"), in that users invoke the API with what they want to do, distinct from what they are allowed to do, and how it gets done.

tl;dr: What kinds of things can or should go in a method in a mapped class when using an ORM, and what should be left out, to live in another layer of abstraction?


问:
Who uses GnuSTEP?
This has been a big question lurking at the back of my head. From what I see, GnuSTEP nowadays is primarily a "hobby" project of a small but tightly-knit group of people. However I haven't seen a large commercial (off-the-shelf) application that uses it, apart from the small applications that comes with the GnuSTEP distribution.

Heck, since even Ubuntu doesn't really use it then is GnuSTEP really more than being a "hobby" framework?

I know that Sony's SNAP at one brief moment uses GnuSTEP, but they killed the platform before it can do anything meaningful.

答: There's Étoilé, a project trying to make a desktop environment based on GnuSTEP, but it seems to be far from anything usable yet.</p>

Title: Who uses GnuSTEP?


答:
I'm mostly with you; your colleague seems to be arguing either for the anemic domain model antipattern or for duplicating the model in a "persistence model" with no obvious benefit (I'm working on a Java project where this was done, and it's a massive maintainability headache, as it means three times the work whenever anything changes in the model).

What kinds of things can or should go in a method in a mapped class when using an ORM, and what should be left out, to live in another layer of abstraction?

Rule of thumb: the class should contain logic that describes basic facts about the data which are true under all circumstances. Logic that is specific to a use case should be somewhere else. An example is validation, there's an interesting article from Martin Fowler where he makes the point that it should be considered context-dependant.


答:
Don't look for trendiness

Any standard programming solution to a certain problem can be considered a design pattern, it doesn't matter how popular they are, or if other programmers use them or not.

You might already be using a design pattern that hasn't been invented/specified yet.

Don't try using them, try thinking in their terms

The problem with design patterns is that sometimes programmers want to fit their problems into them when it is the other way around.

Remember design patterns' design convention have a typical problem to solve, you can even combine design patterns to tackle other bigger problems. This is kind of typical in Service-Oriented Architectures, just see some of the SOA patterns there are.

Look for them in the wild

There are plenty of open source projects where you will find applied design patterns. One example that comes to mind is Joomla: you will find singletons, observers. GUI libraries will have the decorator pattern, command pattern implemented, and maybe even flyweight.

There are other patterns such as data patterns, for example the Doctrine Project alone has used, the active record pattern (1.x), entity manager pattern(2.x), unit of work, repository, query object, metadata mapping, data mapping, and other more general ones like the strategy pattern, and decorator pattern.

There are just so many interesting solutions to choose. See Martin Fowler's Patterns of Enterprise Architecture, there are also data model patterns.

Just learn them for when the time comes

Learn them, know them, obsess over them and when the time comes you'll know how to solve programming problem x, you will be a better programmer already by that time.

Become an architect

I'd say that being able to think in pattern terms to solve problems, effectively turns you into a software architect. Even if you don't want to be a software architect per se, your solutions will have more technical quality, be cleaner and better scalability —in terms of design— by default.

Title: Design patterns - do you use them?

Body:
Being an IT student, I was recently given some overview about design patterns by one of our teachers. I understood what they are for, but some aspects still keep bugging me.

Are they really used by the majority of programmers?

Speaking of experience, I've had some troubles while programming, things I could not solve for a while, but Google and some hours of research solved my problem. If somewhere in the web I find a way to solve my problem, is this a design pattern? Am I using it?

And also, do you (programmers) find yourself looking for patterns (where am I supposed to look, by the way?) when you start the development? If so, this is certainly a habit that I must start to embrace.

UPDATE: I think when I ask if programmers do use them, I'm asking if when you have a problem to solve you think "Oh, I should use that pattern".


答:
My mantra on that is: when its easier and nobody cares about the markup.

You can also leverage both and define a limit where its just too difficult to care about the markup and you'd rather focus on the DOM tree. For example, a form that has dynamic rows (e.g. "add another attachment"), you'd probably want the form in HTML, the "add row" button, and the submit button... you probably don't want to generate the HTML with your server-side language or something.

Another rule of thumb can be reusability. If your solution can be applied to other problems on the client side, encapsulate it in js.

Title: When should JavaScript generate HTML?


答:
There's a list of corporate developers and users. I'm at the inception of a project using GNUstep. I also still work with the people at Brainstorm (see the list), and used to work there myself: they employ some of the GNUstep project maintainers and their technology stack is based on it. However that's not a COTS package.

TestPlant's product, EggPlant is a cross-platform Objective-C product based on GNUstep. They document that in their press release(PDF).

Title: Who uses GnuSTEP?

Body:
This has been a big question lurking at the back of my head. From what I see, GnuSTEP nowadays is primarily a "hobby" project of a small but tightly-knit group of people. However I haven't seen a large commercial (off-the-shelf) application that uses it, apart from the small applications that comes with the GnuSTEP distribution.

Heck, since even Ubuntu doesn't really use it then is GnuSTEP really more than being a "hobby" framework?

I know that Sony's SNAP at one brief moment uses GnuSTEP, but they killed the platform before it can do anything meaningful.


问:
Design in "mixed" languages: object oriented design or functional programming?
In the past few years, the languages I like to use are becoming more and more "functional". I now use languages that are a sort of "hybrid": C#, F#, Scala. I like to design my application using classes that correspond to the domain objects, and use functional features where this makes coding easier, more coincise and safer (especially when operating on collections or when passing functions).

However the two worlds "clash" when coming to design patterns. The specific example I faced recently is the Observer pattern. I want a producer to notify some other code (the "consumers/observers", say a DB storage, a logger, and so on) when an item is created or changed.

I initially did it "functionally" like this:

```<code>producer.foo(item => { updateItemInDb(item); insertLog(item) })
// calls the function passed as argument as an item is processed
</code>```

But I'm now wondering if I should use a more "OO" approach:

```<code>interface IItemObserver {
  onNotify(Item)
}
class DBObserver : IItemObserver ...
class LogObserver: IItemObserver ...

producer.addObserver(new DBObserver)
producer.addObserver(new LogObserver)
producer.foo() //calls observer in a loop
</code>```

Which are the pro and con of the two approach? I once heard a FP guru say that design patterns are there only because of the limitations of the language, and that's why there are so few in functional languages. Maybe this could be an example of it?

EDIT:
In my particular scenario I don't need it, but.. how would you implement removal and addition of "observers" in the functional way? (I.e. how would you implement all the functionalities in the pattern?) Just passing a new function, for example?

答:
I can't really answer the question because I'm not good at functional languages; but I think you should be less concerned about approach as long as what you have works. From what I understand , as long as you are not adding more listeners in the future or not changing the listeners during execution, you can very well skip the Observer pattern here.

I disagree that design patterns make up for "limitations" in OO languages. They are there to make good use of OOP features. Polymorphism and inheritance are features, not limitations. Design patterns make use of these features to promote flexible design. You can make an absolutely non-OO program in an OO. You can, with a lot of care, write an entire program containing objects which have no state, mimicking FP.


问:
What is better for coding - desktop or laptop?
Use of desktops are decreasing day by day in daily life but for coding purpose are there any reasons for using desktop over laptop? </p>

答:
The major plus point with a laptop is portability, and that's a huge plus, but a desktop has the following performance and productivity advantages:

Bigger screen. The average desktop screen is larger than the average laptop screen and you have the option of going all the way up to 30" or so. A laptop can do the same resolution, yes, but the pixels are tiny.

Multiple monitors. Yes, the same thing could be achieved using a laptop and a USB/PCMCIA video card, but then you'd be tied to a desk.. defeating the point of the laptops' portability as they'd need to be at the same height to avoid getting a crick in your neck.

Faster/Multiple CPUs. A desktop can have the very fastest of processors and more than one processor too. A top-of-the-line laptop has a fast processor, but it usually tops out at a Core i5 and never the fastest.

Better/Multiple Graphics cards. A desktop can have multiple high-end graphics cards, possibly linked together.

Lots of RAM. If you want fast response, you put in  as much RAM as you can afford. Not having to swap memory gives a massive performance boost, even if you were using Solid State Drives.

Choice of Keyboard. You can have a bigger keyboard with dedicated function buttons (Volume, Cut/Copy/Paste, etc) and even a split one for improved ergonomics.

Choice of Mouse. You could even have a vertical mouse, trackball or graphics tablet, since you're already sat at a desk. It's hard to use a mouse

Better Speakers. The speakers built into a laptop are very small and often cheap.

Wired networking. No need to worry about Google Street View reading your emails if you're not using Wifi. If you've another machine on the same network (e.g. NAS device), it's a lot quicker to use Wired networking.

Remote Access. It's easy to install secure remote access software such that you can get to your desktop PC from your Phone or some other PC. Many routers can be configured to wake up the PC from 'off' (not just sleep), especially if you have AMT.

Faster/Multiple Hard Drives. SSD is the fastest, yes, but also expensive for lots of storage. If you're doing serious video editing, you'd want multiple hard drives, which is difficult in a laptop. Yes, you could connect a big USB drive to a laptop, but that's a hassle and can't easily be done in the airplane/bus/train.

Better/More webcams. The webcam built into a laptop is often fairly poor compared to a decent HD USB webcam.

Expansion. All of the above hardware items can be upgraded at any time without replacing the entire machine.


问:
How to deal with tautology in comments?
Sometimes I find myself in situations when the part of code that I am writing is (or seems to be) so self-evident that its name would be basically repeated as a comment:

```<code>class Example
{
    /// <summary>
    /// The location of the update.
    /// </summary>
    public Uri UpdateLocation { get; set; };
}
</code>```

(C# example, but please refer to the question as language-agnostic).

A comment like that is useless; what am I doing wrong? Is it the choice of the name that is wrong? How could I comment parts like this better? Should I just skip the comment for things like this?

答: Comments should describe the code, not duplicate it. This header comment just duplicates. Leave it out.

Title: How to deal with tautology in comments?


答:
I'd say it depends on the purpose of the comments.

If they're to be used to generate documentation for use by the team building it (or if they're just inline comments to explain things), then I think it's acceptable to leave that out. It can be safely assumed that it's self-explanatory; and when it's not, there are other team members nearby who can explain it. Of course, if it turns out it's not self-evident for a lot of people, you should add it in.

If the comments will generate documentation for some geographically distant team, then I would put every bit of documentation in there.

Title: How to deal with tautology in comments?

Body:
Sometimes I find myself in situations when the part of code that I am writing is (or seems to be) so self-evident that its name would be basically repeated as a comment:

```<code>class Example
{
    /// <summary>
    /// The location of the update.
    /// </summary>
    public Uri UpdateLocation { get; set; };
}
</code>```

(C# example, but please refer to the question as language-agnostic).

A comment like that is useless; what am I doing wrong? Is it the choice of the name that is wrong? How could I comment parts like this better? Should I just skip the comment for things like this?


答:
I think this topic has been discussed fairly extensively under names like "comments: anti-patterns", or "are comments a code smell?" (one example).

I tend to agree with the general idea that comments should add new information, not duplicate.  By adding trivial comments like that, you are violating DRY, and decreasing the signal to noise ratio of the code.  I tend to find high-level comments explaining the responsibilities, rationale behind, and example usage of the class much more useful than per-property comments (especially superfluous ones).

Personally, in your example, I would leave comment out (if there really is nothing useful to add about the property).

Title: How to deal with tautology in comments?


问:
DI/IoC in Java for a .NET'er used to Castle.Windsor
Is there a Java DI container that works in a similar way to the most excellent Castle.Windsor container on the .NET side?

The Java containers I've had a look at all seem to rely on annotations (Guice) within my services, which I don't dig all that much - I'd like to go POJO all the way if possible. Spring on the other hand can do without the annotations, but it requires a lot of XML. XML configuration != maintainability.

One of the really nice things about Castle.Windsor is the wiring you're able to set up in code with Installers, auto wiring based on naming conventions and whatnot.

Ideally the container should also support lifecycle management and configuration; i.e. registering components as transient, singleton, pooled etc.

Another bonus would be support for interceptors.

Any tips would be greatly appreciated.

答: The most popular DI containers in Java are PicoContainer, Guice and Spring, I'm not sure how they compare to the .NET one you mentioned.</p>


答:
If you can write code that does not require comments then you have achieved programming nirvana!.

The less comments your code requires the better the code!

Title: How to deal with tautology in comments?


答:
Leave them out!

Normally, it is good practice to remove comments where the information expressed in them is already present elsewhere. If you can express the purpose of a method clearly and unambiguously by giving it a good name then there is no need for a comment.

Put them in!

Your example illustrates two exceptions to this rule:

First, "UpdateLocation" may (depending on context) be ambiguous. In that case, you either need to give it a better name or provide a comment to remove the ambiguity. Improving the name is generally the better option, but this is not always possible (when you are implementing a published API, for example).

Second, the "///" in C# indicates a comment that is intended to be used to auto-generate documentation. The IDE uses these comments to tool-tips, and there are tools (Sandcastle) that can generate help files and so forth from these comments. As such, there are arguments for inserting these comments even if the methods they document already have descriptive names. Even then, however, many experienced developers would frown on the duplication of information. The deciding factor should be the needs of those for whom the documentation is intended.

Title: How to deal with tautology in comments?


答:
Do fill comments like that only if you know how you'd benefit from stuff like that; otherwise just wipe them.

To me, case of clear benefit was when there was an automated check for missing comments and I was using that check to detect code where important information needed to be filled; for this I was indeed filling some placeholders - just to make sure that tool report does not contain "false alarms".

I think there is always a way to avoid blatant duplication. Over years I've come to using couple "template fillers" for cases like yours - mostly like self-descriptive name and see above.

For this particular example, I would use something of "self-descriptive kind" (assuming it's not the case where wiping out would do the job), like that:

```<code>class Example
{
    /// <summary>
    /// Self descriptive method name.
    /// </summary>
    public Uri UpdateLocation { get; set; };
}
</code>```

Example when I could use see above kind fillers would be Javadoc comments that require dedicated fields for return value, parameters and exceptions. Quite frequently, I find that it makes better sense to describe most or even all these in single summary sentence, method that returns <describe what is returned> for provided parameters <describe parameters>. In cases like that, I fill in formally required fields with plain see above, pointing reader to summary description.

Title: How to deal with tautology in comments?

Body:
Do fill comments like that only if you know how you'd benefit from stuff like that; otherwise just wipe them.

To me, case of clear benefit was when there was an automated check for missing comments and I was using that check to detect code where important information needed to be filled; for this I was indeed filling some placeholders - just to make sure that tool report does not contain "false alarms".

I think there is always a way to avoid blatant duplication. Over years I've come to using couple "template fillers" for cases like yours - mostly like self-descriptive name and see above.

For this particular example, I would use something of "self-descriptive kind" (assuming it's not the case where wiping out would do the job), like that:

class Example
{
    /// <summary>
    /// Self descriptive method name.
    /// </summary>
    public Uri UpdateLocation { get; set; };
}

Example when I could use see above kind fillers would be Javadoc comments that require dedicated fields for return value, parameters and exceptions. Quite frequently, I find that it makes better sense to describe most or even all these in single summary sentence, method that returns <describe what is returned> for provided parameters <describe parameters>. In cases like that, I fill in formally required fields with plain see above, pointing reader to summary description.


答:
Comments should never duplicate your code. Comments should not answer the "how?" question, but only "why?" and "what?". Why such an algorithm is chosen, what are the implicit assumptions here (unless your language is powerful enough to express it with type system, contracts and alike), what is a reason for doing this thing at all, etc.

I'd recommend to take a look at the Literate Programming practice for an inspiration.

Title: How to deal with tautology in comments?


答:
I strongly disagree with the "don't write comments" responses. Why? Let me point out by changing your example a bit.

```<code>public Uri UpdateLocation ();
</code>```

So what does this function do:

Does it return the "update location"?
or

Does it "update" the location and return the new location?

You can see that without a comment there is ambiguity. A newcommer can easily make the mistake.

In your example, it is a property so the "get/set" methods reveal that the second option is incorrect and it does indeed mean "update location" and not "update the location". But it is far too easy to make this mistake, especially in cases of ambiguous words such as "update". Play safe. Don't confuse someone new to this just for saving a few seconds of your time.

Title: How to deal with tautology in comments?

Body:
I strongly disagree with the "don't write comments" responses. Why? Let me point out by changing your example a bit.

public Uri UpdateLocation ();

So what does this function do:

Does it return the "update location"?
or

Does it "update" the location and return the new location?

You can see that without a comment there is ambiguity. A newcommer can easily make the mistake.

In your example, it is a property so the "get/set" methods reveal that the second option is incorrect and it does indeed mean "update location" and not "update the location". But it is far too easy to make this mistake, especially in cases of ambiguous words such as "update". Play safe. Don't confuse someone new to this just for saving a few seconds of your time.


问:
design for supporting entities with images
I have multiple entities like Hotels, Destination Cities etc which can contain images. The way I have my system setup right now is, I think of all the images belonging to this universal set (a table in the DB contains filePaths to all the images).

When I have to add an image to an entity, I see if the entity exists in this universal set of images. If it exists, attach the reference to this image, else create a new image. E.g.:

```<code>class ImageEntityHibernateDAO {
        public void addImageToEntity(IContainImage entity, String filePath,
                String title, String altText) {
            ImageEntity image = this.getImage(filePath);

            if (image == null)
                image = new ImageEntity(filePath, title, altText);

            getSession().beginTransaction();
                entity.getImages().add(image);
            getSession().getTransaction().commit();

        }
}
</code>```

My question is: Earlier I had to write this code for each entity (and each entity would have a Set collection). So, instead of re-writing the same code, I created the following interface:

```<code>public interface IContainImage {
    Set<ImageEntity> getImages();
}
</code>```

Entities which have image collections also implements IContainImage interface. Now, for any entity that needs to support adding Image functionality, all I have to invoke from the DAO looks something like this:

```<code>// in DestinationDAO::addImageToDestination {
imageDao.addImageToEntity(destination, imageFileName, imageTitle, imageAltText);

// in HotelDAO::addImageToHotel {
imageDao.addImageToEntity(hotel, imageFileName, imageTitle, imageAltText);
</code>```

It'd be great help if someone can provide me some critique on this design ? Are there any serious flaws that I'm not seeing right away ?

答:
I could be wrong but from the question I got an impression that an Entity could only have one image attached to it. If it is only image per Entity then why to have this kind of structuring? IMHO, you would be paying a performance penalty to search whether an image already exists in set before adding to it.

Wouldn't a simpler design would have been to have a 1:1 relationship between entities like Hotel, Cities and ImageEntity?

Even if you need a set of images for an Entity like Hotel - it should still be a 1:M relationship between them. A universal set is not going to give you the advantage as the image of an entity can't be reused for other entities.


答:
The functional version is much shorter, easier to maintain, easier to read, and generally, vastly superior in just about every respect imaginable.

Many- although, far from all- patterns are to make up for the lack of features in OOP, such as Observers. Those are far better modelled functionally.

Title: Design in "mixed" languages: object oriented design or functional programming?

Body:
In the past few years, the languages I like to use are becoming more and more "functional". I now use languages that are a sort of "hybrid": C#, F#, Scala. I like to design my application using classes that correspond to the domain objects, and use functional features where this makes coding easier, more coincise and safer (especially when operating on collections or when passing functions).

However the two worlds "clash" when coming to design patterns. The specific example I faced recently is the Observer pattern. I want a producer to notify some other code (the "consumers/observers", say a DB storage, a logger, and so on) when an item is created or changed.

I initially did it "functionally" like this:

```<code>producer.foo(item => { updateItemInDb(item); insertLog(item) })
// calls the function passed as argument as an item is processed
</code>```

But I'm now wondering if I should use a more "OO" approach:

```<code>interface IItemObserver {
  onNotify(Item)
}
class DBObserver : IItemObserver ...
class LogObserver: IItemObserver ...

producer.addObserver(new DBObserver)
producer.addObserver(new LogObserver)
producer.foo() //calls observer in a loop
</code>```

Which are the pro and con of the two approach? I once heard a FP guru say that design patterns are there only because of the limitations of the language, and that's why there are so few in functional languages. Maybe this could be an example of it?

EDIT:
In my particular scenario I don't need it, but.. how would you implement removal and addition of "observers" in the functional way? (I.e. how would you implement all the functionalities in the pattern?) Just passing a new function, for example?


问:
Creating database connections - Do it once or for each query?
At the moment I create a database connection when my web page is first loaded. I then process the page and run any queries against that conection. Is this the best way to do it or should I be creating a database connection each time I run a query?

p.s It makes more sense to me to create 1 connection and use it but I don't know if this can cause any other issues.

I am using C# (ASP.NET) with MSSQL.

答:
Best practice it to create one connection per query - and in the case of displaying data, best practice is to have the query bring in all the needed data in one go.

Background information:

In .NET, calling SqlConnection.Open() will by default always transparently use connection pooling (see "Using Connection Pooling with SQL Server" on MSDN). So you can just grab a new connection using Open(), and call Close() when you're done, and .NET will do the right thing.

Note that without connection pooling, one connection per query would be a very bad idea because creating real database connections can be very costly (authentication, network overhead etc.), and the number of simultaneous open connections is usually very limited.


答:
That's a good example of two different approaches that carry the notion of performing a task outside the boundary of concern for the calling object.

While it's clear in this example that you should go for the functional approach, in general it will really depend on how complex the behavior the called object has to exhibit is. If it really is a matter of complex behavior, where you'll find yourself reapplying similar logic often, and function generators cannot be used to clearly express it, then you'll probably want to go for class composition or inheritance, where you'll have a bit more freedom to reuse and extend existing behavior on an ad-hoc basis.

One pattern I did observe, though, is that usually developers go for the functional approach initially and only once the demand for more granular behavior arises they decide to go for a class-based approach. I know, for instance, Django went from function-based views, template loaders and test runners to class-based ones once the benefits and requirements became obvious, but not before that.


答:
If you create one per query / transaction, it is much easier to manage "closing" the connections.

I can see why common sense dictates that you should open one and use it throughout, but you will run into problems with dropped connections and multithreading. So your next step will be to open a pool, say of 50, connections and keep them all open, doling them out to different processes. And then you'll find out that this is exactly what the .NET framework does for you already.

If you open a connection when you need it and dispose of it when you've finished, that will not actually close the connection, it'll just return it to the connection pool to be used again.

Title: Creating database connections - Do it once or for each query?

Body:
At the moment I create a database connection when my web page is first loaded. I then process the page and run any queries against that conection. Is this the best way to do it or should I be creating a database connection each time I run a query?

p.s It makes more sense to me to create 1 connection and use it but I don't know if this can cause any other issues.

I am using C# (ASP.NET) with MSSQL.


问:
When you write wrappers for APIs how do you handle usage errors?
When you write wrappers for APIs how do you handle usage errors?

Do you assume that the user uses it right and write the wrapper such that it makes the call to the server and let the server return the error?

Or do you check for the missing parameters and return an error? If yes, how do you convey the error? a string or an error code?

答:
A lot of the answer depends on the API you're wrapping, the target audience for wrapping it and the language you're using. If you're exposing an API written in one particular technology to a different technology, there'd be value in smoothing out some of the common problems in the wrapped technology. For example, .NET wraps up some Win32 APIs, like CreateFile() to read a file. It's quite easy to use the wrong parameters for CreateFile(), so if you want to do something simple like read a text file, there's a utility function to achieve just that operation, rather than just encapsulating each function with a wrapped version.

Checking the input parameters for empty/null/out-of-range before calling the wrapped API would have value, but not if its at the expense of performance - better to decipher the problem when the wrapped function fails.

Exceptions, if available in your wrapping language, would be appropriate for conveying errors to the caller.


问:
Using macro as an abstraction layer
I am having a discussion with a colleague about using macro as a thin (extremely) layer of abstraction vs using a function wrapper. The example that I used is

Macro way.

```<code>#define StartOSTimer(period)  (microTimerStart(period))
</code>```

Function wrapper method

```<code>void StartOSTimer(period)
{
    microTimerStart(period);
}
</code>```

Personally, I liked the second method as it allows for future modification, the #include dependencies are also abstracted as well.

答: Macros are hideous abominations that should be avoided in every situation you can possibly get away with. You'd have to have a fairly extreme justification to use one.</p>

Title: Using macro as an abstraction layer


答: Since you use wrapper, you can also use it with a function pointer. If you use it as such, you can pass a stub function, and unit test functions that uses it. You can not do it with macro.</p>

Title: Using macro as an abstraction layer

Body:
I am having a discussion with a colleague about using macro as a thin (extremely) layer of abstraction vs using a function wrapper. The example that I used is

Macro way.

```<code>#define StartOSTimer(period)  (microTimerStart(period))
</code>```

Function wrapper method

```<code>void StartOSTimer(period)
{
    microTimerStart(period);
}
</code>```

Personally, I liked the second method as it allows for future modification, the #include dependencies are also abstracted as well.


问:
creative & complex vs simple and readable
Which is a better option?

It's not always that when you have something creative your code is going to look ugly.

But at times it does go a bit ugly.

e.g.

```<code>if ( (object1(0)==object2(0) &&
     (object1(1)==object2(1) &&
     (object1(2)==object2(2) &&
     (object1(3)==object2(3) )
    retval = true;
else
    retval = false;
</code>```

is simple and readable

```<code>bool retValue = (object1(0)==object2(0)) &&
                (object1(1)==object2(1)) &&
                (object1(2)==object2(2)) &&
                (object1(3)==object2(3));
</code>```

but having something like this will make some newbies scratch their heads.

So what do I go for? including simple code everywhere might sometime hamper my performance.

What I could think of was commenting wherever necessary but at times you get too curious to know what is actually happening.

答:
When doing any sort of optimization - whether trying to write it all in one line (optimizing my time), or use a shortcut to do the work (optimizing the compiler's time, or maybe the end user's time) - I try to balance the gain against the loss of time on the part of the reader who will come along later and try to understand my code.

One way to try to judge the cost/benefit is to add a comment to the optimized code that will make it as clear as the readable version. If it's too hard to explain well in a comment, it might be too costly.


答:
Edit: The first revision of the question for which I have provided the answer below was changed. Since the question has already been well answered, I won't update this answer.

Your first approach is extendable to accommodate for more occurrences. If in the future your business would require to accommodate 50 objects for example, you must go with the first approach and even abstract the count by providing a variable limit for the loop. If this is not the case, option 2 is better because it is much simpler, contains less variables, and more concise.

Side notes:

1-What if one of the objects is null? Is this possible? One should consider this case.

2-Why did you not initialize the result before the loop in method 1? It is a good practice to do that.*

Title: creative & complex vs simple and readable

Body:
Which is a better option?

It's not always that when you have something creative your code is going to look ugly.

But at times it does go a bit ugly.

e.g.

```<code>if ( (object1(0)==object2(0) &&
     (object1(1)==object2(1) &&
     (object1(2)==object2(2) &&
     (object1(3)==object2(3) )
    retval = true;
else
    retval = false;
</code>```

is simple and readable

```<code>bool retValue = (object1(0)==object2(0)) &&
                (object1(1)==object2(1)) &&
                (object1(2)==object2(2)) &&
                (object1(3)==object2(3));
</code>```

but having something like this will make some newbies scratch their heads.

So what do I go for? including simple code everywhere might sometime hamper my performance.

What I could think of was commenting wherever necessary but at times you get too curious to know what is actually happening.


问:
How do I showcase my work experience in programming?
I'm a student of web development languages like PHP, Ruby, and Python. Currently I'm working on some school projects but I'm trying to work on some weekend projects which I can use to showcase for potential employers, what's the best way to set this up? Specifically, are there any tips you have for a new programmer because I don't want opinions on how this or that should or shouldn't be set up. If possible please give real examples.

Edit: what about Git? Is this a good place to show my projects?

答:
I would suggest looking into the Google AppEngine as it allows you to deploy your web application (Python/Java) to their servers for free for small projects.  You can then have a persistent showcase for your abilities.

Then make that application do something useful and make it as good as you can.  Also make the code easily accessible so they can see how good you are at writing maintainable code.


问:
How to deal with transactions when creating a database connection for each query
In line with this post here I am going to change my website to create a connection per query to take advantage of .NET's connection pooling. With this in mind, I don't know how I should deal with transactions. At the moment I do something like (psuedo code):

```<code>GlobalTransaction = GlobalDBConnection.BeginTransaction();
try
{
    ExecSQL("insert into table ..")
    ExecSQL("update some_table ..")
    ....
    GlobalTransaction.Commit();
}catch{
    GlobalTransaction.Rollback();
    throw;
}
</code>```

ExecSQL would be like this:

```<code>using (SqlCommand Command = GlobalDBConnection.CreateCommand())
{
    Command.Connection = GlobalDBConnection;
    Command.Transaction = GlobalTransaction;
    Command.CommandText = SQLStr;
    Command.ExecuteNonQuery();
}
</code>```

I'm not quite sure how to change this concept to deal with transactions if the connection is created within ExecSQL because I would want the transaction to be shared between both the insert and update routines.

答:
You should be using TransactionScope for transactions in .NET:

```<code>using(var tx = new TransactionScope())
{
    ExecSQL("insert into table ..")
    ExecSQL("update some_table ..")
    ....
    tx.Complete();
}
</code>```

The above code will ensure both statements will belong to one transaction.

You can nest TransactionScopes if needed.

Body:
You should be using TransactionScope for transactions in .NET:

using(var tx = new TransactionScope())
{
    ExecSQL("insert into table ..")
    ExecSQL("update some_table ..")
    ....
    tx.Complete();
}

The above code will ensure both statements will belong to one transaction.

You can nest TransactionScopes if needed.


答:
Your second version IS far more simple and readable, and much better in every way. It's not creative or complex, but perfectly normal, straightforward code.

The only way in which it might confuse newbies is that it requires them to understand that complex boolean expressions are A) still expressions like any other and B) can be used wherever a boolean value is required, rather than just inside an if clause.

But this is something newbies really need to understand, so you should never let the possibility of someone not yet understanding it influence your code.


答:
I don't see what's creative about either example at all, you're mostly just changing whitespace.
If you think it's (potentially) unclear, try clarifying your intent, eg:

```<code>bool sameForEvery(int begin, int end)
{
  for (int i = begin; i <= end; ++i)
  {
    if (object1(i) != object2(i)) return false;
  }
  return true;
}

bool allthesame = sameForEvery(0, 3);
</code>```

in general, understanding the implementation is easier if you know what the code is trying to achieve, and if the function (and variables) are well-named, you don't need to read the implementation to have a reasonable idea what the caller is doing.

Edit: went back and read the original version of the question.

Are you suggesting that manually unrolling this loop is a complex optimisation that might confuse people?

Body:
I don't see what's creative about either example at all, you're mostly just changing whitespace.
If you think it's (potentially) unclear, try clarifying your intent, eg:

bool sameForEvery(int begin, int end)
{
  for (int i = begin; i <= end; ++i)
  {
    if (object1(i) != object2(i)) return false;
  }
  return true;
}

bool allthesame = sameForEvery(0, 3);

in general, understanding the implementation is easier if you know what the code is trying to achieve, and if the function (and variables) are well-named, you don't need to read the implementation to have a reasonable idea what the caller is doing.

Edit: went back and read the original version of the question.

Are you suggesting that manually unrolling this loop is a complex optimisation that might confuse people?


答: Respect to above mentioned example, both are readable and understandable perfectly.  In general we should balance both.</p>


问:
When should JavaScript generate HTML?
I try to generate as little HTML from JavaScript as possible. Instead, I prefer to manipulate existing markup whenever I can and only generate HTML when I need to dynamically insert an element that isn't a good candidate for using Ajax. This, I believe, makes it far easier to maintain the code and quickly make changes to it because the markup is easier to read and trace. My rule of thumb is: HTML is for document structure, CSS is for presentation, JavaScript is for behavior.

However, I've seen a lot of JS code that generates mounds of HTML, including entire forms and content-heavy modal dialogs. In general, which method is considered best practice? In what circumstances should JavaScript be used to generate HTML and when should it not?

答:
There is a trend to use client-side templates, in extreme case you'd have server providing only RESTful API for example in JSON format, while doing all rendering client side. The advantage of that approach is that JS code and templates are static resources that can be cached, proxied and distributed via CDN. Which cannot be done if you have server-side generated dynamic HTML. Also, returning just data from RESTful API in lightweight format uses much less server-side resources, making response faster. Also being lighter it's less network transfer, which again makes it faster. This way you can have very responsive low-latency application even on slow connections such as 3G. Thus this approach is popular for mobile pages and applications.

There are numerous libraries implementing JS templates, one of the popular ones are Pure,  Mustache and dust.js. Later is used by LinkedIn, they have described the advantages in their article "Leaving JSPs in the dust: moving LinkedIn to dust.js client-side templates".

Title: When should JavaScript generate HTML?


问:
The need for source control software - Team Foundation Server? or something different?
Recently,

Here at the company, more than one programmer was appointed in charge for a LightSwitch(C#) software development project and immediately there was a need of some sort of source control/sync.

We have never used Team Foundation Server but we'd gladly use it if it's worth it.

Is it the right tool to use for
synchronising code between
programmers?

Does it have the needed features?

Do you have any other tool in
mind? (I have used TortoiseSVN but
it was too simple and 'texty' if you
know what I mean, we need a
professional tool)

What other features does Team
Foundation has that we can use?

(if you did not understand any of the above please ask me to clarify further)

答:
I aggree with gbjbaanb and Ladislav Mrnka. Both are right.

Team Foundation is a powerfull Application Lifecycle Management Tool. For my projects it fits all the need's I need to care about. But what are your needs?

There would never be one perfect solution for every project. Some like SVN, some like Git some something else. But for that you need to take care about your project needs. Do you only use Source Control? Do you need the Management Tools? How much do you want to pay for it.

I like TFS very much. It has good process templates, like scrum 2.0 (upcomming tfs version), check-in validation, fxcop integration, reports, good security system. The build service is good too, but it needs alot of work to do it the way it should work.

So maybe clarify what you need and search for some products and compare them. Take the product which fits your needs the best.


问:
Why the recent shift to removing/omitting semicolons from Javascript?
It seems to be fashionable recently to omit semicolons from Javascript. There was a blog post a few years ago emphasising that in Javascript, semicolons are optional and the gist of the post seemed to be that you shouldn't bother with them because they're unnecessary. The post, widely cited, doesn't give any compelling reasons not to use them, just that leaving them out has few side-effects.

Even GitHub has jumped on the no-semicolon bandwagon, requiring their omission in any internally-developed code, and a recent commit to the zepto.js project by its maintainer has removed all semicolons from the codebase. His chief justifications were:

it's a matter of preference for his team;

less typing

Are there other good reasons to leave them out?

Frankly I can see no reason to omit them, and certainly no reason to go back over code to erase them. It also goes against (years of) recommended practice, which I don't really buy the "cargo cult" argument for. So, why all the recent semicolon-hate? Is there a shortage looming? Or is this just the latest Javascript fad?

答:
semi colons in JavaScript are optional

My personal reason for not using semi colons is OCD.

When I use semi colons I forget 2% of them and have to constantly check / add them back in.

When I don't use semi colons I never accidentally put one in so I never have to check / remove them.


问:
Reporting in Visual Studio 2010 Express
I want to download Visual Studio 2010 Express Edition to learn all that is new in it. I find it insufficient as there is no Crystal Reports integration in it. Apart from that I want to learn other enterprise features that are bundled with the Professional Edition.

If I download the VS 2010 Professional Edition, it is just limited to 90 days. Is there any other alternative for learners?

Also, is there any FREE alternative for reporting in Express Edition.

答:
After 30 days, you must 'register' the software using a .NET passport account, which is free.

While the product suite is complete - you can write code, no problem - a lot of the interesting features are not there. No class diagrams, mixed-language projects, etc and certainly not any 'Enterprise Features'. In fact, you're actually downloading an ISO file with 4 distinct products in it, so it doesn't feel as 'integrated' as VS Pro.

Title: Reporting in Visual Studio 2010 Express


问:
Adding complexity to remove duplicate code
I have several classes that all inherit from a generic base class. The base class contains a collection of several objects of type T.

Each child class needs to be able to calculate interpolated values from the collection of objects, but since the child classes use different types, the calculation varies a tiny bit from class to class.

So far I have copy/pasted my code from class to class and made minor modifications to each. But now I am trying to remove the duplicated code and replace it with one generic interpolation method in my base class. However that is proving to be very difficult, and all the solutions I have thought of seem way too complex.

I am starting to think the DRY principle does not apply as much in this kind of situation, but that sounds like blasphemy. How much complexity is too much when trying to remove code duplication?

EDIT:

The best solution I can come up with goes something like this:

Base Class:

```<code>protected T GetInterpolated(int frame)
{
    var index = SortedFrames.BinarySearch(frame);
    if (index >= 0)
        return Data[index];

    index = ~index;

    if (index == 0)
        return Data[index];
    if (index >= Data.Count)
        return Data[Data.Count - 1];

    return GetInterpolatedItem(frame, Data[index - 1], Data[index]);
}

protected abstract T GetInterpolatedItem(int frame, T lower, T upper);
</code>```

Child class A:

```<code>public IGpsCoordinate GetInterpolatedCoord(int frame)
{
    ReadData();
    return GetInterpolated(frame);
}

protected override IGpsCoordinate GetInterpolatedItem(int frame, IGpsCoordinate lower, IGpsCoordinate upper)
{
    double ratio = GetInterpolationRatio(frame, lower.Frame, upper.Frame);

    var x = GetInterpolatedValue(lower.X, upper.X, ratio);
    var y = GetInterpolatedValue(lower.Y, upper.Y, ratio);
    var z = GetInterpolatedValue(lower.Z, upper.Z, ratio);

    return new GpsCoordinate(frame, x, y, z);
}
</code>```

Child class B:

```<code>public double GetMph(int frame)
{
    ReadData();
    return GetInterpolated(frame).MilesPerHour;
}

protected override ISpeed GetInterpolatedItem(int frame, ISpeed lower, ISpeed upper)
{
    var ratio = GetInterpolationRatio(frame, lower.Frame, upper.Frame);
    var mph = GetInterpolatedValue(lower.MilesPerHour, upper.MilesPerHour, ratio);
    return new Speed(frame, mph);
}
</code>```

答:
You've gotta ask yourself the question, "why should I refactor it"? In your case when you have "similar but different" code if you make a change to one algorithm you need to make sure that you also reflect that change in the other spots. This is normally a recipe for disaster, invariably someone else will miss one spot and introduce another bug.

In this case, refactoring the algorithms into one giant one will make it too complicated, making it too difficult for future maintenance. So if you can't factor out the common stuff sensibly, a simple:

```<code>// this code is similar to class x function b
</code>```

Comment will suffice. Problem solved.

Body:
You've gotta ask yourself the question, "why should I refactor it"? In your case when you have "similar but different" code if you make a change to one algorithm you need to make sure that you also reflect that change in the other spots. This is normally a recipe for disaster, invariably someone else will miss one spot and introduce another bug.

In this case, refactoring the algorithms into one giant one will make it too complicated, making it too difficult for future maintenance. So if you can't factor out the common stuff sensibly, a simple:

// this code is similar to class x function b

Comment will suffice. Problem solved.


问:
Why rails use yaml to config database instead of plain ruby code?
Most of configuration files in ruby such as Gemfile, gemspec, are just ruby code itself. Why database configuration file in rails is the exception?</p>

答: Personal theory is ruby code is scary to administrators, and the one configuration file they would often have to mess with is the database configuration. YAML is a bit more approachable.</p>


答:
I have two theories:

A)

The thing about this choice is that back in the day, when JSLint etc. were applicable, you were choosing to spend a large amount of time catching obscure syntax errors, or a reasonable amount of time enforcing a standards policy on code.

However, as we move more towards Unit Test-driven code and continuous integration the amount of time (and human interaction) required to catch a syntax error has decreased massively. Feedback from tests will quickly indicate if your code is working as expected, well before it gets near an end-user, so why waste time adding optional verbosity?

B)

Lazy programmers will do anything to make their own lives easier in the short term. Less typing -> less effort -> easier. (also, not having to semicolon will avoid straining your right-hand ring-finger, avoiding some RSIness).

(N.B. I disagree with the idea of omitting something that disambiguates a statement).

Title: Why the recent shift to removing/omitting semicolons from Javascript?

Body:
It seems to be fashionable recently to omit semicolons from Javascript. There was a blog post a few years ago emphasising that in Javascript, semicolons are optional and the gist of the post seemed to be that you shouldn't bother with them because they're unnecessary. The post, widely cited, doesn't give any compelling reasons not to use them, just that leaving them out has few side-effects.

Even GitHub has jumped on the no-semicolon bandwagon, requiring their omission in any internally-developed code, and a recent commit to the zepto.js project by its maintainer has removed all semicolons from the codebase. His chief justifications were:

it's a matter of preference for his team;

less typing

Are there other good reasons to leave them out?

Frankly I can see no reason to omit them, and certainly no reason to go back over code to erase them. It also goes against (years of) recommended practice, which I don't really buy the "cargo cult" argument for. So, why all the recent semicolon-hate? Is there a shortage looming? Or is this just the latest Javascript fad?


问:
How Does Download Size Affect Potential Users of Your Product
Does anyone know (or, I guess, I have gut feeling about) how the download size of a software product affects potential users, bandwidth not withstanding?

For example: Does a bigger download make them
   believe that is it more full-featured
   than it is (like huge .NET Runtimes
   if deployed with your package)?

Reason is, I'm developing a VSTO add-in where there is my add-in (small MB), the VSTO run-time, .NET runtime, and Primary Interops. This could make it more than 70 MB in total size, just for an add-in that does a couple of things well. But that's all they are - just a couple of things.

With VSTO deployments, I know I could deploy a smaller package size by assuming they've got the .NET runtime (and when they don't, initialize the download/install of that, but it seems like a clunky way to make just an ass out of me).

What I really want is for people to just download the app (the trial version) to see if they like it. Is there some kind of magic happy threshold - like users of non-big name apps are more likely to download something that is under 20 MB than 50 MB?

答:
Look at the motivation for Microsoft developing the .NET Client Profile - a smaller download because 350MB for the full .NET framework installer is pretty big. As @Jason says, people are impatient - don't assume that they're on  wired networking or a decent broadband connection. Indeed, this site is migrating from the West Coast to the East Coast of the US to address performance concerns.. and this site is mostly text.

There's no need to ship the frameworks as part of your install - the VS Installer support will check for the existence of your dependent frameworks and instruct the user how to get them.


问:
How do I prevent useless content load on the page in responsive design?
In responsive design, elements are hidden in the page with @media queries and display: none in CSS.

Ok.

In my design however browsers that have less than 800px in width should avoid loading some content at all.

When accessed with on a device with more than 800px of screen, the page loads fully. In mobile devices or even on desktop with less than 800px of width some content is hidden.

I want to make the page load faster for low-resolution devices and avoid loading chunks of content that the user will never see. How can I go about this?

答:
How about deferred loading of the content?

Insert some javascript which verifies screen resolution or some other parameters and only loads the content when the correct values are met.


问:
Project life cycle management - Maven vs 'manual' approach
I have a question concerning the life cycle management of a/multiple project(s), more specific to the advantages/disadvantages of using technologies such as Maven.

Currently we work in a continuous-integration environment but lots of things still need to be manually performed (dependency management, deploying, setting up documentation, generating stats, ...). My impression is that this approach often leads to errors, miscommunications or things just are forgotten.

I know and have used Maven in the past but in smaller environments and I was always really enthusiastic about it. But I was wondering if someone could share some insights, experiences, pros, contras, ... about the use of Maven (or similar technology) in larger environments and for multiple projects.

I would like to use the suggestions made here to start the debate about moving to the next level in project management!

答:
We use maven as our core build system on our huge enterprise system.  It is worth its weight in gold.  We use it to manage dependencies, both for third party libraries and internal modules, to package the application for deployment, to version the application, and generally to do everything else we don't feel like doing manually :-)

When coupled with something like Nexus, Maven is fantastic.  Everyone's guaranteed to be working against the same dependencies, and the POM files are supported very well by IDEs such as Eclipse.

I couldn't go back to doing stuff without Maven; it's just too useful.

The only cons I can think of is that working with Maven means you have to think like Maven - your projects must be done the Maven way and you must show other non-maven devs how to make their projects in the maven way.  It has a non-trivial learning curve.


问:
What is a non commital approach to software analysis
When I think about software analysis the first thing which comes to mind is SSADM and the UML.

But, what I want is a high level view of the system before I commit to a programming paradigm.

Where am I going wrong?

How do I approach a problem in a high level and generic way before I commit to a paradigm?

What are the diagrams/tools available to support me?

Edit:

Some examples of tools that appear to be what I'm after are...

A block diagram - http://en.wikipedia.org/wiki/Block_diagram

A data flow diagram - http://en.wikipedia.org/wiki/Data_flow_diagram

答:
UML offers a variety of diagrams to model your system for various purposes.

The first and foremost aspect of the software to re-engineer or to engineer a software for the required system is the overall Business Scenario (what objectives and goals the software/system should meet). The formal phrase for such requirements is "Business Requirements".

Then comes the requirements, the intended users of the system should be able to meet to achieve the objectives. These are called "User Requirements".

You can model User Requirements in UML by using Use-Case Diagrams. This modeling should be prior to your functional (this includes DFD, ERD) and non-functional requirements (environment, constraints, platform, sclability).


问:
How to measure team productivity in Agile project environment?
Are there any techniques other than velocity? What are pros and cons of using those from your experience?</p>

答:
No I don't think additional metrics are useful or accurate. Some stories require minimal code changes, but lots of time doing other things such as testing, talking to customers, gathering requirements, going to meetings with stakeholders, analyzing the problem, etc etc. Most of these tasks cannot be easily quantified or reduced to a simple metric.

Its still useful to represent these things as stories, because a story is really a piece of functionality from the customer's PoV. They don't care if it takes 1 line of code or 1000. But a good team will realize that the assigned story points are not simply a function of the code size, there's lots of other pieces of work that need to be done. The types of work are so varied and different that finding a uniform, quantitative way to measure them is pretty hopeless. That's why story points are used -- They are a qualitative estimate based on the team's experience with similar features in the past and what those cost in terms of story points.


问:
What's the best way to comment in a code review?
My team just started using crucible/fisheye for initiating code reviews whenever one of us checks something in. There are only 3 of us, and we're each encouraged to review the code and leave comments where we see fit.

My question is, how do I best leave a comment on a line of code I see a problem with? I want to get my point across without seeming abrasive.

I don't want to seem like I'm on a high horse and say "I've been doing it this way...
and I also don't want to seem like I'm trying to be authoritative and say something like "This should be done this way..." but I still need to get the point across that what they're doing is not very good.

To Clarify:
This is a really good resource for what I should be looking to comment on: Is a code review subjective or objective (quantifiable)?, but I'm looking for how to comment on it.

答:
If the code follows your coding standards, but you'd do it a different way you have to ask yourself if what they did is wrong.

If it's not...it's just not how you would have done it and you just can't leave it, try just asking 'Why did you do it this way instead of that way?' Then you are getting them to qualify why they did it the way they did without saying 'I would have done it this way and you should too...'

You might also learn something in the process.