答:
Linux in VM is the easiest option to learn UNIX. If you're running Ubuntu, you can open up terminal and type:

```<code>sudo apt-get install gcc
</code>```

And you'll have your compiler. Debian-based distros in general will make development very easy because if you're missing library X, chances are it's already in the repositories and you can apt-get it with minimum fuss.

For the other part of your question: no, Linux in VM is not the only way to go, but it's the easiest to get started with. You can always intall FreeBSD / Open Solaris / etc but I don't recommend those for your first plunge.

Finally, if you want to force yourself to learn the system, you can install it on bare metal and ditch the VM. I recommend dual-booting to start. You will probably start running into driver / configuration problems :) and ultimately have to learn how everything works.

Good luck.

EDIT

In reference to some comments: MinGW and Cygwin will not help the OP learn UNIX/POSIX. The OP clearly stated that she/he is interested in C programming in UNIX, and that means UNIX-specific APIs, patterns, and issues.

Title: What are the options for setting up a UNIX environment to learn C using Kernighan and Richie's The C Programming Language?

Body:
I'm a novice programmer and have been experimenting with Javascript, jQuery and PHP but felt I wasn't getting a real depth of understanding of what I was doing. So, after reading Joel Spolsky's response to a question on this site (which I can't find now!), I took it back to basics and read Charles Petzold's 'Code' and am about to move onto Kernighan and Richie's The C Programming Language. I want to learn this in a UNIX environment but only have access to a Windows system. I have Ubuntu 12.04 running on a virtualised machine via VMWare Player, and done some coding in the terminal.

Is using a Linux distro the only option for programming in a UNIX environment on Windows? And what are the next steps to start programming in C in UNIX and where do I get a compiler from?

Body:
Linux in VM is the easiest option to learn UNIX. If you're running Ubuntu, you can open up terminal and type:

sudo apt-get install gcc

And you'll have your compiler. Debian-based distros in general will make development very easy because if you're missing library X, chances are it's already in the repositories and you can apt-get it with minimum fuss.

For the other part of your question: no, Linux in VM is not the only way to go, but it's the easiest to get started with. You can always intall FreeBSD / Open Solaris / etc but I don't recommend those for your first plunge.

Finally, if you want to force yourself to learn the system, you can install it on bare metal and ditch the VM. I recommend dual-booting to start. You will probably start running into driver / configuration problems :) and ultimately have to learn how everything works.

Good luck.

EDIT

In reference to some comments: MinGW and Cygwin will not help the OP learn UNIX/POSIX. The OP clearly stated that she/he is interested in C programming in UNIX, and that means UNIX-specific APIs, patterns, and issues.


问:
How can I improve these online java programming puzzles I wrote for my (middle/high school) students?
I'm teaching some middle and high school students programming right now, and I found that some of them really liked online programming puzzles. So I created http://www.kapparate.com/coder/ , and right now there's 4 categories of puzzles.

All the puzzles are set up right now so that variables are pre-initialized, and the user plugs in some code in the middle.

For example, the problem might say these are pre-initialized:

```<code>int x = ????;
int y = ????;
int z;
</code>```

and then the program might ask the student to write the final line of code: z = x + y;.

Now I know I could go a long way in improving the usability of this site (like having an area that lists the pre-defined variables), but I was wondering if this concept seems sound. I know some sites have kids fill in functions, but not all of my students know what functions are yet, and I'm trying to introduce online programming puzzles before that.

答:
You could mix your code and English a little better. It's one of those hassles that StackExchange has tackled pretty well.  You could develop a system like here and highlight any text which is to be taken as code. Also, use a different color for mathematics, because = means different things if the context is mathematics or C.

You have side lessons within the problems. In that second question you introduce and explain the mod op. Put that in it's own paragraph or link to an aside. Or, honestly, just link it.

The actual problems are kinda buried in those paragraphs. I read through a couple and when I got to the end I had no idea what I was trying to solve for. Feel free to have background explanation (which is, you know, the educational part), but try to clearly state the problem.

And things like: "You may search the internet for the appropriate equation to use." shouldn't have to be stated. Programmers have access to the Internet. Not letting them search for solutions is as archaic as expecting them to write their solutions in pencil.

A standard form for the incoming variables and expected results would help.

A personal nitpick is the use of vague and terse variable names. If you're going to teach programming, teach them to use variable names which make sense.

So, taking a crack at rewriting one of your questions:

Complex Numbers: In mathematics, the square root of a number is X if X times X results in the number. However, the square root of negative one is known as "i". i has the properties such that i*i = -1. Complex numbers are written as the sum of their real and imaginary parts. Thus, 3+2i is a complex number with 3 and an imaginary part 2i. These complex numbers obey standard algeberic rules for adding and multiplying equations with variables. Thus, (3+2i)*5 = 15*10i. Additionally, `(a+bi)*(c+di) = a*c + a*d*i + c*b*i + b*d*i*i, which simplifies to (a*c-b*d)+(a*d+c*b)*i. Further reading: "complex numbers", "multiplying imaginary numbers", "the FOIL method", "multiplying complex binomials"

Problem: Write a function that solves (a+bi)^2.

Input:

int realPortion; //Range: any value

int imaginaryPortion; //Range: any value

Output:

realPortion should store the resulting real portion of the equation.

imaginaryPortion should store the resulting imaginary portion of the equation.

Edit

//You do not need to create double a, or double b

The word is "declare". You declare variables. They're going to run into that later and it's good to stay consistent.

hmmm, something about these implied variable declarations still bugs me. I dunno, maybe you want to explicitly show the code that comes before and after?

```<code>void Divisibility_Test()
{
  int x;
  int y;
  boolean xIsDivisibleByY;
</code>```

(text box for students to type in)

```<code>  evaluate(xIsDevisibleByY);
}
</code>```

Also, I think I have a philosophical issue with #7 which uses casting to an int to round off a double. I can't say it doesn't work. Or that it's wrong per se.

This would be above and beyond, but I imagine if you churn through enough impressionable youths you're going to hit those naturally gifted ones which plow through this. If you had challenging bonus questions you might be able to light up some inspiration and get them interested. Things like computing the Fibonacci sequence, constructing markov chains, a bot that can play checkers.

Best of luck. Teaching children to code is a daunting task and it's largely up to them. All you can do is lay out the path. Thinking back, there were an awful lot of pitfalls and hours of frustration. ...of course, that implies anything has changed.

ContentLicense: CC BY-SA 3.0

Body:
You could mix your code and English a little better. It's one of those hassles that StackExchange has tackled pretty well.  You could develop a system like here and highlight any text which is to be taken as code. Also, use a different color for mathematics, because = means different things if the context is mathematics or C.

You have side lessons within the problems. In that second question you introduce and explain the mod op. Put that in it's own paragraph or link to an aside. Or, honestly, just link it.

The actual problems are kinda buried in those paragraphs. I read through a couple and when I got to the end I had no idea what I was trying to solve for. Feel free to have background explanation (which is, you know, the educational part), but try to clearly state the problem.

And things like: "You may search the internet for the appropriate equation to use." shouldn't have to be stated. Programmers have access to the Internet. Not letting them search for solutions is as archaic as expecting them to write their solutions in pencil.

A standard form for the incoming variables and expected results would help.

A personal nitpick is the use of vague and terse variable names. If you're going to teach programming, teach them to use variable names which make sense.

So, taking a crack at rewriting one of your questions:

Complex Numbers: In mathematics, the square root of a number is X if X times X results in the number. However, the square root of negative one is known as "i". i has the properties such that i*i = -1. Complex numbers are written as the sum of their real and imaginary parts. Thus, 3+2i is a complex number with 3 and an imaginary part 2i. These complex numbers obey standard algeberic rules for adding and multiplying equations with variables. Thus, (3+2i)*5 = 15*10i. Additionally, `(a+bi)*(c+di) = a*c + a*d*i + c*b*i + b*d*i*i, which simplifies to (a*c-b*d)+(a*d+c*b)*i. Further reading: "complex numbers", "multiplying imaginary numbers", "the FOIL method", "multiplying complex binomials"

Problem: Write a function that solves (a+bi)^2.

Input:

int realPortion; //Range: any value

int imaginaryPortion; //Range: any value

Output:

realPortion should store the resulting real portion of the equation.

imaginaryPortion should store the resulting imaginary portion of the equation.

Edit

//You do not need to create double a, or double b

The word is "declare". You declare variables. They're going to run into that later and it's good to stay consistent.

hmmm, something about these implied variable declarations still bugs me. I dunno, maybe you want to explicitly show the code that comes before and after?

void Divisibility_Test()
{
  int x;
  int y;
  boolean xIsDivisibleByY;

(text box for students to type in)

  evaluate(xIsDevisibleByY);
}

Also, I think I have a philosophical issue with #7 which uses casting to an int to round off a double. I can't say it doesn't work. Or that it's wrong per se.

This would be above and beyond, but I imagine if you churn through enough impressionable youths you're going to hit those naturally gifted ones which plow through this. If you had challenging bonus questions you might be able to light up some inspiration and get them interested. Things like computing the Fibonacci sequence, constructing markov chains, a bot that can play checkers.

Best of luck. Teaching children to code is a daunting task and it's largely up to them. All you can do is lay out the path. Thinking back, there were an awful lot of pitfalls and hours of frustration. ...of course, that implies anything has changed.


问:
Why is Python used for high-performance/scientific computing (but Ruby isn't)?
There's a quote from a PyCon 2011 talk that goes:

At least in our shop (Argonne National Laboratory) we have three
  accepted languages for scientific computing. In this order they are
  C/C++, Fortran in all its dialects, and Python. You’ll notice the
  absolute and total lack of Ruby, Perl, Java.

It was in the more general context of high-performance computing. Granted the quote is only from one shop, but another question about languages for HPC, also lists Python as one to learn (and not Ruby).

Now, I can understand C/C++ and Fortran being used in that problem-space (and Perl/Java not being used). But I'm surprised that there would be a major difference in Python and Ruby use for HPC, given that they are fairly similar. (Note - I'm a fan of Python, but have nothing against Ruby).

