问:
Are there deprecated practices for multithread and multiprocessor programming that I should no longer use?
In the early days of FORTRAN and BASIC, essentially all programs were written with GOTO statements.  The result was spaghetti code and the solution was structured programming.

Similarly, pointers can have difficult to control characteristics in our programs.  C++ started with plenty of pointers, but use of references are recommended.  Libraries like STL can reduce some of our dependency.  There are also idioms to create smart pointers that have better characteristics, and some version of C++ permit references and managed code.

Programming practices like inheritance and polymorphism use a lot of pointers behind the scenes (just as for, while, do structured programming generates code filled with branch instructions).  Languages like Java eliminate pointers and use garbage collection to manage dynamically allocated data instead of depending on programmers to match all their new and delete statements.

In my reading, I have seen examples of multi-process and multi-thread programming that don't seem to use semaphores.  Do they use the same thing with different names or do they have new ways of structuring protection of resources from concurrent use?

For example, a specific example of a system for multithread programming with multicore processors is OpenMP.  It represents a critical region as follows, without the use of semaphores, which seem not to be included in the environment.

```<code>th_id = omp_get_thread_num();
#pragma omp critical
{
  cout << "Hello World from thread " << th_id << '\n';
}
</code>```

This example is an excerpt from: http://en.wikipedia.org/wiki/OpenMP

Alternatively, similar protection of threads from each other using semaphores with functions wait() and signal() might look like this:

```<code>wait(sem);
th_id = get_thread_num();
cout << "Hello World from thread " << th_id << '\n';
signal(sem);
</code>```

In this example, things are pretty simple, and just a simple review is enough to show the wait() and signal() calls are matched and even with a lot of concurrency, thread safety is provided.  But other algorithms are more complicated and use multiple semaphores (both binary and counting) spread across multiple functions with complex conditions that can be called by many threads.  The consequences of creating deadlock or failing to make things thread safe can be hard to manage.

Do these systems like OpenMP eliminate the problems with semaphores?

Do they move the problem somewhere else?

How do I transform my favorite semaphore using algorithm to not use semaphores anymore?

答:
Apple's Grand Central Dispatch is an elegant abstraction that changed my thinking about concurrency. Its focus on queues make implementing asynchronous logic an order of magnitude simpler, in my humble experience. </p>

<p>When I program in environments where it's available,  it had replaced most of my usages of threads, locks, and inter-thread communication. </p>

Body:
Apple's Grand Central Dispatch is an elegant abstraction that changed my thinking about concurrency. Its focus on queues make implementing asynchronous logic an order of magnitude simpler, in my humble experience.

When I program in environments where it's available,  it had replaced most of my usages of threads, locks, and inter-thread communication.


问:
Making the switch from MySQL to PostgreSQL?
I've spent the last year becoming really comfortable with MySQL, but due to its increasing trendiness and my desire to homogenize my web-apps with Heroku, I'd like to start using PostgreSQL for my web apps instead.  There are a resources out there for learning PostgreSQL, but I don't really want to have database concepts explained to me from scratch again, and I don't want to have to re-learn all the stuff that's pretty much the same.

What are the critical differences that I need to understand - syntactical and conceptual - between MySQL and PostgreSQL that will affect me on a day-to-day basis?

答:
It depends somewhat on how you're using the database.
If you're using an ORM, you might not notice any issues at all.

I switched an application to using Postgresql (for deployment to Heroku), but only after discovering situations where the SQL created by Rails worked fine on SQLite, but not on Postgresql.  Invariably, the issues were caused when joins were querying the same column name on multiple tables.  SQLite didn't care, but Postgresql wanted the relation name specified if it was in the 'where' clause.

Even though I've worked with both MySQL and Postgresql, I'm not sure of any fundamental conceptual differences between them.  They're both fairly solid client-server databases, although PG seems to be generating a better reputation.

However, there are definitely some critical syntactical differences between MySQL and Postgresql.  I found a decent guide to those here: http://en.wikibooks.org/wiki/Converting_MySQL_to_PostgreSQL

ContentLicense: CC BY-SA 3.0


问:
What programming skills does someone in QA need to work effectively in extreme programming projects?
Well, the title really says it all, but to elaborate a bit, can you take a random, typically effective QA department and have them learn to work in an XP environment (with a learning curve to pick up the XP workflow of course) or would they need more programming skills to be effective?  If so, what would they need to know?</p>

答:
For typical test driven development, it's probably not necessary for your QA's to know any programming at all.

But if you're doing behaviour driven development, it would be beneficial for your QA's to know a language like Cucumber.  Especially, if your business analysts are writing story requirements in the Given-When-Then style.

However, it really depends on your 'people', and the tools you're working with.  I would say it's possible for them to be effective with zero programming knowledge, but it certainly wouldn't hurt and may make them more effective.


答:
QA Team Conversion to XP?

This question you ask is one on which many traditional testers depend for career survival.

Short answer is maybe.  You are right to identify the work flow as an issue, but the work flow is simple compared with training for programming and development.  Making testers into programmers may be a bridge too far.  There are many other skills that have closer affinity to your testers' current skill set.

I think there is a role for Software Test Engineers, but two new creatures are on the scene, the Test Driven Developer and the Software Development Engineer in Test who will take over a lot of turf that used to belong to the STE.

XP Workflow

Under an XP workflow, unit test is the responsibility of the developer.  Typically the workflow would involve creating the story card, working up a use case diagram and some use cases, then turning those into test cases.  The test cases would drive the development in a methodology called Test Driven Development (TDD).  Every minute the program exists, there is a test case to be implemented first, followed by some code that will initially fail, then after additional work, pass that test.  When all the tests identified from the story cards pass, the product is done.  Or at least the latest increment is done.  Unit tests are created in a language dependent way and are part of the code.  There are many references, but for a quick intro check Wikipedia, then the following web page by Scott Ambler.

http://www.agiledata.org/essays/tdd.html#WhatIsTDD

There is also significant overlap with the system acceptance testing because the test cases come from the story cards and use cases.  ATDD (Acceptance TDD) makes a distinction, but I think it might be kind of arbitrary.

Not everyone takes testing with equal seriousness.  Managers can push developers to not test.  They can push to have testers not test too.  I was dinged pretty hard one year when the developers on my team were about on budget but the testers on the project tested bug fixes and new features several hours a week even though the project plan had them only working two weeks at the end.  It seemed like the right thing to do, and the project was still profitable and customers had a better product because of it.

Developers must test.  It is very wasteful when they don't because testers must run, report, and repeat.  Software quality is no less the responsibility of developers than testers.  This sharing should make the tester's life less frustrating, but it also amps up the demand for a lot of knowledge and skill on everyone.

If developers fail to take testing seriously, the demands on testers may increase because you will get builds daily.  For a while people may be heard to say, "why does it seem like we take one step forward and two steps backward."  The answer will be because you are now using a system where the team has visibility like it never had before and before it was only at the 90% mark that those people knew about the impending disaster.

The Shift of Testing To Developers

My experience is that to accelerate development, it can help to move jobs done by testers into development.  This is true of everything from UI testing of a touch screen clear up through Windows Hardware Quality Lab testing of a very complex items like a Windows driver for WiFi.

Consider pre-PC days when engineers dictated memos and technical information to a secretary to be typed, duplicated, and distributed.  Compare that to a developer using email, an intranet wiki, comments in the bug tracking, source control or code review tools, instant messaging, etc.  We just have too many changes that we need to test and the surrounding communications and knowledge transfer are so daunting that much of our testing is automated for direct implementation by developers with no delegation to test.

Value Adds for Testers

I have worked with some testers who could be system engineers, and some who have crazy good communications skills (almost mind reading/telepathy).  My most effective work with them was when they did a good job explaining unexpected behavior they saw in the system, usually in writing in the bug tracker, although often a demonstration was extremely helpful.

Another important criteria is that the effort of a code hand off was as small as possible.  For a while developers felt some relief when testers could gen their own builds.  Now, we use constant integration servers so developers need only commit source and provided we used TDD right, there are a lot of tests that run themselves and report back.

Global competition is pushing cycle times and rework is getting reworked out of the system.  If tomorrow I hear from a tester about a defect I added today, how will I compete with the guy who didn't make a defect today (or found it himself)?  We are not there yet, but I think the days of cut-and-try programmers are numbered.  I have seen demos from Google developers who may have rehearsed a lot, but they seem to be able to type in a program from beginning to end during a 90 minute lecture, explaining as they type with few or no problems in the change and execute cycle.  Testers add value by shortening the time between work and rework, so early concise reporting about today's build today is a big plus.

New Test Roles

Many organizations are carving out roles for SDET - Software Developer Engineer in Test.  These guys script, code, and code review.  The following link is to a blog for a SDET at Microsoft.

http://aliabdin.wordpress.com/2007/03/31/what-does-an-sdet-do/

He also describes Software Test Engineers (STE) who feed the bugs they find to SDET.  Another thing that struck me about the SDET role is that unlike the traditional software developers, when they have buggy systems they need to know code for the whole system because almost any part could be the source of the problem, so the extensive mental map helps them track it down.

Forming a Vision that Leads to a Successful Transition

I have encountered a similar issue of a project manager not knowing how to fit that role into scrum.  Being scrum master was her transition destination.  It is a well defined role, and there is training for it.  Keep looking and you may find something similar for testing.

There is more information about Agile testing here:

http://www.ambysoft.com/essays/agileTesting.html#AgileTestingStrategies

and about the independent test team here:

http://www.ambysoft.com/essays/agileTesting.html#IndependentTestTeam

Scott Ambler's observations about the ratio of developers to testers in Agile vs. traditional approaches will not make your day (15:1 vs. 3:1).  I would suggest understanding and creating a vision for your test team based on skills and tools expertise:

Complete fluency with bug tracker.

