答:
To get the real reason, you would have to ask the people who run those institutions (and even then, they might not tell you).

Several possible reasons (and I'm neither defending nor accusing anyone here, just guessing):

You can get things done in Java

Java it is a general purpose language and as such can be used to solve a lot of problems.

Lots of teachers understand Java

It is difficult to teach a language that you don't understand

Java is popular

Which means that there are plenty of Java resources - books, an active community, code libraries etc.

Java is easy

You don't have to understand lots of low-level stuff or theory to do Java. You may not do it well, but at least you can get things done.

Java is pervasive

You can run it on more or less anything.

There are jobs for Java programmers

There are lots of jobs that need Java - teachers are supposed to be preparing students for the real world.

There is limited time

On many courses, there isn't time to teach multiple languages, theories, low-level concepts etc.

It is what students want

Lots of students have already heard of (and even used) Java. They like because it is familiar.

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?


问:
How do you explain the importance of using a [distributed] version control system to someone who's not in the CS field?
A good example of someone who fits that description might be a project manager.

I was asked by my boss the other day, "what this Github thing is and why it's important?"  He has some proprietary projects so he would need private hosting and I found myself struggling to explain beyond the usual: VCSs make collaboration trivial, provide a history and "backup" of all your data, and allow you to record atomic changes in a code base.  In my mind I was thinking, "it's almost as if you have to use a DRVS to really understand how beneficial it is".

I ended up pointing him to BitBucket because they give you unlimited private repositories (I even had to explain what a repository was).

Does anyone have ay really good concrete examples of how a VCS has saved their ass or made life easier, etc -- basically, how would you sell a DVSC to someone who's not unfamiliar with programming, but not a programmer by profession?

答:
Also if you release software the following feature of a VCS is rather essential: Assume your customer finds a bug. The current development of the software is probably in a very different state than the version which the customer has. Maybe the bug is fixed in now, maybe it is not, but in any case the current software is not in a state that you can just ship it to the customer.

A VCS makes it trivial to go back to the version that was shipped to the customer, fix the bug he was requesting, build it and ship him a revised version. All this without disturbing current development, without having to ship him a version with unfinished/unstable features or additional bugs introduced due to the new unfinished development.

In addition a VCS makes it easy for you to port this fix back into the new development branch if the bug is still present there too.

By strong discipline you can probably manage this without a VCS for a very small team, but using one will save you time and in the end money. Most likely it will also help you keep your customers.

ContentLicense: CC BY-SA 3.0


问:
TFS non-chronological deployment?
We have the following scenario:

Changeset #1 is some unfinished buildable checkin

Changeset #2 is a completed small task

..

Changset #5 completes the work done at CS#1

They all affect the same output dll.

How do we deploy changes done at CS#2 without the other work? Also how can we avoid this situation happening again in the future?

答:
I think that in that case you should try to "disable" your #1 changeset.

let's say if it is a new feature, don't make any way to make this code run in the application.

if it is a replacement of an existing code, write it while the old code is in use, and enable it when it is done

Title: TFS non-chronological deployment?


问:
FizzBuzz - really?
When it comes to "interview test" questions, the subject of FizzBuzz often comes up. There is also a Coding Horror post about it.

Now, if you bother reading sites such as this, you are probably less likely to be in the demographic of programmers who would find FizzBuzz anything but trivial.

But is it really true that 99% of programmers will struggle with it?

Really?

What is the evidence to back this up?

Some real-life examples would be very helpful in answering this question.

答:
99%? No. A significant percentage? Yes. From my own direct experience of interviewing people I can testify to this one. It might seem insignificant to you but there are a lot of people in the programming field who have more or less faked their way through for years and apply on non-entry level positions and fail this one.

Even if you CAN easily solve it, but you give me huge static about being asked to do such a menial task will count against you. Being on a team means having to sometimes do things you might not enjoy but are necessary. If right off the bat, before we've even started to work together you think it would be best to try and assert your special status of being above doing something I've asked you to do then it will act as a mark against you.

I don't care necessarily how elegant your solution is (although that would be nice) but seeing you take a stab at it on a whiteboard and talking your way through it shows me that you're at least willing to take a stab at it. If you get indignant and say something along the lines of "I'm a problem solver, not a code monkey!" then you will be knocked down a peg.

I have had interviewees just flat out refuse to even begin to attempt it. Just simply refuse. No. Uh uh. Won't do it. I ask one or two more polite questions, thank them for their time and close the interview off.

I say this as a manager and as a developer.

Title: FizzBuzz - really?

ContentLicense: CC BY-SA 2.5


问:
Separating words in a string
How do I separate words in a string?

In the following I have a random sample of words in a string extracted from text file with over a million words.

Here's the string:
"intervene Pockets Jerusalemand tissues powerful days gadgets rate invention heated Stewartis find communal  working lots internal They caused noise offer goand big jumps lose galaxies All Mall birth child world spin killed produced great center Dont pretend Africa solution times cursor good night professional problem refugees talk"

As you can see, the third word is "Jerusalemand." My goal is to separate "Jerusalem" and "and", and do the same thing for any other words that are stuck together.

Only thing that I could think of as of now is to compare every word in the string to a dictionary (SCOWL perhaps?), and if a segment of the word matches a word in the dictionary, I'll have to split the words to make them independent.

As an example, for "Jerusalemand" I'll loop through every character until a match is found in the dictionary for "Jerusalem," then I can separate that from "and," in turn completing the separation.

Shouldn't there be a better way to do this?

答:
Solutions to this problem are often ambiguous, and it's sometimes difficult to decide an optimum solution, even for a human.

If you need only a single solution where all words exist in a dictionary, then a naive approach will fail as soon as you encounter a word which prefix is also a valid dictionary entry.

For example, if your input string was:

```<code>tryingtomessitup
</code>```

Unless you backtrack, your algorithm would probably come up with:

```<code>try in gtomessitup
</code>```

instead of

```<code>trying to mess it up
</code>```

Correct solution to this problem needs to be done using dynamic programming, or even a brute force recursive algorithm which can decide if a prefix indeed leads to the optimal solution.

A DP example is mentioned in this StackOverflow thread. This answer explains it even more thoroughly (and leads to this article: Splitting words joined into a single string (compound-splitter)).

Title: Separating words in a string

Body:
Solutions to this problem are often ambiguous, and it's sometimes difficult to decide an optimum solution, even for a human.

If you need only a single solution where all words exist in a dictionary, then a naive approach will fail as soon as you encounter a word which prefix is also a valid dictionary entry.

For example, if your input string was:

tryingtomessitup

Unless you backtrack, your algorithm would probably come up with:

try in gtomessitup

instead of

trying to mess it up

Correct solution to this problem needs to be done using dynamic programming, or even a brute force recursive algorithm which can decide if a prefix indeed leads to the optimal solution.

A DP example is mentioned in this StackOverflow thread. This answer explains it even more thoroughly (and leads to this article: Splitting words joined into a single string (compound-splitter)).


问:
Is an API in C++ a better alternative to computing directly in SQL?
I need to perform large amounts of computations on data storerd in a busy Microsoft SQL server. Would it be faster if I retrieve the data from the server, perform the computations locally in C++, and possibly later update the tables on the server, all through an API?

Many thanks.

答:
It depends, firstly you do not want to hog the CPU processing the data if SQLServer wants all that CPU for itself - you'll be defeating the point, so migrating the data crunching task to a different server, even though this would be less efficient, would be faster overall.  Typically DBs use  a lot of CPU, so do some profiling whether you have the capacity.

If you have a mirrored server, that can be the best place to run a heavy computational task on the data, you'll just have to copy the results back to the original in most cases, but at least you'll have quick access to the original data.

Can you do the crunching during quiet times - overnight for example. If so, this is probably the best approach. If you need the data crunched in "real-time" then this obviously won't be sufficient.


答:
If your company has more than two people, then you probably have a word document or an excel document lying somewhere that's edited by multiple persons. And sometimes those persons make local copies, to take on a business trip etc. Or the document gets sent around by email after each change.

If you have such a file, then either some people's modifications have been lost in the past, or will be lost in the future. Or people think they've lost changes, but can't prove it. Or they'd like to see who made what change when and why. That's exactly the problem a VCS solves.

Title: How do you explain the importance of using a [distributed] version control system to someone who's not in the CS field?

Body:
A good example of someone who fits that description might be a project manager.

I was asked by my boss the other day, "what this Github thing is and why it's important?"  He has some proprietary projects so he would need private hosting and I found myself struggling to explain beyond the usual: VCSs make collaboration trivial, provide a history and "backup" of all your data, and allow you to record atomic changes in a code base.  In my mind I was thinking, "it's almost as if you have to use a DRVS to really understand how beneficial it is".

I ended up pointing him to BitBucket because they give you unlimited private repositories (I even had to explain what a repository was).

Does anyone have ay really good concrete examples of how a VCS has saved their ass or made life easier, etc -- basically, how would you sell a DVSC to someone who's not unfamiliar with programming, but not a programmer by profession?


问:
Structure of a single page app
I'm looking to develop a one page app, and will likely be using node.js for my server side coding.

I'm trying to get some advice regards the client-side coding. While i realise that something like backbone.js would really help me, since im very new to development the learning curve is very high for me.

So i'm going to be using something like dust.js for my client side templating.
Currently i'm creating some mockup screens (there are 4 in total) that are being built in just plain html/css.

When i come to doing the client side and server coding, is it better for me to combine all my presentation code into one html file, or into multiple files and then call them separately, considering it's a one page app that i am creating?

答:
It's not a question of singlepage/multipage, it's a question of source code organisation

To exagerate a little: it is like asking if you should have only one source file, since your result is only one executable.

How you present the page to the customer (1 page with js/4 pages with links) is a presentational issue, that should not interfere with how you organise your code.

How you keep your source files should determined by how easy it is for the coders to read, extend, debug them.

And how you meet these needs is determined by the actual tasks at hand, and not nesessarly by whether you present them to the user in a single page.

So, without talking about the projects details, i think, it's not easy to answer your question.

As a general guide how, imho, HTML-Templates should be structured, i would suggest the following:

The general page layout should be structured to provide some kind of inheritance, so that i easily can create new pages with the same header, columns, footer, etc, where only placeholders need to be filled.

each "widget" the page uses should be a functional unit, not depending on it's environment. for example, if you have tags, you should only change a single place in your source if you want all your tags to be dispayed as lowercase

Depending on your Technology Stack, these constrains may already imply a certain file structure: in Jinja2 (python templating engine), the general page layout inheritance needs seperate files, in Rails, the rendering of the widgets would be realised via "partials", which would be separate files, too.

Generally, i prefer small files, but that's more a preference. Before overengineering, just start simple (i.e., one file), and dont hesitate to split, as soon as it starts getting messy.

Title: Structure of a single page app


答:
I assume you're trying to create a single HTML page where the contents change depending on the data returned from the server.

Its not the programming model used by HTML, but I guess it can work... You can reload html sections using jQuery's .html() call - so the server can return chunks of html and you can display it dynamically. Put the sections you'll be reloading in a div and you'll be able to easily find the part of the page that gets reloaded.

Title: Structure of a single page app

Body:
I'm looking to develop a one page app, and will likely be using node.js for my server side coding.

I'm trying to get some advice regards the client-side coding. While i realise that something like backbone.js would really help me, since im very new to development the learning curve is very high for me.

So i'm going to be using something like dust.js for my client side templating.
Currently i'm creating some mockup screens (there are 4 in total) that are being built in just plain html/css.

When i come to doing the client side and server coding, is it better for me to combine all my presentation code into one html file, or into multiple files and then call them separately, considering it's a one page app that i am creating?


答: We (using SVN) usually solve this by using feature branches. This enables larger features to be only merged to the mainline after they are finished. A great article about different strategies is here Link</p>

Title: TFS non-chronological deployment?

Body:
We have the following scenario:

Changeset #1 is some unfinished buildable checkin

Changeset #2 is a completed small task

..

Changset #5 completes the work done at CS#1

They all affect the same output dll.

How do we deploy changes done at CS#2 without the other work? Also how can we avoid this situation happening again in the future?

ContentLicense: CC BY-SA 4.0


答:
There is no single answer for your question, and you have to weigh the costs for each stage to determine what is "best" for your environment.

First off, where is it easiest to establish and maintain a scheduler to fire this job?  Where are admins going to be more comfortable with in having the scheduler located.

Next, what sort of network bandwidth is available between the DB server and the system performing the calculations in C++?  There is a performance cost associated with transferring that data twice (once to the C++ machine, once to return the results).

What are the capabilities of the C++ calculation system?  If they're not comparable or greater than the DB system, then it may take even longer to use the C++ calculation system due to data transfer and calculation time.

What is the nature of the calculations that need to be performed.  Set manipulations are done much more easily within the DB server, but can require a fair amount of coding to replicate in C++.  There is a cost associated with developing, validating, and maintaining the code (be it SQL or C++) that will perform the calculation.  Some things are faster to write in SQL.  Some are written faster in C++.  What's your skill level in both cases?

Who is going to maintain this?  What's their skill level in all of the related categories that have come up?

What sort of auditing and / or logging is required?  Anything at all?  Are custom notifications required from this when the calculations are complete?  Long running jobs frequently require firing off some notice to indicate completion.  What if the process errors out?  How do you want to be notified?  Which system gives you the best access to this information?

How clean is the data?  What sort of errors are you likely to see within the data set?  C++ can be better at error handling because you can customize it to your exact needs.

Have you considered a hybrid approach to optimize the problem for both environments?  Pre-process on the DB server the stuff that SQL can do best, then ship a smaller data set to the C++ calculation system which performs the remainder of the tasks.  Depending upon how large the data set and calculations are, this could be broken up into several iterations between the DB and calculation servers.

Are you able to break the data set into smaller pieces for processing?  An incremental approach generally has less performance impact upon the host system simply because it's not doing as much at any one particular time.

Title: Is an API in C++ a better alternative to computing directly in SQL?

Body:
I need to perform large amounts of computations on data storerd in a busy Microsoft SQL server. Would it be faster if I retrieve the data from the server, perform the computations locally in C++, and possibly later update the tables on the server, all through an API?

Many thanks.


问:
What is the correct order to read these books?
I'm a junior C# developer, I learned at home and now I got my first job :)

I want to buy these books. But what is the correct order to read these books?

Code Complete: A Practical Handbook of Software Construction

Clean Code: A Handbook of Agile Software Craftsmanship

Pragmatic Programmer

答:
There is no "correct" order to reading these books.

They each focus on different aspects of software engineering.

Clean Code - focuses on coding in the small. How to write classes and functions.

Code Complete - focuses on the processes of software engineering.

Pragmatic Programmer - focuses on working within a team producing software.


答:
I only read "Clean Code", and it was very good. Uncle Bob tells you how to become a good Software Craftsman and how to write clean code that is maintainable even in years. So you maybe should read this book first :-) (I wish I had read it earlier).