Is there some specific reason why the one language took off? Is it about the libraries available? Some specific language features? The community? Or maybe just historical contigency, and it could have gone the other way?

答:
This is a great discussion here, I think posts here really answered why python is more popular in the scientific community. However, there are some the counter arguments for ruby sciences:

ruby can be more intuitively coded than python (DSL etc): given the right packages used:

check bioruby: http://bioruby.org/ a sequence reserve can be simply: s.reverse etc.
if you use databases: ruby database binding API is arguably better than python.

ruby allows higher level of abstractions at the same time of being terse.

better package management system: ruby gems are so easier compared to: setuptools, pip etc

However, ruby's adoption was/is/will be hindered by its complexity. I am thinking Lisp is a great/powerful language, but why it didn't take off as a general language? the similar situation is here with ruby - it inherits a lot power from lisp, small talk, and perl!: but only a selection of people will actually use it to get the benefits. In the end, it may remain strong in certain niche/special areas (such as the rail in web, puppet in configuration), it is hard for 'non'programmers to fully enjoy it, but it might be programmer's good friend (saw somecomputer scientists enjoy the language: http://www.cleveralgorithms.com/nature-inspired/index.html )

Some most recent update:it seems python is already taking over the landscape. Recently books such as: http://www.amazon.com/Python-Data-Analysis-Wes-McKinney/dp/1449319793
and many other books (data analysis, machine learning etc), are all written with python as the language used. If ruby wants to catch up, it needs some serious efforts. Considering matplotlib in python, it's probably several man years to get it to the state where it is now. Unless some serious efforts put in ruby, it probably can not catch up with the stage of python data analysis/scientific computation in the next 2-3 years.


问:
Advantages of using pure JavaScript over JQuery
What are the advantages of using Javascript-only versus using JQuery-only?

I have limited experience with JavaScript and JQuery coding. I've added bits and snippets of each to HTML pages but I've mostly coded server-side stuff in other languages. I've noticed that while you can theoretically do the same things using either of the two approaches (and of course you can even mix 'em up in the same project) there seems to be a tendency to always start using JQuery from the very beginning no-matter what the project demands are.

So I'm simply wondering, are there any punctual benefits to not use JQuery-only but instead to just use plain old JavaScript?

I know this looks like a non-question because it can be said about it that "there's no definite answer" or "it can be debated for ever", but I'm actually hoping for punctual answers such as "You can do this in one approach and you cannot do it with the other".

As per scrwtp's comment, I'm not referring just to the DOM Handling part. My question is rather: JQuery is a library. For Javascript. What I find strange about this library as opposed to other libraries for other languages is that in JQyery's case it seems to be designed to be able to use it exclusively and not need to touch Javascript directly. This is as opposed to let's say Hibernate and SQL, where even though the library (or rather framework in this case, but I think the analogy still applies) takes the handle on A LOT of aspects, you still get to use SQL when using it, at least for some fringe cases. However in JQuery & Javascript case, you could do anything you do with Javascript using only JQuery (or at least that's how it seems to me).

As per Stargazer712's comment: yes, I agree with you, the question here is, as you put it "just a matter of how you will be using JavaScript". That's what I was actually thriving to ask, but I've made some bad formulations. Here's another analogy: Spring Expression Language. It's a Java library. You can't use it without Java, it's based on Java, and down through it all you still get to use Java. But in practice what you can do is add this library to a Java project, and then write all your code using Spring EL's expression language which effectively makes your code not resemble Java at all, and it's even paradigm shifting (for example you no longer have strong type enforcement when using this). While I do understand that JQuery is just a JS library, to me it seems that in practice it has the same effect as Spring EL has with Java, i.e you can only use it's APIs through out a project and avoid JavaScript's APIs. And I was wondering if that's a good thing to do, what might be the pitfalls etc.

(and yes, after reading everyone's answers I do understand that :

a. my question is somewhat non-sensical up to a point

b. even if the question were completly accurate, the answer to it would be pretty much "no you can't just use JQuery-only all the time)

答:
I happen to mix the use of both quite a bit. The biggest reason for this is that for some applications (think chrome extensions) you don't need cross browser support. Which means that I can take advantage of new advances like css3 which with things like transitions can simplify your code a ton over the use of jquery.

Also I am often doing something custom. By all means like the others said you shouldn't re-invent the wheel. But when your asked to do some crazy functionality I often find its much easier to write it myself then to try and hack some jquery plugin that's close but not a perfect match.

I have also worked with developers that work with nothing but jquery. And I have to say that they compromised on functionality far more often then not if they couldn't find a jquery plugin that did what they wanted.

At some point in web development you will be asked to do something not pre-packaged in a library. So at that point you better make sure you understand how the base language really functions.

So TLDC: Use both, you are at a disadvantage using just vanilla and you are at a disadvantage if you don't know vanilla inside and out and insist on always using jquery.


问:
What are the options for setting up a UNIX environment to learn C using Kernighan and Richie's The C Programming Language?
I'm a novice programmer and have been experimenting with Javascript, jQuery and PHP but felt I wasn't getting a real depth of understanding of what I was doing. So, after reading Joel Spolsky's response to a question on this site (which I can't find now!), I took it back to basics and read Charles Petzold's 'Code' and am about to move onto Kernighan and Richie's The C Programming Language. I want to learn this in a UNIX environment but only have access to a Windows system. I have Ubuntu 12.04 running on a virtualised machine via VMWare Player, and done some coding in the terminal.

Is using a Linux distro the only option for programming in a UNIX environment on Windows? And what are the next steps to start programming in C in UNIX and where do I get a compiler from?

答:
OSX since 10.5 and forward is offically considered a Unix. Solaris is another option. Either one can be installed on Virtual Box, both include GCC as a compiler. Ignore cygwin under Windows, it is more trouble than it is worth, and isn't a full Unix environment/experience.

I use Virtual Box on both an OSX machine and a Windows machine to host Linux ( CentOS ) and with a dual monitor setup and plenty of RAM you don't even realize that it is not a real machine you are using.


问:
Single statement if block - braces or no?
Which is better/more generally accepted?

This:

```<code>if(condition)
{
  statement;
}
</code>```

Or:

```<code>if(condition)
  statement;
</code>```

I tend to prefer the first one, because I think it makes it easier to tell what actually belongs in the if block, it saves others from adding the braces later (or creating a bug by forgetting to), and it makes all your if statements uniform instead of some with braces and some without.  The second one, however, is still syntactically correct and definitely more compact.  I'm curious to see which is more generally preferred by others though.

答:
Braces. Always. I'm kind of the fan of them, because it gives code some consistency. And also as @dsimcha wrote - less chance for errors on adding additional lines of code.

"Ugliness" of braces around single line of code are less harmful than additional work which is probable in those cases with debugging and/or adding code.

ContentLicense: CC BY-SA 2.5


答:
If you're worried about performance, you should try to use vanilla js
whenever possible. frameworks not only add bandwidth overhead but also processing overhead. And jQuery comes with browser compatibility for pretty old browsers, too.

if you're working on mobile apps or games (or both combined) you need performance and ressource efficieny first.

jQuery and plugins might speed up your development, but especially if you rely on 3rd party jquery Plugins you should know what they are doing inside. Lots of them are bad examples of code quality and efficiency.

jQuery can be 2 to 10 times slower than native JavaScript. And it can easily encourage developers to not properly design their interface and rely on jQuery selectors too much which are much slower than native.

Title: Advantages of using pure JavaScript over JQuery

Body:
What are the advantages of using Javascript-only versus using JQuery-only?

I have limited experience with JavaScript and JQuery coding. I've added bits and snippets of each to HTML pages but I've mostly coded server-side stuff in other languages. I've noticed that while you can theoretically do the same things using either of the two approaches (and of course you can even mix 'em up in the same project) there seems to be a tendency to always start using JQuery from the very beginning no-matter what the project demands are.

So I'm simply wondering, are there any punctual benefits to not use JQuery-only but instead to just use plain old JavaScript?

I know this looks like a non-question because it can be said about it that "there's no definite answer" or "it can be debated for ever", but I'm actually hoping for punctual answers such as "You can do this in one approach and you cannot do it with the other".