Understand developer level source control concepts like commit, branch, tag.

Be able to run reports on code commits and their comments from the source control system.

Learn to deciphering developer speak in commit comments and map then to UI and manual tests not run automatically.

Get a system engineer's understanding of the system, but help clarify rather than make decisions about what is undocumented and ambiguous.

Get on a daily cycle with developers.  This may mean much more frequent and rapid reconfiguration of equipment under test and test tools.

Depending on your environment, developers may be using a much broader tool set than testers.  If your lab has what they use, it is flattering and a more hospitable environment for face time and ad-hoc training from developers.  Examples might include use of Virtual Machine Managers and VMs, remote debug or diagnostics via networks with SSH or remote desktop, the ability to save device state or UI appearance through screen capture or by taking a photo with a camera or smart phone, and logging to network directories or thumb drives.

Preliminary analyses using log data moved into spread sheets and converted to plots.  There is a lot of stuff being written about big data and sometimes the test output from in lab or beta test sites can be big data.

Learn to facilitate customer interface during beta testing.  This may involve retrieving log files by documenting and coaching customers over the phone, or it may be hooked into an automated system that delivers crash dumps directly to the developer (or to you if you have the skill to triage).

Help support quantitative analysis of software and systems level products (as before, but maybe even more).

Look for ways to get developers more aware of how many different testing methods and tools you have at your disposal, and what works well for requesting their work be quality assured, not just at the end of the project, but weekly or daily.

Ask the developers in your organization what vision they have for how testers can help them.  It should go well if you have been watching each others backs thus far.  You should get great ideas together.

Good luck in the transition to XP and in preparing your team to do the same.

Title: What programming skills does someone in QA need to work effectively in extreme programming projects?

Body: Well, the title really says it all, but to elaborate a bit, can you take a random, typically effective QA department and have them learn to work in an XP environment (with a learning curve to pick up the XP workflow of course) or would they need more programming skills to be effective?  If so, what would they need to know?</p>


问:
Why is Java the lingua franca at so many institutions?
EDIT: This question at first seems to be bashing Java, and I guess at this point it is a bit. However, the bigger point I am trying to make is why any one single language is chosen as the one end all be all solution to all problems. Java happens to be the one that's used so that's the one I had to beat on here, but I'm not intentionality ripping Java a new one :)

I don't like Java in most academic settings. I'm not saying the language itself is bad -- it has several extremely desirable aspects, most importantly the ability to run without recompilation on most any platform. Nothing wrong with using the language for Your Next App ^TM. (Not something I would personally do, but that's more because I have less experience with it, rather than it's design being poor)

I think it is a waste that high level CS courses are taught using Java as a language. Too many of my co-students cannot program worth a damn, because they don't know how to work in a non-garbage-collected world. They don't fundamentally understand the machines they are programming for. When someone can work outside of a garbage collected world, they can work inside of one, but not vice versa. GC is a tool, not a crutch. But the way it is used to teach computer science students is a as a crutch.

Computer science should not teach an entire suite of courses tailored to a single language. Students leave with the idea that all good design is idiomatic Java design, and that Object Oriented Design is the ONE TRUE WAY THAT IS THE ONLY WAY THINGS CAN BE DONE. Other languages, at least one of them not being a garbage collected language, should be used in teaching, in order to give the graduate a better understanding of the machines.

It is an embarrassment that somebody with a PHD in CS from a respected institution cannot program their way out of a paper bag.

What's worse, is that when I talk to those CS professors who actually do understand how things operate, they share feelings like this, that we're doing a disservice to our students by doing everything in Java. (Note that the above would be the same if I replaced it with any other language, generally using a single language is the problem, not Java itself)

In total, I feel I can no longer respect any kind of degree at all -- when I can't see those around me able to program their way out of fizzbuzz problems.

Why/how did it get to be this way?

答:
This isn't a Java problem, it's a teaching problem. Not knowing how to program is not a languages fault, it's the students fault. Same goes for all your issues, GC, basic machine knowledge, how things work "under the hood" so to speak.

Your major gripe about garbage collection throws me slightly. Unless you're doing C or C++ garbage collection is typically very good and not an issue. Would you rather they all learn assembly? Higher level languages that are strict are very useful for teaching. It gives you the flexibility of libraries, packages, and other niceties when you need it, without any of the confusing language "sugar" present in most other higher level languages (PHP, Ruby, Python, Perl).

ContentLicense: CC BY-SA 2.5


问:
Scheme vs Haskell for an Introduction to Functional Programming?
I am comfortable with programming in C and C#, and will explore C++ in the future. I may be interested in exploring functional programming as a different programming paradigm. I am doing this for fun, my job does not involve computer programming, and am somewhat inspired by the use of functional programming, taught fairly early, in computer science courses in college. Lambda calculus is certainly beyond my mathematical abilities, but I think I can handle functional programming.

Which of Haskell or Scheme would serve as a good intro to functional programming? I use emacs as my text editor and would like to be able to configure it more easily in the future which would entail learning Emacs Lisp. My understanding, however, is that Emacs Lisp is fairly different from Scheme and is also more procedural as opposed to functional.

I would likely be using "The Little Schemer" book, which I have already bought, if I pursue Scheme (seems to me a little weird from my limited leafing through it). Or would use the "Learn You a Haskell for Great Good" if I pursue Haskell. I would also watch the Intro to Haskell videos by Dr Erik Meijer on Channel 9.

Any suggestions, feedback or input appreciated.

Thanks.

P.S. BTW I also have access to F# since I have Visual Studio 2010 which I use for C# development, but I don't think that should be my main criteria for selecting a language.

答: I think it's easy to get caught up in debates about languages, and miss the point. For someone who just wants to learn what FP is about, the differences between Ocaml/ML/Scheme/Haskell aren't half as important as your comfort with the material (books, videos, tools) you use to learn it. And whether or not you have a friend to help you learn to certain language trumps everything else. </p>

OwnerDisplayName: haziz


问:
Best approach for writing a chess engine?
I'm a chess enthusiast and a programmer. I recently decided to start making a chess engine using my chess and programming knowledge. So here's my question:

What language (I'm familiar with Java, C++ and Python) and methodology should I adapt while writing a chess engine?

A little guidance would be much appreciated.

Edit:

So I decided to make it in JavaScript. I download this Chess UI from github and now I'm all set! My first step would be to write legal moves for it. So can anybody point me in the right direction? (I'm new to jQuery but have alot of programming experience).

P.S: I'm not trying to make a very efficient engine (I know its way too difficult), I just want to get familiar with the process and learn some new techniques along the way.

答:
As per your edit, you're up to the stage of defining 'legal' moves.

There are two ways of describing moves in chess.  Descriptive notation and Algebraic notation.  What you probably want is a function that takes the piece, starting position and ending position as parameters.  eg. Knight from QN1 to QB2 is invalid, but Knight from QN1 to Q2 is valid.  Thinking about it, Algebraic notation may be simpler due to the ability to easily calculate 'relative' positioning.

To ensure you're writing the minimum amount of code required, I'd start with writing tests for that function first.  If you're using Algebraic notation, you probably don't need a test per piece/start/end.  Get each test working, and refactor out duplication before moving on to the next 'move'.  Your code will end up cleaner.

Once you've sufficiently covered the legal and illegal moves for each piece, I'd start adding in checks for other variables (such as moving a King into 'check' and 'mate' conditions).

I recommend qunit for unit tests and jasmine for behavioral tests in JavaScript.


问:
Backbone.js, Rails and code duplication
I'm building a web app and I need a JS framework like Backbone.js to work with my backend provided by Rails that mostly return JSON objects after DB queries.

Searching on the web I've discovered Backbone which seems to be complete, quite popular and actively used in development but I've noticed that a lot of things done by Backbone are simply a duplicate of the work done by Rails: for example, validation and models.

My idea of "perfect" (for my actual needs) JS mvc (it can't be called mvc but I don't have a better name) is something really simple that has a function for each action in my Rails controller that is triggered by a specific event (user/hash changes, click on a button...) and sends requests to the server that respond with a JSON object then I'll load a template or execute some JS code.

Do you have any concerns about/suggestions for my idea?

Do you know of some "micro" js framework like what I have described?

If you have worked with backone.js + rails what can you suggest to me?

答:
I don't have any concerns about your idea, apart from what prashanth already mentioned.
I'd make sure there is some validation on the server side, just in case somebody skips your JS front-end and starts pumping invalid data straight into your JSON API.

As a suggestion, I'd check out TodoMVC.
They've written a TODO application using a number of JavaScript framworks for implementing client-side MVC (including Backbone.js).  They've done a lot of the hard work in highlighting the differences for you.

microjs is another site I'd check out.  I found both soma.js and Stapes.js (really small at 1.7Kb) there.

I haven't worked with any of these frameworks personally, but I know devs using backbone and ember.  Ember seems to be gaining in popularity as it matures.  It seems to be a little more opinionated than backbone is, which I suspect resonates with a lot of rails developers.

Title: Backbone.js, Rails and code duplication


问:
Which CSS attributes should be in HTML and which in BODY?
I have the following:

```<code>html {
overflow-y: scroll;
}

body {
font-family: Georgia, "Times New Roman", serif;
font-size: 1.125em;
line-height: 1.5em;
margin: 0 auto;
max-width: 41em;
}
</code>```

Which attributes should be with the HTML section, and which within the BODY section?

答:
I'm not 100% on which is technically or traditionally correct, but I've used them in a similar way to your example code without issue.

Therefore I'd say that there shouldn't be any side effects by doing it this way, but it may not strictly meet the standard.


问:
Can a loosely typed language be considered true object oriented?
Can a loosely typed programming language like PHP be really considered object oriented?

I mean, the methods don't have returning types and method parameters has no declared type either.

Doesn't class design require methods to have a return type?
Don't methods signatures have specifically-typed parameters?