If you want to get a bigger view (on dependencies between modules) I also can recommend his code-casts: http://www.cleancoders.com/

Title: What is the correct order to read these books?

Body:
I'm a junior C# developer, I learned at home and now I got my first job :)

I want to buy these books. But what is the correct order to read these books?

Code Complete: A Practical Handbook of Software Construction

Clean Code: A Handbook of Agile Software Craftsmanship

Pragmatic Programmer


问:
Confusion of scope of a variable: Is Global Variable a solution?
I am newly learning C Programming.

When we have a C Program with lot of functions, parameter passing, calling and all - It becomes a great problem as to which variable must be declared where.

My question is: If I declare all the variables (or atleast the variables that are confusing me) as Global Variables - my problem will be solved - but is that a Good Practice?

答:
In my experience, the cleanest way to do this is to create a data structure which contains all the variables that you require, and pass a reference to this structure to all your functions.

There is one valid reason to have a global variable, and that is when you need to access this data structure from within a signal handler, either to reload data or to cleanup and exit from the application.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <signal.h>

struct my_data { int a, b, c; };
static struct my_data *_global_cfg = NULL;

void sigint(int signo);
struct my_data * my_init_data(void);
int my_processing(struct my_data *cfg);

int main(void) {
  struct my_data *cfg = my_init_data();
  signal(SIGINT, sigint);
  return my_processing(cfg);
}

void sigint(int signo) {
  printf("SIGINT: a=%d\n", _global_cfg ? _global_cfg->a : 0);
  exit(EXIT_SUCCESS);
}

struct my_data * my_init_data(void) {
  struct my_data *ret = calloc(1, sizeof(*ret));
  _global_cfg = ret;
  return ret;
}