As per scrwtp's comment, I'm not referring just to the DOM Handling part. My question is rather: JQuery is a library. For Javascript. What I find strange about this library as opposed to other libraries for other languages is that in JQyery's case it seems to be designed to be able to use it exclusively and not need to touch Javascript directly. This is as opposed to let's say Hibernate and SQL, where even though the library (or rather framework in this case, but I think the analogy still applies) takes the handle on A LOT of aspects, you still get to use SQL when using it, at least for some fringe cases. However in JQuery & Javascript case, you could do anything you do with Javascript using only JQuery (or at least that's how it seems to me).

As per Stargazer712's comment: yes, I agree with you, the question here is, as you put it "just a matter of how you will be using JavaScript". That's what I was actually thriving to ask, but I've made some bad formulations. Here's another analogy: Spring Expression Language. It's a Java library. You can't use it without Java, it's based on Java, and down through it all you still get to use Java. But in practice what you can do is add this library to a Java project, and then write all your code using Spring EL's expression language which effectively makes your code not resemble Java at all, and it's even paradigm shifting (for example you no longer have strong type enforcement when using this). While I do understand that JQuery is just a JS library, to me it seems that in practice it has the same effect as Spring EL has with Java, i.e you can only use it's APIs through out a project and avoid JavaScript's APIs. And I was wondering if that's a good thing to do, what might be the pitfalls etc.

(and yes, after reading everyone's answers I do understand that :

a. my question is somewhat non-sensical up to a point

b. even if the question were completly accurate, the answer to it would be pretty much "no you can't just use JQuery-only all the time)


答:
Some good answers already.  Just a few insights:

Your problems are fun but at least the first few are as much about math as about  math as about programming.  That's OK if that's the intent.

You might consider introducing the procedure fairly early on.  That would make a nice little bundle that could help define the problem statement and make testing the solution clearer.  Also, it creates a package for variables to pass into and out of.  Instead of seeing that x = 4; y = 2; x + y = 6; a procedure would give the sense of infinite variation such that int plus(int x, int y) { return ???; } would make a lot more sense and I think be clearer for a student to fill in.  It's useful (sort of) outside of the scope of the individual problem.

It's really hard to write a good problem statement.  I'm currently taking Martin Odersky's free online Scala course and I often find myself confused by his problem statements.  But he includes a few unit tests with each problem and reading his tests really nails down the scope and intent of the problem.  The actual grading uses about twice as many tests as he gives you and you are encouraged to make up your own tests.  Really, the unit testing is the first aspect of the course that I can immediately apply at work.

Title: How can I improve these online java programming puzzles I wrote for my (middle/high school) students?

Body:
I'm teaching some middle and high school students programming right now, and I found that some of them really liked online programming puzzles. So I created http://www.kapparate.com/coder/ , and right now there's 4 categories of puzzles.

All the puzzles are set up right now so that variables are pre-initialized, and the user plugs in some code in the middle.

For example, the problem might say these are pre-initialized:

```<code>int x = ????;
int y = ????;
int z;
</code>```

and then the program might ask the student to write the final line of code: z = x + y;.

Now I know I could go a long way in improving the usability of this site (like having an area that lists the pre-defined variables), but I was wondering if this concept seems sound. I know some sites have kids fill in functions, but not all of my students know what functions are yet, and I'm trying to introduce online programming puzzles before that.


问:
GPL licensed software installed on commercial hardware
Do vendors need to provide sources, at the customer's request, for GPL licensed software installed on the hardware they sell?

For example, a vendor sells an IPTV box and pre-installs some proprietary software product which is linked with some GPLed library. As a consequence, the software becomes GPLed itself.

Does the vendor need to provide the source code for it? The vendor doesn't sell that software, he sells hardware.

答:
The long answer is that you should read the terms of the GPL and see whether what you're doing constitutes distribution and what your responsibilities are.

The short answer, for most forms of copying GPL'd software, is "yes."

OwnerDisplayName: Alexander Reshytko


答: In short, yes. When it was revealed that some of the more popular wireless routers were using an open source core, (without the vendors publishing the source) many people were up in arms about it. If the software is being redistributed outside of your company, the GPL takes effect.</p>

Title: GPL licensed software installed on commercial hardware

Body:
Do vendors need to provide sources, at the customer's request, for GPL licensed software installed on the hardware they sell?

For example, a vendor sells an IPTV box and pre-installs some proprietary software product which is linked with some GPLed library. As a consequence, the software becomes GPLed itself.

Does the vendor need to provide the source code for it? The vendor doesn't sell that software, he sells hardware.


答:
Yes - the GPL says nothing about "selling" software, it talks about distributing.
If you distribute GPL software you have to abide by the licence.

The GPL3 uses a slightly different phrase "convey" - to clear up some different meanings of "distribute" in different jurisidictions


问:
How to implement a text editor in a browser?
This is purely an exercise in self improvement and education.I am trying to implement an extension for a vi-like text editor within a browser. Can anyone give any advice or pointers as to where and how I should start?</p>

答:
If you're looking to implement a code editor in the browser it's worth looking at the CodeMirror and the Ajax ACE projects. ACE is more fully featured, CodeMirror is lighter weight.

If nothing else, they should demonstrate that doing this well is a far from trivial job!


问:
Do any OO languages support a mechanism to guarantee an overriden method will call the base?
I think this might be a useful language feature and was wondering if any languages already support it.

The idea is if you have:

```<code>class C
  virtual F
     statement1
     statement2
</code>```

and

```<code>class D inherits C
  override F
     statement1
     statement2
     C.F()
</code>```

There would be a keyword applied to C.F() such that removing the last line of code above would cause a compiler error because it's saying "This method can be overridden but the implementation here needs to run no matter what".

答:
Lisp machine "flavors" allowed methods with type "before" "after" and "around" the inherited
main method.</p>


答:
First off - it's impossible to use jQuery only, all jQuery does is add a $ object to your global scope, with a bunch of methods in it. Even more manipulative libraries like prototype aren't an alternative to javascript, they're a toolbelt to solve common problems.

The main advantages to adding jQuery to your toolbelt would be:

browser compatibility - doing something like .attr() is much easier than the native alternatives, and won't break across browsers.

simplification of usually complicated operations - if you'd like to see a well written cross browser compatible version of an XHR method, take a look at the source for $.ajax - for this method alone it's almost worth the overhead of jQ.

DOM selection - simple things like binding events & selecting DOM elements can be complicated and differ per-browser. Without a lot of knowledge, they can also be easily written poorly and slow down your page.

Access to future features - things like .indexOf and .bind are native javascript, but not yet supported by many browsers. However, using the jQuery versions of these methods will allow you to support them cross browser.

Javascript is no longer just a client side language, and because jQuery is so DOM dependent, it is a terrible candidate to move to the server. I highly recommend putting some time into understanding why you are using jQuery (asking this question is a great first step!), and evaluating when it is necessary. jQuery can be dangerous, a few of the main dangers are:

code quality - jQuery has a huge community and a low learning curve. This is a perfect storm for lots of poorly written open source plugins.

inefficiency - jQuery is easy to write inefficiently. For instance, using jQuery's each instead of for loops is unnecessary and could have a performance impact in some cases. Lots of good info about this stuff at JSPerf

bloat - jQuery is a huge library. Much of the time, you'll use a small subset of it's features, and grab the whole library. There are some great alternatives that will give you subsets of the features, like zepto.js, and underscore.js - depending on your situation, you can save some bytes by choosing the right library for your needs.

Ultimately, jQuery is an incredibly useful and helpful library, when used properly. However, it is not an alternative to javascript. It is a library, just like zepto.js, YUI, Dojo, MooTools, and Prototype - one of which may be a much better choice for your current project.

Javascript is a misunderstood language, and is only recently being regarded as something more than a scripting language by most people. I really recommend reading up on it more, here's a few good places to start:

Edit 07/2014 - I noticed this post is still getting attention, so I added a bunch of links. These are in no particular order, but should be helpful.

Ben Alman's blog - lots of good best practices here. I don't agree with all of them, but I learn new things from his blog all the time.

Code Academy - basic javascript and jQuery training. Sometimes going back to basics helps.

Javascript Garden - a post regarding the more tricky or misunderstood features of javascript. Please read this from time to time, until everything makes sense.

Bocoup - these are training classes. If you're near one, go to it. Many of the best JS speakers and teachers teach these.

Paul Irish's blog - not strictly JS, but plenty of best practices are written about here. Him and Ben's twitter feeds are both great to follow.

Javascript: The Good Parts - often referred to as 'The Javascript Bible', this book by Douglas Crockford is an amazing place to start understanding javascript.

Isaac Schlueter's Blog - Isaac is the creator of npm, and works on the node core. He writes a lot about the javascript community rather than about code conventions, but if you're really getting in to js it's a great read.

Douglas Crockford's Javascript - If Brendan Eich is the father of javascript, Douglas is javascript's outspoken uncle. He is the author of the JSON spec, the javascript bible, and lots of amazing posts on javascript's quirks and meteoric rise.

Brendan Eich's Blog - Brendan is the creator of javascript - he writes about all sorts of silly stuff on his blog, and while he has his faults as a person, his javascript posts are valuable.

James Halliday's (@substack) Blog - Substack is arguably the most important node.js developer in the community - with around 400 (and growing every day) npm modules and a guiding philosophy of tiny, unix-like modules, everything he writes is worth reading.

Max Ogden's Blog Max Ogden is another prolific node.js author, and is excellent at writing blog posts that teach you something. He's also the author (with others I believe) of javascript for cats.

Javascript for Cats - This is a short tutorial that takes you through the basics of javascript from the perspective of a cat. If you're a beginner, read through this. It's fun, and teaches in an hour what many books take weeks to communicate.

Nicholas Zakas' Blog Nicholas is the author of a few fantastic javascript books: Object Oriented Programming in Javascript, Maintainable Javascript, Professional Javascript for Web Developers, and High Performance Javascript. He focuses mainly on the client, but has a ton of best practices and performance tips.

Guillermo Rauch's Blog - Guillermo is another prolific node.js dev, mostly famous for Socket.io and Mongoose. His blog (and his new book, Smashing Node.js are both great resources.

I'm sure there's lots more great resources I'm not thinking of or don't know about, other answerers should feel free to add to that list.


问:
Using T[1] instead of T for functions overloaded for T(&)[N]
The asio::buffer function has (void*, size_t) and (PodType(&)[N]) overloads.

I didn't want to write ugly C-style (&x, sizeof(x)) code, so I wrote this:

```<code>SomePacket packet[1]; // SomePacket is POD
read(socket, asio::buffer(packet));
foo = packet->foo;
</code>```

But that packet-> looks kinda weird - the packet is an array after all.

(And packet[0]. doesn't look better.)

Now, I think if it was a good idea to write such code. Maybe I should stick to unsafe C-style code with void* and sizeof?

Upd: here is another example, for writing a packet:

```<code>SomePacket packet[1]; // SomePacket is POD
packet->id = SomePacket::ID;
packet->foo = foo;
write(socket, asio::buffer(packet));
</code>```

答:
If I were you, I'd create a function:

```<code>template< typename PodType >
whatever buffer(PodType& obj) { return buffer(&obj, sizeof(obj)) }
</code>```

But this is so obvious an omission in the set of overloads provided, that I wonder if I'm missing something.

Body:
If I were you, I'd create a function:

template< typename PodType >
whatever buffer(PodType& obj) { return buffer(&obj, sizeof(obj)) }

But this is so obvious an omission in the set of overloads provided, that I wonder if I'm missing something.


问:
Can Foswiki be used as a distributed Redmine replacement?
I am quite familiar with and love using git, among other reasons due to its distributed nature. Now I'd like to set up some similarly distributed (FOSS) Project Management software with features similar to what Redmine offers, such as

Issue & time tracking, milestones

Gantt charts, calendar

git integration, maybe some automatic linking of commits and issues

Wiki (preferably with Mathjax support)

Forum, news, notifications

Multiple Projects

However, I am looking for a solution that does not require a permanently accesible server, i.e. like in git, each user should have their own copy which can be easily synchronized with others. However it should be possible to not have a copy of every Project on every machine. Since trac uses multiple instances for multiple projects anyway, I was considering using that, but I neither know how well it adapts to simply giting the database itself (which would be be easiest way to handle the distribution due to git being used anyway), nor does it include all of Redmine's feature.

After checking http://www.wikimatrix.org for Wikis with integrated tracking system and RCS support, and filtering out seemingly stale project, the choices basically boil down to Foswiki, TWiki and Ikiwiki. The latter doesn't seem to offer as many usability features, and in the TWiki vs Foswiki issue I tend to the latter. Finally, there is Fossil, which starts from the other end by attempting to replace git entirely and tracking itself. I am however not too comfortable with the thought of replacing git, and Fossil's non-SCM features don't seem to be as developed.

Are there crucial features of Project Management software like Redmine that Foswiki does not provide even with all the extensions available?

答:
I'd argue no, distributed project management apps just don't make sense -- the fundamental point of project management apps is to generate hivemind by having everything for everyone in so that pretty much means you are looking at something centralized by definition.

Now, some sort of project management tool with an offline mode so your people can access and perhaps even update things when off the grid might be worthwhile. Then again, the slice of the world where one cannot get internet access is getting pretty small for most intents and purposes.


问:
When to use C over C++, and C++ over C?
I've been introduced to Computer Science for a little over a year now, and from my experience it seems that C and C++ are both considered to be "ultrafast" languages, whereas others such as Python and such scripting languages are usually deemed somewhat slower.

But I've also seen many cases where a software project or even a small one would interleave files where a certain number n of those files would be written in C, and a certain number m of those files would be written in C++.

(I also noticed that C++ files almost always have corresponding headers, while C files not so much). But my main point of inquiry is to get a general sense of intuition on when it is appropriate to use C over C++, and when it is better to use C++ over C. Other than the facts that (1) C++ is object-oriented whereas C is not, and (2) the syntaxes are very similar, and C++ was intentionally created to resemble C in many ways, I am not sure what their differences are. It seems to me that they are (almost) perfectly interchangeable in many domains.

So it would be appreciated if someone could clear up the situation! Thanks

答:
Both languages are excellent. I think a number of posters have detailed the strengths and the various uses for each. I will simply add this:

I see the C language perfect in 4 areas: 1) I think it's the best language to use when first learning any type of programming [combined with some Assembly and knowledge of machine code], 2) it's great for writing drivers, 3) embedded software, and 4) system software at the lowest level.