How can OOP techniques help you code in PHP if you always have to check the types of parameters received because the language doesn't enforce types?

Please, if I'm wrong, explain it to me.

When you design things using UML, then code classes in PHP with no return-typed methods and no-type parameters... Is the code really compliant with the UML design?

You spend time designing your software architecture, then the compiler doesn't force the programmer to follow your design while coding, letting he/she assign any object variable to any other variable with no "type-mismatch" warning.

答:
The original object-oriented language where Alan Key introduced the concept was Smalltalk. It is dynamically typed.

Actually Alan Key mentioned the classes and interfaces approach of C++ and Java is not what he had in mind when he invented object oriented programming. So the question should perhaps even be the other way, whether statically typed languages can be truly object oriented.

I mean, the methods don't have returning types and method parameters has no declared type either.
  Doesn't class design need methods to have a return type? Doesn't methods signatures have specifically-typed parameters?

No, they don't have specifically typed parameters. Their parameters and return values have to have specific set of methods, but they don't have to be specific types. In statically typed languages that is enforced by declaring an interface. In dynamically typed ones, you just document it.

How can OOP techniques help you code in PHP if you have to always check the types of parameters received because the language doesn't enforce types?

You should never check types of parameters received. You should simply call methods on them. That's called "duck typing" (if it quacks like a duck and walks like a duck, I would call it a duck, or if it has methods like X, it will do for X). It's how things are usually done in smalltalk, perl, python, ruby etc. and as they should be done in PHP.


答:
That's what the industry asked for. There was a shortage of Java developers so schools starting creating them. Companies got developers who can start work as soon as they walked through the door.

Anyway, the language doesn't matter. They could teach a non-GC language and still produce bad programmers. The language schools use is an implementation detail. Schools should teach concepts. If this isn't the case then it's the school that is the problem not the language they teach with. Just because someone doesn't know what a pointer is doesn't mean they can't be an effective programmer.

GC is the way of the future anyway.

Title: Why is Java the lingua franca at so many institutions?

Body:
EDIT: This question at first seems to be bashing Java, and I guess at this point it is a bit. However, the bigger point I am trying to make is why any one single language is chosen as the one end all be all solution to all problems. Java happens to be the one that's used so that's the one I had to beat on here, but I'm not intentionality ripping Java a new one :)

I don't like Java in most academic settings. I'm not saying the language itself is bad -- it has several extremely desirable aspects, most importantly the ability to run without recompilation on most any platform. Nothing wrong with using the language for Your Next App ^TM. (Not something I would personally do, but that's more because I have less experience with it, rather than it's design being poor)

I think it is a waste that high level CS courses are taught using Java as a language. Too many of my co-students cannot program worth a damn, because they don't know how to work in a non-garbage-collected world. They don't fundamentally understand the machines they are programming for. When someone can work outside of a garbage collected world, they can work inside of one, but not vice versa. GC is a tool, not a crutch. But the way it is used to teach computer science students is a as a crutch.

Computer science should not teach an entire suite of courses tailored to a single language. Students leave with the idea that all good design is idiomatic Java design, and that Object Oriented Design is the ONE TRUE WAY THAT IS THE ONLY WAY THINGS CAN BE DONE. Other languages, at least one of them not being a garbage collected language, should be used in teaching, in order to give the graduate a better understanding of the machines.

It is an embarrassment that somebody with a PHD in CS from a respected institution cannot program their way out of a paper bag.

What's worse, is that when I talk to those CS professors who actually do understand how things operate, they share feelings like this, that we're doing a disservice to our students by doing everything in Java. (Note that the above would be the same if I replaced it with any other language, generally using a single language is the problem, not Java itself)

In total, I feel I can no longer respect any kind of degree at all -- when I can't see those around me able to program their way out of fizzbuzz problems.

Why/how did it get to be this way?


问:
Passing the data of a certain page to another page. Windows Phone 7
The user will fill out information in page 1, and the data will be seen in the other page listed in a listbox.

Is it advisable to use data binding?

I've been studying/researching about data binding already for about 2 days and still couldn't understand it.

Simple example would really help.

答:
As you may have understood by now, pages are stateless in wp7, which means that every time you go from one page to another, the state (variables, objects, etc.) of your previous page is lost.

A quick Google search provided me with this great blog article, and this slide show (see page 21 to 23, this is the second solution I list below).

In short, the author describes four solutions to pass data between pages:

Using a Global Variable

Using the Query String

Using PhoneApplicationSerivce States

Using NextPage instance

What should you use? Here is my advice regarding each solution:

Unless the data is something that is shared among all pages of your
application, I suggest you forget about the Global Variable solution, it's not
very clean. And even then, prefer solution 3.

The Query String solution is appropriate if you want to pass simple data between your pages, such as Strings, arithmetic values, Boolean, etc.

About the PhoneApplicationService State, I never needed to use it personally but it looks cleaner than using a global variable. If you want to share some variable/object among all your pages, this is the way to go.

The NextPage solution is the one you should use if you want to pass complex objects between two pages. It's the solution I used the most because I did not need to pass data to all of my pages.

Regardless of the solution you choose, on the second page that is supposed to display data coming from the first page, you will have no trouble loading the data.

Finally, here is a link to a quick tutorial application where data is passed from page to page.


问:
Relevance of Metro to ASP.Net developer?
I am a web developer, working mostly with ASP.Net(webforms + MVC), C#, javascript and so on.

As you know, continuous learning is very important for us, but time is not infinite. I do dabble with the odd technology every now and then that has nothing to do with web but mostly I try to learn more about my field in order to became better at my job.

I have the opportunity to attend either a ASP.Net MVC short course or a Metro app short course and not sure which to pick. On the one hand I feel like I would already know 75% of the MVC course material so would not get as much out of it as with the Metro course. but on the other hand I ask myself how useful is a metro course going to be in my future of being a web developer. I could always dabble in it again when I have the time?

So my real question is, is there any real benefit to a web developer using his time to learn Metro specifically, instead of something else like knockout.js or some other tec that could actually be of use to me in my daily work life?

Thanks

答:
Well if you're into hobbyist software development and think you can make something like WP or W8 app in your spare time go for the Metro thing.

It might also give you some insight into how the MVVM pattern works in other contexts than knockout.js.

That being said, there's nothing like someone actually showing you how a product you are using should be used (I'm talking about mvc 3). Also, this is a great opportunity for networking and finding out what other people are doing with this framework, giving you the opportunity to evaluate your knowledge on the subject against other developers.

Bottom line is if you aren't interested in desktop/embedded development at all go for the mvc 3 course.


问:
Django application strategy
I have been working a while on a Django project which has been growing a bit lately. I have been think a bit about what strategy to use to make it easier to handle. One thing I would like to get some input on would be if I should split my application into several smaller applications. That would make my view and model files smaller and separate some of the concerns.

One thing that bothers me with this is that in my applications I would have several helper methods that will be used across applications. Also some models will also have to be shared/used across applications. Would this make sense? This doesn't go well with the separation of concerns I was hoping to achieve by splitting my app in several smaller apps.
What would be a good approach for sharing helper methods, models etc. across applications?

答:
If your project is getting large, think of apps as reusable modules. You can separate out the functionality that is shared across your apps into its own app.

See the discussions below for more thoughts on the matter:

When to create a new app (with startapp) in
Django?

What is a Django “app” supposed to
mean?

What is an “app” in
Django?

Title: Django application strategy


问:
Haskell GUI: how much can be done with Haskell?
I've been wanting to try out graphics in Haskell. From what I've seen, the available libraries are either front-ends to C/C++ libraries, or an abstraction of them with minimal features. The high-level libraries do not seem to suit my needs, and so I'm left with lower-level front-ends.

What I need is to render tiles and text - basics for a very simple game. I know how to do this with C, and was thinking I could write the graphics in C and interface it with Haskell. The alternative is to write the graphics using a Haskell library.

My question is, can available Haskell libraries achieve what I want? I do not want to bend over backwards; if C can do it better than I would like to know.

答:
If you are asking if there is a good C/C++ alternative to haskell that does GUI well, then look no further:
http://qt-project.org/

Definitely the strongest GUI framework out there for C++.

If however, your question was "find me something better in haskell" then I can't help you :/


问:
How can I multiprocess my program?
I wrote a program which scrape internet sites. It is pretty straigtforward because it process link one by one.

With the limiting factor of the internet speed, the process is rather slow.

I wonder, how can I make it multiprocess? The modules of python is confusing. I don't know the difference between subprocess and multiprocess. I've heard that multiprocessing is difficult and ineffective because of the GIL since python 2.x. I am using Python 3.2, so I wonder if things have been improved.

答:
First of all: the GIL doesn't apply to multi-processing, only to threading, and isn't as big a problem as people seem to make out it is. For one, when using any network or file I/O the lock is released, so anything that scrapes websites is not likely to see any performance bottlenecks on account of the GIL.

The subprocess module is intended to call arbitrary processes from your program, basically anything you can run from the command line on the machine is fair game for this module.

The multiprocessing module on the other hand, is intended to make distributing work across multiple python processes as easy as using threads for the same kind of work. It is the module you should be looking at if you want to implement distributed site scraping using multiple processes.

That said, why don't you take a look at Scrapy, instead:

Scrapy is a fast high-level screen scraping and web crawling framework, used to crawl websites and extract structured data from their pages. It can be used for a wide range of purposes, from data mining to monitoring and automated testing.

Scrapy uses an event-driven loop approach instead of using multiple threads or processes to solve the 'network I/O is slow' problem. An event loop switches between different tasks in the program when network data (or any other I/O) is pending. Instead of waiting for network data to come in before continuing, an event loop switches to a different task instead while leaving it up to the OS to notify the program when the network data has arrived.

