问:
How can I get into "programmer mind" more quickly and more often?
There's a workflow I'm working on. It's so far been web forms filling databases with occasional writing configuration scripts for analysis instruments instruments, and I've written it all, in Perl, Javascript, HTML, Javascript, MySQL.

And right now, the task in front of me is generating a post-instrument analysis Bash script. Or, rather, a Perl-written post-instrument analysis script generator. And it is taking forever.

I have had this as the front-burner task for a while now, and progress has been horribly, embarrassingly slow. In fact, last Friday, I sat, looking at the screen, trying to find my way into the next step of the project, and the first sign of ... inspiration? Of capability? Of knowing and attacking any aspect of the task and being able to code it? Well, it started at 4:30pm, and I rode it until 8:20.

I am looking for and hoping for ideas and techniques to get into that mental space consistently and on my schedule. Any pointers?

答:
Flow is the ultimate answer.  To do that, you need clear objectives.  That encapsulates some of the items others have mentioned.  Sometimes, the route to those objectives isn't so clear, so you need some kind of "mental refresh."

Many people who code for a living also juggle.  I'm not talking about juggling a long task list, I'm talking about juggling objects.  The thing about juggling is that it doesn't require significant cognitive abilities but it DOES require focus and full attention.  If you can pull your mind completely off the task which is bothering you and COMPLETELY FOCUS on something else, you frequently get a "Eureka!" moment and then you can get back to coding.

I don't have the coordination to juggle.  I get on a treadmill, in front of a window, put some white noise in my earbuds, put my e-reader in front of me and walk for about 30 minutes.  The physical exertion (not intense, but steady) gets the "juices flowing."  Others have suggested a walk around the building.  The weather, around here, gets downright nasty; the treadmill is usable, regardless of what the weather is like.  The e-reader, with an engaging book, is usually enough to mentally distract me.  Natural light, especially during the day, helps clear the mind (fluorescent lights tend to do the opposite).

After that, I'm usually mentally refreshed enough that I can tackle whatever problem was bothering me.  And I stand a better chance of finding clear objectives and a path to them, inproving the odds of hitting a "flow" state.


答: I like to perform a TDD Kata (Some Katas) that help me solve a simple problem and perform some deliberate practice. I use this as a warm up or as a distraction if I am solving a particularly frustrating problem.</p>

ContentLicense: CC BY-SA 3.0

Title: How can I get into "programmer mind" more quickly and more often?

Body:
There's a workflow I'm working on. It's so far been web forms filling databases with occasional writing configuration scripts for analysis instruments instruments, and I've written it all, in Perl, Javascript, HTML, Javascript, MySQL.

And right now, the task in front of me is generating a post-instrument analysis Bash script. Or, rather, a Perl-written post-instrument analysis script generator. And it is taking forever.

I have had this as the front-burner task for a while now, and progress has been horribly, embarrassingly slow. In fact, last Friday, I sat, looking at the screen, trying to find my way into the next step of the project, and the first sign of ... inspiration? Of capability? Of knowing and attacking any aspect of the task and being able to code it? Well, it started at 4:30pm, and I rode it until 8:20.

I am looking for and hoping for ideas and techniques to get into that mental space consistently and on my schedule. Any pointers?


问:
What to do when somebody forks my open-source project with the same name?
I have this GPL project, it got stuck for like a year, I really like the idea, then somebody fork it and changed the whole thing but used the same name, I don't mind for the code (it was GPL after all) but I like the name. What's the etiquette for this kind of situation?

The project will benefit myself, and I like it, however the name wasn't for sale..

EDIT:
I know if I contact the author he'll understand and change the name, but I have no time to work on that project right now, so I don't want to be a "name troll" for my folks (small community), so I'll let it be this time, my question is more about the etiquette of forking. If the project is apparently abandoned can they fork and use the same name or they MUST get a new name?

答:
This is exactly the reason why many large open source projects register their project name as a trademark.

This still allows anyone to use their code for an own project, but not under the same name. The Mozilla foundation, for example, has a trademark on "Firefox". That's why Debian ships with a browser called "Iceweasel" which is essentially Firefox.


答:
The most effective way of protecting the name of your project is to register it as a trademark (and make clear in all documentation that the project name is a registered trademark), because then people are required to get your permission before re-using the name.

If you license your project under GPLv3, then you could also add the name-change as additional condition to your copyright license, but I am not sure how effective that really is (ask a lawyer if you want to be sure).

But both of these options only work if you apply them before the name re-use takes place. If you have not taken preventive measures, the only option is to ask the maintainer of the other software nicely.

As for the ethics, if it can be seen as a continuation of an (apparently) abandoned project, then I see no reason to use a different name, but it would be a good gesture to try to contact the previous maintainer to ask if they really abandoned the project.

Title: What to do when somebody forks my open-source project with the same name?

Body:
I have this GPL project, it got stuck for like a year, I really like the idea, then somebody fork it and changed the whole thing but used the same name, I don't mind for the code (it was GPL after all) but I like the name. What's the etiquette for this kind of situation?

The project will benefit myself, and I like it, however the name wasn't for sale..

EDIT:
I know if I contact the author he'll understand and change the name, but I have no time to work on that project right now, so I don't want to be a "name troll" for my folks (small community), so I'll let it be this time, my question is more about the etiquette of forking. If the project is apparently abandoned can they fork and use the same name or they MUST get a new name?


问:
articles in variable names and hard-coding strings
re-edited by author: no this is not 2 questions. This is one question about code review questions containing two separate points. Please do not edit my question.

For naming variables, the two sides are regarding using articles (a, an, the) in the variable name (e.g. theBook vs. book -or- parseTheString vs. parseString).

For hard-coding strings, the three sides are whether to put all strings into constants (public static final) in a separate file (class or interface), put them all in the same file (private static final), or don't use constants for strings at all. (e.g. new Button("Click Me")  vs.  new Button(BUTTON_LABEL_CLICK)).  We also discuss the Hungarian notation issue quite a bit but I've seen that discussed here in other questions.

For a very long time it has been the defacto standard to not use articles in variable names (adds visual clutter without adding value) and to not have hard-coded strings sprinkled through the source code (a potential maintenance nightmare and very poor for internationalization). Now we are starting to see violations of these and the developers seem truly surprised when someone marks these as defects or at least needing attention. The manager has said they don't care one way or the other and these points are not in our company coding standards.

答:
For hard-coding strings, the three sides are whether to put all strings into constants (public static final) in a separate file (class or interface), put them all in the same file (private static final), or don't use constants for strings at all. (e.g. new Button("Click Me") vs. new Button(BUTTON_LABEL_CLICK)). We also discuss the Hungarian notation issue quite a bit but I've seen that discussed here in other questions.

If you want a high-quality user experience, anything that is presented to the user (button labels, error messages, etc.) must be reviewed by the UI designer.  In my experience, when developers are hard-coding text, that doesn't happen.  The developers do the best they can, but the result is a set of messages and labels that are little better than random.


问:
If the model is validating the data, shouldn't it throw exceptions on bad input?
Reading this SO question it seems that throwing exceptions for validating user input is frowned upon.

But who should validate this data? In my applications, all validations are done in the business layer, because only the class itself really knows which values are valid for each one of its properties. If I were to copy the rules for validating a property to the controller, it is possible that the validation rules change and now there are two places where the modification should be made.

Is my premise that validation should be done on the business layer wrong?

What I do

So my code usually ends up like this:

```<code><?php
class Person
{
  private $name;
  private $age;

  public function setName($n) {
    $n = trim($n);
    if (mb_strlen($n) == 0) {
      throw new ValidationException("Name cannot be empty");
    }
    $this->name = $n;
  }

  public function setAge($a) {
    if (!is_int($a)) {
      if (!ctype_digit(trim($a))) {
        throw new ValidationException("Age $a is not valid");
      }
      $a = (int)$a;
    }
    if ($a < 0 || $a > 150) {
      throw new ValidationException("Age $a is out of bounds");
    }
    $this->age = $a;
  }

  // other getters, setters and methods
}
</code>```

In the controller, I just pass the input data to the model, and catch thrown exceptions to show the error(s) to the user:

```<code><?php
$person = new Person();
$errors = array();

// global try for all exceptions other than ValidationException
try {

  // validation and process (if everything ok)
  try {
    $person->setAge($_POST['age']);
  } catch (ValidationException $e) {
    $errors['age'] = $e->getMessage();
  }

  try {
    $person->setName($_POST['name']);
  } catch (ValidationException $e) {
    $errors['name'] = $e->getMessage();
  }

  ...
} catch (Exception $e) {
  // log the error, send 500 internal server error to the client
  // and finish the request
}

if (count($errors) == 0) {
  // process
} else {
  showErrorsToUser($errors);
}
</code>```

Is this a bad methodology?

Alternate method

Should maybe I create methods for isValidAge($a) that return true/false and then call them from the controller?

```<code><?php
class Person
{
  private $name;
  private $age;

  public function setName($n) {
    $n = trim($n);
    if ($this->isValidName($n)) {
      $this->name = $n;
    } else {
      throw new Exception("Invalid name");
    }
  }

  public function setAge($a) {
    if ($this->isValidAge($a)) {
      $this->age = $a;
    } else {
      throw new Exception("Invalid age");
    }
  }

  public function isValidName($n) {
    $n = trim($n);
    if (mb_strlen($n) == 0) {
      return false;
    }
    return true;
  }

  public function isValidAge($a) {
    if (!is_int($a)) {
      if (!ctype_digit(trim($a))) {
        return false;
      }
      $a = (int)$a;
    }
    if ($a < 0 || $a > 150) {
      return false;
    }
    return true;
  }

  // other getters, setters and methods
}
</code>```