C++ is an object-oriented language, but it can also be procedural (very much in the way of C). If you're working on large-scale projects, GUI-based software, gaming software, and other types of graphically-intensive software, then I find C++, Java, or even Objective-C to be your best choice. However, there is plenty of command-line programs or system software where you might find C++ to be as good or better than C.

Title: When to use C over C++, and C++ over C?


问:
Options for Opensource license?
I am choosing a license for my open source software and I've learned about GPL, EBMS and BSD. GPL seems to be most popular one.

The problems are:

Would anybody kindly name a few popular opensource licenses? Since I do not see any EBMS BSD license is popular.

Are there any chart or table that have list out the advantages/disadvantages of using anyone?

Why is the GPL always the license developers choose from, what are its benefits?

答:
According to The Register in March 2011:

At the beginning of his talk, DiBona said that
  according to Google's net crawlers, the web now
  contains over 31 million open source projects,
  spanning 2 billion lines of code. Forty-eight per
  cent of these projects are under the GPL, 23 per
  cent use the LGPL, 14 per cent use the BSD license, 6 per cent use Apache, and 5 per cent use the MIT
  license. All other licenses are used with under 5
  per cent of the projects.

Title: Options for Opensource license?


问:
How Do I Determine the Value of a Technical book?
I'm interested in finding more books like The Pragmatic Programmer. Rather than the run of the mill, technology-specific books that are out of date by the time they go to press. Can you provide advice on finding more books along that vein?</p>

答:
The majority of the tech books out there are hopping onto a particular bandwagon.  With the rate of change of technology (frameworks, languages, cloud applications, fads of the day), many tech authors write poorly done books trying to get them out there to be sold to the masses who are following the fad of the day before it changes.

As such, the books that are good are the ones that are "timeless" and don't require a given framework or language or cloud application.  These books aren't trying to solve or explore a problem that exists today, but rather a problem that has existed for all time.

The first thing to look at is that if the book was written a few years ago and is still in bookstores today, it likely is not something that will not be in a bookstore next year (double negatives are fun).

Books such as The Mythical Man Month, Programming Pearls, Design Patterns: Elements of Reusable Object-Oriented Software, and The Art of Computer Programming have been around for decades and are still good reading for a programmer.  Having a "second edition" would be a good thing when looking at technology books because it means that its lasted long enough that some parts of it need updating, but the core of the book is the same.

Look to see if there is a wikipedia article on the author of the book.  This helps to filter for the people who are more notable than the circle of a given framework (or trying to jump onto the bandwagon mentioned above).  When one sees Martin Fowler, Tom DeMarco, or Steve McConnell - there are wikipedia pages for them and one can see that these individuals are notable outside the context of a single niche of technology and what they are known for isn't going to go away in the next decade.


问:
Torvalds' quote about good programmer
Accidentally I've stumbled upon the following quote by Linus Torvalds:

"Bad programmers worry about the code. Good programmers worry about
  data structures and their relationships."

I've thought about it for the last few days and I'm still confused (which is probably not a good sign), hence I wanted to discuss the following:

What interpretation of this possible/makes sense?

What can be applied/learned from it?

答:
Linus means this:

Show me your flowcharts [code], and conceal your tables [schema], and
  I shall continue to be mystified; show me your tables [schema] and I
  won't usually need your flowcharts [code]: they'll be obvious.

-- Fred Brooks, "The Mythical Man Month", ch 9.

Title: Torvalds' quote about good programmer


问:
What's the proper way to exit program in C?
There are many ways how to exit program in C. Some of them are returning zero or error code, using exit function with EXIT_SUCCESS, EXIT_FAILURE, exit(0), exit(1) or some other error code, abort and probably few more I can't think of now.

My question is which option is the best and why. I'm asking here because every time I asked more experienced programmers this question, it ended up as a holy war.

答:
I think the best thing is return EXIT_SUCCESS or return a non-zero number for which you have documented an error code, or EXIT_FAILURE if you can't define error codes for all the conditions that could cause you to fail. This would let a program using your program (in a pipe or batch function) actually use your error code to determine what to do next if applicable.

Personally I am not married to macros that always, on every single implementation on earth equal 0 but hey that sort of comment can get you downvoted.


答:
Short Answer: Good technical book has very high review rate, and is referenced in many places.

As suggested, there is a list of influential programming books that are a great list to start from. In my opinion, if book has a reference in Wikipedia and high rating in Amazon then it is a very strong indicator of being a good Technical book !

Title: How Do I Determine the Value of a Technical book?

Body: I'm interested in finding more books like The Pragmatic Programmer. Rather than the run of the mill, technology-specific books that are out of date by the time they go to press. Can you provide advice on finding more books along that vein?</p>


问:
How to effectively do manual debugging?
Say you don't have a debugger available, what would be an effective approach to debug code which doesn't work (as expected)?</p>

答:
It depends on the bug.

If the bug is the sort of 'why is the code doing A', then it can be useful to test your own understanding of the code surrounding the location of 'code doing A'. Introduce new code that you expect to generate new bugs (this code should make it do B, this should make it do C). I usually quickly find some new code that generates behavior that I don't expect. Then I wait patiently while my mind builds an updated mental model of the code behavior so that the last change makes sense, and then that mental model change usually explains why the code is doing A.

The second case has been discussed in detail here. Where you've either inherited the code, don't have a solid mental model of how the code works, don't have a good idea on the specific location of the bug, etc. In this case, drilldown/divide-and-conquer methods with print statements can work. And if it's under source control, make sure to check the most recent code change.

Title: How to effectively do manual debugging?


问:
How does a variable introduce state?
I was reading the "C++ Coding Standards" and this line was there:

Variables introduce state, and you should have to deal with as little state as possible, with lifetimes as short as possible.

Doesn't anything that mutates eventually manipulate state? What does you should have to deal with as little state as possible mean?

In an impure language such as C++, isn't state management really what you are doing? And what are other ways to deal with as little state as possible other than limiting variable lifetime?

答:
state means that something is being stored somewhere so you can refer to it later.

Creating a variable, creates some space for you to store some data.  This data is the state of your program.

You use it to do things with, alter it, compute with it, etc.

This is state, whereas the things you do aren't state.

In a functional language, you mostly deal only with functions and passing functions around like they were objects.  Though these functions don't have state, and passing the function around, introduces no state (besides maybe inside the function itself).