If Scrapy doesn't fit your specific needs, you can still make use of the same trick. Take a look at any of the following frameworks to help you do the same thing in your program:

The stdlib asyncore module

twisted

eventlets

greenlets

Scrapy uses twisted, if that makes any difference for you.

Title: How can I multiprocess my program?


答:
```<code>Do you have any concerns about/suggestions for my idea?
</code>```

The problem with your idea is that it couples your back end (Rails) with your font end (JavaScript). Also you say that validation on front end and back end is duplicating code, it is to some degree but you need to do it in both ends to make the site usable and safe. Validating front end helps usability where as validation server side is essential to stop hacks and make the site usable for those that turn JavaScript off.

Do you know of some "micro" js framework like what I have described?

There are lots of Javascript MVC/MVVC frameworks out there like backbone and knockout but they are decoupled. This means they are more portable, more usefull and more likely to be worked on and improved.

Title: Backbone.js, Rails and code duplication

Body:
I'm building a web app and I need a JS framework like Backbone.js to work with my backend provided by Rails that mostly return JSON objects after DB queries.

Searching on the web I've discovered Backbone which seems to be complete, quite popular and actively used in development but I've noticed that a lot of things done by Backbone are simply a duplicate of the work done by Rails: for example, validation and models.

My idea of "perfect" (for my actual needs) JS mvc (it can't be called mvc but I don't have a better name) is something really simple that has a function for each action in my Rails controller that is triggered by a specific event (user/hash changes, click on a button...) and sends requests to the server that respond with a JSON object then I'll load a template or execute some JS code.

Do you have any concerns about/suggestions for my idea?

Do you know of some "micro" js framework like what I have described?

If you have worked with backone.js + rails what can you suggest to me?

Body:
Do you have any concerns about/suggestions for my idea?

The problem with your idea is that it couples your back end (Rails) with your font end (JavaScript). Also you say that validation on front end and back end is duplicating code, it is to some degree but you need to do it in both ends to make the site usable and safe. Validating front end helps usability where as validation server side is essential to stop hacks and make the site usable for those that turn JavaScript off.

Do you know of some "micro" js framework like what I have described?

There are lots of Javascript MVC/MVVC frameworks out there like backbone and knockout but they are decoupled. This means they are more portable, more usefull and more likely to be worked on and improved.


问:
Are small amounts of functional programming understandable by non-FP people?
Case: I'm working at a company, writing an application in Python that is handling a lot of data in arrays. I'm the only developer of this program at the moment, but it will probably be used/modified/extended in the future (1-3 years) by some other programmer, at this moment unknown to me. I will probably not be there directly to help then, but maybe give some support via email if I have time for it.

So, as a developer who has learned functional programming (Haskell), I tend to solve, for example, filtering like this:

```<code>filtered = filter(lambda item: included(item.time, dur), measures)
</code>```

The rest of the code is OO, it's just some small cases where I want to solve it like this, because it is much simpler and more beautiful according to me.

Question: Is it OK today to write code like this?

How does a developer that hasn't written/learned FP react to code like this?

Is it readable?

Modifiable?

Should I write documentation like explaining to a child what the line does?

```<code> # Filter out the items from measures for which included(item.time, dur) != True
</code>```

I have asked my boss, and he just says "FP is black magic, but if it works and is the most efficient solution, then it's OK to use it."

What is your opinion on this? As a non-FP programmer, how do you react to the code? Is the code "googable" so you can understand what it does? I would love feedback on this.

答:
Post a code snippet to a fellow dev that isn't as fluent in python, and ask him if he can spend 5 minutes checking out the code to see if he/she understands it.

If yes, you are probably good to go. If not, you should look at making it clearer.

Could your colleague be daft and not understand something that should be obvious? Yes, but you should always program in accordance with KISS.

Maybe your code is more efficient/good looking/elegant than a more straightforward, idiot-proof approach? Then you need to ask yourself: do I need to do this? Again, if the answer is no, then don't do it!

If after all this, you still think you need and want to do it the FP way, then by all means do it. Trust your instincts, they are better suited for your needs than most people on any forum :)

ContentLicense: CC BY-SA 4.0


问:
What's your favourite quote about programming?
What's your favourite quote about programming?

One quote per answer, and please check for duplicates before posting!

答:
Il semble que la perfection soit atteinte non quand il n'y a plus rien à
ajouter, mais quand il n'y a plus rien à retrancher.

  — Antoine de Saint-Exupéry, French writer (1900-1944), Terre des Hommes (1939)

(It would seem that perfection is attained not when there is nothing left to add, but when there is nothing left to take away.)

LastEditorDisplayName: Roger Pate


问:
What makes C developers so curious if "i++ == ++i"?
Just a random observation, it seems that on StackOverflow.com, there are questions about if "++i == i++". That question gets asked all the time though, I think I saw it asked about 6 or 7 times in the past 2 months.

I just wonder why C developers are so interested in it? The same concept/question exists for C# and Java devs as well, but I think I saw only one C# related question.

Is it because so many examples use ++i? Is it because there is some popular book or tutorial? Is it because C developers just love to cram as much as possible into a single line for 'efficiency'/'performance' and therefore encounter 'weird' constructs using the ++ operator more often?

答:
A few years ago I read that these operators were considered dangerous so I tried to dig more info on it. If stackoverflow had been up at that time, I would have asked it there.

Now it is because some twisted people write loops such as

```<code>while( [something] )
{
  a[++j] = ++j;
}
</code>```

Even now, I'm not too sure about what will/should happen, but it's pretty clear to me that multiple ++[var] on the same line is asking for trouble.

Body:
A few years ago I read that these operators were considered dangerous so I tried to dig more info on it. If stackoverflow had been up at that time, I would have asked it there.

Now it is because some twisted people write loops such as

while( [something] )
{
  a[++j] = ++j;
}

Even now, I'm not too sure about what will/should happen, but it's pretty clear to me that multiple ++[var] on the same line is asking for trouble.


答:
Let's imagine that you have two pages: MainPage.xaml and SecondPage.xaml.

also you have two viewModels MainViewModel.cs and SecondViewModel.cs