int my_processing(struct my_data *cfg) {
  if (cfg == NULL) return -1;
  while (1) {
    printf("%d - Waiting for SIGINT\n", cfg->a++);
    sleep(1);
  }
  return 0;
}
</code>```

Body:
In my experience, the cleanest way to do this is to create a data structure which contains all the variables that you require, and pass a reference to this structure to all your functions.

There is one valid reason to have a global variable, and that is when you need to access this data structure from within a signal handler, either to reload data or to cleanup and exit from the application.

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>

struct my_data { int a, b, c; };
static struct my_data *_global_cfg = NULL;

void sigint(int signo);
struct my_data * my_init_data(void);
int my_processing(struct my_data *cfg);

int main(void) {
  struct my_data *cfg = my_init_data();
  signal(SIGINT, sigint);
  return my_processing(cfg);
}

void sigint(int signo) {
  printf("SIGINT: a=%d\n", _global_cfg ? _global_cfg->a : 0);
  exit(EXIT_SUCCESS);
}

struct my_data * my_init_data(void) {
  struct my_data *ret = calloc(1, sizeof(*ret));
  _global_cfg = ret;
  return ret;
}

int my_processing(struct my_data *cfg) {
  if (cfg == NULL) return -1;
  while (1) {
    printf("%d - Waiting for SIGINT\n", cfg->a++);
    sleep(1);
  }
  return 0;
}


答:
Version control is great for (at least) three four things: backup, sharing code between developers, finding+fixing bugs and progress tracking.

Backup. If nothing else, it's backup on steroids. You have the entire development history, each commit is a snapshot of your entire code with an id (revision number), a description, timestamp, user info. And it's simple to compare files between revisions. If nothing else, it's faster than a simple backup (only file changes are sent and stored), and contains much more useful metadata. Why reinvent this?

Sharing code between developers. If you have at least two developers working on the same product simultaneously, I don't see any other way to reliably and consistently share code changes and merge them. Sending zips by mail?

Finding and fixing bugs. When your customers report a bug for a specific product version, you can quickly get the actual source snapshot in order to reproduce and fix it. It's hard to reproduce bugs if your source is different from customer's. Do you ask them to send the executable so that you can disassemble it? Furthermore, if you have problem identifying the cause of a bug, you can use VCS to pinpoint the exact revision where it was introduced.

Progress tracking. When you commit your work in snapshots, it allows you (and your manager) to track progress on feature implementations and status of open bugs. VC systems are also easily integrated with tracking systems and continuous integration systems. It's close to impossible to keep a level of quality for anything else other than a hobby project, unless you have a VCS.

Once you have all agreed that no software development should ever be done outside a VCS (I wouldn't miss it even for a hobby project), then you can discuss features of a (slightly more complicated) DVCS (the following part blatantly copied from Wikipedia):

Each user has its own local copy of the repository (and effectively, a backup copy)

Allows users to work productively even when not connected to a network

Makes most operations much faster since no network is involved

Allows participation in projects without requiring permissions from project authorities

Allows private work, so users can use their revision control system even for early drafts they do not want to publish

Avoids relying on a single physical machine as a single point of failure


问:
Moving from PHP to Python - framework considerations
As a long time PHP developer, I am now starting to explore the Python world.

I have narrowed the choice of framework down to Django and Pyramid, probably no big surprise there. I have played a bit both both frameworks.

I really like Djangos admin, and the fact that everything is already integrated. My concern with Django, however, is that it appears more difficult to break out of doing things the way that they want you to. For a large complex site, that could be problematic down the road. Is this a valid concern?

What really caught my eye is that the community for Django seems MUCH larger. Let alone the massive number of docs and tutorials for Django (couldnt fine much for Pyramid outside the official docs?). Of biggest concern is the sheer number of apps that have been built specifically for Django: south, tastypie, multi-tenancy, registration, etc. Am I right to assume that these apps are (mostly?) Django specific, and that they cant be used in Pyramid? Where are the Pyramid specific apps? Or, will they interoperate just fine?

答:
The short answer is to learn both. It's always good to have a lot of tools in your tool belt.

The long answer, though, is to learn Django first and then add Pyramid in later.

Your first reaction to the breadth of Django documentation and resources available is the right one. As you're picking up python, you'll find more help for building, deploying, and scaling your Django apps than you will your Pyramid apps. You'll learn how to do pythonic web development and how to use the language to efficiently meet your business requirements.

Lots of large applications use django - Instagram and Disqus come to mind first. So you don't have to worry about how complex a django app can be. Here are the dev blogs for both of those companies:

http://instagram-engineering.tumblr.com/

http://code.disqus.com/

Coming from PHP, you'll find a few things about Django that will be more obvious as well. Take, for example, retrieving POSTed form data:

PHP

```<code>$foo = $_POST['bar']
</code>```

Django Python

```<code>foo = request.POST['bar']
</code>```

Pyramid Python

```<code>foo = request.params['bar']
</code>```

Once you've built a few Django apps and shipped a thing or two, then go and learn Pylons or Flask and add SQLAlchemy to your tool belt as well.

Body:
The short answer is to learn both. It's always good to have a lot of tools in your tool belt.

The long answer, though, is to learn Django first and then add Pyramid in later.

Your first reaction to the breadth of Django documentation and resources available is the right one. As you're picking up python, you'll find more help for building, deploying, and scaling your Django apps than you will your Pyramid apps. You'll learn how to do pythonic web development and how to use the language to efficiently meet your business requirements.

Lots of large applications use django - Instagram and Disqus come to mind first. So you don't have to worry about how complex a django app can be. Here are the dev blogs for both of those companies:

http://instagram-engineering.tumblr.com/

http://code.disqus.com/

Coming from PHP, you'll find a few things about Django that will be more obvious as well. Take, for example, retrieving POSTed form data:

PHP

$foo = $_POST['bar']

Django Python

foo = request.POST['bar']

Pyramid Python

foo = request.params['bar']

Once you've built a few Django apps and shipped a thing or two, then go and learn Pylons or Flask and add SQLAlchemy to your tool belt as well.


问:
De-facto standards for customer information record
I'm currently evaluating a potential new project that involves creating a DB for typical customer information (userid, pwd, first & last name, email, adress, telfnr ...). At this point, requirements are only roughly defined.

The customer DB is expected in the O(millions) of records. In order to calculate some back-of-the-envelope numbers for DB sizing and evaluate potential DB options & architectures, I'm looking for some de-facto standards for these kind of records. In particular, the std size of every field (first name, last name, address,...) or typical avg for a simple customer record would be great info.

With so many e-commerce websites out there, there should be some kind of typical config that can be reused and avoid re-inventing the wheel.

Any ideas?

---- edit ----

The answers seems to be steering towards adopting an standard customer record vs designing your own. I would like to stress that the focus of this question is to locate a reference for field sizing for a customer object, and avoid figuring that out on my own.(I've emphasized that part on the original text -now in bold-)

答:
I would say "You ain't gonna need it (yet)". And with Ron Jeffries: "Always implement things when you actually need them, never when you just foresee that you need them."

So maybe if it is time to add a concrete database to the project you have much more knowledge about the data that will be stored there.


问:
CSRF Protection with codeigniter
I have very little knowledge in application security. I have often seen to protect your application from csrf attacks developers use tokens and pass these tokens with request to validate. I want to know if i just validate the request is coming from my server and rejects all requests coming from any other server how can it be unsafe?</p>

答:
You cannot know where the request is coming from for sure. Sure, you can check the HTTP referer, but that has implications as well.

Many users have set their browsers to not supply the server with the referrer, so you will get rubbish data. If you don't allow empty referrers you will block a lot of legitimate requests. If you allow empty referrers, then all those that have set their browser to not send referrer can be a victim of CSRF.

So rejecting requests based on this will get you nowhere.

Edit: It's called 'HTTP referer', a misspelling of the word referrer.

Title: CSRF Protection with codeigniter


答:
When trying to convince anyone of anything, you always need to try to come at it from their point of view.

Your project manager has a simple goal - completing projects on time and on budget.

If you aren't currently using version control, then your development team is solving the problems that version control solves by hand. All of those problems have been well enumerated by other answers, so I won't get into them here.

What you need to do is explain to your project manager that the team is spending X number of hours every week manually solving the problems that GIT could solve automatically, or in, say, 0.1 * X number of developer hours.

Don't approach it using reasons GIT will make your life easier or the lives of your fellow developers easier, approach it from the perspective that GIT will ship software faster and cheaper.


问:
Where should instantiated classes be stored?
I'm having a bit of a design dilemma here. I'm writing a library that consists of a bunch of template classes that are designed to be used as a base for creating content. For example:

```<code>public class Template
{
    public string Name {get; set;}
    public string Description {get; set;}
    public string Attribute1 {get; set;}
    public string Attribute2 {get; set;}

    public Template()
    {
        //constructor
    }

    public void DoSomething()
    {
        //does something
    }
    ...
}
</code>```

The problem is, not only is the library providing the templates, it will also supply quite a few predefined templates which are instances of these template classes. The question is, where do I put these instances of the templates?

The three solutions I've come up with so far are:

1) Provide serialized instances of the templates as files.

On the one hand, this solution would keep the instances separated from the library itself, which is nice, but it would also potentially add complexity for the user. Even if we provided methods for loading/deserializing the files, they'd still have to deal with a bunch of files, and some kind of config file so the app knows where to look for those files. Plus, creating the template files would probably require a separate app, so if the user wanted to stick with the files method of storing templates, we'd have to provide some kind of app for creating the template files.

Also, this requires external dependencies for testing the templates in the user's code.

2) Add readonly instances to the template class

Example:

```<code>public class Template
{
    public string Name {get; set;}
    public string Description {get; set;}
    public string Attribute1 {get; set;}
    public string Attribute2 {get; set;}

    public Template PredefinedTemplate
    {
        get
        {
            Template templateInstance = new Template();
            templateInstance.Name = "Some Name";
            templateInstance.Description = "A description";
            ...
            return templateInstance;
        }
    }

    public Template()
    {
        //constructor
    }

    public void DoSomething()
    {
        //does something
    }
    ...
}
</code>```

This method would be convenient for users, as they would be able to access the predefined templates in code directly, and would be able to unit test code that used them. The drawback here is that the predefined templates pollute the Template type namespace with a bunch of extra stuff. I suppose I could put the predefined templates in a different namespace to get around this drawback. The only other problem with this approach is that I'd have to basically duplicate all the namespaces in the library in the predefined namespace (e.g. Templates.SubTemplates and Predefined.Templates.SubTemplates) which would be a pain, and would also make refactoring more difficult.

3) Make the templates abstract classes and make the predefined templates inherit from those classes.

For example:

```<code>public abstract class Template
{
    public string Name {get; set;}
    public string Description {get; set;}
    public string Attribute1 {get; set;}
    public string Attribute2 {get; set;}

    public Template()
    {
        //constructor
    }

    public void DoSomething()
    {
        //does something
    }
    ...
}
</code>```

and

```<code>public class PredefinedTemplate : Template
{
    public PredefinedTemplate()
    {
        this.Name = "Some Name";
        this.Description = "A description";
        this.Attribute1 = "Some Value";
        ...
    }
}
</code>```

This solution is pretty similar to #2, but it ends up creating a lot of classes that don't really do anything (none of our predefined templates are currently overriding behavior), and don't have any methods, so I'm not sure how good a practice this is.

Has anyone else had any experience with something like this? Is there a best practice of some kind, or a different/better approach that I haven't thought of? I'm kind of banging my head against a wall trying to figure out the best way to go.

Thanks!

答:
In a roundabout way, it sounds like you're grappling with a special case of the singleton pattern.

There are pros and cons to that pattern, with the primary benefit being that it will answer your immediate need and the primary drawback is that it takes solid governance to keep the singletons from bloating and deviating from their original purpose.  SO and PSE have a number of threads related to the singleton pattern.

You'll end up with multiple singletons following the generic layout you specified in option 3.  I would make them read-only and take advantage of whatever language features you have available for implementing those predefined instances of the templates.

I'd vote for option 3.  It's not quite clear how your end users were intended to use these templates in the first place, but I don't think that knowing the full use case would change my answer.

If you were wanting to use the predefined templates as a means of pre-filling another template that was going to be modified for XYZ reason, then you could have additional constructors within the main template class.

```
public class Template
{
  ...
  public Template( Template predef )
  {
    //Copy in values from predef to this...
  }
}