In C++ you can create function objects, which are struct or class types which have operator()() overloaded.  These function objects can have local state, though this is not necessarily shared among other code in your program.  Functors (ie function objects) are very easy to pass around.  This is about as close as you can imitate a functional paradigm in C++. (AFAIK)

Having little or no state means you can easily optimize your program for parallel execution, because there's nothing that can be shared among threads or CPU's, so nothing that contention can be created about, and nothing you have to protect against data races, etc.

Title: How does a variable introduce state?

OwnerDisplayName: Tony


答:
And what does the "you should have to deal with little state" mean?

This means that your classes should be as small as possible, optimally representing a single abstraction. If you put 10 variables in your class, most likely you are doing something wrong, and should see how to refactor your class.

Title: How does a variable introduce state?

Body:
I was reading the "C++ Coding Standards" and this line was there:

Variables introduce state, and you should have to deal with as little state as possible, with lifetimes as short as possible.

Doesn't anything that mutates eventually manipulate state? What does you should have to deal with as little state as possible mean?

In an impure language such as C++, isn't state management really what you are doing? And what are other ways to deal with as little state as possible other than limiting variable lifetime?

OwnerDisplayName: BЈовић


答:
To understand how a program works, you must understand its changes of state. The less state you have and the more local it is to the code that uses it, the easier this will be.

If you've ever worked with a program that had a large number of global variables you would understand implicitly.

Title: How does a variable introduce state?

OwnerDisplayName: Mark Ransom


答:
Doesn't any mutable thing really manipulate state?

Yes.

And what does the "you should have to deal with little state" mean?

It means that less state is better than more state. More state tends to introduce more complexity.

In an impure language like C++, isn't state management really what you are doing?

Yes.

What are other ways to "deal with little state" other than limiting variable lifetime?

Minimize the number of variables. Isolate code that manipulates some state into a self-contained unit so that other code sections can ignore it.

Title: How does a variable introduce state?

OwnerDisplayName: David Schwartz


答:
Doesn't any mutable thing really manipulate state?

Yes. In C++, the only mutable things are (non-const) variables.

And what does the "you should have to deal with little state" mean?

The less state a program has, the easier it is to understand what it does. So you shouldn't introduce state that isn't needed, and you shouldn't keep it once you no longer need it.

In an impure language like C++, isn't state management really what you are doing?

In a multi-paradigm language like C++, there's often a choice between a "pure" functional or a state-driven approach, or some kind of hybrid. Historically, language support for functional programming has been fairly weak compared to some languages, but it's improving.

What are other ways to "deal with little state" other than limiting variable lifetime?

Restrict the scope as well as the lifetime, to reduce coupling between objects; favour local rather than global variables, and private rather than public object members.

Title: How does a variable introduce state?

OwnerDisplayName: Mike Seymour


答:
State is simply stored data. Every variable is really some sort of state, but we usually use "state" to refer to data that is persistent between operations. As a simple, pointless example, you may have a class that internally stores an int and has increment() and decrement() member functions. Here, the internal value is state because it persists for the life of the instance of this class. In other words, the value is the state of the object.

Ideally, the state that a class defines should be as small as possible with minimal redundancy. This helps your class meet the single responsibility principle, improves encapsulation and reduces complexity. The state of an object should be entirely encapsulated by the interface to that object. This means that the result of any operation on that object will be predictable given the semantics of the object. You can further improve encapsulation by minimizing the number of functions that have access to the state.

This is one of the major reasons for avoiding global state. Global state may introduce a dependency for an object without the interface expressing it, making this state hidden away from the user of the object. Invoking an operation on an object with a global dependency may have varying and unpredictable results.

Title: How does a variable introduce state?

OwnerDisplayName: sftrabbit


答:
Others have provided good answers to the first 3 questions.

And what are other ways to "deal with as little state as possible" other than limiting variable lifetime?

The key answer to question #1 is yes, anything that mutates eventually impacts state. The key then is to not mutate things. Immutable types, using a functional programming style where the result of one function is passed directly to the other and not stored, passing messages or events directly rather than storing state, calculating values rather than storing and updating them...

Otherwise you're left with limiting the impact of state; either via visibility or lifetime.

Title: How does a variable introduce state?


问:
What is occurring in the world of server-side technologies in regards to the mobile app boom?
With mobile technologies becoming increasingly popular what is happening on the server-side with most of these apps when they need to communicate with a back end?

I'm used to the world of technology from 10 years ago when most resources were accessed by requesting a dynamic web page that behind the seen used a server-side language to get the information it needed from a relational database.

Is this still the case, and if not, what are the big changes?

答:
From top of my head:

Use of webservices instead of direct access to DB from client.

REST instead of SOAP. SOAP seems to be too heavy-weight for mobile communication with backend. REST using JSON is much simpler to set up and consume. Especially if you use different technologies on client and server.

Focus on multiple views for webpages. One for desktop and one for mobile. It should be easy if someone uses MVC, but it is still quite problematic.

There are probably more. Mobile apps are mostly regarded as normal clients, that consume data and display them.


问:
is Java free for mobile development?
Q1. I would like to know if it's free for a developer (I mean, if I have to pay no royalties to Sun/Oracle) to develop (Android) mobile apps in Java?

After reading this snippet about use of Java field, I'm getting the impression that Java is not free for mobile development, is that right?

.."General Purpose Desktop Computers and Servers" means computers, including desktop and laptop computers, or servers, used for general computing functions under end user control (such as but not specifically limited to email, general purpose Internet browsing, and office suite productivity tools). The use of Software in systems and solutions that provide dedicated functionality (other than as mentioned above) or designed for use in embedded or function-specific software applications, for example but not limited to: Software embedded in or bundled with industrial control systems, wireless mobile telephones, wireless handheld devices, netbooks, kiosks, TV/STB, Blu-ray Disc devices, telematics and network control switching equipment, printers and storage management systems, and other related systems are excluded from this definition and not licensed under this Agreement...

and from http://www.excelsiorjet.com/embedded/

Notice : The Java SE Embedded technology license currently prohibits the use of Java SE in cell phones.

Q2. how come these plethora of Android Java developers aren't paying Sun/Oracle a dime?

答:
This is more of a licensing question and therefore might not actually be a relevant question in this space, but I believe android developers don't pay licensing fees because they build their applications on a Java system already in place (that I assume has already been paid for by Google).

So if you wanted to make your own OS on a mobile device that's built on Java, you would probably have Sun/Oracle knocking at your door.  However, if you're building this software on top of the Android system, I believe your use is already covered in the licensing Google has with Sun/Oracle.

Title: is Java free for mobile development?


问:
Is agile about development or management?
On a debate over what Scrum is all about, I found that perhaps I totally misunderstood the agile thing. It appears to me that Scrum (which is certainly considered an Agile process) is all about managing features and sprints and roles and stuff with nothing to do with TDD, pair programming, CI, refactoring and other developer centric techniques and practices that I though (until now) are the heart of agile. Now I am facing a difficulty !

1) Is Scrum agnostic to whether developers do agile practices?

2) Can you implement Scrum in a team that does not utilize automated tests? does not perform refactoring or does not adhere to the agile programming practices?

答: Infact, you can use scrum in projects that have nothing to do with software development whatsoever. It's a projectmanagement/team management method.</p>


问:
What did Bill Gosper mean by saying a data structure is just a stupid programming language?
There's a quotation by Ralph William Gosper, Jr that says:

A data structure is just a stupid programming language.

What did he mean by this?  Alas, all I can find in Google about it is relentless copy/pastes of the quotation itself, without any context.

答:
I believe that what Bill Gosper intended is that all data structures are just programming constructs with limited applicability. This is also related to the idea that "Language design is library design and library design is language design" [1].

One way of thinking about the issue is to consider data structures merely on an algorithmic basis. Forget about storage requirements or type annotations for the moment because these are simply ancillary.

For example, you could codify an associative array (called a map in some languages) in two ways: Either by using some kind of index stored in memory or by using a simple case expression.

In Haskell you could codify an associative array as a data structure...

```<code>let assocArray = [("a", 1),("b", 2),("c", 3)]
let key = "b"
lookup key assocArray
</code>```

...or by using a case expression...

```<code>let key = "b"
case key of
  "a" -> 1
  "b" -> 2
  "c" -> 3
</code>```

...or even more directly...

```<code>let key = "b"
if key == "a"
  then 1
  else if key == "b"
    then 2
    else if key == "c"
      then 3
      else undefined
</code>```

It is easy to see to that this kind of mirroring between data structures and code is possible by looking at the lambda calculus. Any value can be represented by a function in the lambda calculus and the calculus itself is universal (turing complete).

[1] The quote is thanks to Bjarne Stroustrup.

Body:
I believe that what Bill Gosper intended is that all data structures are just programming constructs with limited applicability. This is also related to the idea that "Language design is library design and library design is language design" [1].

One way of thinking about the issue is to consider data structures merely on an algorithmic basis. Forget about storage requirements or type annotations for the moment because these are simply ancillary.

For example, you could codify an associative array (called a map in some languages) in two ways: Either by using some kind of index stored in memory or by using a simple case expression.

In Haskell you could codify an associative array as a data structure...

let assocArray = [("a", 1),("b", 2),("c", 3)]
let key = "b"
lookup key assocArray

...or by using a case expression...

let key = "b"
case key of
  "a" -> 1
  "b" -> 2
  "c" -> 3

...or even more directly...

let key = "b"
if key == "a"
  then 1
  else if key == "b"
    then 2
    else if key == "c"
      then 3
      else undefined

It is easy to see to that this kind of mirroring between data structures and code is possible by looking at the lambda calculus. Any value can be represented by a function in the lambda calculus and the calculus itself is universal (turing complete).