And the controller will be basically the same, just instead of try/catch there are now if/else:

```<code><?php
$person = new Person();
$errors = array();
if ($person->isValidAge($age)) {
  $person->setAge($age);
} catch (Exception $e) {
  $errors['age'] = "Invalid age";
}

if ($person->isValidName($name)) {
  $person->setName($name);
} catch (Exception $e) {
  $errors['name'] = "Invalid name";
}

...

if (count($errors) == 0) {
  // process
} else {
  showErrorsToUser($errors);
}
</code>```

So, what should I do?

I'm pretty happy with my original method, and my colleagues to whom I have showed it in general have liked it. Despite this, should I change to the alternate method? Or am I doing this terribly wrong and I should look for another way?

答:
In layman's words:

The first approach is the correct one.

The second approach assumes that those business classes will only be called by those controllers, and that they will never be called from other context.

Business classes must throw an Exception everytime a business rule is violated.

Controller or presentation layer must decide whether it throws them or it does it's own validations to prevent the exceptions from happening.

Remember: your classes will potentially be used in different contexts and by different integrators. So they must be smart enough to throw exceptions to bad inputs.


问:
Which are the significant algorithms for humankind in past decades?
Which world most important algorithms have contributed most to humankind in past decades?

I thought this is a good general knowledge for a developer to know about.

Update:

If possible, please keep the answer to a specific programming algorithm.

I would like to get a list of the most important ones, only one algorithm per answer.

Please consider to state why the algorithm is significant and important...

答:
Siam named the following as the most important algorithms of the 20th century:

1946: The Metropolis Algorithm for Monte Carlo. Through the use of random processes, this algorithm offers an efficient way to stumble toward answers to problems that are too complicated to solve exactly.

1947: Simplex Method for Linear Programming. An elegant solution to a common problem in planning and decision-making.

1950: Krylov Subspace Iteration Method. A technique for rapidly solving the linear equations that abound in scientific computation.

1951: The Decompositional Approach to Matrix Computations. A suite of techniques for numerical linear algebra.

1957: The Fortran Optimizing Compiler. Turns high-level code into efficient computer-readable code.

1959: QR Algorithm for Computing Eigenvalues. Another crucial matrix operation made swift and practical.

1962: Quicksort Algorithms for Sorting. For the efficient handling of large databases.

1965: Fast Fourier Transform. Perhaps the most ubiquitous algorithm in use today, it breaks down waveforms (like sound) into periodic components.

1977: Integer Relation Detection. A fast method for spotting simple equations satisfied by collections of seemingly unrelated numbers.

1987: Fast Multipole Method. A breakthrough in dealing with the complexity of n-body calculations, applied in problems ranging from celestial mechanics to protein folding.

Personally I would replace Integer Relation Detection with PageRank.

ContentLicense: CC BY-SA 2.5


答:
Apple use articles - inconsistently - in their ObjC code.  It adds nothing to the legibility of their code or the descriptiveness of their variable names:

```<code>- (id)viewWithTag:(NSInteger)aTag;
- (id)initWithFrame:(NSRect)frameRect mode:(int)aMode cellClass:(Class)factoryId numberOfRows:(int)rowsHigh numberOfColumns:(int)colsWide;
</code>```

Note aTag and aMode vs frameRect.

I hate the semi-standard and don't use it.  It makes the code sound moronic.

Title: articles in variable names and hard-coding strings

Body:
re-edited by author: no this is not 2 questions. This is one question about code review questions containing two separate points. Please do not edit my question.

For naming variables, the two sides are regarding using articles (a, an, the) in the variable name (e.g. theBook vs. book -or- parseTheString vs. parseString).

For hard-coding strings, the three sides are whether to put all strings into constants (public static final) in a separate file (class or interface), put them all in the same file (private static final), or don't use constants for strings at all. (e.g. new Button("Click Me")  vs.  new Button(BUTTON_LABEL_CLICK)).  We also discuss the Hungarian notation issue quite a bit but I've seen that discussed here in other questions.

For a very long time it has been the defacto standard to not use articles in variable names (adds visual clutter without adding value) and to not have hard-coded strings sprinkled through the source code (a potential maintenance nightmare and very poor for internationalization). Now we are starting to see violations of these and the developers seem truly surprised when someone marks these as defects or at least needing attention. The manager has said they don't care one way or the other and these points are not in our company coding standards.

Body:
Apple use articles - inconsistently - in their ObjC code.  It adds nothing to the legibility of their code or the descriptiveness of their variable names:

- (id)viewWithTag:(NSInteger)aTag;
- (id)initWithFrame:(NSRect)frameRect mode:(int)aMode cellClass:(Class)factoryId numberOfRows:(int)rowsHigh numberOfColumns:(int)colsWide;

Note aTag and aMode vs frameRect.

I hate the semi-standard and don't use it.  It makes the code sound moronic.


问:
What are considered the definitive references for bootstrapping one's client-side expertise?
I'm a server-side junkie, and by that I mean I spend time writing code that's not visible to anyone.

I'm interested in rounding out my skillset and becoming more self-sufficient with writing full-stack webapps.

But, I find it difficult to work with the the sort of 'organicity' of client-side html tech.

I know there is no substitute for time and experience, but if an experienced client-side dev was starting over from scratch, what would he read/do?

EDIT: an example of an answer that I'd give for server-side:

Learn the best practices of the language you're working in, eg. for
  java, read 'effective java'. Learn fundamentals of algorithms,
  application design concepts that are useful in any language, two good
  sources are 'design patterns', 'SICP'.

I'm not looking for:
'Learn CSS, HTML and Javascript.'

I am looking for something like:

Intent, rationale, concepts of X are well-explained in Y. Framework Z
  is a good example and the source-code is enlightening and well-documented.

答: I recently got started working with client-side web languages. I had some basic HTML4 and CSS2 experience, but not much beyond that. I started working with Javascript by using http://learn.knockoutjs.com. Knockout.JS is a javascript library that gave me a quick crash-course in Javascript, object-oriented programming, and the Model-View-View-Model design pattern (which lead to Model-View-Controller pattern for a couple of .NET projects). The mini-examples the tutorial runs you through live on their website gave me ideas on how to expand them by adding other libraries for additional features (jQuery) or other languages (C#).</p>


问:
Does relying on intellisense and documentation a lot while coding makes you a bad programmer?
Is a programmer required to learn and memorize all syntax, or is it ok to keep handy some documentation?

Would it affect the way that managers look at coders?

What are the downside of depending on intellisense and auto-complete technologies and pdf documentation?

答:
It is completely normal. Hardly anyone can say that he/she knows the syntax of every PHP or Java class, function or framework.

Your brain is better used for problem solving than for memorizing things.

Obviously you tend to memorize things you use in a daily basis but as soon as several month pass without doing that specific thing, you forget the syntax.

If remembering syntax was key in developing, computers would have already substituted humans in that field.

Using your brain for abstraction, imagination, problem solving and pattern recognition is priceless. For everything else, there's Master Card. (1)

(1) Or in this case documentation, auto-completion etc.

What you shouldn't definitively do is ask your co-workers every time you don't remember the syntax of something. That would be laziness.


答:
CSS and HTML are trivial to learn. A competent programmer can pick up the syntax in 15 minutes and learn the basics of HTML in another 30.

It is very important to know and understand the box model. This is the method that the browser uses to render the DOM. That said, you should probably at the very least read the wikipedia page for the DOM.

Next, learn JavaScript. I would start with JavaScript: The Good Parts. I would also learn to use and understand jQuery - it is the most ubiquitous JavaScript library for a reason. You'll also need to understand the basics of the Module pattern, and understand how RequireJS works and why it is so useful.

Once you know those basics, you'll want to start learning about things like repaints, maybe the canvas tag, etc.

Title: What are considered the definitive references for bootstrapping one's client-side expertise?

Body:
I'm a server-side junkie, and by that I mean I spend time writing code that's not visible to anyone.

I'm interested in rounding out my skillset and becoming more self-sufficient with writing full-stack webapps.

But, I find it difficult to work with the the sort of 'organicity' of client-side html tech.

I know there is no substitute for time and experience, but if an experienced client-side dev was starting over from scratch, what would he read/do?

EDIT: an example of an answer that I'd give for server-side:

Learn the best practices of the language you're working in, eg. for
  java, read 'effective java'. Learn fundamentals of algorithms,
  application design concepts that are useful in any language, two good
  sources are 'design patterns', 'SICP'.

I'm not looking for:
'Learn CSS, HTML and Javascript.'

I am looking for something like:

Intent, rationale, concepts of X are well-explained in Y. Framework Z
  is a good example and the source-code is enlightening and well-documented.


答:
In terms of memorization, I think it's pretty crucial to have a solid knowledge of your language's core syntax. That does not mean, however, that you need to memorize the core libraries. For Java that's the JSCL, for C#/VB that's .NET, for PHP it's, well... that.

Anyway, point is, know your syntax, but not necessarily every class, function, and/or method. Knowing the syntax is like knowing grammar in english: you know how a sentence should be formed. Knowing the libraries is more akin to vocabulary. If you don't know a word, you can look it up pretty easily; you may not find the perfect word, but you'll find something suitable. If you don't know the grammar, you're going to have a much harder time getting a message across clearly and correctly, and a much harder time looking up what you need when you need it.

Title: Does relying on intellisense and documentation a lot while coding makes you a bad programmer?

Body:
Is a programmer required to learn and memorize all syntax, or is it ok to keep handy some documentation?

Would it affect the way that managers look at coders?

What are the downside of depending on intellisense and auto-complete technologies and pdf documentation?


问:
Isn't GPL enough to make a software free as in free speech?

Background

I have read people rebutting the fact that a certain software is free as in free speech, even when it is licensed under GPL.