... someOtherFunc()
{
  Template myTemp = new Template( predefTempFoo.Instance );
}
```

Body:
In a roundabout way, it sounds like you're grappling with a special case of the singleton pattern.

There are pros and cons to that pattern, with the primary benefit being that it will answer your immediate need and the primary drawback is that it takes solid governance to keep the singletons from bloating and deviating from their original purpose.  SO and PSE have a number of threads related to the singleton pattern.

You'll end up with multiple singletons following the generic layout you specified in option 3.  I would make them read-only and take advantage of whatever language features you have available for implementing those predefined instances of the templates.

I'd vote for option 3.  It's not quite clear how your end users were intended to use these templates in the first place, but I don't think that knowing the full use case would change my answer.

If you were wanting to use the predefined templates as a means of pre-filling another template that was going to be modified for XYZ reason, then you could have additional constructors within the main template class.

public class Template
{
  ...
  public Template( Template predef )
  {
    //Copy in values from predef to this...
  }
}

... someOtherFunc()
{
  Template myTemp = new Template( predefTempFoo.Instance );
}


答:
Congrats on getting your first job! And you really made good book choices!

These books are master pieces for every programmer to read at least once.

From my personal experience i would advice to read books interchangeably. It is a fact that you may get tired/bored from one book, and switching to related book will make you re-focus and behind the scene your brain will kick off to process the information. Thus, you may maximum benefit from this process.

Edit: as mentioned in comment, it is a kinda multi-threading solution to add up in efficiency :)

However, don't over-heat yourself. Having more than 3 books might be hard to deal at the same time.


问:
How do I preview my mobile web application on a Windows 7 PC?
I am developing a mobile web application that may be browsed in an iPhone. I would like to test this application, but I lack a mobile web device.

How can I test this mobile application on a Windows 7 PC?

答:
Please disregard this as an answer - I do not see an option for me to comment and I really want to throw in my 1 cent.

Anyway, this is a big issue for me now, too. I am used to developing .NET solutions on my local machine, setting up different sites within IIS 7. I am trying to transition to mobile site development but figuring out how to set up a test environment is becoming a huge obstacle.

I have not yet been able to get an emulator to even browse to any of my localhost sites on my Windows 7 machine. I am wondering if I am going to have to set up a site through my hosting provider for testing purposes only. Obviously this is not an ideal solution, which is why I wanted to chime in on this discussion to see if anyone would be willing to divulge any solutions they have found.


答:
I agree with the answers of "no correct order", but I will offer a different spin...

Start and fully digest Code Complete.  It's the most basic, most comprehensive basis book.  Spend a LOT of time reading and re-reading it.  It should give you the most returns if you're a beginner.


问:
What should be in a coding standard?
What should be in a good (read:useful) coding standard?

Things the code should have.

Things the code shouldn't have.

Should the coding standard include definitions of things the language, compiler, or code formatter enforces?

What about metrics like cyclomatic complexity, lines per file, etc?

答:
Some good old common sense wouldn’t go amiss; there are far too many coding standard documents that labour on irrelevant points (items such as font type and size being one of the more extreme ones I’ve seen).

The best thing to do if you’re in a group of developers is to talk to each other and look at your code, form a consensus on what is acceptable and if you need to write down the main points as guidelines, but keep them as just that guidelines. If you can’t justify any divergence from the guidelines you really should consider why you’re doing it.

At the end of the day clear and understandable code is more important than any rigid rule on layout or typography.

Title: What should be in a coding standard?


问:
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?

答:
In all honesty I do not think that you should lose respect for all degrees and especially not CS because the only language taught is Java. </p>

<p>Any decent comp. sci student understands that his CS degree is nothing more than a piece of paper and that real knowledge will come from personal projects and personal study. I would like to think that the good students know they need to know C and learn how to get things done in Linux / Unix and learn how to NOT have their hand held by modern languages. </p>

Body:
In all honesty I do not think that you should lose respect for all degrees and especially not CS because the only language taught is Java.

Any decent comp. sci student understands that his CS degree is nothing more than a piece of paper and that real knowledge will come from personal projects and personal study. I would like to think that the good students know they need to know C and learn how to get things done in Linux / Unix and learn how to NOT have their hand held by modern languages.


问:
visibility:hidden Vs visibility:collapse
In CSS, what is the difference between visibility:hidden and visibility:collapse

They are given to be separate in W3Schools, but I see no difference in their output.

I have tried it in Google Crome.

答:
hidden means the element is invisible, though the space it takes on the page remains.

collapsed means the element is invisible, AND the space it takes on the page is gone, but it only applies to table elements (otherwise, just like hidden).

See the details on MDN.


问:
What can be done to programming languages to avoid floating point pitfalls?
The misunderstanding of floating point arithmetic and its short-comings is a major cause of surprise and confusion in programming (consider the number of questions on Stack Overflow pertaining to "numbers not adding correctly"). Considering many programmers have yet to understand its implications, it has the potential to introduce many subtle bugs (especially into financial software). What can programming languages do to avoid its pitfalls for those that are unfamiliar with the concepts, while still offering its speed when accuracy is not critical for those that do understand the concepts?

答:
One thing I would like to see would be a recognition that double to float should be regarded as a widening conversion, while float to double is narrowing(*).  That may seem counter-intuitive, but consider what the types actually mean:

0.1f means "13,421,773.5/134,217,728, plus or minus 1/268,435,456 or so".

0.1 really means 3,602,879,701,896,397/36,028,797,018,963,968, plus or minus 1/72,057,594,037,927,936 or so"

If one has a double which holds the best representation of the quantity "one-tenth" and converts it to float, the result will be "13,421,773.5/134,217,728, plus or minus 1/268,435,456 or so", which is a correct description of the value.

By contrast, if one has a float which holds the best representation of the quantity "one-tenth" and converts it to double, the result will be "13,421,773.5/134,217,728, plus or minus 1/72,057,594,037,927,936 or so"--a level of implied accuracy which is wrong by a factor of over 53 million.

Although the IEEE-744 standard requires that floating-point maths be performed as though every floating-point number represents the exact numerical quantity precisely at the center of its range, that should not be taken to imply that floating-point values actually represent those exact numerical quantities.  Rather, the requirement that the values be assumed to be at the center of their ranges stems from three facts: (1) calculations must be performed as though the operands have some particular precise values; (2) consistent and documented assumptions are more helpful than inconsistent or undocumented ones; (3) if one is going to make a consistent assumption, no other consistent assumption is apt to be better than assuming a quantity represents the center of its range.

Incidentally, I remember some 25 years or so ago, someone came up with a numerical package for C which used "range types", each consisting of a pair of 128-bit floats; all calculations would be done in such fashion as to compute the minimum and maximum possible value for each result.  If one performed a big long iterative calculation and came up with a value of [12.53401391134 12.53902812673], one could be confident that while many digits of precision were lost to rounding errors, the result could still be reasonably expressed as 12.54 (and it wasn't really 12.9 or 53.2).  I'm surprised I haven't seen any support for such types in any mainstream languages, especially since they would seem a good fit with math units that can operate on multiple values in parallel.

(*)In practice, it's often helpful to use double-precision values to hold intermediate computations when working with single-precision numbers, so having to use a typecast for all such operations could be annoying.  Languages could help by having a "fuzzy double" type, which would perform computations as double, and could be freely cast to and from single; this would be especially helpful if functions which take parameters of type double and return double could be marked so that they would automatically generate an overload which accepts and returns "fuzzy double" instead.


答:
I've read Pragmatic Programmer and I'm in the process of reading "Code Complete".

From my experience so far, I think that "Pragmatic Programmer" is a great place to start because it gives a high-level view of different coding issues.  I read it over the course of a week; as I read it, I was immediately enlightened of some better ways to solve problems I deal with every day.

"Code Complete" is longer and more exhaustive.


答: A reasons for every requirement.  This way, following the standard doesn't become some sort of cargo cult and people know that it's ok to change the standard if the reason for it no longer applies, or to violate the standard in specific cases where the reason clearly doesn't apply.</p>

Title: What should be in a coding standard?

Body:
What should be in a good (read:useful) coding standard?

Things the code should have.

Things the code shouldn't have.

Should the coding standard include definitions of things the language, compiler, or code formatter enforces?

What about metrics like cyclomatic complexity, lines per file, etc?


问:
Cataloging events, projects and tasks: Is SQL appropriate?
I have this idea for a database: it would hold everything I "need to remember", and allow future coding projects to access the information.  These future projects include a day-planner and historical analysis of what I've been up to.

The things I need to remember break down in to two main categories: Events and Tasks.  Some tasks (like "wash dishes") won't be part of a project, but most will (like "write abstract for AIAA paper").  Both Events and Tasks will always have a category like "Home", "School", "Work", or "Family".

I want to base this on a few SQL tables because I have used SQL before at work, and it was really straightforward and easy to work with.  I also recently became acquainted with it so it is fun and new to me.  For this specific project, I was thinking a big table for the actual entries with foreign keys for their project and category.

My question is this: Is SQL the right choice for this, or am I using a jackhammer to open a screen door?  I am sure that it is possible to do it this way; but I am worried that there might be a more sensible solution out there, and I am certain that the shiny new-ness of SQL is clouding my vision.

Edit after reflecting on comments: A spreadsheet introduces the possibility of errors due to constantly repeating myself instead of referencing predefined entities; furthermore, it sacrifices machine readability to provide a cumbersome GUI.  I accept the notion that SQL would be inappropriate but I do not think a spreadsheet could meet my needs.

Final Edit: I did some more searching around and found a few potential ways to implement this that strike a nice balance between "sensible" and "interesting".  I realized while I was reading y'all's comments that I needed to decide if I wanted to do it the "right" way or the fun way.  And I think I want to do it the fun way.

I did some exploring and found a few solutions that could extend my toolset for future projects without being completely superfluous like SQL.

KirbyBase is a really simple ruby database that seems to be perfect for small, silly projects like this one.

There are also a lot of interesting NoSql options that I intend to do more research on: MongoDB, CouchDB, and neo4j.

I am going to go ahead and select the only answer that answered the question and let this topic sink because most of the commentary (not excluding my own) is too subjective for SE.  Thank you all for the advice!

答: A spreadsheet IMO is the correct tool for this job. I understand the educational endeavor though but you asked for the most sensible solution and IMO a spreadsheet is the most sensible.</p>


答:
I don't see a problem with using Java. The biggest problem (as you mentioned) is when universities teach imperative programming as the best and only way to solve all your problems. This is very far from the truth. For example instead of using three imperative languages (or even worst the same language) for three different courses, they should use three different programming paradigms. An example is Java (imperative), Prolog (declarative), and Haskell (functional).

As for why this happens, I think it's a combination of (1) politics - chairmen are not open minded or have personal benefits/sponsors, and (2) laziness - professors were once students and they teach whatever they know or like.


问:
Is it relevant to warn about truncating real constants to 32 bits?
I'm toying around with LLVM and looking at what it would take to make yet another strongly-typed language, and now that I'm around the syntax, I've noticed that it seems to be a pet peeve of strongly typed language to warn people that their real constants won't fit inside a float:

```<code>// both in Java and C#
float foo = 3.2;
// error: implicitly truncating a double into a float
// or something along these lines
</code>```

Why doesn't this work in Java and C#? I know it's easy to add the f after the 3.2, but is it really doing anything useful? Must I really be that aware that I'm using single-precision reals instead of double-precision reals? Maybe I'm just missing something (which, basically, is why I'm asking).

Note that float foo = [const] is not the same thing as float foo = [double variable], where requiring the cast seems normal to me.

答: One should not warn about truncating floating-point quantities, constant or otherwise, to a 32 float.  Any floating-point quantity has a single correct 32-bit representation.  That representation will not uniquely identify the number, but will--if the original quantity is known precisely--identify a range of values the number is known to be within.  In only one very narrow corner case will a conversion from double to float not yield a result strictly with the +/- 0.5lsb, and in that narrow case, the result will still be within 0.50000001lsb) What compilers should warn about (but alas do not) is casting in the other direction--feeding 32-bit floats into calculations which expect double.  Casting from a double to a float should be considered perfectly fine if the result of the computation will never be converted back into a double.  Conversely, casting from float to double should be considered dubious even when there would be no other basis for a diagnostic.  For example, in the statement double foo = (1.0f / 10.0f); all of the floating-point constants are represented precisely, but the result is off by an amount billions of times larger than what should be expected in a double.  Such an assignment is far more likely to represent a mistake than is e.g. the passing of a double to a drawing routine that expects a float; unfortunately, languages seem to regard the latter as worthy of a diagnostic and the former not.


问:
Allow app analytics opt-out?
Given that mobile app analytics reporting can cost a customer data traffic that, unlike a web app, use of the mobile app may otherwise not require, should a mobile app provide a user accessible setting to allow customers to opt out of app analytics collection or reporting?

If and where should a customer be notified that running a given mobile app might capture and transmit analytics data on the app's usage?

Are there any app stores where either of the above is a requirement?

答:
Allowing a user to configure whether background processes like that run is a good idea for user friendliness, or even default to only do this while connected to WiFi. Not only for allowing users to save data usage, but battery life as well.

I believe that listing that an app runs analytics is required to be listed with the other requirements for running the app, though it may be possible to simply list internet access as a general requirement.

I don't think its required to have an app do anything like this, but at least for android users are required to hit an accept button on a list of features the app requires, so there is a notice that an app may do X.

Title: Allow app analytics opt-out?


问:
Are Persistence-Ignorant objects able to implement lazy loading?
Persistence Ignorance is an application of single responsibility principle, which in practice means that Domain Objects (DO) shouldn't contain code related to persistence, instead they should only contain domain logic.

a) I assume this means that the code which contacts lower layers ( ie persistence layers ) lives outside of the domain model in other classes ( OC ) of a business logic layer?

b) If my assumption under a) is correct, then DO, say Customer, never contains methods such as GetCustomers or GetCustomerByID?

c) If my assumptions under a) and b) are correct, and assuming Customer domain object uses lazy loading for some of its properties, then at some point Customer's  internal logic must contact OC, which in turn retrieves deffered data. But if Customer needs to contact OC to receive deffered data, then we can't really claim that Domain Objects don't contain logic related to persistence?!

Thank you

REPLYING TO jkohlhepp

1) I assume OrderProvider and CustomerProvider classes are contained within business logic layer?

2) I gather from your reply that  my assumptions under b) are correct?

3)

... I would check to see if some private orders field was populated or
  if it was null. If it is null ...

But  as far as I can tell, as soon as domain code needs to check whether private order field was populated, and if it isn't,contacting OrderProvider, we are already violating PI principle?!

答: You just have some wireup class that populates the domain objects (say, something called "repository").  You can implement lazy loading or whatever kind of cache coherence scheme you want and the domain objects are none the wiser.  You're separating the responsibility of populating domain objects from being domain objects.</p>


答:
I believe you are correct in your assumptions A and B around persistence ignorance.

How you would best accomplish lazy loading of database objects is greatly dependent on your particular problem and implementation.  However, I will attempt a generic answer to how to do lazy loading while still maintaining separation of concerns between persistence and domain logic classes.

I tend to implement persistence ignorance using the following classes:

Domain classes - e.g. Customer

Provider / repository classes - e.g. CustomerProvider

Generic database querying classes - e.g. DatabaseQuery

The DatabaseQuery class would be responsible for using the database driver to query the database and assemble the resulting data into a generic result set such as a DataTable.  The CustomerProvider would be responsible for using the DatabaseQuery class to execute SQL against the database and use the results of that SQL to assemble Customer instances.  Customer would be "pure" domain object that contained data and logic related to customers.

As for whether the provider classes should be in the business tier or the data tier, I don't have a strong opinion.  I can see a case for both.  The important part is that you separate the responsibilities across classes.

So now let's discuss lazy loading.  Let's say I wanted Customer to have a collection of Orders, but I don't want to pull Orders out of the database unless the consumer tries to access them.  I would create a property on Customer called Orders.  In the getter of that property, I would check to see if some private orders field was populated or if it was null.  If it is null, load the orders from the database using an OrderProvider.  Otherwise, just return the collection that was already loaded.

In my opinion, the need for Customer to contact OrderProvider does not violate PI.  Customer still doesn't know how it gets orders.  It just knows that it gets them from OrderProvider.  There might be other reasons to decouple Customer from OrderProvider, but I don't think PI is a problem here.

This assumes that you are doing persistence ignorance manually.  If you are a using an ORM framework such as Entity Framework or Hibernate, then those frameworks generally have features for supporting lazy loading automagically.

Title: Are Persistence-Ignorant objects able to implement lazy loading?

Body:
Persistence Ignorance is an application of single responsibility principle, which in practice means that Domain Objects (DO) shouldn't contain code related to persistence, instead they should only contain domain logic.

a) I assume this means that the code which contacts lower layers ( ie persistence layers ) lives outside of the domain model in other classes ( OC ) of a business logic layer?

b) If my assumption under a) is correct, then DO, say Customer, never contains methods such as GetCustomers or GetCustomerByID?

c) If my assumptions under a) and b) are correct, and assuming Customer domain object uses lazy loading for some of its properties, then at some point Customer's  internal logic must contact OC, which in turn retrieves deffered data. But if Customer needs to contact OC to receive deffered data, then we can't really claim that Domain Objects don't contain logic related to persistence?!

Thank you

REPLYING TO jkohlhepp

1) I assume OrderProvider and CustomerProvider classes are contained within business logic layer?

2) I gather from your reply that  my assumptions under b) are correct?

3)

... I would check to see if some private orders field was populated or
  if it was null. If it is null ...

But  as far as I can tell, as soon as domain code needs to check whether private order field was populated, and if it isn't,contacting OrderProvider, we are already violating PI principle?!


问:
How is the JVM and Java's WORA different from other high level languages?
In the Java world, we often talk about the JVM, and when Java was new it had the supposedly killer feature of "Write Once, Run Anywhere."

From the way people talk and write, this seems different from the way that Python, for example, works.  Yet I've not been aware of any way that Python code that I've written would work differently on another machine.  (Though I haven't written that much Python.)

So what am I missing?  How is the JVM different from a Python interpreter?  Is there a way that Python lacks Java's platform independence?  Or is this just a cultural difference?

答:
Does Python have a platform independent GUI?

Anyway, the WORA feature was - again - to lure C programmers over, as C tended to model the underlying platform closely, and as platforms were different (size of word?  endianess?) creating fully portable C programs required great care and attention.

The Java promise was that all this tediousness did not have to be done, as the platform is very well defined and you KNOW that a char is 16 bit etc.   Also the GUI is written in Java and also 100% portable, which means that your program can run on a computer you've never heard of and even run correctly.


问:
Composition vs. Inheritance
Here's what is given:

```<code>public interface Request {}