[1] The quote is thanks to Bjarne Stroustrup.


问:
Why does Java have a "bad rap"
I hear a lot of people speak poorly of Java, especially the ones coming from C/C++. Is there a historical reason why? Is it because it used to be machines were too slow to run the JVM without lag?</p>

答:
Programmers from the 'real programmers code in binary' clan will probably hate Java till the end of time. But for the rest of us, Java helps get the job done fast and with a (slightly) shorter learning curve.

The C/C++ times gave good programmers the fun of being able to play with memory the way they wished. Java made garbage collection automatic, so that fun was lost. Also those languages compiled to machine code, and so was statistically faster because of the absence of the JVM process. But times have changed and with today's hardware this is hardly even noticeable (unless you're trying to encode video or something). Also, i must say, there is a certain added satisfaction when you pull something off (non-trivial) in C/C++ where-in you had to do all the memory management etc the hard way.

Title: Why does Java have a "bad rap"


问:
Complex Release Vehicle Management
I'm looking into improving our build and release system.  We are a .Net/Windows shop, and I don't see any really good tools for Windows for generating the files that are to be dropped in patch or hotfix.  We are currently using TFSBuild 2010 with Windows Workflows for our continuous integration builds as well as our daily full build which includes an Installshield package for deployment.

What is a good way of generating the list of files to be included in a "patch" style release, where one does not redistribute all the files, but only those necessary to accomplish the necessary changes?  Are there any open source tools that work well for this, or do teams usually roll their own?  I have considered using Beyond Compare but I would prefer something open source.  The file "patch" creation must be 100% automatable.

Which release vehicles really ought to be patch style? And which releases should replace all system files related to our application?  Assume we have a very large amount of resources necessary to maintain.

Is there any established material that is trusted within the industry for strategies about this? I realize it is different for "enterprise" rather than with typical websites. I am looking more for "enterprise" strategies due to our product distribution style.

tl;dr > Looking for info on how to ship more reliable packages?

答:
How about

http://www.codeproject.com/Articles/125721/Installer-and-Patching-Program-using-Visual-Studio

... solution that was capable of installing a .NET application for the first time, and keep it updated throughout its life cycle

Title: Complex Release Vehicle Management


答:
Generally speaking Java gets a bad rap because it's essentially relatively weak at both of it's touted strong points:

"Java is write once, deploy everywhere":  Larger programs generally don't work flawlessly across multiple platforms without additional work. EDIT --  After some research it seems that this has actually improved quite a bit since the last time I seriously used Java (good on Java!) - articles I can find are from the 90s ( http://www.mactech.com/articles/mactech/Vol.14/14.05/WritingJavaCross-Platform/index.html ).  A non-Java specific issue that may be erroneously called a Java flaw is that different platforms often just have completely different UI paradigms (e.g. mouse vs. touch, keyboard or no keyboard), and it's just downright difficult to design an application that actually works well on all possible platforms through no fault of the language.