if you use some MVVM framework (MVVM light for example http://mvvmlight.codeplex.com/ ) you can use a ViewModelLocator, or you can write your own.

so, in OnNavigatied event in every page you can run this code:

```<code>var viewModel = ViewModelLocator.MainViewModel;
this.DataContext = viewModel;
</code>```

Also you can do in a xaml. See the example here : http://jesseliberty.com/2011/01/04/wpfs-mvvm-light-toolkit-soup-to-nuts-part-i/

You can inject a data provider to every view model. So, when the user adds data on the MainPage, MainViewModel saves the data to the data provider (wich holds the data in a memory, or saves it to the isolated storage.)

Then, when you navigates to the SecondPage, SecondViewModel gets a data from the dataProvider.

ViewModelLocator should be responcible for Main and Second view models has the same DataProvider instance.

If you need to pass any flag (was the data updated, Id, ect) you can do it by passing it in a Query String. ( http://jesseliberty.com/2011/01/09/passing-parameters-with-behaviors-in-mvvm-light-for-windows-phone/ )

This variant is good because your app can be thombstoned ( http://blogs.microsoft.co.il/blogs/arik/archive/2011/05/01/managing-tombstone-state-in-a-windows-phone-7-application.aspx) by the OS in any moment. You can handle this situation by sending a signal (executing a command, sending a message) to a current view model. And it will save data to storage. The

Title: Passing the data of a certain page to another page. Windows Phone 7

Body:
The user will fill out information in page 1, and the data will be seen in the other page listed in a listbox.

Is it advisable to use data binding?

I've been studying/researching about data binding already for about 2 days and still couldn't understand it.

Simple example would really help.

Body:
Let's imagine that you have two pages: MainPage.xaml and SecondPage.xaml.

also you have two viewModels MainViewModel.cs and SecondViewModel.cs

if you use some MVVM framework (MVVM light for example http://mvvmlight.codeplex.com/ ) you can use a ViewModelLocator, or you can write your own.

so, in OnNavigatied event in every page you can run this code:

var viewModel = ViewModelLocator.MainViewModel;
this.DataContext = viewModel;

Also you can do in a xaml. See the example here : http://jesseliberty.com/2011/01/04/wpfs-mvvm-light-toolkit-soup-to-nuts-part-i/

You can inject a data provider to every view model. So, when the user adds data on the MainPage, MainViewModel saves the data to the data provider (wich holds the data in a memory, or saves it to the isolated storage.)

Then, when you navigates to the SecondPage, SecondViewModel gets a data from the dataProvider.

ViewModelLocator should be responcible for Main and Second view models has the same DataProvider instance.

If you need to pass any flag (was the data updated, Id, ect) you can do it by passing it in a Query String. ( http://jesseliberty.com/2011/01/09/passing-parameters-with-behaviors-in-mvvm-light-for-windows-phone/ )

This variant is good because your app can be thombstoned ( http://blogs.microsoft.co.il/blogs/arik/archive/2011/05/01/managing-tombstone-state-in-a-windows-phone-7-application.aspx) by the OS in any moment. You can handle this situation by sending a signal (executing a command, sending a message) to a current view model. And it will save data to storage. The


问:
Dealing with API and error messages
We are in the process of constructing an API (using WCF).

So far I noticed 2 ways in which methods could go wrong due to problems with the parameters sent.

wrong format, for example we have a string date parameter which should be in a certain format, if it's in a different format the method cannot continue.

if a method role is to do something identified by an ID, but that ID does not exist in the application (DB)

First we thought throwing an exception, but I realize now that this is not truly an "exceptional" situation, these kind of things is pretty common.

Right now we deal with it in the following way:

We have an abstract class which is called APIResponse.
it has a boolean success variable, and an array of messages for the API's client.
Each group of methods has a corresponding implementation of this class and that will be the returned object.

is this kind of approach ok?

答:
I do like this approach, it is totally acceptable.

Take a look at the Flickr API. They are using error codes and error messages in their api response too.

http://www.flickr.com/services/api/

http://www.flickr.com/services/api/flickr.activity.userComments.html
(example api method)

Serving error codes and error messages instead of exceptions is imho much better when dealing with multiple (unknown) client frameworks (.net, java, etc..) If an client api-implementation is wrong because it is using a wrong format, it's much better to display the error message from the server ("Invalid date format. Must be ddMMyyy.") instead of getting an weird "FormatException" (+stacktrace).

Having error ids and error messages:

improves api usability

improves maintainability

improves user / developer experience

API User(Developer) could reference easily to their problem and that will save your time.  It would be much easier for you to track down a possible bug/taskswith a specific errorId/errorMessage instead of having "Hey, I'm getting those weird Exceptions when calling XYZ. What am I doing wrong?"

Edit based upon request:

Let's say we have a "BaseResponse" (similar to your APIResponse, comments are stripped out for better readability)

```<code>public class BaseResponse
{
  public int ErrorId { get; set; }

  public string ErrorMessage { get; set; }

  public bool Successful { get; set; }
}
</code>```

And we're having an GetDocumentResponse (implemented by DocumentService, see below)

```<code>public sealed class GetDocumentsResponse : BaseResponse
{
   public IList<Document> Documents { get; set; }
}
</code>```

DocumentService Contract

```<code>[ServiceContract]
public interface IDocumentService
{
    [OperationContract]
    [WebInvoke(
         Method = "POST",
         BodyStyle = WebMessageBodyStyle.WrappedRequest,
         ResponseFormat = WebMessageFormat.Json,
         RequestFormat = WebMessageFormat.Json)]
    GetDocumentsResponse GetDocuments(string date);
}
</code>```

DocumentService Implementation (simplified)

```<code>public GetDocumentsResponse GetDocuments(string date)
{
     bool isFormatValid = // parse Date
     if (!isFormatValid)
     {
        // Response = static class, provides generic responses and sets properties of response
        return Response.ProvideFault<GetDocumentsResponse>(100, "The date-format is not valid. Valid: mmddyyyy");
        // return new GetDocumentsResponse { Successful = false, ErrorId: 100, ErrorMessage = "The date-format is not valid. Valid: mmddyyyy"};
     }

     var documents = this.documentRepository.GetDocuments(...)
     return new GetDocumentsResponse { Successful = true, Documents = documents };
}
</code>```

So, let's say I'm a developer and I want to use this api.

1. - Making an valid api call & getting an valid response from server
(JSON Response)

```<code>{
   "ErrorId":0,
   "ErrorMessage":null,
   "Successful":true,
   "Documents":[
      {
         "DocumentId":13,
         "Name":"xyz"
      }
   ]
}
</code>```

2. - Making an invalid api call & getting an invalid response from server

```<code>{
   "ErrorId":100,
   "ErrorMessage":"The date-format is invalid. Valid: mmddyyyy",
   "Successful":false,
   "Documents":[

   ]
}
</code>```

So, for the first call I've done everything right.

The second call says clearly what is wrong, I do not have to research some .NET specific exceptions (or better: wcf faults) if I'm a java developer. In a few seconds after getting the response I do know what went wrong and why it went wrong. I do not have to research documentation or much worse to ask YOU about the current implementation of GetDocuments and why my date format is invalid. It saves you and me a lot of time.

Title: Dealing with API and error messages

Body:
I do like this approach, it is totally acceptable.

Take a look at the Flickr API. They are using error codes and error messages in their api response too.

http://www.flickr.com/services/api/

http://www.flickr.com/services/api/flickr.activity.userComments.html
(example api method)

Serving error codes and error messages instead of exceptions is imho much better when dealing with multiple (unknown) client frameworks (.net, java, etc..) If an client api-implementation is wrong because it is using a wrong format, it's much better to display the error message from the server ("Invalid date format. Must be ddMMyyy.") instead of getting an weird "FormatException" (+stacktrace).

Having error ids and error messages:

improves api usability

improves maintainability

improves user / developer experience

API User(Developer) could reference easily to their problem and that will save your time.  It would be much easier for you to track down a possible bug/taskswith a specific errorId/errorMessage instead of having "Hey, I'm getting those weird Exceptions when calling XYZ. What am I doing wrong?"

Edit based upon request:

Let's say we have a "BaseResponse" (similar to your APIResponse, comments are stripped out for better readability)

public class BaseResponse
{
  public int ErrorId { get; set; }

  public string ErrorMessage { get; set; }

  public bool Successful { get; set; }
}

And we're having an GetDocumentResponse (implemented by DocumentService, see below)

public sealed class GetDocumentsResponse : BaseResponse
{
   public IList<Document> Documents { get; set; }
}

DocumentService Contract

[ServiceContract]
public interface IDocumentService
{
    [OperationContract]
    [WebInvoke(
         Method = "POST",
         BodyStyle = WebMessageBodyStyle.WrappedRequest,
         ResponseFormat = WebMessageFormat.Json,
         RequestFormat = WebMessageFormat.Json)]
    GetDocumentsResponse GetDocuments(string date);
}

DocumentService Implementation (simplified)

public GetDocumentsResponse GetDocuments(string date)
{
     bool isFormatValid = // parse Date
     if (!isFormatValid)
     {
        // Response = static class, provides generic responses and sets properties of response
        return Response.ProvideFault<GetDocumentsResponse>(100, "The date-format is not valid. Valid: mmddyyyy");
        // return new GetDocumentsResponse { Successful = false, ErrorId: 100, ErrorMessage = "The date-format is not valid. Valid: mmddyyyy"};
     }

     var documents = this.documentRepository.GetDocuments(...)
     return new GetDocumentsResponse { Successful = true, Documents = documents };
}

So, let's say I'm a developer and I want to use this api.

1. - Making an valid api call & getting an valid response from server
(JSON Response)

{
   "ErrorId":0,
   "ErrorMessage":null,
   "Successful":true,
   "Documents":[
      {
         "DocumentId":13,
         "Name":"xyz"
      }
   ]
}

2. - Making an invalid api call & getting an invalid response from server

{
   "ErrorId":100,
   "ErrorMessage":"The date-format is invalid. Valid: mmddyyyy",
   "Successful":false,
   "Documents":[

   ]
}

So, for the first call I've done everything right.

The second call says clearly what is wrong, I do not have to research some .NET specific exceptions (or better: wcf faults) if I'm a java developer. In a few seconds after getting the response I do know what went wrong and why it went wrong. I do not have to research documentation or much worse to ask YOU about the current implementation of GetDocuments and why my date format is invalid. It saves you and me a lot of time.


问:
How to explain that sample size does not influence project length
We have big enterprise projects they normally involve copying data from a source database to a destination database and then setting up a number of additional applications that sync this data etc.

The last project contained 250,000 items (rows of data). The next project will only contain 4,000 items. Project managers / business people believe the project should be 1/10 the time to complete because its only a fraction of the size of the last project.

What is a good analogy I can use to explain that writing code to transfer data from one system to another takes the same amount regardless of the number items - writing it for 1 item or for 100,000,000 will take roughly the same amount of time from a programming point of view.

答:
Tell them it's like building a new four lane highway to a remote part of the country. Whether that road gets used by 100 cars a day or 1000 cars a day, the effort to create the road will be about the same. </p>

<p>Granted, if it's going to support 1,000,000 cars a day you'll have to make the road a little more robust, but regardless, you're going to have to cut down the same trees, blast through the same mountains, level the same amount of dirt, and these activities are pretty much a fixed cost no matter how many cars use the road.  </p>

Body:
Tell them it's like building a new four lane highway to a remote part of the country. Whether that road gets used by 100 cars a day or 1000 cars a day, the effort to create the road will be about the same.

Granted, if it's going to support 1,000,000 cars a day you'll have to make the road a little more robust, but regardless, you're going to have to cut down the same trees, blast through the same mountains, level the same amount of dirt, and these activities are pretty much a fixed cost no matter how many cars use the road.


答:
Give them a calculator and ask them to add 1238783423 to 9858238483, time how long it takes. then ask them to add 3423 to 8483 and tell them you expect the answer approximately 100000 time quicker.

You might also explain the amount of data (probably) effects the length of time the software will take to run not the development time.

Title: How to explain that sample size does not influence project length

Body:
We have big enterprise projects they normally involve copying data from a source database to a destination database and then setting up a number of additional applications that sync this data etc.

The last project contained 250,000 items (rows of data). The next project will only contain 4,000 items. Project managers / business people believe the project should be 1/10 the time to complete because its only a fraction of the size of the last project.

What is a good analogy I can use to explain that writing code to transfer data from one system to another takes the same amount regardless of the number items - writing it for 1 item or for 100,000,000 will take roughly the same amount of time from a programming point of view.


问:
Is there a limit on how many global consts are used before an application is considered bad programming?
Basically, I develop websites, some large with many crud operations, etc...

However I've gotten into the habit of storing re-usable data as a constant in my PHP applications

I currently have 44 constants defined in one application.

These range from:

Database config

Home page for admin and guest

url slug names

declaring development mode

declaring maintenance mode

a few directory shortcuts ( instead of writing /admin/templates/images ill use const ADM_IMAGES )

session names

cookie names

random things like MAX_IMAGE_SIZE, THUMB_SIZE and MAX_LOGIN_ATTEMPTS

I don't have any problems using all these constants... It's kind of helpful having all these in my application.

I just wanted to know if its a 'good practise' to use them in this excess

If not, how else could this data be encapsulated to be useful AND easy enough to reach in my application? Also bearing readability in mind.

答:
Having many constants in an application is not a problem for itself - having them all in the global namespace may become one when your application gets larger. So if you have 44 constants, you may consider to group them into classes or namespaces.

Another thing to consider is if it is a good idea to have all those constants beeing part of your program. Separating some of them into a config file allows you to hand over the maintenance of these values to another person (for example, an admin of your customer). So you can more easily deploy a new release of your application to your customer with a smaller risk that those customized values get accidentally overwritten.


问:
Help with DB Structure, vOD site
I have a video on demand style site that hosts series of videos under different modules.  However with the way I have designed the database it is proving to be very slow.  I have asked this question before and someone suggested indexing, but i cannot seem to get my head around it.  But I would like someone  to help with the structure of the database here to see if it can be improved.  The core table is Videos:

```<code>ID       bigint(20) (primary key, auto-increment)
pID      text
airdate  text
title    text
subject  mediumtext
url      mediumtext
mID      int(11)
vID      int(11)
sID      int(11)
</code>```

pID is a unique 5 digit string to each video that is a shorthand identifier.  Airdate is the TS, (stored in text format, right there maybe I should change that to TIMESTAMP AUTO UPDATE), title is self explanatory, subject is self explanatory, url is the hard link on the site to the video, mID is joined to another table for the module title, vID is joined to another table for the language of the video, (english, russian, etc) and sID is the summary for the module, a paragraph stored in an external database.

The slowest part of the website is the logging part of it.  I store the data in another table called 'Hits':

```<code>id      mediumint(10)   (primary key, auto-increment)
progID  text
ts      int(10)
</code>```

Again, here (this was all made a while ago) but my Timestamp (ts) is an INT instead of ON UPDATE CURRENT TIMESTAMP, which I guess it should be.  However This table is now 47,492 rows long and the script that I wrote to process it is very very slow, so slow in fact that it times out.  A row is added to this table each time a user clicks 'Play' on the website and then so the progID is the same as the pID, and it logs the php time() timestamp in ts.

Basically I load the entire database of 'Hits' into an array and count the hits in each day using the TS column.  I am guessing (i'm quite slow at all this, but I had no idea this would happen when I built the thing) that this is possibly the worst way to go about this.

So my questions are as follows:

Is there  a better way of structuring the 'Videos' table, is so, what do you suggest?

Is there a better way of structuring 'hits', if so, please help/tell me!

Or is it the fact that my tables are fine and the PHP coding is crappy?

答:
Basically I load the entire database of 'Hits' into an array and count the hits in each day using the TS column.

You want speed, De-normalize.
This is one of those rare occasions when De-normalization is OK. to slow you site even a little bit for something as minor as hit counter is Crazy.

So create a Table like such:

```<code>Video bigint(20)
Date (Date Only)
HitCounter int
</code>```

Each time you have a hit Update this table, adding one to the HitCounter. (Insert a new record with the first hit of the day). Now you can always get your counts in an instant.

Important Note: Anytime you de-normalize like this make sure you have a routine that can repair the data in your summary table. This routine should run regularly.

As others have pointed out, because you have so little data, I am in agreement with them in doubting the counter is the cause of your performance problem. The solution above is most likely similar to what YouTube is doing for counts.

Title: Help with DB Structure, vOD site

Body:
Basically I load the entire database of 'Hits' into an array and count the hits in each day using the TS column.

You want speed, De-normalize.
This is one of those rare occasions when De-normalization is OK. to slow you site even a little bit for something as minor as hit counter is Crazy.

So create a Table like such:

Video bigint(20)
Date (Date Only)
HitCounter int

Each time you have a hit Update this table, adding one to the HitCounter. (Insert a new record with the first hit of the day). Now you can always get your counts in an instant.

Important Note: Anytime you de-normalize like this make sure you have a routine that can repair the data in your summary table. This routine should run regularly.

As others have pointed out, because you have so little data, I am in agreement with them in doubting the counter is the cause of your performance problem. The solution above is most likely similar to what YouTube is doing for counts.


问:
Is it must for a junior Programmer to have a mentor?
I am a Jr. ASP.NET/C# Developer and I have been working with a Company for the past 9 months. I have been appointed to try and develop their Legacy System (built in Visual FoxPro) in ASP.NET/C#.

I am the only developer working on this project and it's a bit overwhelming, but I complete the tasks assigned to me within a reasonable time frame using Google, SO and other forums as references.

My senior developer is a FoxPro developer and has very little knowledge of .NET. I do not get any sort of help from my Senior developer. I am working completely on my own.

By working as a solo developer I have learnt quite a few things and feel like I am moving forward. However as I am working alone I feel that there are so many things that I might have missed out on having not worked in a team.

I feel I need someone who can just guide me on do's and the don'ts. I feel the need to have a mentor who can help me with the many questions that I cannot ask on SO or earch on Google.

Questions:

Is it normal to feel this way or I am just not doing enough?

How important is mentoring for a junior developer?

How important is it for a Jr. Developer to work in a team?

答:
When I started, I didn't have a mentor as such. I was assigned to a guy who would leave the place in three months and told to pick his brains to learn as much as I could. What have I learned? Working in a place without any knowledge management strategies sucks.

Since then I've been assigned a bunch of interns / trainees / new people and told to mentor them. What have I learned? You cannot get anything done when someone is constantly nagging you with questions that SO or Google would answer within 15 seconds and the reluctance to ask such questions is very low if you're declared mentor. Most resources they need are available on our wiki (yes, we learned a bit in between) and for the remaining questions (not covered by either local and web resources) are few and far between.

I think it is very important to give some guidance to new devs. I schedule about the same time for code reviews with new people as it took to write the code in the first place, and those are where most of the teaching takes place. Whenever possible, we try to pair them up with experienced devs / testers for a specific task. However, I thoroughly dislike being or assigning 'mentors' on a long-term basis.

Edit: One point I forgot. Junior devs shouldn't be left hanging on some solitary fringe of a project or - worse still - an project unrelated to everyone else's. Try to talk to someone up the chain to be moved to a part of the project where you can interact.


答:
I think that a mentor and work team are very good for a young developer as he learns and becomes better and more knowledgeable.

That being said, I also think that we have so many good sources of knowledge nowadays, that if you are really an eager and passionate developer, you can develop yourself a lot by yourself and with the help of google and SO of course.

So make the best out of this situation, you can still learn a lot.

I think that your wage and working hours shouldnt be part of this question... it is unrelated.

Title: Is it must for a junior Programmer to have a mentor?

Body:
I am a Jr. ASP.NET/C# Developer and I have been working with a Company for the past 9 months. I have been appointed to try and develop their Legacy System (built in Visual FoxPro) in ASP.NET/C#.

I am the only developer working on this project and it's a bit overwhelming, but I complete the tasks assigned to me within a reasonable time frame using Google, SO and other forums as references.

My senior developer is a FoxPro developer and has very little knowledge of .NET. I do not get any sort of help from my Senior developer. I am working completely on my own.

By working as a solo developer I have learnt quite a few things and feel like I am moving forward. However as I am working alone I feel that there are so many things that I might have missed out on having not worked in a team.

I feel I need someone who can just guide me on do's and the don'ts. I feel the need to have a mentor who can help me with the many questions that I cannot ask on SO or earch on Google.

Questions:

Is it normal to feel this way or I am just not doing enough?

How important is mentoring for a junior developer?

How important is it for a Jr. Developer to work in a team?


问:
Why is Java the lingua franca at so many institutions?
EDIT: This question at first seems to be bashing Java, and I guess at this point it is a bit. However, the bigger point I am trying to make is why any one single language is chosen as the one end all be all solution to all problems. Java happens to be the one that's used so that's the one I had to beat on here, but I'm not intentionality ripping Java a new one :)

I don't like Java in most academic settings. I'm not saying the language itself is bad -- it has several extremely desirable aspects, most importantly the ability to run without recompilation on most any platform. Nothing wrong with using the language for Your Next App ^TM. (Not something I would personally do, but that's more because I have less experience with it, rather than it's design being poor)

I think it is a waste that high level CS courses are taught using Java as a language. Too many of my co-students cannot program worth a damn, because they don't know how to work in a non-garbage-collected world. They don't fundamentally understand the machines they are programming for. When someone can work outside of a garbage collected world, they can work inside of one, but not vice versa. GC is a tool, not a crutch. But the way it is used to teach computer science students is a as a crutch.

Computer science should not teach an entire suite of courses tailored to a single language. Students leave with the idea that all good design is idiomatic Java design, and that Object Oriented Design is the ONE TRUE WAY THAT IS THE ONLY WAY THINGS CAN BE DONE. Other languages, at least one of them not being a garbage collected language, should be used in teaching, in order to give the graduate a better understanding of the machines.

It is an embarrassment that somebody with a PHD in CS from a respected institution cannot program their way out of a paper bag.

What's worse, is that when I talk to those CS professors who actually do understand how things operate, they share feelings like this, that we're doing a disservice to our students by doing everything in Java. (Note that the above would be the same if I replaced it with any other language, generally using a single language is the problem, not Java itself)

In total, I feel I can no longer respect any kind of degree at all -- when I can't see those around me able to program their way out of fizzbuzz problems.

Why/how did it get to be this way?

答:
I mostly agree but to a certain degree.

If you are to teach CS cource focused on data structures or algorithms. Getting most of the unnecessary stuff out of the way is a good thing. You don't wan't students to deal with low level stuf when learning high level concepts.

On the other hand low level stuff should be also taught. Just so we get more all-around programmers.


答:
It's okay to break programming rules if you understand the potential problems the rules are designed to avoid.  For global constants, the main problems are discoverability, name clashes, difficulty unit testing, and difficulty recognizing poor cohesion.  I would seriously consider refactoring them out in the following circumstances:

You are constantly hunting around trying to find either where an existing constant is defined, or where a new one should be.

You find yourself making names like HOME1, HOME2, etc. because the name you wanted is already taken.

The example is causing a less experienced colleague to use globals where they are neither helpful nor more readable.

You are wanting write unit tests that need to change those constants.

Feature requests or bugs frequently require changing several files.

To take them out, you have a couple options:

Limit the scope of a constant to a single file instead of the entire application.  If this is difficult to do, it probably means your code is not cohesive enough and needs refactoring.

Make an object or objects that you pass to functions that need it.  This takes some practice to define a hierarchy that works.

Title: Is there a limit on how many global consts are used before an application is considered bad programming?

Body:
Basically, I develop websites, some large with many crud operations, etc...

However I've gotten into the habit of storing re-usable data as a constant in my PHP applications

I currently have 44 constants defined in one application.

These range from:

Database config

Home page for admin and guest

url slug names

declaring development mode

declaring maintenance mode

a few directory shortcuts ( instead of writing /admin/templates/images ill use const ADM_IMAGES )

session names

cookie names

random things like MAX_IMAGE_SIZE, THUMB_SIZE and MAX_LOGIN_ATTEMPTS

I don't have any problems using all these constants... It's kind of helpful having all these in my application.

I just wanted to know if its a 'good practise' to use them in this excess

If not, how else could this data be encapsulated to be useful AND easy enough to reach in my application? Also bearing readability in mind.


答:
The short version:

Should interns have a mentor? Yes

Should junior devs have a mentor? Probably

The long version:

Mentors should exist, but they are like the people on SO. They should not be used as a primary resource, but rather as a safety net when you can't google whatever it is you are banging your head against.

Examples:

Some very specific problem that nobody else outside the company knows
about.

Explaining of product vision (what should this look like, user experience questions etc)

Some bizzare errors that nobody has heard of (in most cases this is just a missing file, library or misconfiguration of IDE or
something like that).

I'm in my third internship right now, and the only time I go to my mentor is when I feel that I am stuck or when I need his input to take a product decision.

A golden rule is to never ever go to your mentor before you have researched possible answers to whatever questions you have. Even if it is company-specific, most of the time there are some docs laying around that some poor ex-intern has made for exactly this problem.

Your Questions:

Is it normal to feel this way or I am just not doing enough?

Yes to the first and if you don't get some proper mentoring, the second part might also be true.

Should I consider a job switch in such circumstances?

Hard to answer, but if you don't like it, leave it. On the other hand, you are supposed to be out of your comfort zone. Otherwise it's just stale and boring, no?

How important is mentoring for a junior developer?

Can't answer since I haven't been one before

How important is for a Jr. Developer to work in a team?

Interns normally don't get to work in teams. This is both frustrating and alienating to a certain degree. I have been lucky in that regard and have always been placed in a team, which have had specific project goals and a clear long-time plan.

I imagine the same is true for junior developers. The point is that we are social creatures. While it might be fun to do a solo project on the weekends, in the long run most prefer teams.

Good luck!


答:
Having senior developer as mentor without knowledge of how to use him - will not help you.

Senior developer is like google with complex queries support. Good Senior Developer also has comet connection with developer.

BTW question "Should I have senior developer as mentor?" is similar to question "Can I learn without teacher?". Yes you can, if you genius.


问:
Openfire licensing with custom code
I am thinking of integrating the openfire chat server with my custom website. Openfire server and the smack client library is licensed under Apache License, Version 2.0.

If I decide to use openfire, will it require my website source code to be also made available under the Apache license?

Tried going through the licensing terms, but the legal language is a bit confusing.

Thanks in advance for any insights!

Rohit.

答:
The short answer is no, there is nothing in the Apache licence which could require your website source code to be also made available under the Apache license.

From wikipedia:

Like any free software license, the Apache License allows the user of the software the freedom to use the software for any purpose, to distribute it, to modify it, and to distribute modified versions of the software, under the terms of the license.

The Apache License is permissive, so it does not require modified versions of the software to be distributed using the same license (unlike copyleft licenses - see comparison). In every licensed file, any original copyright, patent, trademark, and attribution notices in redistributed code must be preserved (excluding notices that do not pertain to any part of the derivative works); and, in every licensed file changed, a notification must be added stating that changes have been made to that file.

And from the Apache License and Distribution FAQ:

I'm not a lawyer. What does it all MEAN?

Describing legal documents in non-legalese is fraught with potential for misinterpretation. Notwithstanding the text that follows, the actual text of the license itself is legally binding and authoritative.

That said, here's what the Apache license says in layman's terms:

It allows you to:

freely download and use Apache software, in whole or in part, for personal, company internal, or commercial purposes;

use Apache software in packages or distributions that you create.

It forbids you to:

redistribute any piece of Apache-originated software without proper attribution;

use any marks owned by The Apache Software Foundation in any way that might state or imply that the Foundation endorses your distribution;

use any marks owned by The Apache Software Foundation in any way that might state or imply that you created the Apache software in question.

It requires you to:

include a copy of the license in any redistribution you may make that includes Apache software;

provide clear attribution to The Apache Software Foundation for any distributions that include Apache software.

It does not require you to:

include the source of the Apache software itself, or of any modifications you may have made to it, in any redistribution you may assemble that includes it;

submit changes that you make to the software back to the Apache Software Foundation (though such feedback is encouraged).

Title: Openfire licensing with custom code


答:
Having a mentor is a great thing, but in many situations you need to find your own mentor, and not necessarily a senior person where you work.  Also, different people mentor in different ways.  One otherwise excellent mentor would come in early to work to take hardware out of my PC and add it to his.  He didn't exactly take me under his wing.  I still learned a lot from him by reading his excellent code and asking him questions, usually the "why" type question, wanting background for why something worked the way it did.

Check out your local users groups (if there are such things for ASP/.NET/C#) or even your local Java users group which is the most similar language to C#.  Sorry to be negative, but Microsoft technologies seem to have much less "grass roots" support resources like users groups than open-source or even cross-platform technologies.  If you change jobs, you might want to think about that.

At the same time, no single mentor will know everything.  As frustrating as it can be, teaching yourself from books is a critical skill.  Manuals are boring, but developing mad kung-fu coding skills is cool and to do that you have to cultivate a taste for boring manuals.  Just like you won't become a body-builder without lifting weights.

Find the best tech bookstore in your area.  In Boston, the MIT bookstore is pretty awesome, but probably not for Microsoft technologies.  In South Carolina, I trek almost an hour away to the Barnes and Noble with the big tech section a couple times a year and browse for a few hours to find just the right book.

Good luck.  The desire for a mentor will not go away when you become more proficient and a good mentor becomes harder to find.  Cultivating a network of valued opinions is a skill you will need to carry with you through your career.

Please also do not confuse your want of a mentor with a lack of confidence which is another serious hurdle for many programmers.  You may have to trick yourself to skip the part of each task where you wallow in thoughts like, "I can't do this" and just learn to do it anyway and fix it to make it better after you get something working.

Good luck!


问:
Reasonable test coverage requirements when dealing with a contractor?
We're outsourcing some work to an external developer, so I'm busy writing up a contract about what constitutes a deliverable.

So far I require that the code is shipped with automated tests.

But, what is a reasonable way to specify the detail of tests up-front in the contract in a measurable way?

I'm loathe to say "100% code coverage" because it's been established pretty often that 100% is pretty meaningless, and the diminishing returns above about 70-80% would probably just be pushing up our costs unnecessarily, and possibly even pushing up the complexity of certain things that might otherwise be very simple.

Internally we pretty much leave it up to our developers to decide on the level of tests needed, based on their intuition and experience. With a contractor however there is a fixed price that has to be agreed to up front and we need some way to enforce a certain level of quality.

Any suggestions or recommended reading matter would be appreciated!

答: You can come up with more specific measure. E. g. 100% coverage for methods with cyclomatic complexity >= 5. Etc...</p>


问:
Should we use python 2.6 or 2.7 or 3.x?
The version of python which I am using is 2.6, and there is a 2.7 and 3.x. Usually I use python for some trivial program/snippet. I realize there are some major difference between 2.x and 3.x. I would really like to know, if I am going to make a bigger project with python, which version of python should I use?

Should I upgrade to 2.7, or go to 3.x or stay with 2.6?

The decision should be based on these terms:

Number of user in the internet as a community. More users mean more open-source package and help from them.

Functionality.

Support from official development team.

Compatibility for existing module/package.

Thanks!

答: I was in the same boat previously and this is what I found. Python 2.6, 2.7, and 3.2 can be installed side-by-side using MacPorts and can easily be switched. (I am a Mac user). Look for alternatives to Macports for your platform. </p>

Title: Should we use python 2.6 or 2.7 or 3.x?


答:
In general, globals are discouraged.  But some things are really "global" in the sense that a single value or setting needs to be shared by many different pieces of code.  Sometimes, as Karl points out, sharing data between different areas of your application can mean that your application is structured poorly.  If you have 26 source files (named A-Z for simplicity) and 10 globals and 5 of those "globals" are used only by files C, H, and N, then you may want to look at C, H, and N to see what else they have in common and see if it makes sense to merge C, H, and N and make half of your former globals private.

On the other hand, some information may be truly global, like "application-name" or "is-whole-app-in-special-testing-mode."  These things may be used in most files of your application.  Some tests for good globals are:

Is the value immutable once it is set (good) or do you have to worry about one part of your application changing it at runtime and another part getting the old value by mistake (bad)?

Is it truly global - a single value that needs to be used by several different independent sections of your application?  Obviously you want to eliminate unnecessary dependencies, but some dependencies are necessary.

Don't be an idiot.  I've heard stories of people making "currently-logged-in-user" a global, thus limiting that web application to a single logged-in user.  This kind of global is too stupid to be called evil, but it happens.

For example, when you say "session names" that could mean two things:

```<code>GOOD Global:
// Key used to look up number of items in individual user's shopping cart
// Each user's session has a hashtable of values and this is better than
// hard-coding the "numCartItems" string each time you use it because
// the compiler will catch a typo in the NUM_CART_ITEMS symbol, but not
// in a string:
String NUM_CART_ITEMS = "numCartItems";

BAD Global:
// Stores number of items in individual user's shopping cart
// but puts everyone's items in the same cart - OOPS!
int NUM_CART_ITEMS = 0;
</code>```

Body:
In general, globals are discouraged.  But some things are really "global" in the sense that a single value or setting needs to be shared by many different pieces of code.  Sometimes, as Karl points out, sharing data between different areas of your application can mean that your application is structured poorly.  If you have 26 source files (named A-Z for simplicity) and 10 globals and 5 of those "globals" are used only by files C, H, and N, then you may want to look at C, H, and N to see what else they have in common and see if it makes sense to merge C, H, and N and make half of your former globals private.

On the other hand, some information may be truly global, like "application-name" or "is-whole-app-in-special-testing-mode."  These things may be used in most files of your application.  Some tests for good globals are:

Is the value immutable once it is set (good) or do you have to worry about one part of your application changing it at runtime and another part getting the old value by mistake (bad)?

Is it truly global - a single value that needs to be used by several different independent sections of your application?  Obviously you want to eliminate unnecessary dependencies, but some dependencies are necessary.

Don't be an idiot.  I've heard stories of people making "currently-logged-in-user" a global, thus limiting that web application to a single logged-in user.  This kind of global is too stupid to be called evil, but it happens.

For example, when you say "session names" that could mean two things:

GOOD Global:
// Key used to look up number of items in individual user's shopping cart
// Each user's session has a hashtable of values and this is better than
// hard-coding the "numCartItems" string each time you use it because
// the compiler will catch a typo in the NUM_CART_ITEMS symbol, but not
// in a string:
String NUM_CART_ITEMS = "numCartItems";

BAD Global:
// Stores number of items in individual user's shopping cart
// but puts everyone's items in the same cart - OOPS!
int NUM_CART_ITEMS = 0;


答:
If you have a list of sites to scrape, your answer may be as simple as breaking that into two lists and running two copies of your python program - one against each list.  If the program normally spends most of its time waiting for the site to respond, you'll see a speed up.  If, on the other hand, your program speed is limited by your network bandwidth, or how fast your program can process each site, you will see a slowdown.  So time your program running with one instance (maybe and average time for 100 sites), then time two instances, then three...  You will find a sweet spot where more or fewer instances slows your program down.

Multiprocessing is very difficult where the two processes share data.  Make sure they do not need to share any data or communicate with each other and multi-processing is easy.  Of course, really being sure that there are no dependencies is hard.  :-)

Title: How can I multiprocess my program?

Body:
I wrote a program which scrape internet sites. It is pretty straigtforward because it process link one by one.

With the limiting factor of the internet speed, the process is rather slow.

I wonder, how can I make it multiprocess? The modules of python is confusing. I don't know the difference between subprocess and multiprocess. I've heard that multiprocessing is difficult and ineffective because of the GIL since python 2.x. I am using Python 3.2, so I wonder if things have been improved.


答:
Why do you have a string pID when you already have a unique integer identifier in ID?  The ID column, declared as a primary key is probably already indexed, and integer comparisons are much faster than string ones.  Why can't you just use ID instead of pID everywhere and drop the pID column?

I think #1 above is a minor error.  Have you timed your application to prove to yourself exactly where the slowness is?  Unless you are absolutely certain what is slow, you are wasting your time trying to speed up the wrong things.

In Java I use:

```<code>long startMs = System.currentTimeMs();
logger.info("Time before doing first thing: " + System.currentTimeMs() - startMs);
// do first thing.
logger.info("Time before doing second thing: " + System.currentTimeMs() - startMs);
// do second thing.
logger.info("Time after doing second thing: " + System.currentTimeMs() - startMs);
// etc.
logger.info("Total time: " + System.currentTimeMs() - startMs);
</code>```

Run the slow part of your program at least 5 times, maybe 10 times to be sure that your test system isn't busy doing something else and throwing your timings off.  Write down your timings, specifically what is slow, exactly how slow, AND the total time.  You don't want to speed up one part by slowing down another part so much that you actually make the whole thing slower.

Title: Help with DB Structure, vOD site

Body:
I have a video on demand style site that hosts series of videos under different modules.  However with the way I have designed the database it is proving to be very slow.  I have asked this question before and someone suggested indexing, but i cannot seem to get my head around it.  But I would like someone  to help with the structure of the database here to see if it can be improved.  The core table is Videos:

```<code>ID       bigint(20) (primary key, auto-increment)
pID      text
airdate  text
title    text
subject  mediumtext
url      mediumtext
mID      int(11)
vID      int(11)
sID      int(11)
</code>```

pID is a unique 5 digit string to each video that is a shorthand identifier.  Airdate is the TS, (stored in text format, right there maybe I should change that to TIMESTAMP AUTO UPDATE), title is self explanatory, subject is self explanatory, url is the hard link on the site to the video, mID is joined to another table for the module title, vID is joined to another table for the language of the video, (english, russian, etc) and sID is the summary for the module, a paragraph stored in an external database.

The slowest part of the website is the logging part of it.  I store the data in another table called 'Hits':

```<code>id      mediumint(10)   (primary key, auto-increment)
progID  text
ts      int(10)
</code>```

Again, here (this was all made a while ago) but my Timestamp (ts) is an INT instead of ON UPDATE CURRENT TIMESTAMP, which I guess it should be.  However This table is now 47,492 rows long and the script that I wrote to process it is very very slow, so slow in fact that it times out.  A row is added to this table each time a user clicks 'Play' on the website and then so the progID is the same as the pID, and it logs the php time() timestamp in ts.

Basically I load the entire database of 'Hits' into an array and count the hits in each day using the TS column.  I am guessing (i'm quite slow at all this, but I had no idea this would happen when I built the thing) that this is possibly the worst way to go about this.

So my questions are as follows:

Is there  a better way of structuring the 'Videos' table, is so, what do you suggest?

Is there a better way of structuring 'hits', if so, please help/tell me!

Or is it the fact that my tables are fine and the PHP coding is crappy?

Body:
Why do you have a string pID when you already have a unique integer identifier in ID?  The ID column, declared as a primary key is probably already indexed, and integer comparisons are much faster than string ones.  Why can't you just use ID instead of pID everywhere and drop the pID column?

I think #1 above is a minor error.  Have you timed your application to prove to yourself exactly where the slowness is?  Unless you are absolutely certain what is slow, you are wasting your time trying to speed up the wrong things.

In Java I use:

long startMs = System.currentTimeMs();
logger.info("Time before doing first thing: " + System.currentTimeMs() - startMs);
// do first thing.
logger.info("Time before doing second thing: " + System.currentTimeMs() - startMs);
// do second thing.
logger.info("Time after doing second thing: " + System.currentTimeMs() - startMs);
// etc.
logger.info("Total time: " + System.currentTimeMs() - startMs);

Run the slow part of your program at least 5 times, maybe 10 times to be sure that your test system isn't busy doing something else and throwing your timings off.  Write down your timings, specifically what is slow, exactly how slow, AND the total time.  You don't want to speed up one part by slowing down another part so much that you actually make the whole thing slower.


问:
What is the difference (if any) between (null != $object) and ($object != null) when using PHP?
I am used to Java and therefore always think conditions are interpreted from left to right, i.e. there is a vital difference in null != $obj and $obj != null

Now this seems not to be the case with PHP.

Can I do something wrong in PHP when I always start with null on the left-hand side? Can I keep my behaviour from Java or do I need to train myself to do something else when dealing with PHP conditions?

答: @phant0m: OK point taken... NEVER USE != or == always use !=== and === when you code with PHP. Therefore this question was wrong in the beginning, and there is no best practice with NULL on either side of the condition when it comes to PHP.</p>


答:
I'm really surprised this is the situation as many schools.  When I got my CS degree, I had a series of languages courses that between them included all the popular languages of the day (this was almost 40 years ago): assembler (Univac 1108 and MIX), FORTRAN IV, SNOBOL4, COBOL, Lisp, and Algol 68.  I can't imagine having just one language being taught.  Or how I could appreciate what compilers had to do without having written some assembler programs.

We did use Algol and FORTRAN for most of the data and algorithms courses.  I would have liked to have spent more time with Lisp -- instead we had just an introduction and now am trying to re-learn some of the concepts.  We used SNOBOL4 for writing parsers -- and its pattern matching with backtracking built a good foundation for later work the regex libraries included with many modern languages.

This introduction to half a dozen languages sparked an interest in me that has continued ever since.


问:
Migrating from jdbc to MyBatis -- advice needed
I am working on a Java application (an ERP) that has grown pretty large, and will continue to grow for the next couple of years. We have been using Spring-JDBC for our DAO layer. But the amount of boilerplate code that needs to be written is slowing us down significantly, not to mention introducing silly bugs in the system.

So now we're looking for a solution that will:

Reduce the amount of time we need to spend on the DAO layer

Doesn't have a very steep learning curve

Gives us control over our queries, like we have with JDBC.

We should be able port our existing code part-by-part, not all at once.

I thought MyBatis would be a good choice, but I'm not sure if it would satisfy all our requirements. In particular, would it be able to work alongside our Spring-JDBC code without creating problems in transaction management, handling concurrency etc?

Edit: Forgot to mention that we're using Spring-AOP for transaction management, which we'd prefer to continue with.

Thanks!

答:
MyBatis is good solution of given problems.

You can still use spring-aop with MyBatis as like in spring-jdbc.

It will take so very less, to migrate your queries from Spring-JDBC to MyBatis. MyBatis is very easy to learn and provides Object mappers to automatic convert native SQL query data to pojos. If you are using spring-jdbc, you already have java beans, those you can reuse with MyBatis.