// there are 20 subclasses of Request
public class CreateUserRequest implements Request {
  @NotEmpty
  public String userName;
}

// request processor is a thing that aimed to process requests
public interface RequestProcessor<TRequest extends Request> {
  boolean processRequest(TRequest request);
}

public class ServiceFacade {
  // 20 processors like this one
  private final RequestProcessor<CreateUserRequest> createUserRequestProcessor;

  public ServiceFacade(
    RequestProcessor<CreateUserRequest> createUserRequestProcessor) {
    this.createUserRequestProcessor = createUserRequestProcessor;
  }

  // 20 methods like this one
  public boolean createUser(CreateUserRequest request) {
    createUserRequestProcessor.processRequest(request);
  }
}
</code>```

An object implementing RequestProcessor<T> is aimed to process requests of type T. Moreover, it is responsible for handling all the related errors (like invalid request, DB access failure and so forth). So, the workflow for CreateUserRequest should look like this:

```<code>request
validate/throw
make sure user doesn't exist yet/throw
create user
</code>```

As usual, other types of requests may require more steps to be performed.

As an illustration: in case of AddUserAsFriendRequest we'll have to check that both users exist and that friend candidate has allowed others to add him as friend. Oh, and also, if one user adds more than 10 friends in a day, he's then limited to 1 friend per 2 hours for the rest of the day.

The question is, which hierarchy/structure/approach should I use in order to be able to extend this functionality in both "number of request types" and "request process workflow".

There are only 2 approaches I see.

Inheritance

```<code>public abstract class ValidatingRequestProcessor<TRequest extends Request>
implements RequestProcessor<TRequest> {
  protected final Validator validator;

  public ValidatingRequestProcessor(Validator validator) {
    this.validator = validator;
  }

  public boolean processRequest(TRequest request) {
    Set<ConstraintViolation<TRequest>> violations =
      validator.validate(request);
    if(!violations.isEmpty()) {
      return false;
    }

    return processValidatedRequest(request);
  }

  protected abstract boolean processValidatedRequest(TRequest request);
}