"Java hides a lot of things that you don't have to know":  Larger programs often require additional deep knowledge of how the language and VM work to tweak things to make them work fast enough for real use (there's a whole page dedicated to it here: http://www.javaperformancetuning.com/tips/) .  This can actually cut the other way theoretically as well - a JIT-compiled Java program and/or an updated VM can have hardware-specific optimizations that weren't available at the original time of writing the program (see e.g. http://en.wikipedia.org/wiki/Java_performance#Program_speed).

There is no inherent fatal flaw with Java except that it's really not much better at anything than other languages.

However, it DOES have an impressive collection of libraries available across platforms, and it's disingenuous to consider the language only without the libraries.  As a tool to "get the job done" it's VERY general purpose "out of the box" to cover a lot of bases more than well enough for real-world usage.  It's an advanced swiss army knife, if you will (one with a lot of safety features to avoid hurting yourself).

C++ developers specifically may have a dislike for Java for some other reasons as well:

Java enforces object orientation, and "everything is an object" - multi-paradigm C++ developers are often allergic to being limited in that way (full disclosure: I'm one of that type of C++ developers :)).

As mentioned above, a hardcore Java developer needs to know the internals as well to get the maximum out of things (as is always the case, in any language), and a C++ developer is used to actually having access to those internals, so they feel (rightly or wrongly) that they might as well work close to the metal if they have to know it anyway.

Title: Why does Java have a "bad rap"

Body: I hear a lot of people speak poorly of Java, especially the ones coming from C/C++. Is there a historical reason why? Is it because it used to be machines were too slow to run the JVM without lag?</p>


答:
For every language you will find People who Speak poorly of it. It's just the way it is.

Java is no exception.

Title: Why does Java have a "bad rap"


答:
From the end-user point of view, many older Java programs (actually the JVM) used humongous amounts of memory for the simplest of programs. Often well over 100 MB for a simple FTP client or similar. Especially during times when most systems had 256 MB to 512 MB of RAM, that was simply unacceptable. And as Java programs were quite common in the desktop area, many people came to the same conclusion about memory usage.

Also, the Java Runtime Environment has a long history for severe security issues (even right now), so the reputation has dropped quite sharply with the increasing use of Java in general public.

Java Security Alerts:

http://www.oracle.com/technetwork/topics/security/alerts-086861.html#SecurityAlerts (2009 - 2012)
http://www.oracle.com/technetwork/topics/security/beaarchive-159946.html (2006 - 2009)
http://www.oracle.com/technetwork/topics/security/alertsarchive-101846.html (pre-2006)

Security Alerts

Oracle will issue Security Alerts for vulnerability fixes deemed too
  critical to wait for distribution in the next Critical Patch Update.

To me, the size of those lists is just horrendous.

Title: Why does Java have a "bad rap"


问:
String patterns that can be used to filter and group files
One of our application filters files in certain directory, extract some data from it and export a document from the extracted data. The algorithm for extracting the data depends on the file, and so far we use regex to select the algorithm to be used, for example .*\.txt will be processed by algorithm A, foo[0-5]\.xml will be processed by algo B, etc.

However now we need some files to be processed together. For example, in one case we need two files, foo.*\.xml and bar.*\.xml. Part of the information to be extracted exist in the foo file, and the other part in the bar file. Moreover, we need to make sure the wild card is compatible. For example, if there are 6 files

```<code>foo1.xml
foo23.xml
bar1.xml
bar9.xml
bar23.xml
foo4.xml
</code>```

I would expect foo1 and bar1 to be identified as a group, and foo23 and bar23 as another group. bar9 and foo4 has no pair, so they will not be treated.

Now, since the filter is configured by user, we need to have a pattern that can express the above requirement. I don't think you can express meaning like above in standard regex. (foo|bar).*\.xml will match all 6 file above and we can't identify which file is paired for a particular file.

Is there any standard pattern that can express it? Or any idea how to modify regex to support this, that can be implemented easily?

答:
I think what you have in mind could be solved by backreferences. See, for example, here:

http://msdn.microsoft.com/en-us/library/thwdfzxy.aspx

or here

http://www.regular-expressions.info/brackets.html

An expression like

```<code>(foo([0-9])\.xml) .* (bar\1\.xml)
</code>```

applied to the space separated list of file names will deliver you pairs like foo1.xml, bar1.xml as matches. Of course, you may have to solve the problem of bringing the files names into correct order before (or provide a reg exp which is indedependent from the order of files).

EDIT: concerning order of files: you could specify this with two different rules, since I guess you want your processing done in a specific order. So when the above expression delivers you a pair

```<code>(filename1,filename2)
</code>```

you run the processing algo P with parameters

```<code>P(filename1,filename2)
</code>```

and when the second rule

```<code>(bar([0-9])\.xml) .* (foo\1\.xml)
</code>```

delivers you a pair

```<code>(filename1,filename2)
</code>```

you call P with the order of the names switched:

```<code>P(filename2,filename1)
</code>```

Of course, depending on your reg exp processor, you can also use newlines for separating the file names and use multiline matching. I used whitespace above just for easier demonstration purposes.

Body:
I think what you have in mind could be solved by backreferences. See, for example, here:

http://msdn.microsoft.com/en-us/library/thwdfzxy.aspx

or here

http://www.regular-expressions.info/brackets.html

An expression like

(foo([0-9])\.xml) .* (bar\1\.xml)

applied to the space separated list of file names will deliver you pairs like foo1.xml, bar1.xml as matches. Of course, you may have to solve the problem of bringing the files names into correct order before (or provide a reg exp which is indedependent from the order of files).

EDIT: concerning order of files: you could specify this with two different rules, since I guess you want your processing done in a specific order. So when the above expression delivers you a pair

(filename1,filename2)

you run the processing algo P with parameters

P(filename1,filename2)

and when the second rule

(bar([0-9])\.xml) .* (foo\1\.xml)

delivers you a pair

(filename1,filename2)

you call P with the order of the names switched:

P(filename2,filename1)

Of course, depending on your reg exp processor, you can also use newlines for separating the file names and use multiline matching. I used whitespace above just for easier demonstration purposes.


答:
Q1

You don't need to pay Sun / Oracle any licensing fees to develop for Android.

The license text quoted in the question refers to Oracle's own Java implementations. If you want to use one of these, then you will obviously have to agree to a license under Oracle's terms. But that is completely separate from Android. There is also the OpenJDK, which is the major open source implementation of Java and can be used pretty much anywhere you like without restrictions.

Q2

This is complex, but the reasons are broadly:

Google basically engineered the whole Android stack independently from Sun/Oracle. So Oracle have no IP rights regarding the implementation.

Courts have generally maintained that you can't copyright a language syntax or API definition. So Google (and you!) can use the Java langauge syntax and core Java API definitions freely.

Oracle owns the Java trademark. So Google can't advertise Android as "Java" unless they obtain an appropriate license from Oracle. But Google doesn't really care since they are advertising it under their own Android brand instead.

Oracle tried suing Google recently over these issues, and lost pretty badly.

P.S. IANAL so don't treat this as legal advice. Obviously.

Title: is Java free for mobile development?

Body:
Q1. I would like to know if it's free for a developer (I mean, if I have to pay no royalties to Sun/Oracle) to develop (Android) mobile apps in Java?

After reading this snippet about use of Java field, I'm getting the impression that Java is not free for mobile development, is that right?

.."General Purpose Desktop Computers and Servers" means computers, including desktop and laptop computers, or servers, used for general computing functions under end user control (such as but not specifically limited to email, general purpose Internet browsing, and office suite productivity tools). The use of Software in systems and solutions that provide dedicated functionality (other than as mentioned above) or designed for use in embedded or function-specific software applications, for example but not limited to: Software embedded in or bundled with industrial control systems, wireless mobile telephones, wireless handheld devices, netbooks, kiosks, TV/STB, Blu-ray Disc devices, telematics and network control switching equipment, printers and storage management systems, and other related systems are excluded from this definition and not licensed under this Agreement...

and from http://www.excelsiorjet.com/embedded/

Notice : The Java SE Embedded technology license currently prohibits the use of Java SE in cell phones.

Q2. how come these plethora of Android Java developers aren't paying Sun/Oracle a dime?


问:
Is it bad form to change multiple tables in a single Rails migration file?
I wrote a migration file with the following code:

```<code>class AddScheduleIdToPlayers < ActiveRecord::Migration
  def change
        add_column :players, :schedule_id, :integer
        add_column :schedules, :coach_id, :integer
  end
end
</code>```

Is it bad form to not create two migration files, one for each change, or is this fine?

答:
You want to keep related changes together. For example, if you implement bidirectional relation and add columns/tables to suffice AR relations you want to keep those in one migration.

If changes in schema are not related to each other (parts of different features, for example) it's better to keep them in separate migrations.

I do a mental experiment when I'm not sure. I try to break up migration for the smallest possible pieces and then check if my feature still works if I take down only one of the pieces. If it is that piece is likely doesn't belong to this migration.

Yours look to me like it can be split into two migrations. It seem to be you have two features here. One is about adding schedules for players and another for adding coaches to schedules.


答:
There is no one "best". If you want to maximize portability, you can only use three values: EXIT_SUCCESS, EXIT_FALURE, and 0 (and 0 and EXIT_SUCCESS mean the same thing). If you don't mind losing some portability, it's often useful to return various other values to indicate why something failed, or (in some cases) return a non-zero value even in case of success to indicate things like how many of X it found, or carry the result of a calculation, etc.

As such, you have a choice between portability (but mostly to systems you probably don't care about, chiefly VMS) and functionality on a slightly reduced set of systems. You have to decide which is more important to you.

Edit: No, EXIT_SUCCESS does not always equal zero -- but (at least as far as the standard cares) the two mean the same thing. There was at least one compiler on VMS, however, that defined EXIT_SUCCESS to a non-zero value (VMS normally interpreted even numbers as failure and odd numbers as success, so EXIT_SUCCESS was defined to the proper odd number, and 0 was treated specially, so the system got an odd number when/if you returned it).

Title: What's the proper way to exit program in C?

Body:
There are many ways how to exit program in C. Some of them are returning zero or error code, using exit function with EXIT_SUCCESS, EXIT_FAILURE, exit(0), exit(1) or some other error code, abort and probably few more I can't think of now.

My question is which option is the best and why. I'm asking here because every time I asked more experienced programmers this question, it ended up as a holy war.


问:
GPL licensed software installed on commercial hardware
Do vendors need to provide sources, at the customer's request, for GPL licensed software installed on the hardware they sell?

For example, a vendor sells an IPTV box and pre-installs some proprietary software product which is linked with some GPLed library. As a consequence, the software becomes GPLed itself.

Does the vendor need to provide the source code for it? The vendor doesn't sell that software, he sells hardware.

答: In short: Yes, as it is states in the reference: "The GPL is the first copyleft license for general use, which means that derived works can only be distributed under the same license terms." - reference is here.


答:
Is this still the case, and if not, what are the big changes?

I think there are still applications that use the mentioned server-side or client-server architecture. However, in recent years there is a big move toward SOA (Service Oriented Architecture) . Thus, communication through secure services opens new capabilities to all client applications, and access/reuse of back-end business services at the same time.

With emerging markets of mobile and tablets, it is becoming even more important to use HTTP services as an important communication channel to provide extended service to the client applications.

Title: What is occurring in the world of server-side technologies in regards to the mobile app boom?

Body:
With mobile technologies becoming increasingly popular what is happening on the server-side with most of these apps when they need to communicate with a back end?

I'm used to the world of technology from 10 years ago when most resources were accessed by requesting a dynamic web page that behind the seen used a server-side language to get the information it needed from a relational database.

Is this still the case, and if not, what are the big changes?


问:
Should I use a workflow engine?
I need to add some new features to a PHP application. It is to follow the steps of a order. A process create some orders, the order goes to confirmation, then if approved is sent to a provider, later the provider confirm that can deliver the order, a request is made to the provider and so on...

I need to register when every step is made and send notifications. Also, some steps have a estimate time, and if that time is elapsed I need to send notifications so everybody know about the delay.

When a process starts, it have a predefined set of steps, but in a middle the user should be able to create new sub-steps, and delete or skip future steps..

Should I use a workflow engine? Which one do you suggests (free-opensource only)?

答:
You've outlined some requirements which are typically catered for by workflow engines, such as following some process, task allocation, escalations and notifications.  From this point of view, it would make a lot of sense to go with an actual workflow engine.  There are two areas which make me question whether it will actually prove to be beneficial to use one in your case:

Workflow engines can involve a significant investment of your time to learn.  They also tend to complicate the environment in which your application runs.  If your requirement is a "once-off", and you are unlikely to implement similar workflow-related features in the future, you might want to reconsider using one.  E.g. I wouldn't use a full-blown document management system if all I wanted to do was upload an attachment on one screen, and something similar applies here.  I would normally advise against "rolling your own", but in this case I'm not so hesitant; I have been faced with your exact requirements in the past, and chosen to write my own (due to insane deadlines, don't ask) - it was a resounding success.

Your requirement about the user modifying the process, I have several issues with.  Firstly, it's the kind of wishy-washy requirement that will grow in time.  "Oh, we forgot, the user needs to specify who is going to action that extra step.  Oh yeah, it can be someone outside of the company.  Oh yeah, they need to be able to specify that at least 2 of the 5 targeted managers must approve", etc.  Also, workflows can be complex beasts, and it's usually difficult to allow an actual user to modify them without breaking them, and to do so in a way which is quick and intuitive to the user.  Beyond that, many workflow engines will not easily allow the dynamic modification of the process, so you may be limited to some kind of fixed logic like: "repeat this generic step until we run out of user-defined steps".  My experience lies outside of open-source engines, but this would have been a difficult requirement to implement in the 3 or 4 proprietary ones I've worked with over the years.

To summarise, with the exception of the user-modifiability, your requirements are a pretty good match for a workflow engine.  My suggestion: figure out whether there's an engine out there which gives you everything that you need (perhaps someone else can suggest specifics), and do some R&D with it.  You will then be in a better position to weigh up your options.

EDIT:  Sorry, my connection went down as I made that post, and seems to have been truncated.  I've recovered it now.

Title: Should I use a workflow engine?


问:
TDD - Outside In vs Inside Out
What is the difference between building an application Outside In vs building it Inside Out using TDD?

These are the books I read about TDD and unit testing:

Test Driven Development: By Example

Test-Driven Development: A Practical Guide: A Practical Guide

Real-World Solutions for Developing High-Quality PHP Frameworks and Applications

Test-Driven Development in Microsoft .NET

xUnit Test Patterns: Refactoring Test Code

The Art of Unit Testing: With Examples in .Net

Growing Object-Oriented Software, Guided by Tests--->This one was really hard to understand since JAVA isn't my primary language :)

Almost all of them explained TDD basics and unit testing in general, but with little mention of the different ways the application can be constructed.

Another thing I noticed is that most of these books (if not all) ignore the design phase when writing the application. They focus more on writing the test cases quickly and letting the design emerge by itself.

However, I came across a paragraph in xUnit Test Patterns that discussed the ways people approach TDD. There are 2 schools out there Outside In vs Inside Out.

Sadly the book doesn't elaborate more on this point. I wish to know what is the main difference between these 2 cases.

When should I use each one of them?

To a TDD beginner which one is easier to grasp?

What is the drawbacks of each method?

Is there any materials out there that discuss this topic specifically?

答:
Short Answer: As usual it will depend on your coding preference and team approach.

Inside out coding is great because you always have something working. The downside is that it doesn’t necessarily help you get to a radically different place. It is harder to chart a course this way. Similarly, writing code outside in has the downside of not necessarily having the benefit of rapid iterative development, and not necessarily seeing all of the opportunities and patterns that may arise from deep in the structure of the code.

I have come to believe that both styles of development are important, and that it is in fact helpful to have a mix of styles on a team. The idea is that inside out is great for creating building blocks, and the outside in thinking provides form structure and direction.

Part of my reasoning is coming from a very popular school of thought that currently promotes iterative development, which is often synonymous with inside out development. I believe iterative development is great when you don’t have too far to go. But I think that big picture thinking, as opposed to a purely iterative process is invaluable to certain types of innovation and to getting to a less obvious place. Properly managed, inside out and outside in together can be a very effective combination.

Title: TDD - Outside In vs Inside Out


问:
How to read Scala code with lots of implicits?

Consider the following code fragment (adapted from https://stackoverflow.com/a/12265946/1333025):

// Using scalaz 6
import scalaz._, Scalaz._

object Example extends App {
  case class Container(i: Int)

  def compute(s: String): State[Container, Int] = state {
    case Container(i) => (Container(i + 1), s.toInt + i)
  }

  val d = List("1", "2", "3")

  type ContainerState[X] = State[Container, X]

  println( d.traverse[ContainerState, Int](compute) ! Container(0) )
}
```

<p>I understand what it does on high level. But I wanted to trace what exactly happens during  the call to <code>d.traverse</code> at the end. Clearly, <code>List</code> doesn't have <code>traverse</code>, so it must be <code>implicit</code>ly converted to another type that does. Even though I spent a considerable amount of time trying to find out, I wasn't very successful. First I found that there is a method in <code>scalaz.Traversable</code></p>

<pre class="lang-scala prettyprint-override"><code>traverse[F[_], A, B] (f: (A) => F[B], t: T[A])(implicit arg0: Applicative[F]): F[T[B]]
</code>```

but clearly this is not it (although it's most likely that "my" traverse is implemented using this one). After a lot of searching, I grepped scalaz source codes and I found scalaz.MA's method

traverse[F[_], B] (f: (A) => F[B])(implicit a: Applicative[F], t: Traverse[M]): F[M[B]]
```

which seems to be very close. Still I'm missing to what List is converted in my example and if it uses MA.traverse or something else.

The question is: What procedure should I follow to find out what exactly is called at d.traverse?

Having even such a simple code that is so hard analyze seems to me like a big problem. Am I missing something very simple?

How should I proceed when I want to understand such code that uses a lot of imported implicits? Is there some way to ask the compiler what implicits it used? Or is there something like Hoogle for Scala so that I can search for a method just by its name?

答:
Short answer: use the-Xprint:typer when compiling. I also asked this question here.

As for Hoogle, we have Scalex. You can even use it from sbt via a plugin.


问:
How to prevent duplicate data access methods that retrieve similar data?
In almost every project I work on with a team, the same problem seems to creep in. Someone writes UI code that needs data and writes a data access method:

```<code>AssetDto GetAssetById(int assetId)
</code>```

A week later someone else is working on another part of the application and also needs an AssetDto but now including 'approvers' and writes the following:

```<code>AssetDto GetAssetWithApproversById(int assetId)
</code>```

A month later someone needs an asset but now including the 'questions' (or the 'owners' or the 'running requests', etc):

```<code>AssetDto GetAssetWithQuestionsById(int assetId)
AssetDto GetAssetWithOwnersById(int assetId)
AssetDto GetAssetWithRunningRequestsById(int assetId)
</code>```

And it gets even worse when methods like GetAssetWithOwnerAndQuestionsById start to appear.

You see the pattern that emerges: an object is attached to a large object graph and you need different parts of this graph in different locations.

Of course, I'd like to prevent having a large number of methods that do almost the same. Is it simply a matter of team discipline or is there some pattern I can use to prevent this? In some cases it might make sense to have separate methods, i.e. getting an asset with running requests may be expensive so I do not want to include these all the time. How to handle such cases?

答:
Is it simply a matter of team discipline or is there some pattern I can use to prevent this?

Yes, it is a matter of some guidelines in naming pattern for the team. You may set simple 4 methods like GetEntityById(), GetAllEntities(), SetEntity(), DeleteEntityById().

In addition, you may have two dto's with the naming AssetSimpleDto GetAssetById(assetId) and another detailed dto called as AssetDto GetAssetDetailById(assetId) . The first method and dto is customized to bring bare minimum , while second is bringing all related information that your functionality may need.


答:
Inside-Out and Outside-In are fairly rare terms, more often I have heard/read about Classic school and London school.

Inside-Out (Classic school, bottom-up): you begin at component/class level (inside) and add tests to requirements. As the code evolves (due to refactorings), new collaborators, interactions and other components appear. TDD guides the design completely.

Outside-In (London school, top-down or "mockist TDD" as Martin Fowler would call it): you know about the interactions and collaborators upfront (especially those at top levels) and start there (top level), mocking necessary dependencies. With every finished component, you move to the previously mocked collaborators and start with TDD again there, creating actual implementations (which, even though used, were not needed before thanks to abstractions). Note that outside-in approach goes well with YAGNI principle.

Neither of the approaches is the one and only; they both have their place depending on what you do. In large, enterprise solutions, where parts of the design come from architects (or exists upfront) one might start with "London style" approach. On the other hand, when you face a situation where you're not certain how your code should look (or how it should fit within other parts of your system), it might be easier to start with some low-end component and let it evolve as more tests, refactorings and requirements are introduced.

Whichever you use, more often than not it is situational.

For further reading, there's Google group post with rather interesting discussion on how this distinction (might have) originated and why London might not be the most appropriate name.

Title: TDD - Outside In vs Inside Out

Body:
What is the difference between building an application Outside In vs building it Inside Out using TDD?

These are the books I read about TDD and unit testing:

Test Driven Development: By Example

Test-Driven Development: A Practical Guide: A Practical Guide

Real-World Solutions for Developing High-Quality PHP Frameworks and Applications

Test-Driven Development in Microsoft .NET

xUnit Test Patterns: Refactoring Test Code

The Art of Unit Testing: With Examples in .Net

Growing Object-Oriented Software, Guided by Tests--->This one was really hard to understand since JAVA isn't my primary language :)

Almost all of them explained TDD basics and unit testing in general, but with little mention of the different ways the application can be constructed.

Another thing I noticed is that most of these books (if not all) ignore the design phase when writing the application. They focus more on writing the test cases quickly and letting the design emerge by itself.

However, I came across a paragraph in xUnit Test Patterns that discussed the ways people approach TDD. There are 2 schools out there Outside In vs Inside Out.

Sadly the book doesn't elaborate more on this point. I wish to know what is the main difference between these 2 cases.

When should I use each one of them?

To a TDD beginner which one is easier to grasp?

What is the drawbacks of each method?

Is there any materials out there that discuss this topic specifically?


答: Most back-ends now support JSON and REST and not just SOAP.  Other than that, there's not a lot of difference between a web front-end and a mobile app.  I think most of the challenges for mobile apps are on the front end (how best to fit information onto a smaller screen).  Some apps are starting to leverage mobile capabilities (like location reporting), but that's on both ends.</p>


问:
Is it bad practice to pass instances through several layers?
In my program design, I often come to the point where I have to pass object instances through several classes. For example, if I have a controller that loads an audio file, and then passes it to a player, and the player passes it to the playerRunnable, which passes it again somewhere else etc. It looks kind of bad, but I don´t know how to avoid it. Or is it OK to do this?

EDIT: Maybe the player example is not the best because I could load the file later, but in other cases that does not work.

答: Passing data trough a bunch of layers isn't a bad thing, its really the only way a layered system can work without violating the layered structure. The sign there are problems is when you are passing your data around to several objects in the same layer to achieve your goal.</p>


答:
Passing object instances around is a normal thing to do. It reduces the need for keeping the state (i.e. instance variables) and decouples the code from its execution context.

One issue that you may face is refactoring, when you must change signatures of multiple methods along the invocation chain in response to changing parameter requirements of a method near the bottom of that chain. However, it can be mitigated with the use of modern software development tools that help in refactoring.

Title: Is it bad practice to pass instances through several layers?

Body:
In my program design, I often come to the point where I have to pass object instances through several classes. For example, if I have a controller that loads an audio file, and then passes it to a player, and the player passes it to the playerRunnable, which passes it again somewhere else etc. It looks kind of bad, but I don´t know how to avoid it. Or is it OK to do this?

EDIT: Maybe the player example is not the best because I could load the file later, but in other cases that does not work.


答: It's quite a common design that ends up happening although you might have latency problems if your app is sensitive to that sort of thing.</p>


答: Maybe minor, but there's the risk of assigning this reference somewhere in one of the layers potentially causing a dangling reference or memory leak later on..</p>


答:
As others have mentioned, this isn't necessarily a bad practice, but you should pay attention that you're not breaking the layers' separation of concerns and passing layer-specific instances between layers. For instance:

Database objects should never be passed up to higher layers. I've seen programs using .NET's  DataAdapter class, a DB-access class, and passing it up to the UI layer, rather than using the DataAdapter in the DAL, creating a DTO or dataset, and passing that up. DB access is the domain of the DAL.

UI objects should, of course, be limited to the UI layer. Again, I've seen this violated, both with ListBoxes populated with user data passed up to the BL layer, instead of an array/DTO of its content, and (a particular favorite of mine), a DAL class that retrieved hierarchical data from the DB, and rather than returning a hierarchical data structure, it just created and populated a TreeView object, and passed it back to the UI to be added dynamically to a form.

However, if the instances you're passing are the DTOs or entities themselves, it's probably ok.


问:
Should I create an Enum mapping to my database table
I have a database table containing a list of systems relevant to the tool I am building, mostly in-house applications, or third-party systems we receive data from. This table is added to infrequently, approx every 2 months.

One of these systems is Windows itself, which is where we store our users' LANs, and I now need to explicitly reference the ID relating to Windows to query for user name, team etc. I know it would be bad practice to embed the ID itself into the code, so my question is what would be the best way to avoid this? I'm assuming my options are:

create a global constant representing this ID

create a global enum containing all systems now

create a global enum and add systems to it as & when they are required in the code

retrieve the ID from the database based on system name

I appreciate this may seem a trivial question, but I am going to have many situations like this during the course of this build, and although we are in complete control of the database I would like to conform to best practice as far as possible.

Many thanks!

答: Data that changes should either be kept in a config file or in database. Data that need to be used in queries that represent business data should be in database. I would choose integrity over performance specially for small size data. I would go with option 4. Remember that changes to code requires version management. If this becomes frequent practice, you will get to spend unnecessary time in version management.</p>