Some say Java isn't free because to obtain a professional certification you must get it from Oracle.

Some say Java JDK is not free to re-distribute.

Some people even say the openJDK is not free or open.

But Java is officially GPL.

Questions

Doesn't GPL explicitly mean you are free to re-distribute ?

Isn't GPL enough to make a software free as in free speech ?

How can Java be both GPL and not-free as in free speech ?

Is there is any license that trully makes a software free beyond any possible subjetive point of view?

EDIT: These question is not about names or trademarks, it's about the code.

答:
The GPL is "free" for certain definitions of the word "free".  One major restriction of it is that you are not free to do the wrong thing - you simply can't take a bunch of GPL code, incorporate it in a program that's not under a GPL-compatible license, and release the result as proprietary software.

That's not truly "free", and in order to ensure that GPL code remains under the GPL, it is necessary to impose this restriction on you.  This is not intended as criticism of the GPL (although it could be seen as a criticism), and it's something that the FSF openly admit (e.g. see the text of the GPL itself) although they use a different wording than the one I have chosen here.

The only truly "free" software license - including total freedom to do bad stuff with it if you wish to - is public domain or equivalent.


问:
Choosing the right language for the job
I'm currently working for a company on the engineering team of about 5-6 people and have been given the job of heading up the redesign of an embedded system tester. We've decided the general requirements and attributes that would be desirable in the system, and now I have to decide on a language to use for the system, or at the very least come up with a list of languages with pros and cons to present to the team.

The general idea of the project is that we currently have a tester written in c++, which was never designed to be a tester, but instead has evolved to be such over the course of 3-4 years due to need. Writing tests for a new product requires modifying the 'framework' and writing code that is completely non-human readable or intuitive due to the way the system was originally designed. Now, we've decided that the time to modify this tester for each new product that we want to test has become too high and want to partially re-write the system so that we can program the actual tests in a scripting language that would then use the modified c++ framework on the back end to test the actual systems. The c++ framework would be responsible for doing all the actual work and the scripting language would just integrate with that to tell the framework what to do.

Never having programmed in a scripting language (we program embedded systems), I've run into a wall where I have no experience with any of the languages that we could possibly use, but must somehow give pros and cons of each language so that we can choose the best one for the job.

Currently my short list of possibilities includes:

Python

TCL

Lua

Perl

My question is this: How can a person evaluate a language that he/she has never used before? What criteria are good indicators for a languages potential usability on a project?

While helpful suggestions for my particular case are appreciated, I feel that this is a good skill to possess and would like to be able to apply this to many different projects if at all possible

答:
Use it. Grab a tutorial, give it a spin. This will both give you an idea of what it's like to use the language, and, what kind community it has.

Stack Overflow Question Counts: This is a rough indication of overall use and how likely you are to find an answer to your question

Open Source library/package counts: This is a rough indication of overall use and how likely you are to find a pre-existing solution

Look for pre-existing solutions to problems you know you have; check them out in a bit more detail. This will give you an idea of the kind of code and documentation the community supplies for your problem domain, and how active that community is in that domain.

Then, I'd say, look up the philosophies that the community endorses; Python's 10 Principles vs Ruby's Enjoyment for the Programmer - but at that point you're getting /really/ subjective.

Oh! Also - Figure out where you, your team, your problem, and your possible languages fall on the "conservative vs liberal" programming "spectrum". It's a really useful axis for comparison.

Title: Choosing the right language for the job


问:
Is Haskell function composition an instance of pipe & filter architectural pattern
The pipe & filter architectural pattern is defined as a chain of processing elements, arranged so that the output of each element is the input of the next. Every example seems to consider inter-process or inter-thread connection performed through some kind of shared buffer.

To me, it seems that Haskell function composition is performing the same task. Can we say that it is an instance of this pattern even if it is just about function ordering and no explicit buffer is use as pipe? If yes, can we say the same thing for non-lazy language?

答:
There is a difference.  Pipes and filters deal with data and data connections, whereas Haskell Function Composition deals with first-class functions.  First-class functions are composable in ways that pipes and filters are not.

Further Reading

What does composability mean in context of functional programming?


答:
Is a programmer required to learn and memorize all syntax, or is it ok to keep handy some documentation?

No and yes.  Programmers who can't learn new things from documentation are crippled.  They can't solve new problems.  All they can do is cut-and-paste code that someone else has written.  I prefer programmers who read documentation, because they know enough not to reinvent existing library functions.  In hiring, I rarely care if the candidate has any experience with our current implementation language.  We may start using a new language any day now, so I want people who are happy to work in multiple languages.

Would it affect the way that managers look at coders?

No, except for a subset of measure zero.


答:
They are connected, but the connection is the other way around (sort of).

Morphism composition in an appropriate category accurately models both function composition (where the category is Set for a strict language and CPO for a lazy language) and process composition (where the category is the (AFAIK, unnamed) category where the objects are strings , morphisms are shell processes, and composition is the pipe operator).  Shell processes can be seen, without loss of either generality or accuracy, as (lazy) functions of type String -> WriterT String IO String, and pure functions of type String -> String can be losslessly converted to and from functions of type String -> Identity String, so both are really just (>>=) in disguise.

Title: Is Haskell function composition an instance of pipe & filter architectural pattern

Body:
The pipe & filter architectural pattern is defined as a chain of processing elements, arranged so that the output of each element is the input of the next. Every example seems to consider inter-process or inter-thread connection performed through some kind of shared buffer.

To me, it seems that Haskell function composition is performing the same task. Can we say that it is an instance of this pattern even if it is just about function ordering and no explicit buffer is use as pipe? If yes, can we say the same thing for non-lazy language?


答:
I've found that if I'm having trouble figuring out how to proceed on something then I haven't grasped the problem domain completely yet.

I think one thing which holds me back is feeling pressure to produce something. What I like to do is freely explore the problem domain without attempting to design or implement. Once I've been exploring a while, I can see the components and what needs to be done. Then I can design the objects and flow, figuring out what I want to do and how, and then I can implement it. But if I try to push either of the latter into the exploration phase, I get brain freeze.

I often find that my mind feels the freedom to explore when I'm away from the computer and can write things down -- as others have mentioned. If I'm at the computer then I feel like I should be coding, which is not what I need to do starting off.

Sometimes a little coding or prototyping will be helpful/necessary, but I only get to that point after exploring a bit.

It could be that maybe you're just not a morning person? I had a co-worker who complained of the same thing -- not being productive until towards the end of the day. Maybe that's just how some people work?


答:
I'm going to tell you a story.

Up until about May 30th 1999, John Carmack did not know that scissor test was not enabled by default in OpenGL.

The next thing is sort of funny. I had been suspecting that a lot of the OpenGL drivers were clearing the entire depth buffer for each of the 3D icons on the status bar, instead of limiting it to the scissor region. I added code to the g200 driver to explicitly crop the clear region in the driver, but it never got executed. A little more investigation showed that I had been making an improper assumption for years -- scissor is not enabled by default. Doh.

Finding this out came to him totally by accident, in the context of doing something else, and gave his code a fairly nice performance increase (given that he works in an area where performance is hugely important, this is worth noting):

Now I know that I was just being an idiot about that for the last three years... With scissor enabled, most of the cards got a few percent faster.

It's also worth noting his self-awareness here: "I was just being an idiot about that for the last three years".

Now, if he had read the documentation ("The test is initially disabled"), he would have been aware that scissor test was disabled by default and would not have made that mistake.

Is this a case where reading documentation would have made John Carmack a bad programmer?  Is this a case where not reading documentation made John Carmack a better programmer?  I don't think I need to answer those questions.

As for intellisense, it's important to realize that intellisense is a productivity tool, designed to save your time.  You type "." or "->" and up pops a list of members, you type the first few characters of the one you want, and hey-presto!  That's your precious time it's saved, it may have also saved you breaking a build owing to that supid typo you made because you hadn't had your coffee yet, and you've now got more time to get on with doing productive stuff instead of just grinding out code.

Intellisense is not designed as a crutch for bad programmers, it's an example of what Fred Brooks calls a "Sharp Tool".

By the same logic that one may dismiss intellisense, one comes to the obvious end conclusion that any tool designed to increase programmer productivity is also something that may make one a bad programmer.  That's a dangerous line of thinking because next thing you'll be rejecting compilers and debuggers.

When I was back in college last century, one of my lecturers told us that "the best programmers are lazy".  That's very tongue-in-cheek, and what he meant was that the best programmers find ways to maximize their productive time and minimize time spent doing donkey work.  I still think that's good advice today.


问:
Which design patterns would I use for this algorithm?
I need to create a string using the following algorithm:

Generate a GUID as a byte array.

Convert that GUID to a string.

From this string, get the UTF-8 encoding as a byte array.

From this byte array, hash those bytes to another byte array.

From this byte array, get the base64 encoding as a string.

Append a string constant to this string.

What design pattern(s) would I use? I am thinking builder and/or chain-of-responsibility, although I am not sure I would handle the changing between string and byte array types.

UPDATE:

I am programming in an object-oriented language (C++, Java, C#).

The encoding of UTF-8 may change in the requirements, as well as the hashing algorithm in step 4. I am asking about design patterns to adapt for a change in requirements.

答:
That seems simple enough to me that you don't really need a design pattern, per say.  You're got 6 steps, each of which requires only a single line of execution (except Line 4, as that could be a complex hash).

Chain of Command is more of a fire-and-forget method between distinct objects.  That's not really the case here.  And Builder is more of using a single execution path to perform the same action on multiple types of objects.  Again in your case, it's a single, consistent path, so I wouldn't think it'd fit either.


答:
The class which does all this would be a Factory with a function generate().

When the hashing algorithm and the character encoding have to be exchangeable, you would do so by implementing these as Strategies.

These strategies could either be passed to the constructor of the factory, you could have different sub-classes of factories which use different sets of strategies (Abstract Factory pattern), you could pass the strategies to each call of the generate function or you could set the strategies to use for all subsequent calls through setters of the factory (Builder pattern). Which one of these option to use (or maybe a mix of them) is a matter of taste.

Title: Which design patterns would I use for this algorithm?

Body:
I need to create a string using the following algorithm:

Generate a GUID as a byte array.

Convert that GUID to a string.

From this string, get the UTF-8 encoding as a byte array.

From this byte array, hash those bytes to another byte array.

From this byte array, get the base64 encoding as a string.

Append a string constant to this string.

What design pattern(s) would I use? I am thinking builder and/or chain-of-responsibility, although I am not sure I would handle the changing between string and byte array types.

UPDATE:

I am programming in an object-oriented language (C++, Java, C#).

The encoding of UTF-8 may change in the requirements, as well as the hashing algorithm in step 4. I am asking about design patterns to adapt for a change in requirements.


答:
No way; on the contrary, it makes you a way better programmer since they are productivity tools, and programmers using them makes a program faster/better. The purpose of the programmer is to make a program not to know how a library or framework has some methods or classes called.

A programmer doesn't necessarily need to know the syntax of a language; but in someway it obliged to know it since the modern IDE immediately alerts him/her if something is wrong, so s/he will definitely learn it just to stop the IDE prompting error messages. I really cannot imagine anyone programming with red underlines under some words, before solving the issue. Regarding the utility of a library s/he should know only that a library can perform a certain functionality and eventually s/he will find a way to use it.

I can say that code completion really helps a programmer to find new functionality of a given library. Any good library is based on abstraction - interfaces. Suppose we have an interface Sort that is supposed to perform some logic of sorting; now this logic can be performed in some various ways but I as a programmer don't know what the given library can really do with it. So I type Sort sort = Ctrl+Space and immediately all the possible implementations appear (I have really discovered new things about many libraries in this way). Among the implementations QuickSort appears, but I don't really know so much about it so (in my IDE - Intellij) I press Ctrl+Q and I immediately see the documentation of the class, and I see how it can be used. Things go further as I might be interested how QuickSort is implemented so I press Ctrl+B and choose to download the implementation from Maven repository and I immediately see implementation code.


问:
Declare variable as interface
When should or shouldn't a variable be declared as a custom Interface type?

When walking through some code, I required to know what was happening here:

```<code>Public Class MyMainProject
    ....
    Public Sub DoMyWork()
        Dim objIMyInterface As IMyInterface
        ....
        objIMyInterface = GetReturnObject()
    End Sub
    ....
End Class
</code>```

According to what I saw, objIMyInterface is only being used for one thing.  I didn't know how many classes implement it, but there's no casting of similar types in this code. objIMyInterface is used just like a regular type, not anonymous in the least.  Second of all, my research helped a little...

GetReturnObject happens to return an instance of IMyInterface.  The return object of GetReturnObject, of course, has a call to another method.

```<code>Public Function GetReturnObject() As IMyInterface
    Dim retObject As IMyInterface
    ...
            retObject = AnotherMethod()
    ...
    Return retObject
End Function
</code>```

So I try to step into AnotherMethod, but it's in a project with no symbols.  So after some research, I find the source and go through it.  After repeating this process a few times, I eventually get to something like this:

```<code>Public Function FinalMethod() As IMyInterface
    Dim FinalObject As MyClassType
    ...
            FinalObject = GetMyClassType()
    ...
    Return FinalObject
End Function
</code>```

Yay!  GetMyClassType returns MyClassType!  I go to that Class and of course:

```<code>Public Class MyClassType
    Implements IMyInterface
    ...
End Class
</code>```

What I end up finding out is that IMyInterface is used by nothing else but this class.  No biggie, it's all good code by the looks of it.  But then I go back to my original project I notice this:

```<code>Public Class MyMainProject
    ....
    Public Sub DoMyWork()
        Dim objIMyInterface As IMyInterface
        ....
        objIMyInterface = GetReturnObject()
    End Sub
    ....
    Public Sub OtherWork()
        Dim objMyType As MyClassType
        ....
    End Sub
    ....
End Class
</code>```

The guy who created this is long gone, but I'd like to know what your thoughts are on which method should be used.  Should I declare both as IMyInterface?  Or both as MyClassType?  The code works fine either way.

答:
Normally, you'd only declare a return type of an interface if you weren't absolutely certain what type you were going to get, but you did know that whatever type came back, it would definitely certainly implement that interface.

For example...

```<code>public Interface IMammal()
{
    public void Breastfeed();
}

public class Cat : IMammal()
{
    public void Breastfeed()
    {
        // stuff happens here
    }

    public bool Killsmice()
    {
        return true;
    }
}

public class Elephant : IMammal
{
    public void Breastfeed()
    {
        // stuff
    }

    public bool HasTrunk()
    {
        return true;
    }
}
</code>```

Now, let's look at when this might be useful.

```<code>public class Zoo
{
    public void AnimalType(IMammal mammal)
    {
        // here, the Breastfeed method could safely be called, but the HasTrunk or
        // KillsMice methods (they're methods because they are neither get nor set)
        // cannot safely be called. All this method knows is that it's getting a
        // class which implements IMammal
    }
}
</code>```

In your case, you've got an interface which only applies to one single class. Provided you're certain you'll never create another class which implements the interface, you're better off instantiating the actual class - your code will be more readable.

Title: Declare variable as interface

Body:
Normally, you'd only declare a return type of an interface if you weren't absolutely certain what type you were going to get, but you did know that whatever type came back, it would definitely certainly implement that interface.

For example...

public Interface IMammal()
{
    public void Breastfeed();
}

public class Cat : IMammal()
{
    public void Breastfeed()
    {
        // stuff happens here
    }

    public bool Killsmice()
    {
        return true;
    }
}

public class Elephant : IMammal
{
    public void Breastfeed()
    {
        // stuff
    }

    public bool HasTrunk()
    {
        return true;
    }
}

Now, let's look at when this might be useful.

public class Zoo
{
    public void AnimalType(IMammal mammal)
    {
        // here, the Breastfeed method could safely be called, but the HasTrunk or
        // KillsMice methods (they're methods because they are neither get nor set)
        // cannot safely be called. All this method knows is that it's getting a
        // class which implements IMammal
    }
}

In your case, you've got an interface which only applies to one single class. Provided you're certain you'll never create another class which implements the interface, you're better off instantiating the actual class - your code will be more readable.


答:
I am asking about design patterns to adapt for a change in requirements.

Don't think about design patterns to adapt for a change in requirements

Use design patterns to simplify code that you have written to meet known requirements.  Attempting to predict future requirements is only slightly easier than predicting stock prices.


问:
What are the pros and cons of HTML5, native and hybrid mobile app approaches?
I want to develop a mobile application. I recently read an article on Telerik Forum, which compares among three types of mobile application and I don't know which one should I select to begin with. Here is an image describing the pros and cons of different mobile design choices

To decide between these design choices, I would like to better understand the pros and cons of each architecture choice listed in the diagram.  What are the pros and cons of each architecture approach?

答:
If you need to access the phones hardware, you should build a native app (in HTML5 you can access some of the hardware components of the device such as GPS).

If you are more comfortable with web development, you should stick with that unless you need to make a native app.

As far as what you should know, i would say that you should keep in mind all the different screen sizes (including vertical and horizontal orientation). You should keep in mind various versions of the OS (this is more for android). Since these are mobile deivces, there is the chance that the user will answer a phone call it its a phone and also they do not have the computing power of a desktop or server.


答:
This seems like typical use-case for a template method pattern; have a class which has 7 methods, 6 for each corresponding step and one method that calls all the other 6 methods in order. The methods that can change make them abstract and come with implementation for them in subclasses; for example make subclasses for UTF-8 and for other encoding; the same for other methods that may very. In a simplified way:

```<code>public abstract class StringProcessor {
    public void perform() {
        generateGuid();
        generateEncoding();
        //...
    }

    protected void generateGuid() {
        //logic
    }

    protected abstract void generateEncoding();
}

public class Utf8EncodingStringProcessor extends StringProcessor {
    protected generateEncoding() {
         //UTF-8 logic
    }
}

public class OtherEncodingStringProcessor extends StringProcessor {
    protected generateEncoding() {
         //Other logic
    }
}
</code>```

This would not be so useful if you need UTF-8 with hashing algorithm 1, UTF-8 with hasing algorithm 2, other encoding with hashing algorithm 1, other encoding with hashing algorithm 2 etc. If you need that much flexibility I would recommend using template method pattern combined with strategy pattern for each method that may vary. Something simplified might look:

```<code>public abstract class StringProcessor {
    private Encoding encoding;
    private Hashing hashing;

    public StringProcessor(EncodingType encodingType, HashingType hashingType) {
         if (UTF8.equals(encodingType)) {
              encoding = new Utf8Encoding();
         } else if( ....)
    }

    public void perform() {
        generateGuid();
        encoding.encode();
        hashing.generateHash();
        //...
    }

    public void generateGuid() {
        //logic
    }
}

public enum EncodingType {
    UTF8, OTHER, //...
}

public interface Encoding {
    void encode();
}

public class Utf8Encoding implements Encoding {
    public void encode() {
         //UTF-8 logic
    }
}
</code>```

Builder and chain of responsibility do not seem to work since builder lets you create only a partial object, but you need to call all the methods; also chain of responsibility is not useful since you always will need to delegate upper in the hierarchy and always reach the top in command to in order to call all the methods.

Body:
This seems like typical use-case for a template method pattern; have a class which has 7 methods, 6 for each corresponding step and one method that calls all the other 6 methods in order. The methods that can change make them abstract and come with implementation for them in subclasses; for example make subclasses for UTF-8 and for other encoding; the same for other methods that may very. In a simplified way:

public abstract class StringProcessor {
    public void perform() {
        generateGuid();
        generateEncoding();
        //...
    }

    protected void generateGuid() {
        //logic
    }

    protected abstract void generateEncoding();
}

public class Utf8EncodingStringProcessor extends StringProcessor {
    protected generateEncoding() {
         //UTF-8 logic
    }
}

public class OtherEncodingStringProcessor extends StringProcessor {
    protected generateEncoding() {
         //Other logic
    }
}

This would not be so useful if you need UTF-8 with hashing algorithm 1, UTF-8 with hasing algorithm 2, other encoding with hashing algorithm 1, other encoding with hashing algorithm 2 etc. If you need that much flexibility I would recommend using template method pattern combined with strategy pattern for each method that may vary. Something simplified might look:

public abstract class StringProcessor {
    private Encoding encoding;
    private Hashing hashing;

    public StringProcessor(EncodingType encodingType, HashingType hashingType) {
         if (UTF8.equals(encodingType)) {
              encoding = new Utf8Encoding();
         } else if( ....)
    }

    public void perform() {
        generateGuid();
        encoding.encode();
        hashing.generateHash();
        //...
    }

    public void generateGuid() {
        //logic
    }
}

public enum EncodingType {
    UTF8, OTHER, //...
}

public interface Encoding {
    void encode();
}

public class Utf8Encoding implements Encoding {
    public void encode() {
         //UTF-8 logic
    }
}

Builder and chain of responsibility do not seem to work since builder lets you create only a partial object, but you need to call all the methods; also chain of responsibility is not useful since you always will need to delegate upper in the hierarchy and always reach the top in command to in order to call all the methods.


问:
WCF Keep Alive: Whether to disable keepAliveEnabled
I have a WCF web service hosted in a load balanced environment. I do not need any WCF session related functionality in the service.

QUESTION

What are the scenarios in which performances will be best if

keepAliveEnabled = false

keepAliveEnabled = true

Reference

From Load Balancing

By default, the BasicHttpBinding sends a connection HTTP header in messages with a Keep-Alive value, which enables clients to establish persistent connections to the services that support them. This configuration offers enhanced throughput because previously established connections can be reused to send subsequent messages to the same server. However, connection reuse may cause clients to become strongly associated to a specific server within the load-balanced farm, which reduces the effectiveness of round-robin load balancing. If this behavior is undesirable, HTTP Keep-Alive can be disabled on the server using the KeepAliveEnabled property with a CustomBinding or user-defined Binding.

答:
Because you asked about performance:

keepAliveEnabled = false

For best performance, if your average latency is low, use this (though it probably won't make a huge difference).

keepAliveEnabled = true

For best performance, if your average latency is high, use this.


问:
Should I fully parenthesize expressions or rely on precedence rules?
Let's say I have a boolean condition a AND b OR c AND d and I'm using a language where AND has a higher order of operation precedence than OR. I could write this line of code:

```<code>If (a AND b) OR (c AND d) Then ...
</code>```

But really, that's equivalent to:

```<code>If a AND b OR c AND d Then ...
</code>```

Are there compelling arguments in favor or against including the extraneous parentheses?

Does practical experience suggest that including them significantly improves readability?

Or is wanting them a sign that a developer really needs to sit down and become conversant in the  basics of their language?

答: I will use parenthesis even if it is optional, why because it helps to better understand for everyone, for the one who write the code as well as the one ready to see that code. In your case even the boolean operators have precedence it might work well at first, but we can't say it will help you in every case. so i prefer to user parenthesis in any condition that it may require it or optionally.</p>

ContentLicense: CC BY-SA 4.0


问:
How can you explain "beautiful code" to a non-programmer?
When speaking with a non-programmer friend, I happened to mention the concept of "beautiful code" and she wanted to understand what that meant, but I was at a bit of a loss as to how to explain it to someone who would have no context whatsoever.

When all code looks like gibberish to someone anyways, how can you explain what makes one piece of code prettier than another? Analogies could be useful too.

答:
It's like a lean mean company where everybody knows their role, it's easy to figure out who is good at what, and there's no duplication of effort

Vs.

Office Space where mediocrity is championed, three managers have nothing better to do than bug you about TPS reports, the !@#$ing FAX MACHINE NEVER WORKS!!! and any given employee might only get about 15 minutes of actual work done a week. An employee might not even technically work there anymore because somebody forgot to fire him (it's hard to tell really because nobody works efficiently and it's hard to evaluate what they're trying to accomplish). And to get anything practical done requires navigating an absurdly over-complicated system that somebody read about and thought would look neat-o on their resume even though it doesn't actually solve a problem they had.


问:
When did the first "REST"-model and friendly URL web technology come to be?
Everyone knows that the "current" way to do things is to have user-readable URLs. Like:

http://example.com/blog/edit/1234

Rather than:

http://example.com/blog.php?action=edit&id=1234

When exactly did people start making web technologies handling this though? I remember in the dark ages of the early 2000s, I don't remember ever seeing a friendly URL. In fact, I think Stackoverflow (in 2008/9) may have been the first time I noticed them.

When exactly did this become so popular, and what were the first servers/frameworks built with friendly URLs in mind?

I'm interested as well in when rewriting to friendly URLs became common, and when serving friendly URLs natively became common

答:
I would probably go with this link which puts the idea being put to an acronym at 2000.

http://en.wikipedia.org/wiki/Restful

I can only offer anecdotal on your last concern. I don't recall being particularly aware of Restful vs. Soap until shortly after I became UI web developer in 2005ish but definitely had the sense it was still something a lot of people didn't think about.


问:
Best way to check for specific types
Normally I do this:

```<code>if (Animal is Dog)
{
    Doc d = (Dog)Animal;
    // d. etc..
}
else if (Animal is Cat)
{
    Cat c = (Cat)Animal;
    // c. ....
}
</code>```

Is this a good way or are there better ways to implement this code above (performance, ...) ?

Should it be like this?:

```<code>Dog d = Animal as Dog;

if (d != null;)
{
    // d. etc..
}
else if (Animal is Cat)
{
    Cat c = (Cat)Animal;
    // c. ....
}
</code>```

Or maybe like this?:

```<code>Dog d = Animal as Dog;
Cat c;

if (d != null;)
{
    // d. etc..
}
else if ((c = Animal as Cat) != null)
{
    // c. ....
}
</code>```

Or maybe something else?

答:
Ideally, you should aim for just:

```<code>Animal.DoWhateverYouNeedDone();
</code>```

That is, implement the polymorphic behavior (if it's a dog, do a dog thing, if it's a cat, do a cat thing, etc.) in the classes themselves. So instead of this:

```<code>if (Animal is Dog) {
    var d = Animal as Dog;
    d.Bark();
}
if (Animal is Cat) {
    var c = Animal as Cat;
    c.Meow();
}
</code>```

Do this:

```<code>Animal.Speak();

// where:

public class Dog: Animal {
    public void Speak() {
        this.Bark();
    }
    // ---- snip -----
}
public class Cat: Animal {
    public void Speak() {
        this.Meow();
    }
    // ---- snip -----
}
</code>```

Title: Best way to check for specific types

Body:
Ideally, you should aim for just:

Animal.DoWhateverYouNeedDone();

That is, implement the polymorphic behavior (if it's a dog, do a dog thing, if it's a cat, do a cat thing, etc.) in the classes themselves. So instead of this:

if (Animal is Dog) {
    var d = Animal as Dog;
    d.Bark();
}
if (Animal is Cat) {
    var c = Animal as Cat;
    c.Meow();
}

Do this:

Animal.Speak();

// where:

public class Dog: Animal {
    public void Speak() {
        this.Bark();
    }
    // ---- snip -----
}
public class Cat: Animal {
    public void Speak() {
        this.Meow();
    }
    // ---- snip -----
}


问:
Are Ruby on Rails / Grails the fastest frameworks for getting sites up quickly?
I'm considering using Grails for a new website, but am open to other/new programming languages and frameworks.  I have done development using J2EE/JSF2, ASP.NET, and PHP.  Is Grails or Ruby on Rails pretty much the best way to get functionality up and running quickly?

Some initial thoughts:

DJango looks similar to RoR/Grails and I'd consider it

GWT is an interesting concept but it doesn't seem like turnaround time is quite as fast

Thanks,
-Jon

答:
I've dabbled in Django and Rails and found Rails to more of my liking. That being said, I prefer ASP.Net MVC 2 much better than Rails. I'm much faster in MVC (or even just web forms) than Rails simply because my mind "works better" with C#.

To me it comes down to what you know and what you enjoy. I've heard from many people that Ruby is fun, not to me it isn't. C# is fun! Haskell is fun! If you don't enjoy the language/framework then you won't be as fast as a "slower" framework you enjoy.


问:
Messages from UI or from subs?
I am designing a small application that is really justa gui for a command line using vb.net.

Question 1.

Should messages(msgbox) to the user come from the UI or should messages come from subs and functions that the UI calls.

Question 2.

Should subs and functions throw new exceptions to the UI or should they be containd in the sub/function

Question 3.

Should if statements be used at the UI level or should users input be passed to subs and functions for if statement processing ?

答:
Your questions are pretty broad and cannot really be answered without making a lot of assumptions or giving many alternatives and considerations. From the questions it seems you are looking for rules about what logic goes where. That is generally known as layering. The most common pattern being having three layers: UI; Business (Application) and Data(base). This answer on SO and the links contained within it, will probably help you on your way.

With regard t0 1: The message box should not be displayed by the subs/functions. Message boxes are UI specific implementations and a concern for the UI. The message displayed by the message box can of course come from the subs/functions. If the sub does not return an error message directly but an error code, it is fine to have a separate sub (in the application layer) to return messages based on an error code. This could be part of a separate "localizaion" service when dealing with a multi-lingual UI.

With regard to 2: Depends. They can throw exceptions or they can contain them and return an error code. If you are even remotely considering putting the subs/funcions in a separate module (exe or dll): exceptions should never cross module boundaries. In that case containing exceptions and returning error codes is the way to go.

With regard to 3: The UI can have logic, but that logic should be confined to UI stuff, like enabling and disabling controls. Validation is a business/domain/application concern and the UI should defer to that layer. It should of course have logic, including if statements :-) to process the results of that validation and reflect it in the UI.

Title: Messages from UI or from subs?


答:
tdammers answer is the correct way to do it, and 99% of the time you should do it that way.

very occasionally there maybe situations when you don't want to do it that way. In these circumstances I'd use the 'as and check for null' approach. Indeed FxCop will actually warn you that you are casting twice (once with is and once with an actual cast) in your first approach

Title: Best way to check for specific types

Body:
Normally I do this:

```<code>if (Animal is Dog)
{
    Doc d = (Dog)Animal;
    // d. etc..
}
else if (Animal is Cat)
{
    Cat c = (Cat)Animal;
    // c. ....
}
</code>```

Is this a good way or are there better ways to implement this code above (performance, ...) ?

Should it be like this?:

```<code>Dog d = Animal as Dog;

if (d != null;)
{
    // d. etc..
}
else if (Animal is Cat)
{
    Cat c = (Cat)Animal;
    // c. ....
}
</code>```

Or maybe like this?:

```<code>Dog d = Animal as Dog;
Cat c;

if (d != null;)
{
    // d. etc..
}
else if ((c = Animal as Cat) != null)
{
    // c. ....
}
</code>```

Or maybe something else?


答:
When exactly did people start making web technologies handling this though?

mod_rewrite handles this functionality on Apache and mod_rewrite has been available since Apache 1.3, which was released on June 6, 1998.

See also:

http://en.wikipedia.org/wiki/Rewrite_engine

Title: When did the first "REST"-model and friendly URL web technology come to be?

Body:
Everyone knows that the "current" way to do things is to have user-readable URLs. Like:

http://example.com/blog/edit/1234

Rather than:

http://example.com/blog.php?action=edit&id=1234

When exactly did people start making web technologies handling this though? I remember in the dark ages of the early 2000s, I don't remember ever seeing a friendly URL. In fact, I think Stackoverflow (in 2008/9) may have been the first time I noticed them.

When exactly did this become so popular, and what were the first servers/frameworks built with friendly URLs in mind?

I'm interested as well in when rewriting to friendly URLs became common, and when serving friendly URLs natively became common


答:
Let's get away from the Java example and concentrate on GPL software in general.

One problem with the GPlv2 is the patent issue. A software isn't really free when you can't use it without violating a software patent. The GPLv3 solves this issue.

Another problem occurs in the context of client/server applications or applications which run "in the cloud"™ on a machine the end-user accesses remotely. Now that more and more computing becomes distributed, this becomes an actual problem. Lots of typical desktop applications move to the web browser and selling remote access to virtualized desktop systems becomes a viable business model. Although the end-user makes use of the software in these cases, the GPL doesn't require a relicense to them, because the software runs somewhere else and they don't actually receive a copy of the software.

There is the Affero GPL which addresses this concern by adding a clause to the GPL which garants the same right to everyone who uses the software over a network.

Title: Isn't GPL enough to make a software free as in free speech?

Body:
Background

I have read people rebutting the fact that a certain software is free as in free speech, even when it is licensed under GPL.

Some say Java isn't free because to obtain a professional certification you must get it from Oracle.

Some say Java JDK is not free to re-distribute.

Some people even say the openJDK is not free or open.

But Java is officially GPL.

Questions

Doesn't GPL explicitly mean you are free to re-distribute ?

Isn't GPL enough to make a software free as in free speech ?

How can Java be both GPL and not-free as in free speech ?

Is there is any license that trully makes a software free beyond any possible subjetive point of view?

EDIT: These question is not about names or trademarks, it's about the code.


问:
Pattern to use for different Stages in a software
I am developing a software for a laboratory to test some devices. To test each device there are multi subtests which should be done to reach to the final result.To perform a complete test, the software must pass Stage1 then automatically goes to Stage2 then Stage3 and so on until the whole test is finished. meanwhile the user can select to just have the Stage3 or Stage2 or any other Stages independently to be performed (which she selects that at runtime).
this is the thing I have done so far:

```<code>public class IronTestWorkFlow:ITestWorkFlow
    {
        private readonly List<ITestStages> _testStageses;

        public IronTestWorkFlow(List<ITestStages> testStageses )
        {
            if (testStageses == null)
            {
                throw new ArgumentNullException("testStageses");
            }
            _testStageses = testStageses;
        }
    }
</code>```

I am useing a DI container. But I don't know how to change the list of Stages in ITestWorkFlow at runtime.

Questions:

1- Am I designing this right?

2- If yes which pattern shall I follow to obey the principles and change the stages at runtime? and how can I do that?

答:
This problem doesn't necessarily need to be solved with design patterns but, to answer your question, you could arrange the tests you need using a simple list or use a composite pattern if you want to make a little more complicated. You could then use different strategies to iterate over the list of tests, each strategy reacting to success or failure appropriately.

This might not be your final solution, but it's food for thought...

OwnerDisplayName: Mehrdad Kamelzadeh

OwnerDisplayName: David Osborne


问:
Representational Equality versus Value Equality
I am coding a system where I have objects which represent a set of resources. These resources are identifiable (they have an ID). There can only be one resource with the same ID, and so multiple objects with the same ID really should have the same values.

My problem is with the equality concept in this case. Should it be based on the ID or on the values alone? Is object A = object B because they have the same ID OR should object A == object B because their fields are the same.

One possibility I was thinking of was to have the ID-based comparison be "equals" and the field-based comparison be "equivalent". Alternatively I could have it so the field-based comparison was "equals" and the ID based comparison was "representSameObject" (or something). Just a pseudo-code example:

```<code>class A {
   String uuid;
   int field1;
   double field2;
   List<String> listField;

   @Override
   public boolean equals(Object other) {
       return uuid.equals(other.uuid);
   }

   public boolean equivalent( other ) {
       if (this == other) {
           return true;
       }
       if (null == other) {
           return false;
       }
       if (other.getClass() != this.getClass()) {
           return false;
       }

       A rhs = (A) other;
       return new EqualsBuilder().append(field1, rhs.field1).append(field2, rhs.field2).append(listField, other.listField).isEquals();
   }
}
</code>```

In the end this may come down to a personal preference coupled with system requirements, but I am very interested to learn how others have approached this concept. It has been annoying the heck our of me since I started on this project!

If it makes a difference I am programming at the minute in Java. I don't mind where the answer comes from though as this is obviously a conceptual issue.

答:
You should actually go one step further and consider it an error if there are two distinct objects that both represent the resource with ID X.
This means that if you have two references to the object for ID X, then the two references should compare equal with the == operator (which compares reference equality in Java).

Allowing multiple objects to represent one and the same resource inevitably results in the objects becoming out-of-sync and bugs because different parts of the system having different, incompatible, views on the state of the resource.

Also, if you use the reference equality as a check for resource identity, then you could could use the equals method to check if two resources happen to have the same value at that moment.


答:
Oracle owns the copyright for the source code of Java brought from Sun, and other open source contributors are required to sign Contributor Agreement which grants Oracle the same copyright on their contributed code.

That's why Oracle can release a proprietary version of it. Others may fork openJDK, but the "forkers" are restricted with the license of GPL 2 since they don't hold the copyright, Oracle does.


问:
How to use BPMN and use case and other diagrams together
I asked this question on stackoverflow, but it seems this question is not suitable there, so I post here for discussion.

BPMN (Business Process Modeling Notations) is used for modeling business process by visualization, thus making intangible ideas become physically concrete through the expression of BPMN diagrams. The question is, how do I organize the BPMN with the UML.

Initially, I thought of two ways to organize use cases and business process diagram:

1 to one/many: By mapping each step (step here means each node in the BPMN digram) in the business process diagram with one or several use cases. Each use case is mapped with relevant several class diagrams/component diagrams (I prefer this one, since you can encapsulate a set of classes into one component which has input and output), several sequence diagrams (optional). After you have class diagrams/sequence diagrams, code is written/generated based on the model.

Many to one: By mapping several steps into one use case. The subsequence steps are the same.

Many to many: For example, one step in the business process can be mapped with two or more use cases, and the same two or more use cases can be mapped with other steps.

The above methods can be done by the modeling tool, and in my case, I use Enterprise Architect from Sparx System. I discover it recently and I am using its trial, but I will buy it in the future. I can organize many use case diagrams with one step of the BPMN diagram, and can click to view the necessary use cases. However, I don't if it supports many to many cases.

After thinking my own method for organizing BPMN and Use Cases, I searched the Internet, and found two other papers, each suggest the following method:

Turn each use case into each step of BPMN diagrams: To visualize how refined use cases fit into the business process. I like this approach, since the business process with steps can be modeled, and later each step is turned into a use case. One step is one use case.  This is the same with my one to one mapping above. Original presentation is here: Visualizing Use Case Sets as BPMN Processes

Each use case is exactly a business process: Each step in the use case is each step of the business process. Original paper is here: Describing Business Processes with Use Cases

It seems to me that there's not standardized way of gluing these artifacts (BPMN and Use Cases and other digrams) together. Maybe it's a management problem and rely more on creative usage rather than follow a formal steps. What are the usage of these diagrams together?

答:
Hope you question is answered in this blog article

On The Future of BPMN (Too)...

[5] BPMN replaces UML activity diagrams. Activity diagrams as currently defined in UML are deprecated and replaced with BPMN notations and semantics. BPMN essentially replaces a portion of UML behaviors.

[6] BPMN grows to make UML not required. BPMN grows to encompass all the capabilities required for business-focused modeling and architecture, thus making any integration with UML redundant. BPMN may, some day, replace UML.

[7] BPMN and UML are separate models, mapped with QVT. BPMN and UML are separate metamodels as they are now. A QVT mapping is specified between them such that a portion of a model in BPMN can be used to create a UML model and a portion of a UML model can be used to create a BPMN model. Since the notations are not the same, notations would not be mapped.


答:
One thing you can do is to look at how ORM frameworks, like Hibernate handle these situations. I believe by default 'domain objects' (objects that can be persisted) get an id as well as an equals() and hashCode() (that use the provided id for equivalence) by default.

They do suggest however that if you want to use these domain objects in collections, you should always override their provided equals() and hashCode() methods.

So maybe it's a matter of context. I believe that Hibernate uses the ids to see if it has a persisted object already. If the id is null, it will try to do an 'insert' versus if the id is not null, it will try to look up the persisted object and update its fields. If the id is not found, that is an error condition.

I hope this answer at least points you to some direction.

Title: Representational Equality versus Value Equality

Body:
I am coding a system where I have objects which represent a set of resources. These resources are identifiable (they have an ID). There can only be one resource with the same ID, and so multiple objects with the same ID really should have the same values.

My problem is with the equality concept in this case. Should it be based on the ID or on the values alone? Is object A = object B because they have the same ID OR should object A == object B because their fields are the same.

One possibility I was thinking of was to have the ID-based comparison be "equals" and the field-based comparison be "equivalent". Alternatively I could have it so the field-based comparison was "equals" and the ID based comparison was "representSameObject" (or something). Just a pseudo-code example:

```<code>class A {
   String uuid;
   int field1;
   double field2;
   List<String> listField;

   @Override
   public boolean equals(Object other) {
       return uuid.equals(other.uuid);
   }

   public boolean equivalent( other ) {
       if (this == other) {
           return true;
       }
       if (null == other) {
           return false;
       }
       if (other.getClass() != this.getClass()) {
           return false;
       }

       A rhs = (A) other;
       return new EqualsBuilder().append(field1, rhs.field1).append(field2, rhs.field2).append(listField, other.listField).isEquals();
   }
}
</code>```

In the end this may come down to a personal preference coupled with system requirements, but I am very interested to learn how others have approached this concept. It has been annoying the heck our of me since I started on this project!

If it makes a difference I am programming at the minute in Java. I don't mind where the answer comes from though as this is obviously a conceptual issue.


问:
Programming as fast as you can touch-type... How to get to that stage?
I took a test recently and found that I could touch type comfortably at around 100 wpm... and if given some sort of autocorrect/intellisense then that would be even faster (who knows maybe 150 wpm?)...

I definitely do not program anywhere near that speed... This led me to wonder how exactly does one become faster at programming? Once I look at a problem and design the algorithm to solve it (the problem is solved... I know what i'm going after give or take some debug runs) why does it take so much longer for me to actually type up the program? What I found was that in general when I'm coding, until I am done typing a word... even if it is just the letter a or number 1, I cannot simultaneously think and type. What that means is that I can come up with stuff as I'm typing but I don't have the ability to look ahead. Its either one or the other... For example in writing this, I might have a feel for where this goes, but until my fingers hit the keyboard, I don't really know what I'm going to say next.

How do I change this? How do I get the ability to think ahead while typing so that I can take advantage of my typing speed?

Also just in general how does one become a faster problem solver? I know the usual list of practice (which I have no problem with) but is there any particular excercise one should emphasize to train their mind? For example is playing various logic games (sudoku etc...) carry much help in improving your sense of logic in other areas of programming?

Sorry its a bunch of questions at once but they are all sort of related...

P.S. Is it possible to use a stenograph to program? I've heard that users of stenographs can achieve blistering speeds like 200 - 300 wpm. Assuming I can somehow think faster... that would be pretty cool.

Obviously fast programming != good programming. But if your always training to become a better programmer, it doesn't hurt to be able to do it fast.

答:
Practice

If you want to improve your coding speed, code more often. Give yourself a small problem and see how fast you can code it. Project Euler has some short problems that would be good to check out. Don't you know your ABC's?

If you want to improve your problem-solving speed, solve more problems. Again, give yourself a problem and see how fast you can figure it out. The catch? Don't code it. Don't worry about syntax or anything like that. Just write out some ideas and try to figure out how to solve it as fast as you can.

This isn't something that is done easily or quickly. Becoming a good, fast programmer takes years of experience and as Mike30 said, you probably will never be able to type as fast as you think. Although, you can get pretty close, so whip out your favorite text editor and start programming.


答:
You're never going to be able to solve new problems as fast as you can type. Just accept that. It might work for simple problems you've already done 1000 times.

But there is still value in typing skills. Muscle memory typing allows you to keep your mind in the problem, not on the keyboard. Your mind stays in the zone and the keyboard is just a natural extension. It's not about speed, it's about fluidity. If you can effortlessly type your thoughts, your mind can stay in a deep thinking zone while you try things out.

I dedicated some time to learn all special characters and numbers by heart. It's worth it.

Title: Programming as fast as you can touch-type... How to get to that stage?

Body:
I took a test recently and found that I could touch type comfortably at around 100 wpm... and if given some sort of autocorrect/intellisense then that would be even faster (who knows maybe 150 wpm?)...

I definitely do not program anywhere near that speed... This led me to wonder how exactly does one become faster at programming? Once I look at a problem and design the algorithm to solve it (the problem is solved... I know what i'm going after give or take some debug runs) why does it take so much longer for me to actually type up the program? What I found was that in general when I'm coding, until I am done typing a word... even if it is just the letter a or number 1, I cannot simultaneously think and type. What that means is that I can come up with stuff as I'm typing but I don't have the ability to look ahead. Its either one or the other... For example in writing this, I might have a feel for where this goes, but until my fingers hit the keyboard, I don't really know what I'm going to say next.

How do I change this? How do I get the ability to think ahead while typing so that I can take advantage of my typing speed?

Also just in general how does one become a faster problem solver? I know the usual list of practice (which I have no problem with) but is there any particular excercise one should emphasize to train their mind? For example is playing various logic games (sudoku etc...) carry much help in improving your sense of logic in other areas of programming?

Sorry its a bunch of questions at once but they are all sort of related...

P.S. Is it possible to use a stenograph to program? I've heard that users of stenographs can achieve blistering speeds like 200 - 300 wpm. Assuming I can somehow think faster... that would be pretty cool.

Obviously fast programming != good programming. But if your always training to become a better programmer, it doesn't hurt to be able to do it fast.


问:
When is it a good time to reason about performance in Haskell?
Simon Peyton Jones himself recognizes that reasoning about performance in Haskell is hard due to the non strict semantics.

I have yet to write a significant project in haskell so I wonder: can I reason about performance only at the beginning of a project (when choosing basic data structures & IO library) and whenever a problem arise, deal with it with the profiler?

To put it differently, is it possible (ie not too painful) to postpone dealing with performance when you have performance issues, or do you have to learn to predict how GHC will run your code (for exemple: infer what the strictness analyser will decide)?

答:
Optimize the big stuff before you code, and the little things when you're finished.

For example, before you start coding you should be thinking about the following:

Are the libraries/frameworks that you're going to use decently fast?

Try to keep your data structures simple.

Try to keep your algorithms and design patterns as simple as possible.

How fast is the language I'm using?

...and so on.

Then, when you're almost finished with your code, think about the little things like which built-in function is faster, should I rewrite that area of code to make it more efficient, etc.

This is true for any language, and it really depends on what type of software that you're writing. Haskell is a general-purpose language, so you're probably (correct me if I'm wrong) not making anything that needs to be extremely fast. If so, you should be using a lower-level language. If speed is an issue, but not enough that you should be using a low-level language, then you should be optimizing your performance based on the above.

Of course, everybody does things differently, so if your personal experience makes you think that you should be doing it differently based on your situation, then you probably should.


问:
Why would a developer create a public class that has all static properties?
A previous developer has a couple public classes that do not inherit from any other classes but are filled with static properties. Is this another way of creating a struct or enum? Is this an older or newer technique of housing static data to be referenced? I find it odd/different to see a class built in this way but am wondering what other fellow programmers thoughts or feelings are about what this coder was trying to accomplish.

This is a made up example of what I am seeing...

```<code>    public class CashRegister
    {
        public static decimal OneDollarBill
        {
            get { return (decimal)1; }
        }

        public static decimal TenDollarBill
        {
            get { return (decimal)10; }
        }
    }
</code>```

答:
As you said, this kind of a class can act like an enum, see the int enum pattern(seen at least in java before java introduced enums as their own class).

Another reason would be to group up all kinds of small utility methods, such as handling xml, constants and the like, especially if handling them in their languange of choice is verbose.

It could also just mean that the developer who wrote the code does not know how to/is not comfortable using enums.


答:
It's just a limitation of the human brain.  If people could think creatively as fast as they can type, they could crank out an average novel in two work days.  The main benefit of fast, reflexive typing for a programmer is that it gives you more time to think, and shorter interruptions.

As far as practicing your ability to think ahead while you type, it might be beneficial to take up a musical instrument.  Music has strict real-time deadlines for every note, and it's impossible to play correctly without reading at least one note ahead, or more, depending on how complex the music and the instrument is.

Aside from that, all you can really do is practice.


答:
It rather depends on what behaviour you're trying to access. Expounding on your previous example:

```<code>        if (Animal is Dog)
        {
            Dog d = (Dog)Animal;
            d.BuryBone();
        }
        else if (Animal is Cat)
        {
            Cat c = (Cat)Animal;
            c.DrinkSaucerOfMilk();
        }
</code>```

This is perfect if you're after dog or cat specific behaviour. Otherwise if you want to use the more general methods of the base class:

```<code>Animal.EatFood();
</code>```

Or if you've defined an interface:

```<code>IAnimal tiddles = new Cat();
IAnimal rex = new Dog();

tiddles.EatFood();
rex.EatFood();
</code>```

Title: Best way to check for specific types

Body:
It rather depends on what behaviour you're trying to access. Expounding on your previous example:

        if (Animal is Dog)
        {
            Dog d = (Dog)Animal;
            d.BuryBone();
        }
        else if (Animal is Cat)
        {
            Cat c = (Cat)Animal;
            c.DrinkSaucerOfMilk();
        }

This is perfect if you're after dog or cat specific behaviour. Otherwise if you want to use the more general methods of the base class:

Animal.EatFood();

Or if you've defined an interface:

IAnimal tiddles = new Cat();
IAnimal rex = new Dog();

tiddles.EatFood();
rex.EatFood();


答:
I'd like to add to Dynamic's answer:

Make your code modular and loosely coupled.

Hide implementation details of your modules.

When you realize later in development what bottlenecks your code has, it can be really painful to refactor the whole project. If your code is well structured, the bottlenecks are easier to find and to optimize/fix.

Title: When is it a good time to reason about performance in Haskell?

Body:
Simon Peyton Jones himself recognizes that reasoning about performance in Haskell is hard due to the non strict semantics.

I have yet to write a significant project in haskell so I wonder: can I reason about performance only at the beginning of a project (when choosing basic data structures & IO library) and whenever a problem arise, deal with it with the profiler?

To put it differently, is it possible (ie not too painful) to postpone dealing with performance when you have performance issues, or do you have to learn to predict how GHC will run your code (for exemple: infer what the strictness analyser will decide)?


答:
Bottom Line - You Can't So Don't Try

Syntax is not the same as "The lazy black dog jumped over the fence chasing a brown fox". You are comparing apples and oranges. Programming doesn't take place at the keyboard. Programming takes place at whiteboards, in discussions around the table, on napkins over lunch with a friend.

Most of the time you will spend as a programmer will be modifying code that has already been written and needs to have it's functionality extended. Typing speed is not a factor with regard to this type of work.

IMHO, you'd be better off and more valuable as an employee if you spent your time learning how to translate "geek speak" to non geeks.

For example: How would you describe a database to a non technical person?

Answer:

(seloh eibbuc otni ffuts tup uoy stel taht loot a si esabatad A)


问:
Domain Lookup API
I am looking to incorporate a domain name lookup facility in my website to make sure if a domain is available or not. The only api I could find on the net is http://www.domaintools.com/api/docs/domain-search/ . But this is paid. Is there any other api available which might be cheaper / free.

I am working with php, query.

答:
A domain is available or not may mean two different concepts

Domain is available for registration

Domain has a valid presence on DNS system (eg. has a website, can accept email etc.)

You mention about domaintools, hence probably you are interested in concept 1 mentioned above.

The most reliable way to find out whether a domain is available for registration or not is to query whois server for that TLD or ccTLD. Query to whois servers is always free. Although there may be strict limitations as to how many queries can be made per min/hour etc.

Finding out availability based on DNS is not reliable. It is possible that a domain may not have nameservers set with the registrars, in that case the response from DNS server would be "domain does not exists" though the domain is not available for registration.

ProgrammableWeb has a good collection of domain related apis here.

Title: Domain Lookup API


答:
Funny, I can't imagine why you'd use an enum if it's just human-readable representations of a variety of numbers.

Enums are good for a bunch of text values that don't have numeric representations.

```<code>public enum Days
{
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
    Sunday
}
</code>```

They're also good for enumeration maths (State = State ++). In C#, they've also been designed to handle flags easily.

But for what you're doing there, I much prefer a static class. Ultimately, it's no different, but it does express the fact that I'm not expecting it to be enumerable.

In your example, I'm more disturbed by the use of (decimal)1, which creates a constant int and casts it to a decimal, rather than 1M which would be a constant decimal.

Title: Why would a developer create a public class that has all static properties?

Body:
A previous developer has a couple public classes that do not inherit from any other classes but are filled with static properties. Is this another way of creating a struct or enum? Is this an older or newer technique of housing static data to be referenced? I find it odd/different to see a class built in this way but am wondering what other fellow programmers thoughts or feelings are about what this coder was trying to accomplish.

This is a made up example of what I am seeing...

```<code>    public class CashRegister
    {
        public static decimal OneDollarBill
        {
            get { return (decimal)1; }
        }

        public static decimal TenDollarBill
        {
            get { return (decimal)10; }
        }
    }
</code>```

Body:
Funny, I can't imagine why you'd use an enum if it's just human-readable representations of a variety of numbers.

Enums are good for a bunch of text values that don't have numeric representations.

public enum Days
{
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
    Sunday
}

They're also good for enumeration maths (State = State ++). In C#, they've also been designed to handle flags easily.

But for what you're doing there, I much prefer a static class. Ultimately, it's no different, but it does express the fact that I'm not expecting it to be enumerable.

In your example, I'm more disturbed by the use of (decimal)1, which creates a constant int and casts it to a decimal, rather than 1M which would be a constant decimal.


问:
When presenting a software design to upper management
I'm presenting a software design for approval today and as I'm going through the hundreds of pages of design documentation, cherry picking what's important, I'm unsure if I should start with the activity diagrams or use cases.  I was thinking of having it stacked like so:

Activities Diagrams

Use Cases Diagrams

Sequence Diagrams

Class Models

I've spent the last 7 months of my life creating this and I want it to be presented in the most logical order and done with.

答:
Depending on how technically inclined the audience is, you might want to leave some parts out, and add others. If you show them class models, will they understand? Will they care?

Most of the people that I work with who would count as "upper management" do not care very much about implementation details (it sounds like this is what your presentation focuses on), they mostly will care about:

introduction and general overview (what is the point of this system?)

high-level architecture (how is it built - at a high level?)

user stories (what can a user do with this system?)

data model (sometimes these are useful/necessary, but it depends on the project)

(I would run the presentation in that order as well)

Some members of the audience might care about the other types of diagrams (probably the use-case diagrams more than the others), and the diagrams can be useful in explaining other parts of the presentation, but I'm not sure I'd launch into them straightaway or make them the focus of the presentation.

Of course, if your audience is highly technical and want to see this kind of info, then go for it! But I'd still start off the presentation with some kind of general overview, just to give some context for the rest of the presentation.


答:
The upper management folk that I've met tend to be focused on

Will it do what I want/need?

When will I get it?

What are the risks involved?

and

Have you done your homework (and/or 'do you know what you are talking about?')

Showing them class models might be useful to show that you know what you're talking about, but beyond that you'll bore them to tears.  Not recommended.

Stick to a very high level overview, sound confident, and be prepared to back up anything with details.

Don't do any on-the-spot engineering.  You will get it wrong.  If asked a complex question, write it down and get back to them.

Title: When presenting a software design to upper management

Body:
I'm presenting a software design for approval today and as I'm going through the hundreds of pages of design documentation, cherry picking what's important, I'm unsure if I should start with the activity diagrams or use cases.  I was thinking of having it stacked like so:

Activities Diagrams

Use Cases Diagrams

Sequence Diagrams

Class Models

I've spent the last 7 months of my life creating this and I want it to be presented in the most logical order and done with.


答:
You should start with one diagram. What are the big parts of this software?

Talk about the responsibility of each at the high level, focus on tying in the boxes to their understanding of the business.

After the one high level diagram, I would get 1-2 layers more detailed. I would make sure that you take time to let people ask questions.

Do not try to let them get mastery of the design, sell them on the idea that you know what you're doing, and that more often involves making them know that you know the domain (what terms to use for each area, what insights relate between them). They often can't judge a software design or your technical skills.

If they think you know what you're doing, that's what will drive their approval more than any logical presentation.


答:
The only thing that occurs to me is reflection.  If you have a function somewhere that gets values using reflection, maybe a serilization function, it might make sense to do this.  While you can use reflection on a static class, you can't get an instance of it to pass around.

Note that while I am tossing this out as an answer, chances are that it is not /the/ answer.


答:
We actually have Google to thank for this.

Google was founded in 1998, but in 1999 they released PageRank which was a popular tool for checking the ranking of a site in Google's index. PageRank was this ambiguous number that represented the score of a URL compared to other URLs in Google's database.

When PageRank was released Google gave limited information on how their page ranking algorithm worked, but one thing they did state was that words in the URL were included in ranking.

Now when you search for content using Google. It will also highlight search terms in the URL as part of the results highlighting.

Thus was born human readable URLs. Everyone wanted to get a better ranking so all these cryptic query parameters were replaced with keywords.

We call them human readable but they are really web crawler readable.


问:
Which are the significant algorithms for humankind in past decades?
Which world most important algorithms have contributed most to humankind in past decades?

I thought this is a good general knowledge for a developer to know about.

Update:

If possible, please keep the answer to a specific programming algorithm.

I would like to get a list of the most important ones, only one algorithm per answer.

Please consider to state why the algorithm is significant and important...

答:
Data compression algorithms

In computer science and information
  theory, data compression or source
  coding is the process of encoding
  information using fewer bits (or other
  information-bearing units) than an
  unencoded representation would use,
  through use of specific encoding
  schemes.