public class CreateUserValidatingRequestProcessor
extends ValidatingRequestProcessor<CreateUserRequest> {
  public CreateUserValidatingRequestProcessor(Validator validator) {
    super(validator);
  }

  protected boolean processValidatedRequest(TRequest request) {
    // request is valid, so I can try to create user here
  }
}
</code>```

and so forth here. In case of N "logical steps", I'm going to have (N-1) nested extends and N classes:

```<code>class A implements RequestProcessor {}
class B extends A {}
class C extends B {}
class D extends C {}
...
class Z extends Y {}

RequestProcessor requestProcessor = new Z(); // TADA!
</code>```

Composition

```<code>public class ChainingRequestProcessor<TRequest extends Request>
implements RequestProcessor<TRequest> {
  private final RequestProcessor<TRequest> processorA;
  private final RequestProcessor<TRequest> processorB;

  public ChainingRequestProcessor(
    RequestProcessor<TRequest> processorA,
    RequestProcessor<TRequest> processorB) {
    this.processorA = processorA;
    this.processorB = processorB;
  }

  public boolean processRequest(TRequest request) {
    return processorA.processRequest(request) &&
      processorB.processRequest(request);
  }
}

public RequestValidatorProcessor<TRequest extends Request>
implements RequestProcessor<TRequest> {
  private final Validator validator;

  public RequestValidatorProcessor(Validator validator) {
    this.validator = validator;
  }

  public boolean processRequest(TRequest request) {
    return !validator.validate(request).isEmpty();
  }
}

public CreateUserProcessor
implements RequestProcessor<CreateUserRequest> {
  public boolean processRequest(CreateUserRequest request) {
    // not sure whether request is valid or not
    // can try to create user here
  }
}
</code>```

and so forth. In case of N "logical steps" I'm just going to have N classes. So:

```<code>class A implements RequestProcessor {}
class B implements RequestProcessor {}
class C implements RequestProcessor {}
class D implements RequestProcessor {}
...
class Z implements RequestProcessor {}

// just guess
RequestProcessor requestProcessor = new A(new B(), new C(new D())); // TADA!
</code>```

Which approach is better for this task? Better means:

Easier to modify logic

Easier to add logic

Easier to test

答:
Based on your example, I would definitely go for composition over inheritance.  It would be much easier to rearrange the order in which the processors are executed using composition, thus giving you the logic modifiability.  As far as adding logic, you could easily implement a new RequestProcessor and inject it anywhere in the processor chain that you would like without have to untangle a deep inheritance tree.  For testing, it will be a lot easier to isolate a single processor for testing when it does not extend a bunch of other processors.

If you are going to use composition, I would not recommend having processors take other processors in their constructors.  This level of coupling can probably be avoided.  Instead, have a collection of processors and just loop through the processors to process the request.  If one processor needs data from another processor to do its job, represent this with a state bag dictionary or a context object.  Avoiding coupling different processors together will also improve testability.

Title: Composition vs. Inheritance


问:
How can I create a software patcher for OS X?
I'm building some software for OS X that isn't distributed through the Mac App Store. My software allows users to download different modules uploaded by various people too.

How can I create a software patcher to patch my software, as well as update modules that users might be uploading when necessary? I've looked a bit into diff and patch, which come with OS X but they seem to be largely for plaintext.

Any ideas? I've been googling but I'm a bit stumped which is surprising since software patching seems to be in most applications.

答:
The bsdiff utility should come with OSX.  If that can't work for you, there are other binary diff tools.

However, with the advent of high bandwidth connections, the practice of distributing binary patches is becoming much less common.  You can just as easily distribute a complete updated version of your program if need be..

FURTHER: A [good] module system should not require you to patch your program whenever someone wants to download and install another user's module.  I suggest a system where this is not the case.  For example, have your program scan a plugins directory and load any valid plugin files found.


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

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

If so, what did their code look like?

答: I work for a software editor in France. Code is always in English. The variables and function names are all in English even if mistakes occur sometimes. The worst mix of French and English I encountered was "connexionKey". On the other hand, comments are not always in English depending on how confortable the developer is writing English.</p>


问:
PHP - Internal APIs/Libraries - What makes sense?
I've been having a discussion lately with some colleagues about the best way to approach a new project, and thought it'd be interesting to get some external thoughts thrown into the mix.

Basically, we're redeveloping a fairly large site (written in PHP) and have differing opinions on how the platform should be setup.

Requirements:

The platform will need to support multiple internal websites, as well as external (non-PHP) projects which at the moment consist of a mobile app and a toolbar. We have no plans/need in the foreseeable future to open up an API externally (for use in products other than our own).

My opinion:

We should have a library of well documented native model classes which can be shared between projects. These models will represent everything in our database and can take advantage of object orientated features such as inheritance, traits, magic methods, etc. etc. As well as employing ORM.

We can then add an API layer on top of these models which can basically accept requests and route them to the appropriate methods, translating the response so that it can be used platform independently. This routing for each method can be setup as and when it's required.

Their opinion:

We should have a single HTTP API which is used by all projects (internal PHP ones or otherwise).

My thoughts:

To me, there are a number of issues with using the sole HTTP API approach:

It will be very expensive performance wise. One page request will result in several additional http requests (which although local, are still ones that Apache will need to handle).

You'll lose all of the best features PHP has for OO development. From simple inheritance, to employing the likes of ORM which can save you writing a lot of code.

For internal projects, the actual process makes me cringe. To get a users name, for example, a request would go out of our box, over the LAN, back in, then run through a script which calls a method, JSON encodes the output and feeds that back. That would then need to be JSON decoded, and be presented as an array ready to use.

Working with arrays, as appose to objects, makes me sad in a modern PHP framework.

Their thoughts (and my responses):

Having one method of doing thing keeps things simple. - You'd only do things differently if you were using a different language anyway.

It will become robust. - Seeing as the API will run off the library of models, I think my option would be just as robust.

What do you think?

I'd be really interested to hear the thoughts of others on this, especially as opinions on both sides are not founded on any past experience.

答:
Your approach looks like the way to go. A single HTTP API isn't that simple if you need to be making http requests all the time.

Features like "good documentation" and ORM will be a necessity when the project becomes larger.


问:
Is it recommended to use DocBlock even if I'm not using phpDocumentor?
I'm developing a simple website for a client.

I have read about phpDocumentor and DocBlocks, and I thought that documenting my classes and functions will be very useful.

I'm almost sure I will not generate any documentation for the site, since it's a pretty simple website, and guess what? It doesn't have an API...

But is it still recommended to write DocBlocks in my code? From what I know many programmers even don't write simple comments, but DocBlocks.

I'm not going to generate any readable documentation by the client/ next programmer but I still think that making some comments that are more than just simple text will be better.

edit - If you think that DocBlocks are redundant in my case, are there any other "standards" for writing comments / documentation?

The last time everything that doesn't have a standard makes me feel stupid, that I'm not sure if it's better to write if(){ or if () {, /* */ or //, etc.

I'm new to the documentor and DockBlocks, and I'm still not sure if I have to write this question here or in StackOverflow. Thank you very much anyway!

答:
It is useful to document similar stuff in a similar way. This makes it easy to read the code as you can grasp the important things easily. Using an established standard as a foundation is useful as new team members will quickly get used to the scheme. phpdocumentor format is based on JavaDoc. The same form is sometimes used in other languages, too. Therefore even developers not familiar with PHP are more like to understand and use it quickly.

Additionally tools like IDEs support the format. And can derive information for some help from it.

If you should be strict in using it is a different question. You might use just little parts of it and modify others to your needs. Just like with any other tool ;-)


问:
FizzBuzz - really?
When it comes to "interview test" questions, the subject of FizzBuzz often comes up. There is also a Coding Horror post about it.

Now, if you bother reading sites such as this, you are probably less likely to be in the demographic of programmers who would find FizzBuzz anything but trivial.

But is it really true that 99% of programmers will struggle with it?

Really?

What is the evidence to back this up?

Some real-life examples would be very helpful in answering this question.

答: Unfortunately, many people with impressively looking resumes do seem to lack basic programming skills.  I have seen many cases when people who list C and C++ on their resumes could not answer basic questions about pointers.</p>

Title: FizzBuzz - really?


答: I think a database is a good idea for any project that requires automated use of existing stored data. SQL as a language is easy to use as you have experienced and once you are are comfortable using it, then interaction with your stored data will be straight forward. I'd say work hard and set your database up to your needs. Then write some queries and automate your life by displaying your daily tasks and task history. It's simply endless as to what you can do when an idea meets passion.</p>

Title: Cataloging events, projects and tasks: Is SQL appropriate?

Body:
I have this idea for a database: it would hold everything I "need to remember", and allow future coding projects to access the information.  These future projects include a day-planner and historical analysis of what I've been up to.

The things I need to remember break down in to two main categories: Events and Tasks.  Some tasks (like "wash dishes") won't be part of a project, but most will (like "write abstract for AIAA paper").  Both Events and Tasks will always have a category like "Home", "School", "Work", or "Family".

I want to base this on a few SQL tables because I have used SQL before at work, and it was really straightforward and easy to work with.  I also recently became acquainted with it so it is fun and new to me.  For this specific project, I was thinking a big table for the actual entries with foreign keys for their project and category.

My question is this: Is SQL the right choice for this, or am I using a jackhammer to open a screen door?  I am sure that it is possible to do it this way; but I am worried that there might be a more sensible solution out there, and I am certain that the shiny new-ness of SQL is clouding my vision.

Edit after reflecting on comments: A spreadsheet introduces the possibility of errors due to constantly repeating myself instead of referencing predefined entities; furthermore, it sacrifices machine readability to provide a cumbersome GUI.  I accept the notion that SQL would be inappropriate but I do not think a spreadsheet could meet my needs.

Final Edit: I did some more searching around and found a few potential ways to implement this that strike a nice balance between "sensible" and "interesting".  I realized while I was reading y'all's comments that I needed to decide if I wanted to do it the "right" way or the fun way.  And I think I want to do it the fun way.

I did some exploring and found a few solutions that could extend my toolset for future projects without being completely superfluous like SQL.

KirbyBase is a really simple ruby database that seems to be perfect for small, silly projects like this one.

There are also a lot of interesting NoSql options that I intend to do more research on: MongoDB, CouchDB, and neo4j.

I am going to go ahead and select the only answer that answered the question and let this topic sink because most of the commentary (not excluding my own) is too subjective for SE.  Thank you all for the advice!


答:
One thing languages could do--remove the equality comparison from floating point types other than a direct comparison to the NAN values.

Equality testing would only exist is as function call that took the two values and a delta, or for languages like C# that allow types to have methods an EqualsTo that takes the other value and the delta.

Title: What can be done to programming languages to avoid floating point pitfalls?

Body: The misunderstanding of floating point arithmetic and its short-comings is a major cause of surprise and confusion in programming (consider the number of questions on Stack Overflow pertaining to "numbers not adding correctly"). Considering many programmers have yet to understand its implications, it has the potential to introduce many subtle bugs (especially into financial software). What can programming languages do to avoid its pitfalls for those that are unfamiliar with the concepts, while still offering its speed when accuracy is not critical for those that do understand the concepts?


答:
At my previous jobs we didn't use DocBlocks for PHP if the code was not an API and was not going to be used to generate documentation. Here was our philosophy on comments:

Use /**/ only for formal documentation at the top of the script that includes the author, date, brief description, etc. Use // for all other comments.

We noticed that comments can get out-dated and turn into lies about the code. We instead would try to write "self-illuminating" code by choosing function/class names that better reflect their purpose/function. We would also re-factor complex functions into simpler functions that "do one thing" instead of writing large functions that had a short novel comment above it to try and describe what it did.

The only benefit I can see that we were missing is labeling the function arguments on what data type they expecting and what data type the return value is. But then again, PHP is a loosely typed language where the DocBlocks could betray you (best to just use === and !== and is_*() functions if you really need to look at data types).

Title: Is it recommended to use DocBlock even if I'm not using phpDocumentor?

Body:
I'm developing a simple website for a client.

I have read about phpDocumentor and DocBlocks, and I thought that documenting my classes and functions will be very useful.

I'm almost sure I will not generate any documentation for the site, since it's a pretty simple website, and guess what? It doesn't have an API...

But is it still recommended to write DocBlocks in my code? From what I know many programmers even don't write simple comments, but DocBlocks.

I'm not going to generate any readable documentation by the client/ next programmer but I still think that making some comments that are more than just simple text will be better.

edit - If you think that DocBlocks are redundant in my case, are there any other "standards" for writing comments / documentation?

The last time everything that doesn't have a standard makes me feel stupid, that I'm not sure if it's better to write if(){ or if () {, /* */ or //, etc.

I'm new to the documentor and DockBlocks, and I'm still not sure if I have to write this question here or in StackOverflow. Thank you very much anyway!


问:
Is this an assembly language?
In my childhood I used to program on an MK-61 Soviet calculator. It had four operating registers (X, Y, Z, T) and 15 storage registers. A program could have 105 steps.

As I recall it, it had commands like:

Swap X and Y registers

Shift registers (Z to T, Y to Z, X to Y)

Copy from storage register (1..15) to X

Copy from X to storage register (1..15)

If X < 0 then go to program step ##

Perform operation (+, -, *, /) using X and Y values and put result to X

Is this command set an assembly language? Did I have a basic idea of assembly languages by using this device?

It turns out it is something called "keystroke programming".

Funny fact: a similar calculator (like this one, but with energy independent memory) was used as a back-up hardware for space mission trajectory calculations in 1988. :-)

答:
Yes, that definitely sounds like an assembly language to me.

It's hard to say whether or not that actually is assembly just from the description, because the definition--a language whose commands map 1:1 with its target platform's machine code--is hard to determine without a knowledge of the machine code itself, but that does sound like the way ASM works on other platforms.

Title: Is this an assembly language?


答:
Coding Standards help a little when you are writing the code the first time, they help a lot  when you, or your replacement, has to update the code 2 years later.

The ideal standard leads to code where you can jump to any arbitrary page in the code, and understand excactly what it is doing on the first read-through, because

the names clearly describe what data is being manipulated,

the braces make the flow of control clear,

the comments explain any non-obvious algorithm, etc.

On the other hand, too many arbitrary standards can disrupt the flow of writing code. So I believe that every item in a proposed coding convention should be evaluated against these 2 criteria:

Does this rule help ensure that the code is Correct?

Does this rule help ensure that the code is Clear?

If neither is true, the item is just arbitrary, and probably unnecessary

I would include the following things in a standard I write:

For Clarity:

File Organization:   Specifying a fixed order for the items in a file lets the team easily navigate others files.   You shouldn't have to hunt to find #defines, or structure definitions.

Naming conventions:  Consistent naming aids readability.  But avoid over-specifying too many rules, that harms writeability.

Code Structure.  Curly Brace placement, indentation levels, spaces vs tabs, etc.   Yes, this can be a strong personal preference, but the goal is clear code.  Find the best option for the team, and stick with it.

For Correctness:

Best Practices specific to your problem type:   Rules about memory allocation, or concurrency, or portability.

"Const Correctnesss", proper use of static and volatile, etc.

Rules about preprocessor macros, and other easily abused features of the language.

Title: What should be in a coding standard?


答:
That is right, posted code fragment does look like assembly language.
The proper conversion of this code would define the version.

Edit: it has some specific language for this device, but it is not assembly.

It is also look like a USSR made calculator.
Does it run on rounded batteries/cord?

Title: Is this an assembly language?

Body:
In my childhood I used to program on an MK-61 Soviet calculator. It had four operating registers (X, Y, Z, T) and 15 storage registers. A program could have 105 steps.

As I recall it, it had commands like:

Swap X and Y registers

Shift registers (Z to T, Y to Z, X to Y)

Copy from storage register (1..15) to X

Copy from X to storage register (1..15)

If X < 0 then go to program step ##

Perform operation (+, -, *, /) using X and Y values and put result to X

Is this command set an assembly language? Did I have a basic idea of assembly languages by using this device?

It turns out it is something called "keystroke programming".

Funny fact: a similar calculator (like this one, but with energy independent memory) was used as a back-up hardware for space mission trajectory calculations in 1988. :-)


问:
Which is the correct licence?
So I found this very interesting library in Google Code site. It turns out it is advertised as "LGPL", which is good enough for me. However, in the README file of the library the author contradicts himself saying it is not available for commercial purposes.

I'm guessing that when you sign up to create your project in Google Code you can only choose open source licenses. Open source licenses allow selling software, offering commercial support, etc. So my guess is that either the author confused the word "commercial" with "proprietary", or that he just wanted a good place to host his software even violating GoogleCode standards...

The thing is, if I want to use the library, which licence should I consider the software to be under? I've already asked the author by email but he has not replied.

Thanks very much.

答:
Answer: have a legal question? well, ask to a lawyer. Seriously!

Call a reputable lawyer, don't trust information/advice/speculation from a website.

If you serious in using this code for commercial purposes, better to get a paid consultation. Otherwise, you may risk the future of your product as well the company. Law suits are serious matters.

Title: Which is the correct licence?


答:
IANAL

Well, it's a risk you shouldn't take: he's agreed once to license the code under LGPL, so him relicensing his code might be a violation of his agreement with Google, not with you.

Which in turn means, you probably can't do a lot. You can contact him and request more information (in multiple channels, if you have to) and, if he tries to tell you that the code is not LGPL, you could report this project to Google.

I don't really think this would help much. If it's not an honest mistake he's made, he will probably pull his code off Google Code and publish it somewhere else, while you're left with a bad aftertaste.

Another thing - he might not be ignoring you, his email server might just be throwing your mails to SPAM/Trash and he could be totally oblivious about it. So you might try to repeat or use a different communication channel (IRC is common for open-source), if there's a PM function in Google Code, try this as well, etc.

Bottom point: You can't rely on using his code under LGPL, unless you get a good confirmation from him that the license is indeed LGPL.

Also, make sure to talk to a lawyer about this stuff - don't trust some strangers, potentially half a world away, in an entirely different jurisdiction to give you advice on these topics. Heck, even professional lawyers sometimes have difficulties answering FOSS licensing questions... If answers in this site had tags, IANAL would have been the top one.

Title: Which is the correct licence?

Body:
So I found this very interesting library in Google Code site. It turns out it is advertised as "LGPL", which is good enough for me. However, in the README file of the library the author contradicts himself saying it is not available for commercial purposes.

I'm guessing that when you sign up to create your project in Google Code you can only choose open source licenses. Open source licenses allow selling software, offering commercial support, etc. So my guess is that either the author confused the word "commercial" with "proprietary", or that he just wanted a good place to host his software even violating GoogleCode standards...

The thing is, if I want to use the library, which licence should I consider the software to be under? I've already asked the author by email but he has not replied.

Thanks very much.


问:
Alternative to XML / XSLT for artifact generation?

The scenario:

A system needs to produce a variety of artifacts to present to end-users during the normal course of business.  Examples of these artifacts would be permits, invoices, or receipts -- imagine any online app that gives you one of those "print this page for your records" pages.  I'm working on a system that produces artifacts like this, but we're expected to be able to recall a previously-generated artifact and present it again when it's needed.

Currently, the system retains transactional data and recreates the "artifact" page as needed from that online data.  This presents a number of problems:

More data is needed during transactional processing than is used in artifact generation.  Once the transaction is complete, though, we're unable to archive the transactional data because it may be needed to reproduce the artifact at some point in the future.

Artifact generation is slightly more expensive than it needs to be, because each time we pull up one of these artifacts, we're re-generating it.  Frankly, this isn't a huge deal in practice, but it bugs me.

If we ever change the way a specific artifact is generated, an old artifact will be "upgraded" if it's reproduced.  Although this seems like a virtue, I maintain that since the whole objective is to show the artifact as it was originally generated, this is a detriment.

The two most reasonable design fixes that leap to mind are PDF generation and XML / XSLT.  I'm not very excited about the PDF option because I really don't think I need to store the static portions of each artifact over and over again.

The XML / XSLT option still seems to have merit.  In this approach, I'd need to assemble an XML document for each artifact containing only the data needed for that artifact plus a reference to the proper XSLT document.  New versions of the artifact would be deployed with a new XSLT, such that old XML uses old XSLT, and new XML uses new XSLT, and so on.

The question:

Is there another killer design or technology I'm missing that would fit this need?  This is a .Net system, for what it's worth.

答:
You could store whatever data you planned to store in XML in your database, in tables solely for that purpose.  This is no more redundant than database+XML.  It also allows you the option of having some of your data exactly as it was at the time and some up to date, if you ever decide to do so.

It also means generating from transactional data is more similar to generating from historical data than if it were in XML - potentially the report generator can just use one stored procedure instead of another and keep the rest the same.  You might still need to associate the data with a report version.

So, to answer your specific question: Yes.  A relational database.


答:
It certainly has some close similarities to an assembly language, but I'm going to argue that that's not what it really is.

In an assembly language, the operations mostly map 1-to-1 to CPU instructions. There are some exceptions, such as macros and pseudo-ops (like, say, a CLEAR instruction that really XORs a register with itself); the real point is that an assembly program exactly determines the CPU instructions to be generated. (That's the fundamental difference between an assembly language and a higher-level language like C; in the latter, programs specify behavior).

The calculator undoubtedly has a CPU in it, but I doubt that individual CPU instructions refer to the X, Y, Z, and T "registers", or perform high-level operations like xy or sin (or ПРГ, whatever that means!).

Instead, I'm sure that many or most of the visible operations are done as subroutine calls. And for each operation executed, there must be a significant amount of extra work done to display the result.

You can think of the visible operations as an assembly language for a high-level virtual machine, but that virtual machine is implemented via something like an interpreter running on the real CPU.

Still, I'd say that the answer to the second part of your question:

Did I have a basic idea of assembly languages using this device?

is yes.

Title: Is this an assembly language?


问:
How common is meta-programming?
How often do you or have you seen meta-programming be used in projects? In uni I've never seen this be applied, but I've seen this on my previous job (when I saw it I was blown away of how effective it was).

But how common is it? Is it used all the time, or just occasionally?

答:
It tends to show up commonly and consistently in Common Lisp projects. Check out OnLisp and Let Over Lambda for some explanation/insight.

If you're just after examples (and know CL), check out the Antiweb repository; there's a good deal of meta-programming going on under the covers.

Title: How common is meta-programming?