问:
Trimming script size by using array notation for frequently accessed properties
I noticed some redundancy in a script I ran through Google Closure Compiler.

```<code>(function(){function g(a){var k;if(a){if(a.call)a.prototype=j,a.prototype[e]={}}else a=
{};var c=a,b,c=(a=c.call?c:null)?new a(a):c;b=c[e]||{};var f=b.extend;b=b.a;var
d=c.hasOwnProperty("constructor")?c.constructor:b?b:f?g.b(f):new Function;if
(f)b=d.prototype,k=new h(h.prototype=f.prototype),f=k,h.prototype={},d.prototype=f,i
(d.prototype,b);i(d,a);i(d.prototype,c);return d.prototype.constructor=d}function i(a,c)
{for(var b in c)c.hasOwnProperty(b)&&"prototype"!=b&&b!=e&&(a[b]=c[b])}var h=new Function,
e="decl-data",j={extend:function(a){return(this[e].extend=a).prototype},a:function(a)
{return(this[e].a=a).prototype}};g.c=function(a){e=a};return g})().b=function(g){return
function(){g.apply(this,arguments)}};
</code>```

It looks like a big sea of prototype and constructor, doesn't it?

I was was able to get it to about 6/7 of the size of the original by storing  "constructor" and "prototype" strings and using array notation everywhere to access prototypes and constructors. The size savings should grow as the size of the script grows. Here's what it looks like after the change:

```<code>(function(b,h){function i(a){a?a.call&&(a[b]=l,a[b][f]={}):a={};var d=a,c,d=(a=d.call?
d:null)?new a(a):d;c=d[f]||{};var g=c.extend;c=c.a;var e=d.hasOwnProperty(h)?d[h]:c?c:g?i.b
(g):new Function;if(g){c=e[b];var m=b,g=new j(j[b]=g[b]);j[b]={};e[m]=g;k(e[b],c)}k(e,a);k(e
[b],d);return e[b][h]=e}function k(a,d){for(var c in d)d.hasOwnProperty(c)&&c!=b&&c!=f&&(a
[c]=d[c])}var j=new Function,f="decl-data",l={extend:function(a){return(this[f].extend=a)
[b]},a:function(a){return(this[f].a=a)[b]}};i.c=function(a){f=a};return i})
("prototype","constructor").b=function(b){return function(){b.apply(this,arguments)}};
</code>```

Is it worth it to damage readability to save a few bytes? It's hard to know when to stop... hasOwnProperty only appears twice, I might use it once more. So, should I replace .hasOwnProperty with [_has]? Should I just stop here? Or should I put it back the way it was, and not worry about the few extra bytes?

On the other hand, maybe this doesn't damage readability at all, and could just be looked at as convenient shortcuts.

Another alternative would be abstracting the behavior using macros; write .prototype and have it converted to [_p] at build time, of course declaring _p somewhere. But that seems overly complicated for a relatively minor size optimization. Speaking of which, I wonder why closure-compiler doesn't do something like this already?

I'm curious what the community thinks about this.

For reference, the un-minified source before the size optimization:

```<code>var decl = (function(){

var Clone = new Function(), // dummy function for prototypal cloning
    /** dataKey

        The name of the property where declaration objects'
        metadata will be stored. If you want to pass objects to decl
        instead of functions, put the metadata (parent, partial, etc.)
        in this property.
    */
    dataKey = 'decl-data',

    /** proto

        This object is used as a prototype for declaration objects,
        so all properties are available as properties of `this`
        inside the body of each declaration function.

    */
    proto = {

      /** extend

          Perform prototypal inheritance by calling `this.extend(ParentCtor)`
          within your decalration function.

          @param {Function} ctor to extend.

          @return {Object} prototype of parent ctor.
      */
      extend: function (ctor) {
        return (this[dataKey].extend=ctor).prototype;
      },

      /** augment

          Finish a partial declaration.
          TODO: test for bugs, possibly retroactively fix child classes when augmenting parent.

          @param {Function} ctor to augment.

          @return {Object} prototype of partial ctor.
      */
      augment: function (ctor) {
        return (this[dataKey].augment=ctor).prototype;
      }

    };

/** decl

    Create a prototype object and return its constructor.

    @param {Function|Object} declaration
*/
function decl (declaration) {
  if (!declaration) {
    declaration = {};
  }
  else if (declaration.call) {
    declaration.prototype=proto;
    declaration.prototype[dataKey]={};
  }
  return getCtor(declaration);
}

/** setDataKey

    Sets the name of the property where declaration objects'
    metadata will be stored. If you want to pass objects to decl
    instead of functions, put the metadata (parent, partial, etc.)
    in this property.

    @param {String} String value to use for dataKey
*/
decl.setDataKey = function (value) { dataKey=value; };

/** clone

    Create a copy of a simple object.

    @param {Object} obj

    @return {Object} clone of obj.

*/
function clone (object) {
  var r=new Clone(Clone.prototype=object);
  Clone.prototype={};
  return r;
};

/** merge

    Merge src object's properties into target object.

    @param {Object} target object to merge properties into.

    @param {Object} src object to merge properties from.

    @return {Object} target for chaining.

*/
function merge (target, src) {
  for (var k in src) {
    if (src.hasOwnProperty(k) && k!='prototype' && k!=dataKey) {
      target[k] = src[k];
    }
  }
  return target;
};

/** getCtor

    Prepare a constructor to be returned by decl.

    @param {Function|Object} declaration

    @return {Function} constructor.

*/
function getCtor (declaration) {
  var oldProto,
      declFn = declaration.call ? declaration : null,
      declObj = declFn ? new declFn(declFn) : declaration,
      data = declObj[dataKey] || {},
      parent = data.extend, partial = data.augment,
      ctor =  // user-defined ctor
              declObj.hasOwnProperty('constructor') ? declObj.constructor :
              // ctor already defined (partial)
              partial ? partial :
              // generated wrapper for parent ctor
              parent ? decl.wrap(parent) :
              // generated empty function
              new Function();

  // If there's a parent constructor, use a clone of its prototype
  // and copy the properties from the current prototype.
  if (parent) {
    oldProto = ctor.prototype;
    ctor.prototype = clone(parent.prototype);
    merge(ctor.prototype, oldProto);
  }

  // Merge the declaration function's properties into the constructor.
  // This allows adding properties to `this.constructor` in the declaration function
  // without defining a constructor, or before defining one.
  merge(ctor, declFn);

  // Merge the declaration objects's properties into the prototype.
  merge(ctor.prototype, declObj);

  // Have the constructor reference itself in its prototype, and return it.
  return (ctor.prototype.constructor=ctor);
};

return decl;

}());

// This is outside of the main closure so wrapper functions
// will have as short a lookup chain as possible.

/** wrap

    Generate wrapper for parent constructor.

    @param {Function} parent constructor to wrap.

    @return {Function} child constructor.

*/
decl.wrap = function (parent) {
  return function(){ parent.apply(this, arguments); };
};
</code>```

And after:

```<code>var decl = (function(_p, _c){

var Clone = new Function(), // dummy function for prototypal cloning

    /** dataKey

        The name of the property where declaration objects'
        metadata will be stored. If you want to pass objects to decl
        instead of functions, put the metadata (parent, partial, etc.)
        in this property.
    */
    dataKey = 'decl-data',

    /** proto

        This object is used as a prototype for declaration objects,
        so all properties are available as properties of `this`
        inside the body of each declaration function.

    */
    proto = {

      /** extend

          Perform prototypal inheritance by calling `this.extend(ParentCtor)`
          within your decalration function.

          @param {Function} ctor to extend.

          @return {Object} prototype of parent ctor.
      */
      extend: function (ctor) {
        return (this[dataKey].extend=ctor)[_p];
      },

      /** augment

          Finish a partial declaration.
          TODO: test for bugs, possibly retroactively fix child classes when augmenting parent.

          @param {Function} ctor to augment.

          @return {Object} prototype of partial ctor.
      */
      augment: function (ctor) {
        return (this[dataKey].augment=ctor)[_p];
      }

    };

/** decl

    Create a prototype object and return its constructor.

    @param {Function|Object} declaration
*/
function decl (declaration) {
  if (!declaration) {
    declaration = {};
  }
  else if (declaration.call) {
    declaration[_p]=proto;
    declaration[_p][dataKey]={};
  }
  return getCtor(declaration);
}

/** setDataKey

    Sets the name of the property where declaration objects'
    metadata will be stored. If you want to pass objects to decl
    instead of functions, put the metadata (parent, partial, etc.)
    in this property.

    @param {String} String value to use for dataKey
*/
decl.setDataKey = function (value) { dataKey=value; };

/** clone

    Create a copy of a simple object.

    @param {Object} obj

    @return {Object} clone of obj.

*/
function clone (object) {
  var r=new Clone(Clone[_p]=object);
  Clone[_p]={};
  return r;
};

/** merge

    Merge src object's properties into target object.

    @param {Object} target object to merge properties into.

    @param {Object} src object to merge properties from.

    @return {Object} target for chaining.

*/
function merge (target, src) {
  for (var k in src) {
    if (src.hasOwnProperty(k) && k!=_p && k!=dataKey) {
      target[k] = src[k];
    }
  }
  return target;
};

/** getCtor

    Prepare a constructor to be returned by decl.

    @param {Function|Object} declaration

    @return {Function} constructor.

*/
function getCtor (declaration) {
  var oldProto,
      declFn = declaration.call ? declaration : null,
      declObj = declFn ? new declFn(declFn) : declaration,
      data = declObj[dataKey] || {},
      parent = data.extend, partial = data.augment,
      ctor =  // user-defined ctor
              declObj.hasOwnProperty(_c) ? declObj[_c] :
              // ctor already defined (partial)
              partial ? partial :
              // generated wrapper for parent ctor
              parent ? decl.wrap(parent) :
              // generated empty function
              new Function();

  // If there's a parent constructor, use a clone of its prototype
  // and copy the properties from the current prototype.
  if (parent) {
    oldProto = ctor[_p];
    ctor[_p] = clone(parent[_p]);
    merge(ctor[_p], oldProto);
  }

  // Merge the declaration function's properties into the constructor.
  // This allows adding properties to `this.constructor` in the declaration function
  // without defining a constructor, or before defining one.
  merge(ctor, declFn);

  // Merge the declaration objects's properties into the prototype.
  merge(ctor[_p], declObj);

  // Have the constructor reference itself in its prototype, and return it.
  return (ctor[_p][_c]=ctor);
};

return decl;

}('prototype', 'constructor'));

// This is outside of the main closure so wrapper functions
// will have as short a lookup chain as possible.

/** wrap

    Generate wrapper for parent constructor.

    @param {Function} parent constructor to wrap.

    @return {Function} child constructor.

*/
decl.wrap = function (parent) {
  return function(){ parent.apply(this, arguments); };
};
</code>```

答: Bear in mind that any decently configured server is going to send out the script using compression, which will cancel out the size savings for frequently used strings, but still leave the minor cost of execution and the significant cost of readability and maintenance.  So I would say its not worth it.</p>


问:
Are there good techniques or tests for naming types?
An awkward, open question, but it's a problem I'm always bumping against:

Software that's easy to maintain and work with is software designed well. Trying to make a design intuitive means naming your components in such a way that the next developer should be able to infer the function of the component. This is why we don't name our classes "Type1", "Type2", etc.

When you're modelling a real-world concept (e.g. customer) this is generally as simple as naming your type after the real-world concept being modelled. But when you're building abstract things, which are more system-oriented, it's very easy to run out of names which are both easy to read and simple to digest.

It gets worse (for me) when trying to name families of types, with a base-type or interface which describes what the components have to do, but not how they work. This naturally leads to each derived type trying to describe the flavour of the implementation (e.g. IDataConnection and SqlConnection in the .NET Framework), but how do you express something complicated like "works by reflection and looking for a specific set of attributes"?

Then, when you've finally picked a name for the type you think describes what it's trying to do, your colleague asks "WTF does this DomainSecurityMetadataProvider actually do?"

Are there any good techniques for choosing a well-meaning name for a component, or how to build a family of components without getting muddled names?

Are there any simple tests that I can apply to a name to get a better feel for whether the name is "good", and should be more intuitive to others?

答:
Using a thesaurus

Very often I will refer to a thesaurus when doing new development in order to find appropriate words to describe my classes and methods.

Classes that primarily contain operation logic

I tend to name classes that primarily provide operation methods in a noun-verb structure such as "EntityProvider", "EntityLocator", etc.

These classes generally don't contain a lot of state.

Classes that contain state

UI screens and data entities are generally stateful, and so I simply name these classes with a noun or adjective-noun pattern.

Examples:  Person, Employee, CurrentEmployee, FormerEmployee

Utility classes

Classes that only contain static methods are generally considered "utility" classes, so I consistently name them with a "Utility" suffix.

Examples:  NetworkUtilities, FileUtilities

Tests

I don't have any good tests for deciding whether something is poorly named, but I would suggest to try to use a single noun and/or a single verb in the name, then think about whether that noun/verb accurately describes what you're naming.

If you feel that there is more to the class/method that is not captured by the name, then that class/method might need to be refactored.

Alan Green and Jeff Attwood have written about the evils of naming classes with the "Manager" suffix.  They argue that the term "Manager" is overused and is too vague to convey anything meaningful.  I have to agree.

Jeff's article also provides a list of suggested guidelines from Steve McConnell's Code Complete.

variables

Recently I've been experimenting with longer descriptive variable/parameter names that incorporate prepositions, such as "Of", "By", "For", etc.  Some examples are shown below:

```<code>string firstNameOfEmployee;

string lastNameOfEmployee;

// here I nimbly avoid worrying about whether to call it "Id" or "ID" :)
int idOfEmployee;

decimal amountForDeposit;

Account accountForDeposit;
</code>```

I find that this works fine with Visual Studio's intellisense feature making it easy to type these long names.  I also find that there is less duplication of variable name prefixes (e.g. personID, personFirstName, personLastName vs. idOfPerson, firstNameOfPerson, lastNameOfPerson), providing a better "hash" that makes intellisense even more useful.

ContentLicense: CC BY-SA 3.0

Body:
Using a thesaurus

Very often I will refer to a thesaurus when doing new development in order to find appropriate words to describe my classes and methods.

Classes that primarily contain operation logic

I tend to name classes that primarily provide operation methods in a noun-verb structure such as "EntityProvider", "EntityLocator", etc.

These classes generally don't contain a lot of state.

Classes that contain state

UI screens and data entities are generally stateful, and so I simply name these classes with a noun or adjective-noun pattern.

Examples:  Person, Employee, CurrentEmployee, FormerEmployee

Utility classes

Classes that only contain static methods are generally considered "utility" classes, so I consistently name them with a "Utility" suffix.

Examples:  NetworkUtilities, FileUtilities

Tests

I don't have any good tests for deciding whether something is poorly named, but I would suggest to try to use a single noun and/or a single verb in the name, then think about whether that noun/verb accurately describes what you're naming.

If you feel that there is more to the class/method that is not captured by the name, then that class/method might need to be refactored.

Alan Green and Jeff Attwood have written about the evils of naming classes with the "Manager" suffix.  They argue that the term "Manager" is overused and is too vague to convey anything meaningful.  I have to agree.

Jeff's article also provides a list of suggested guidelines from Steve McConnell's Code Complete.

variables

Recently I've been experimenting with longer descriptive variable/parameter names that incorporate prepositions, such as "Of", "By", "For", etc.  Some examples are shown below:

string firstNameOfEmployee;

string lastNameOfEmployee;

// here I nimbly avoid worrying about whether to call it "Id" or "ID" :)
int idOfEmployee;

decimal amountForDeposit;

Account accountForDeposit;

I find that this works fine with Visual Studio's intellisense feature making it easy to type these long names.  I also find that there is less duplication of variable name prefixes (e.g. personID, personFirstName, personLastName vs. idOfPerson, firstNameOfPerson, lastNameOfPerson), providing a better "hash" that makes intellisense even more useful.


问:
How to avoid "DO YOU HAZ TEH CODEZ" situations?
I have a strange situation at work, where a colleague of mine often asks me and other co-workers for working code.

I would like to help him, but this constant request of trivial snippets interrupts my thoughts and sometimes makes it hard to concentrate.

Plus, I have the impression (...) that this requests are generated by lack of competence, more than by laziness. In fact, he often asks things pretending to know the answer, since when I solve the problem he usually says things like "Sure", "Yes, that's what I thought", giving me the impression that my answer isn't worth it.

How can I solve this embarrassing situation?

Should I show more explicitly in front of other colleagues his lack of knowledge (by saying things like: "do it yourself if you can, please") or continue giving him what he wants?

I think that he should aggregate all his questions in one, so that I can give him a portion of my time and he can work all by himself on his things.

There is no hierarchy in the team, I must say we both have a similar seniority of five years, more or less. For the same reason I believe I cannot report to management, since trivial questions are often ignored.

I discussed with other two members and they agree with me: in fact he often ask things cycling through colleagues.

答:
I know exactly how you feel, i have been in this situation before. It's just role playing and manipulation. It usually happens for many reasons :
- That person doesn't know the answer, is incompetent and doesn't want to come up as incompetent, hence the that's what i thought.
- If that person is asking you dumb question in front of people, and answering them right after, he might try to put you in the incompetent place, or playing games on you (the work place is full of that type of people, trying to climb on top of you).
- That person is lazy and wants you to do his job for him.
- That person is the "by hear" type of guy which means he can reproduce a sample of code but cannot adapt it because he doesn't understand how it works, just where to use it.

The good approach IMO is just to tell that guy, sorry pal, you're on your own now, you're going to have to figure it out yourself this time, I've got things to do. If the problem persists, talk to your manager about it (i know stooling is not the best but hopefully you have a competent manager that has seen snowing before :) )


问:
Is it possible to automatically convert code from a low level language to a high level language?
I have seen several applications that claim to convert Java code to valid C or even C++. Converting from a high level language to a low level language is possible, no doubt about it. At least in theory, can the reverse be done without any manual steps?

For instance:

Converting Assembly to C or Machine Code to Assembly?

Hardware Description Languages (HDL) to Assembly? (which ever is lowest?)

C to C#?

答:
Theoretically it's possible to write a compiler from any Turing complete language to any other Turing complete language.

Practically, going from a lower level language to a higher level one will be highly problematic, as you are going towards higher abstraction and that usually requires humans. Think of how there isn't a "correct" approach in object orientation...

For similar level languages, it's a little bit easier, checkout code2code which translates C++ code translates C# & VB.NET. And since some C++ code is valid C code, you can say that it also translates C to C#, to a certain extend.


答:
I would consider most of the answers, even having a conversation with them, an "Escalation" whereas my first response would be something along the lines of offering to pair with them.  At this point you have offered help and if they refuse it you can escalate with a clear conscience. If they do pair with you then you can evaluate their actual competence level.

The thing is, if one person writes a library it's completely acceptable to ask them to write code that interfaces with it--at least as a test.  There are other examples that are less obviously acceptable but still questionable--like where someone thinks you have already worked through a problem and still might have the resultant code handy.

If they are actually asking you to do their job, it's STILL reasonable to ask to pair, in fact it's a good suggestion if you are stumped and it's a great way to learn.

If they are not interested in pairing then I'd happily go on to any of the other solutions here--in fact depending on their reaction I might skip discussing it with them and go straight to the manager (with not only their request for your help but an indisputable assertion that you offered help and found that what they REALLY wanted was more than just help)

Title: How to avoid "DO YOU HAZ TEH CODEZ" situations?

Body:
I have a strange situation at work, where a colleague of mine often asks me and other co-workers for working code.

I would like to help him, but this constant request of trivial snippets interrupts my thoughts and sometimes makes it hard to concentrate.

Plus, I have the impression (...) that this requests are generated by lack of competence, more than by laziness. In fact, he often asks things pretending to know the answer, since when I solve the problem he usually says things like "Sure", "Yes, that's what I thought", giving me the impression that my answer isn't worth it.

How can I solve this embarrassing situation?

Should I show more explicitly in front of other colleagues his lack of knowledge (by saying things like: "do it yourself if you can, please") or continue giving him what he wants?

I think that he should aggregate all his questions in one, so that I can give him a portion of my time and he can work all by himself on his things.

There is no hierarchy in the team, I must say we both have a similar seniority of five years, more or less. For the same reason I believe I cannot report to management, since trivial questions are often ignored.

I discussed with other two members and they agree with me: in fact he often ask things cycling through colleagues.


问:
Should I go with PHP.NET and Resharper or PHPStorm
I am a fairly adept .NET and PHP programmer. These days my pattern of choice for complex web apps is an SOA approach where I use PHP as the front end, and WCF web services as the middle tier. My ajax calls are usually to JSON webHttpBinding WCF endpoints. On the .NET side of things I am absolutely in love with the Visual Studio plugin ReSharper.

So my question is as follows, I want to rethink my tool chain on the PHP side of things. On one side JetBrains, the makers of Resharper, have a PHP IDE called PHPStorm. On the other side, I can use VS.PHP and ReSharper. Does anyone use the later combination fo VS.PHP and Resharper? Can you recommend it?

答:
Since you're also working with WCF Web Services, I'd recommend you stick with Visual Studio.

I've done quite a bit with that platform and it works well.  PHP Storm is probably very nice, but it's going to cost extra and be a new environment that you'll have to get used to.  If it's not broke, don't fix it :)

ContentLicense: CC BY-SA 2.5


答:
Not much. Translating from a higher-level language to a lower-level language means re-implementing all of the higher-level language features using only those features available in the lower-level language. This is basically what a compiler does. Eg. one line might become many, many assembly language instructions.

If you're translating from a lower-level language to a higher-level language you can either (a) just implement exactly the same program in the higher-level language -- eg. translate a compiled machine language program into a sequence of python commands for "model registers using these variables, load this value into this register, add these registers, store this value, jump to line xxx" etc etc which is pretty useless. (For instance, almost all C programs are already valid C++ programs, or very nearly so, just without using any of the features that making using C++ useful).

Or (b) try to guess what original language features were translated into the lower-level language. If the lower-level language was originally compiled, this can be somewhat successful: the decompiler looks for the sorts of code compilers usually generate, and guesses what the original code may have been. An example picked off google: http://boomerang.sourceforge.net/cando.php.

However, that only applies if it was originally compiled from that higher level language using a known compiler in the first place (or written by hand using many idioms which have corresponding language features).

If you have a pile of C code and you want to convert it to C++ code, you need to make value decisions about which bits of the code will be extensible, which functions should be grouped into classes, how to avoid global state, etc, etc, which is what programmers do, and can't be immediately automated.

Title: Is it possible to automatically convert code from a low level language to a high level language?

Body:
I have seen several applications that claim to convert Java code to valid C or even C++. Converting from a high level language to a low level language is possible, no doubt about it. At least in theory, can the reverse be done without any manual steps?

For instance:

Converting Assembly to C or Machine Code to Assembly?

Hardware Description Languages (HDL) to Assembly? (which ever is lowest?)

C to C#?


答:
Although it's possible, it's likely that the "lifting" compiler will end up generating code whose structure emulates the programming model of the lower-level language. Thus, you will end up with "COBOL in Haskell" or "ASM in Java" or what-have-you, and it will be more complex and less efficient than your lower-level language.

For instance, if the lower-level language has explicit memory management and your higher-level language does not, you cannot just throw away the frees -- perhaps the behavior of the underlying program depends upon determinism. So you would have to model, in your high-level language, the memory model of the low-level language (yuck). Similarly, if the lower-level language has arbitrary gotos a la JMP you'd have to generate high-level code where such gotos could be executed (arbitrary function boundaries).

The reason that decompilers do not face this problem is that they are not really working with the complete capabilities of the underlying machine code unless they are on a VM that happens to be very tightly coupled to a language's programming model.


问:
How to correctly chain overloaded functions?
Assuming you have functions which take an increasing number of optional parameters (and a pseudo language which does not allow optional parameters and an arbitrary number of parameters) like this:

```<code>function doStuff(Param a)
function doStuff(Param a, Param b)
function doStuff(Param a, Param b, Param c)
</code>```

What is a good way to unify them to a single call? I can imagine two designs:

Fall through everything:

```<code>function doStuff(Param a)
    doStuff(a, defaultB)

function doStuff(Param a, Param b)
    doStuff(a, b, defaultC)

function doStuff(Param a, Param b, Param c)
    // magic goes here
</code>```

The Upside: Not much code duplication, easy changing of a single default parameter.

The Downside: Many function calls, might render Stacktraces harder to read or useless.

Or directly call the 'last' function:

```<code>function doStuff(Param a)
    doStuff(a, defaultB, defaultC)

function doStuff(Param a, Param b)
    doStuff(a, b, defaultC)

function doStuff(Param a, Param b, Param c)
    // magic goes here
</code>```

The Upside: Not many function calls, not worries if a new function is added into the chain.

The Downside: Much code duplication, especially the default values.

What did I not think of?

答: I prefer the first method.  The possibility of duplicated default values all over the place can severely reduce maintainability. I've encountered that specific issue in the wild, and it was a nightmare.</p>

OwnerDisplayName: Bobby


答:
I would opt for the second paradigm (directly calling the "last" function.). This is fine, and it does not constitute real code duplication, because it does not involve manipulation of any kind of state.

It also helps to realize that what you are doing by providing multiple overloads is simply a trick just so as to provide the illusion of optional parameters. Once you see it this way, it becomes obvious that the "last" and only the "last" method is the one which is supposed to do any real work, so any delegation among the non-last methods is just pointless.

Personally, I do not have to worry about this problem anymore, because I am using C#, which supports optional parameters, thus sparing me from having to do tricks like these in order to emulate them.

Title: How to correctly chain overloaded functions?

Body:
Assuming you have functions which take an increasing number of optional parameters (and a pseudo language which does not allow optional parameters and an arbitrary number of parameters) like this:

```<code>function doStuff(Param a)
function doStuff(Param a, Param b)
function doStuff(Param a, Param b, Param c)
</code>```

What is a good way to unify them to a single call? I can imagine two designs:

Fall through everything:

```<code>function doStuff(Param a)
    doStuff(a, defaultB)

function doStuff(Param a, Param b)
    doStuff(a, b, defaultC)

function doStuff(Param a, Param b, Param c)
    // magic goes here
</code>```

The Upside: Not much code duplication, easy changing of a single default parameter.

The Downside: Many function calls, might render Stacktraces harder to read or useless.

Or directly call the 'last' function:

```<code>function doStuff(Param a)
    doStuff(a, defaultB, defaultC)

function doStuff(Param a, Param b)
    doStuff(a, b, defaultC)

function doStuff(Param a, Param b, Param c)
    // magic goes here
</code>```

The Upside: Not many function calls, not worries if a new function is added into the chain.

The Downside: Much code duplication, especially the default values.

What did I not think of?


问:
How is Python used in the real world?
I'm looking to get a job as a Python programmer. I know the basics of the language and have created a few games with it using pygame. I've also started to experiment with Django.

However, looking at the job market, it doesn't seem very many Python jobs are web-related. On the desktop side of things, it doesn't seem like very many companies use the popular GUI libraries like pyQt or wxPython.

How are companies actually using Python? What areas should one focus on to land a job as a Python programmer?

答: Python is used everywhere in the modern world. Dropbox was written in Python and like vartec said it is a general purpose langauge. To get a better idea of what python has been used for before and can do give sourceforge a look at http://sourceforge.net/directory/os:mac/?q=Python. As for your part about finding a job as a python programmer just look around. Many startups are hiring Python developers at least the ones I know of.</p>

Title: How is Python used in the real world?


答:
Python is widely used on the server side. This of course mostly includes web apps, though other kinds of servers exist. (Some keywords to google: Django, Pyramid, Zope, Twisted.)

Python is rather widely used for scripting. This includes various testing / building / deployment / monitoring frameworks, scientific apps and just quick scripts.

Python is rather widely used as embedded language. See e.g. Maya, Blender, various games.

Few (if any) desktop apps are commercially developed in Python. Open-source desktop apps written in Python are abundant, though, and can serve as examples (but usually will not give you a paying job).

Title: How is Python used in the real world?

Body:
I'm looking to get a job as a Python programmer. I know the basics of the language and have created a few games with it using pygame. I've also started to experiment with Django.

However, looking at the job market, it doesn't seem very many Python jobs are web-related. On the desktop side of things, it doesn't seem like very many companies use the popular GUI libraries like pyQt or wxPython.

How are companies actually using Python? What areas should one focus on to land a job as a Python programmer?


问:
How do I learn Python from zero to web development?
I am looking into learning Python for web development.

Assuming I already have some basic web development experience with Java (JSP/Servlets), I'm already familiar with web design (HTML, CSS, JS), basic programming concepts and that I am completely new to Python, how do I go about learning Python in a structured manner that will eventually lead me to web development with Python and Django?

I'm not in a hurry to make web applications in Python so I really want to learn it thoroughly so as not to leave any gaps in my knowledge of the technologies involving web development in Python. Are there any books, resource or techniques to help me in my endeavor? In what order should I do/read them?

UPDATE:

When I say learning in a structured manner, I mean starting out from the basics then learning the advanced stuff without leaving some of the important details/features that Python has to offer. I want to know how to apply the things that I already know in programming to Python.

答:
I also would like to recommend the Python Koans for learning: http://github.com/gregmalcolm/python_koans

They are pretty similar to the Ruby Koans (a lot of it was directly ported) and are pretty cool.


问:
Example of time-saving usage of compile-time meta-programming?
The webpage of Converge states that:

Converge has a macro-like facility that can embed domain specific languages with arbitrary syntaxes into source files.

I am most intrigued by the possibility to create domain specific languages. My understanding of the purpose of such languages, is that they enables the developer to become much more efficient when solving domain specific problems.

So, I went on to read the "about" section. There are two examples of usage here, but none of them describe how the developer could save development-time by utilizing Converge. Can anyone come up with an example or refer me to an example? I am happy to read examples in other languages than Converge.

答:
I can't speak specifically of Converge, but I regularly use the D Programming Language which has very strong meta-programming features.

Here's an example of D library for units of measurement. The programmer can write:

```<code>auto dist1 = Meters(5.2);
auto velocity = dist1 / Seconds(2.1);
auto kmPerSecond = cast(Kilometers)velocity;
</code>```

By using the type-system to create a DSL, the programmer is freed from juggling unit conversions and ensuring that operations make sense (e.g. time + distance would be an error).

Another (old) D example is the Blade library. This library is capable of parsing algebraic expressions at compile-time and generating very precise, fast assembly. For a programming who needs the speed, this sort of thing is a real life-saver.

Finally, check out Ruby on Rails if you haven't already. The whole thing is a giant DSL, though not a compile-time one.

Body:
I can't speak specifically of Converge, but I regularly use the D Programming Language which has very strong meta-programming features.

Here's an example of D library for units of measurement. The programmer can write:

auto dist1 = Meters(5.2);
auto velocity = dist1 / Seconds(2.1);
auto kmPerSecond = cast(Kilometers)velocity;

By using the type-system to create a DSL, the programmer is freed from juggling unit conversions and ensuring that operations make sense (e.g. time + distance would be an error).

Another (old) D example is the Blade library. This library is capable of parsing algebraic expressions at compile-time and generating very precise, fast assembly. For a programming who needs the speed, this sort of thing is a real life-saver.

Finally, check out Ruby on Rails if you haven't already. The whole thing is a giant DSL, though not a compile-time one.


答:
There is an important difference between converting to a high-level language from something that has been written manually vs. from something that has been generated automatically.

In the first case, little, if anything, is there to direct your reverse translation, so your translator will be "writing Fortran programs in (some other) language".

The second case is different, though: compilers leave behind enough "marks" to make reverse translation a possibility. For instance, you can examine binary code generated from C++, and figure out a lot of things about the classes from which the code has been generated:

You can learn the layout of the fields in a class by examining code that accesses a class

You can find virtual functions of the class by examining vtables

You can find member functions by un-mangling the names from the .o files

You can make educated guesses about constants that were defined in a class

You can translate expressions back to a human-readable form, perhaps with fewer or more sets of parentheses

You can detect uses of common STL containers expanded from templates

Granted, the result will never be identical to the original source, because nice things such as comments and names of local variables are irretrievably lost. But you would definitely get something better than a piece of assembly written out using the C++ syntax.


问:
Find all points within a certain distance of each other?
Let's say, we have... 50k points randomly allocated in 3D space, according to some volumetric function, so that in some parts of the space, points are closer together, but in other parts, they are further away. Every point has a random color (represented by an integer, for example)

I would like to find all points that:

Are within a certain (general) distance of each other, and

are of different color.

What is the fastest way to compute this?

Further, non-mandatory details:

My end goal, is to remove all points with the same color, until there are no more collisions. I would like to remove as few colors as possible, however, this is not mandatory I could simply remove all colors that are involved in any collisions AT ALL, though, it could result in a lower quality result.

The distance does not need to be exact. For instance, if an exact "collision radius" represents a perfect sphere, then I would be fine with the collision radius being the shape of, say, a cube. I am also fine with a trigger-happy solution. That is, I am fine if points get "detected" even if they are not too close. I just don't want this to happen very often, and I cannot accept points that are to close not being detected.

Also, I'm sure there is a family of algorithms devoted to this, but I can't for the life of me come up with any names... Knowing the name of an algorithm of this type would be immensely helpful.

答:
We'll start approaching your problem from the 'points are close' requirement, and check the colors after.

KD-trees are probably the best choice for you. You can build one in O(n log n) time (O(n log^2 n) using a simpler approach) on your points, after which you can answer questions 'give me the points at least this distance from this point' (a 'nearest neighbours' query) in O(k + log n) time, where k is the number of points returned. You can then run through these points and check their colors in O(k^2) time (you can get this down to O(k log k) if needed). This gives a total running time of O(n k log k + n log n) time.

If your data points are also moving around (they change their locations), then octrees are probably the best. KD-trees are quite bad at handling a mix of data changes and nearest neighbour queries. Do make sure you don't happen to hit the worst-case of octrees though: make sure you understand how they work and when they break, as you might just have points that are distributed in a bad way for octrees.

If you're feeling particularly algorithmic, you could even try to employ locality-sensitive hashing, but the above are probably easier and better.

You could also approach this problem starting from the colors. If it is rare that two points share the same color, you could also use an algorithm to find the points with the same colors, and then check the distances between these points to see if they need removing.

Analysis: sort-based duplicate finding gives you a O(n log n) first step (possibly improvable to O(n)), and then an O(n k^2) step to compare the distances between all colored nodes.

If k is very small, that's very efficient. For moderately large k (k > 100 probably) you could improve the performance of the last step by building a KD-tree for those equal-valued colors exactly as I described at the start, reducing the run time of the second bit to O(n + k (l + log k)) (where l is the number of nodes returned per nearest neighbour query).

You can even adapt this approach to moving points: build a binary tree (or a hashmap if you like them) containing octrees of points of the same color: inserting a new point then takes O(log n + log k) expected time.


问:
What method is the easiest/fastest way for developing Android Apps
Which one of these is the easiest/fastest choice for developing simple Android apps/games? I'm familiar with all this technologies.

```<code>   • Android SDK or NDK
   • C# on MonoDroid platform
   • Adobe Flash & Adobe AIR
   • Corona SDK
   • Converting tools like PhoneGap
</code>```

Fundamentally, Could you explain adventages and disadventages of this methods.

答:
Despite the Android ecosystem accepts other frameworks and embrace that(the Android market doesn't forbide the use of other API's), i suggest you use the native SDK/NDK for Android, not just because they're the original tools, but for the power to develop easily anything you need. For example: using RhoStudio allows you build iOS, Android, WP7 and BlackBerry apps using the same source code, however, you are so tightly constrained to use the UI the framework generates.

In the case of Adobe Air, i think you're adding an extra layer of complexity and moreover, their performance is something we should really consider to bring a better experience.

If you are proficient using Java, you should give a try. There are a strong Android community of developers looking to help.


问:
Interesting or unique types in programming languages?
We have all seen integer, floating point, string, and the occasional decimal type. What are some of the most strange or unique or useful types you have encountered, useful or not?</p>

答:
Felix has anonymous sum types. The type is written like:

```<code>typedef il = int + long;
</code>```

as it would be in theory. The values are ugly:

```<code>case 0 of il (1)
case 1 of il (2L)
</code>```

except perhaps for a unit sum such as  3 = 1 + 1 + 1

```<code>case 0 of 3
case 1 of 3
</code>```

which unfortunately uses zero origin counting for "C compatibility". Anonymous sums are necessary for structurally typed algebraic types, for example:

```<code>(1 + T * li) as li
</code>```

is a (singly linked) list of T. All other languages I know of required nominally typed sums, where both the type itself and the constructors must be given names.

The shorthand 3 used above is cute, the following is in the library:

```<code>typedef void = 0;
typedef unit = 1;
typedef bool = 2;
</code>```

and this notation:

```<code> T ^ 3
</code>```

is an array of static length 3 .. the 3 is not an integer but a sum of 3 units. What a pity + is not associative :)

Body:
Felix has anonymous sum types. The type is written like:

typedef il = int + long;

as it would be in theory. The values are ugly:

case 0 of il (1)
case 1 of il (2L)

except perhaps for a unit sum such as  3 = 1 + 1 + 1

case 0 of 3
case 1 of 3

which unfortunately uses zero origin counting for "C compatibility". Anonymous sums are necessary for structurally typed algebraic types, for example:

(1 + T * li) as li

is a (singly linked) list of T. All other languages I know of required nominally typed sums, where both the type itself and the constructors must be given names.

The shorthand 3 used above is cute, the following is in the library:

typedef void = 0;
typedef unit = 1;
typedef bool = 2;

and this notation:

 T ^ 3

is an array of static length 3 .. the 3 is not an integer but a sum of 3 units. What a pity + is not associative :)


答: I work as a Python developer at a data mining and aggregation company focusing on the Insurance industry.  We have a large internal Python application that has both web and data manipulation pieces.  The company is extremely happy with the language, especially the fact that it allows us to be very fast as developers adding new features to the software.  A lot of companies that deal with data manipulation and process tracking use python for these tools.  It is internal usually, and it is not glamorous, but the work is definitely there.</p>

Title: How is Python used in the real world?


答:
In company I work for (80K employees) we use Python for:

test automation

some scripts where shell scripts will be too complicated

build environment

and silently... for fun :-)

Title: How is Python used in the real world?


问:
Does long term programming affect writing in a native spoken languages?
So, I am getting some years under my belt in long term programming.  I have noticed, however, when the frequency and duration started increasing in my coding sessions that when I actually went to write a paper, email, document, or anything else that required writing more than a few sentences that my writing quallity appeared to suffer.  I started forgetting the basic rules and vocabulary of written English.

I am now going back for my Masters and find that writing papers does not come as easy as it used to.  I remember thinking to myself how my Creative Writing class back in my freshman year of college helped a great deal in writing for my other classes.  Hate to say it, but it feels like I could use a refresher.  Also, my hand writing has especially not got any better!  I feel inclined to say it's a side-effect of long term programming but want know any if real studies have been done or just from personal experience from programmers.

答:
Isn't it the same as asking "does long term programming affect your ability to do Calculus" or "does long term Calculus affect writing in a native spoken language".

We get good at things the more we practice those things. And conversely, if we stop doing something, over time our skills worsen at doing that task.  You probably used to write a lot more papers than you do now, and therefore, in the past you used to be better at it.

I have forgotten 98% of Calculus but I don't think I would put the blame on being a programmer for the last 13 years.


答:
This question made me laugh, because as soon as I saw it, I thought of myself. I have developed (as in written code) several times weekly for about three years now.

My world generally consists of diagrams, code structures, project plans, and sentence-long emails. Hopefully, studies will be done on this subject, but I can definitely say that my writing has suffered, especially since my college days. I now experience hand cramps within 15 minutes of starting a hand-written document, but can endure hours on a keyboard. I make a lot of spelling mistakes, make some poor (and childish) word choices, and generally struggle to churn out a few paragraphs.

As developers, we just don't need to actually write things down when we can do it a hundred times faster on a computer, and in addition, use such a limited vocabulary. Getting into the habit of forcing handwritten notes and keeping up the practice will ensure that we don't turn into keyboard monkeys.

Title: Does long term programming affect writing in a native spoken languages?

Body:
So, I am getting some years under my belt in long term programming.  I have noticed, however, when the frequency and duration started increasing in my coding sessions that when I actually went to write a paper, email, document, or anything else that required writing more than a few sentences that my writing quallity appeared to suffer.  I started forgetting the basic rules and vocabulary of written English.

I am now going back for my Masters and find that writing papers does not come as easy as it used to.  I remember thinking to myself how my Creative Writing class back in my freshman year of college helped a great deal in writing for my other classes.  Hate to say it, but it feels like I could use a refresher.  Also, my hand writing has especially not got any better!  I feel inclined to say it's a side-effect of long term programming but want know any if real studies have been done or just from personal experience from programmers.


问:
Time complexity of a nested loop where the inner value is decreased in every step
I have problems to give the right time complexity in O notation for the following loop:

```<code>k := 0
for i := 0 to N
   for j := k to M
     // something
   k = k + 1
</code>```

Where N = M. Without the modified starting value of j of the inner value this would be of course O(N * M), but with the decreasing running time of the inner loop in every step of the outer loop I am quite confused. How can this be approached?

答: The decreased running time isn't enough to change the time complexity- the inner loop still runs in O(M).</p>


问:
How to store personal information properly?
It's not about security or something. There is a table to record user information, like username, password, postcode and so on, one record per person. There is also a table called post to record the posts the users posted. It's very easy to set a relation to identify the user who posted the post. But think of this situation, how to store the posts that has been read by a user? If use many-to-many relation, the table will increase to very huge size. What's more, there's a lot things to record, I just take one of them for example. I call this personal information. The problem is how should I store it properly?</p>

答:
to solve your read posts issue you should use a mapping table that links a post and a user, then insert a record for each post read by each user. Creating a mapping table is the basic strategy to resolve many to many relationship issues.

Databases can grow large, but if you design properly you can limit repeated data and use the smallest necessary data type to conserve disk space, also disk space is one of the cheapest parts of hosting a website so database getting large isn't a huge problem. You can also implement policies to help limit the size of your database, things like deleting a user after X months of no activity, or only storing history for the previous X months.

If you want to know how to design a table to properly store all this information you should read up on database normalization. If you are wondering how to store the information securely you should read up on encryption and hashing, and only stored hashed or encrypted values for sensitive information like a password.


答:
I don't know of any formal studies of the effects of programming language usage on native language competency, but I can share anecdotal evidence and pet theories.

First off, even speaking more than one natural language has interesting side effects. If, for instance, I were to travel to France, speak only French for several years, and return to the United States, I would likely find myself thinking in French and having to correct my English occasionally.This has actually happened to me following vacations in Quebec.

Programming languages don't correlate well to natural languages, due to the fact that they are designed to perform a task and/or to represent specific types of data and relationships between/operations on said data. Natural languages evolve organically and deal with much fuzzier concepts than programming languages, generally speaking.

As far as things like punctuation, there are quirks programmers tend to develop, e.g. putting punctuation like periods and commas outside of punctuation marks. Why do we do this? Flow control (periods, commas) shouldn't be embedded in a string literal.

I think if programming impacts natural language use, it's because programming changes how you think. We tend to want to be more precise than natural languages generally allow for. We get frustrated by ambiguity because it causes compiler warnings in our brains.

I wouldn't say it's a good thing or a bad thing necessarily; but there's a reason certain stereotypes about programmers exist, such as:

We are terrible at writing documentation

We are bad a communicating with non-technical people

We tend toward tunnel-vision and don't like context-switching

Of course, these are stereotypes and not universal truths, but stereotypes start somewhere. My explanation for these boils down to "it's not a bug, it's a feature!"

Taken one at a time:

We don't write good documentation because:
1) it takes time away from writing code,
2) our code should be 'self-documenting', and
3) that's a job for a technical writer, not a programmer.

We don't communicate well with non-technical people because we are good at what we do and thus don't think like non-technical people any more.

We tend toward tunnel-vision because closures and lexical scoping are very good things, and context-switching is expensive.

So, I'm not sure if this is helpful, but it's something I've considered myself in the past. As far as a solution to your problem? Don't hold your English to the same standard as your code. It's not like you can write unit tests for your term papers. Do your best, use spelling and grammar checkers, find a peer to proofread before you submit, and if you get stuck, there's always https://english.stackexchange.com/


答:
The number of records will grow very large, but the amount of data per row will be very small. Each time an article is read a user_number reads an article_number at timex.

This table will allow you to know how many different people read the article, the number of reads per day, the number of articles read by the average user...

Don't store the user name, or the article title, or anything else. These names/title are not constant; so if the title is edited in the article table, there will be a mismatch with the data in the articles read table.

also checkout https://dba.stackexchange.com/faq

Title: How to store personal information properly?

Body: It's not about security or something. There is a table to record user information, like username, password, postcode and so on, one record per person. There is also a table called post to record the posts the users posted. It's very easy to set a relation to identify the user who posted the post. But think of this situation, how to store the posts that has been read by a user? If use many-to-many relation, the table will increase to very huge size. What's more, there's a lot things to record, I just take one of them for example. I call this personal information. The problem is how should I store it properly?</p>


问:
Years experience over unfinished degree?
I'm currently in my placement year and working for a great software development company. It was always my intention of getting to this stage through university, getting enough academic experience as well as the year’s placement and then try to get a full time programming job without the need to finish my degree. I decided this from an early stage as I have never really liked the whole university environment. I was so unhappy at university and I’m so happy now I’m on my placement year, I really don’t know if I can go back.

My question is, do you think companies will take me on if I apply for other jobs after my placement year and not penalize me for not finishing my degree?

I guess at the end of the day I don't want to look back on my life and think "god, why didn't I just spend one more year being unhappy to have a job I love" but I know that even if I get a degree I could still end up without a programming job and this worries me more than anything.

答:
Certainly having a degree is not needed to be proficient as a programmer. You should think deeply about what you want to achieve in your career as a software professional. Here are some bullets if you've already decided to drop college:

If you are passionate about programming, you should be self-taught and looking to use your free time to code because you love it and you want to solve hard problems.

Look for companies who want valuable people, invest your spare time attending programming events and find local developers community.

Remember, having a grade is a tool for get a job, but contributing to open source projects and helping other programmers can help you to have great opportunities where people understand hacker culture.


答: When M >= N, decreasing by one makes the inner loop run (2*M+N)/2 on the average, so the overall complexity remains O(M*N). When N > M, the outer loop runs M times, and then becomes an empty operation for the remaining N-M iterations, because once k reaches M, the inner loop executes zero times. So the overall result is O(M*min(M,N))

Title: Time complexity of a nested loop where the inner value is decreased in every step

Body:
I have problems to give the right time complexity in O notation for the following loop:

```<code>k := 0
for i := 0 to N
   for j := k to M
     // something
   k = k + 1
</code>```

Where N = M. Without the modified starting value of j of the inner value this would be of course O(N * M), but with the decreasing running time of the inner loop in every step of the outer loop I am quite confused. How can this be approached?


答: I agree with DXM.  The fact that your writing ability has declined is not a side effect of programming. It is a side effect of not writing.  You probably had to write a lot in college, so you got good at it.  Now that you have been out of college for several years, you are not writing as well as you used to.  This is just like anything else, no big whoop. </p>


问:
Separating a "wad of stuff" utility project into individual components with "optional" dependencies
Over the years of using C#/.NET for a bunch of in-house projects, we've had one library grow organically into one huge wad of stuff. It's called "Util", and I'm sure many of you have seen one of these beasts in your careers.

Many parts of this library are very much standalone, and could be split up into separate projects (which we'd like to open-source). But there is one major problem that needs to be solved before these can be released as separate libraries. Basically, there are lots and lots of cases of what I might call "optional dependencies" between these libraries.

To explain this better, consider some of the modules that are good candidates to become stand-alone libraries. CommandLineParser is for parsing command lines. XmlClassify is for serializing classes to XML. PostBuildCheck performs checks on the compiled assembly and reports a compilation error if they fail. ConsoleColoredString is a library for colored string literals. Lingo is for translating user interfaces.

Each of those libraries can be used completely stand-alone, but if they are used together then there are useful extra features to be had. For example, both CommandLineParser and XmlClassify expose post-build checking functionality, which requires PostBuildCheck. Similarly, the CommandLineParser allows option documentation to be provided using the colored string literals, requiring ConsoleColoredString, and it supports translatable documentation via Lingo.

So the key distinction is that these are optional features. One can use a command line parser with plain, uncolored strings, without translating the documentation or performing any post-build checks. Or one could make the documentation translatable but still uncolored. Or both colored and translatable. Etc.

Looking through this "Util" library, I see that almost all potentially separable libraries have such optional features that tie them to other libraries. If I were to actually require those libraries as dependencies then this wad of stuff isn't really untangled at all: you'd still basically require all the libraries if you want to use just one.

Are there any established approaches to managing such optional dependencies in .NET?

答:
Full disclosure, I'm a Java guy.  So I understand you're probably not looking for the technologies I'll mention here.  But the problems are the same, so perhaps it'll point you in the right direction.

In Java, there are a number of build systems which support the idea of a centralized artifact repository that houses built "artifacts" - to my knowledge this is somewhat analogous to the GAC in .NET (please execuse my ignorance if it's a strained anaology) but more than that because it is used to produce independent repeatable builds at any point in time.

Anyway, another feature that is supported (in Maven, for instance) is the idea of an OPTIONAL dependency, then depending on specific versions or ranges and potentially excluding transitive dependencies. This sounds to me like what you're looking for, but I could be wrong.  Take a look at this intro page on dependency management from Maven with a friend that knows Java and see if the problems sound familiar.  This will allow you to build your application and construct it with or without having these dependencies available.

There are also constructs if you need truly dynamic, pluggable architecture; one technology that tries to address this form of runtime dependency resolution is OSGI. This is the engine behind Eclipse's plugin system.  You'll see it can support optional dependencies and a minimum/maximum version range.  This level of runtime modularity imposes a good number of constraints on you and how you develop.  Most people can get by with the degree of modularity Maven provides.

One other possible idea that you could look into that might be orders of magnitude simpler to implement for you is to use a Pipes and Filters style of architecture.  This is largely what has made UNIX such a long standing, successful ecosystem that has survived and evolved for half a century.  Take a look at this article on Pipes and Filters in .NET for some ideas about how to implement this kind of pattern in your framework.


问:
Too much free time in work place

Possible Duplicate:

  How to productively spend “free time” at the office

I am a Coldfusion Web Developer. I recently changed a company so that I can relocate to a different state. The current project I have is just a backup position for 3 months. I am not having much work, and the work I have also has nothing to do with programming. How do you other programmers generally make use of so much of free time? (I am going to stay here for another two months though)

答:
Make the very most of it. You may never say this again in your career. The more common question is "what happened to my spare time?"

When I say "Make the most of it." I do not mean "lie back and enjoy it." I mean use it very wisely. Learn, work on a personal project, join an open-source project, do ANYTHING with that time which will advance your skills (both for you and the company you work for).

The one time in my life where I was short of things to do (I was key to one project which meant I needed to be free on demand, so I couldn't really join other projects properly), I actually convinced the company to pay for a metric ton of O'Reilly books and sat learning all about web development. Which didn't actually come in handy til some years later but, when it did, it really did.

Edit: That was obviously back in the days when we had to learn things from books. You could get an O'Reilly subscription nowadays, or just cruise the internet, or read Stack Exchange sites all day.

Title: Too much free time in work place


问:
User story does not fit in a sprint

Possible Duplicate:

  Scrum: how to handle backlog-items that are longer than one sprint

I have a project with complex user stories which take way longer to implement than spring length.

For example: user story sounds like this :

"User is able to receive a report at 10:00 am daily"

But behind the scenes, it requires around 2.5 month of development so it does not fit in our two weeks sprints.

Could you share the best practices for this case?

答:
Create an epic, see: http://scrummethodology.com/scrum-epics/

In Scrum, the teams that complete the work assign effort estimates to every user story. Of course, that assumes that a team can reach a consensus for an appropriate estimate. What happens when a story includes too many unknowns to tell just how big it is? Or what if the story’s requirements are known, but its effort is too huge to complete in a single sprint? We call these stories “epics.” While a team should be able to tackle a typical story in four to sixteen hours, an epic is a story that would require twelve or many more to complete. Most Scrum experts suggest that any task requiring twelve or more hours should be decomposed into several smaller tasks. These stories will not only be smaller in scope, but also more narrowly defined. Basically, breaking down epics helps the development team translate its work into chunks that can be accomplished in a single day.

Is there any danger to estimating an epic? Quite simply, the answer is yes. Estimating epics can be harmful because it creates a false sense of certainty for the Product Owner...

Title: User story does not fit in a sprint

OwnerDisplayName: pors


答:
Split your user story in smaller stories which fulfill an enclosed part of your Story.
Normally your new stories are more detailed.

e.g. The user needs a report that (report definition) - the user is able to receive the report - the user is able to schedule the report generation / sending...

If one of the new stories is still too large, re-define it till it is small enough and detailed enough to implement it.

That is the normal way of backlog grooming.

Title: User story does not fit in a sprint

Body:
Possible Duplicate:

  Scrum: how to handle backlog-items that are longer than one sprint

I have a project with complex user stories which take way longer to implement than spring length.

For example: user story sounds like this :

"User is able to receive a report at 10:00 am daily"

But behind the scenes, it requires around 2.5 month of development so it does not fit in our two weeks sprints.

Could you share the best practices for this case?

OwnerDisplayName: cpater

ContentLicense: CC BY-SA 4.0


问:
How do I get feedback about whether escape analysis had any affect on my code or not?
One problem I have with compiler optimization is, that I actually never know what the compiler (or in this particular case the Jit) does with my code. So is there any possibility for me to know whether a particular compiler optimization took place or not? I just want to be sure about that some objects (math vectors) are created on the stack and not on the heap.</p>

答:
The short answer is that you cannot.

Whether or not your vectors are created on a stack or on the heap is not determined by JIT, it is a property of the JVM that is running your application.

The JVM specification has sections describing the stacks and the heap. The section on stacks says

Because the Java virtual machine stack is never manipulated directly
  except to push and pop frames, frames may be heap allocated.


问:
Nulls in every type and checked exceptions in Java?
I know that null being added to every type in Java is a source of much frustration regarding the language's type system. At the same time I generally hear complaining about checked exceptions - that they clutter interfaces, encourage exception swallowing, etc. It seems to me like null inhabiting every type is a way around the language - like I want the type of this to be X, but it's actually X or null; it just doesn't look like that and is easy to forget. Don't checked exceptions provide a way for the type of something to be X or throws Exception instead of it appearing to just be X? It provides an in-code way to specify how something can fail.

Nulls in every type and unchecked exceptions seem like they are dual concepts, but one is scorned and the other praised. Why is that?

答:
Most people who scorn NULLs have never actually written in a language without them. People who scorn checked exceptions have written in a language with them. People have seen the downsides of checked exceptions much more then the downsides of NULL-less programming. Popular languages have used checked exceptions, but no popular language has gotten rid of NULLs.

Both of these idea are trying to prove some notion correctness in a program. In my view, that sounds like a good idea in theory but tends to fall apart in practice. The effort and restrictions placed on your attempts to prove correctness are generally not worth the benefits of the limited amount of correctness being proved.

Many specific criticisms of checked exceptions exist. I'm not going to repeat them all here, I'm sure that's been done to death. NULL may not have the same issues show up. However, the lack of widespread NULL-less programming may mean that we simply haven't had time to see them. Or perhaps checked exceptions simply produce more problems then NULL-less programming does.


问:
What suitable Q & A application can integrate with a Java portal?
I'm looking for suggestions on whether we should build or are there readymade applications that do the following:

Allow admins to build a structured
workflow of support Q & A, similar to
Windows Troubleshooting i.e. when you
try one tip, you then get the next
one.

Allow end-users to search and follow
the Q & A

We have an existing Liferay portal which we would like to plug in this app to it - is there some suitable app like a CMS which does this? I mean building the structured questions - not just plain content like a wiki.

Open source options are welcome, but I'd like to know of COTS as well.

答: Confluence is a pretty good solution. We use it where I work for knowledge management. It is primarily a wiki, but extremely extensible with good integration with Office, JIRA, etc. You can definitely create content flows for end users similar to what you're seeking. Not sure about Liferay integration, although I just heard we're moving our enterprise portal to Liferay this year, so hopefully it's not to much of a hassle.</p>


问:
How to provide SaaS integration with enterprise systems (from the SaaS provider perspective)?
I'm doing some general research for a potential SaaS project.  The solution we are considering creating will need data integration capabilities with various enterprise systems.

I understand that SaaS adds complexity to enterprise integration since it lives in the cloud and outside of the firewall.

I've read a few articles that describe approaches for enterprises to integrate data with SaaS solutions.  Integration approaches range from the primitive FTP transfers, custom point to point integration, to a vast and growing range of commercial solutions (appliance, cloud-based, and EAI).

These articles are focused on the customer perspective.  In other words they are intended to help enterprises better understand their options for integrating with SaaS providers.

Can anyone provide some insight and advice from the SaaS provider perspective when it comes to making their solution as easily integratable as possible?

I assume the SaaS provider needs to create and publish web services API's and RESTful interfaces.  Any other advice or resources would be most appreciated.

PS: I realize saying "need to integrate with various enterprise systems" is incredibly vague.

答:
There are generally two big pieces to the "integrating with enterprise services" puzzle: single-sign on and data.

SSO can be the easier piece, depending on what the client institution has in place.

For instance: I work at a large institution with strict SSO requirements. We have an OpenID provider in place for authenticating to our SaaS vendors, and OAuth is in the works. If your customers can do one of these identity services, that takes one issue out of the way.

Data integration can get much, much hairier. Especially with hospitals and universities (due to HIPAA and FERPA compliance), data security is often a reason SaaS offerings are rejected in favor of on-site solutions, whether COTS or in-house developed. Although you could just provide a REST API and let the client handle their end of the data, the best way I've seen this done is to have some sort of agent software that lives inside the firewall and communicates with the cloud application over TLS.

Even in this case, however, it often requires heavy customization on a per-client basis, so if integration with client data is necessary, you will either need to provide consulting services, or have clients with an extremely skilled and competent technical staff. Probably both.

The advantage of this approach, however, is that it allows you to keep your API consistent, on both the server and client side, and to always design to an interface rather than an implementation.

My main advice is to keep anything intended to run on client hardware for integration as platform-independent and database-agnostic as possible. There's nothing worse than telling a Unix shop you require Windows Server, or a Microsoft shop you require RHEL.


答: I find that programming has had an overall positive effect on my writing, even though while studying in the USA I took a 9 year break from writing in my native language. I have developed the patience to edit and re-edit my writings, (when I have the time to do so,) until they come out perfect. Just like I tend to refactor my code until it comes out perfect. ;-)</p>


问:
How to resolve methods with the same name and parameter types?
In many cases, I want to write methods that have the same functionality for different types of inputs. This is easily accomplished by method overloading if the parameter types are different.

But what's the best (most robust) way to go about resolving the case when the parameter types are the same (i.e. two different representations of the data with the same type)?

An example of this would be an integer matrix which can naturally be stored as an int[][]. But what if you want to write a method which accepts the transpose of the matrix as well? The transpose is also an int[][] but a clearly different representation altogether.

I can see a couple ways of doing this:

Giving the methods different names

Adding a flag to the method

Wrapping each representations in different classes

I think the third method is the most clear way of doing this. Unfortunately I'm working on some high performance libraries where that's not a feasible solution.

答: Use different method names if the parameter types are the same. Simple enough, no?</p>


答:
You need to be careful designing APIs that have methods overloaded on parameter type: the methods need to do exactly the same things, otherwise the users will be confused.

Two methods that take a matrix, one taking a "straight" one and the other taking a transposed one, are definitely not doing the same thing, so overloads on different types is an unlikely fit.

Choosing a "flag" vs. "different name" is easy: if your method looks like this

```<code>int[][] mul(int[][] a, int[][] b, bool flag) {
    if (flag) {
        // Do one thing
    } else {
        // Do another thing
    }
}
</code>```

then you should use separate methods. If your method with a flag shares great deal of code, then you should use a method with a flag.

Title: How to resolve methods with the same name and parameter types?

Body:
In many cases, I want to write methods that have the same functionality for different types of inputs. This is easily accomplished by method overloading if the parameter types are different.

But what's the best (most robust) way to go about resolving the case when the parameter types are the same (i.e. two different representations of the data with the same type)?

An example of this would be an integer matrix which can naturally be stored as an int[][]. But what if you want to write a method which accepts the transpose of the matrix as well? The transpose is also an int[][] but a clearly different representation altogether.

I can see a couple ways of doing this:

Giving the methods different names

Adding a flag to the method

Wrapping each representations in different classes

I think the third method is the most clear way of doing this. Unfortunately I'm working on some high performance libraries where that's not a feasible solution.

Body:
You need to be careful designing APIs that have methods overloaded on parameter type: the methods need to do exactly the same things, otherwise the users will be confused.

Two methods that take a matrix, one taking a "straight" one and the other taking a transposed one, are definitely not doing the same thing, so overloads on different types is an unlikely fit.

Choosing a "flag" vs. "different name" is easy: if your method looks like this

int[][] mul(int[][] a, int[][] b, bool flag) {
    if (flag) {
        // Do one thing
    } else {
        // Do another thing
    }
}

then you should use separate methods. If your method with a flag shares great deal of code, then you should use a method with a flag.


答: I don't know what language you are in, but possibly a structure or tuple would group together the int[][] plus a flag into one "thingy" with acceptable performance, and it results in a cleaner interface. If not, I think the most logically similar thing to a class is breaking out what would otherwise be the class type into another parameter (maybe an enumeration or something rather than a flag to keep your options more open).  And you would be consciously choosing speed over a cleaner interface.  You might check the speed to make sure it matters, if the matrices are 1,000 by 1,000 it might not matter.  Though I imagine this has already occurred to you.</p>


答:
I vote for "Giving the methods different names" option especially if performance matters.

Don't use method1(int[][]) and method2(int[][]).
Use method(int[][]) and method_transposed(int[][]) for example.

Method name should always help the reader to understand what it does.


问:
Automatic sorting of class/module members and its possible impact on productivity and code quality
Recently I saw some possibilities of some IDEs (via plugins) to sort members of their classes/modules based on some criteria, sou you could have everything sorted automaticaly no matter where you would put the elements in time of writing it to editor.

Do you think that this kind of sorting in class/module may have positive impacts on productivity, readability, comprehensibility etc?

答:
I use a template that creates what you might called "structured comments" when I start a file, this provides a section (analogous to the C# #regions) for each classification of member, so the breakdown is like

```<code>internal members
  internal static members
  internal constant members
private members
  //etc
protected members
  //etc
public members
  //etc
</code>```

then repeat above with properties

then the constructors

then repeat above with

```<code>commands:pub,prt,pvt (fns that return void)
event handlers
functions:pub,prt,pvt
</code>```

end of class

This forces you to think of and remember the role a member has, before and after its creation. As development proceeds, I generally put new functions at the bottom of the proper section until they mature, then migrate them to a position in the section that is dependency or functionally based.

Once you have that in place, make some macros so you can quickly jump to the end of a section, I use a popup menu -

internal,public,protected,private
 |[static,const]
   |members,properties,ctors,commands,functions

so the keystrokes are alt-q, (popup), 1,3,2 -- to take me to internal const properties

(sorry about the lingo, a const property is simply one with no setter)

To add to this, I create an expansion macro that will popup a dialog asking for name, params and retval -- then it creates the stub according to the section you are in.

I have found that this type of boundary grouping works best, compared to clusters of members or some other scheme -- it forces you to think about architecture.

Here is a snippet of what it looks like in real life

```<code>//#+, public    members
  //;
  //#+*, public static     members
    // ReSharper disable UnaccessedField.Local
    // ReSharper disable InconsistentNaming
     /// <summary>
     /// Public Static Members
     /// </summary>
    private static object __UtilsWin32_public_static_members;
    // ReSharper restore InconsistentNaming
    // ReSharper restore UnaccessedField.Local
    #region "public_static_members"
    // Z_DOT typedef EnumWindowsProc(int hwnd_, int lparam_):bool ::UtilsWin32::UtilsCL:UtilsWin32.cs  z.1711900400436177.2009.05.18.07.08.11|+*,
       /// <summary>
       /// Delegate for EnumWindowsProc
       /// </summary>
       /// <param name="hwnd_">The window</param>
       /// <param name="lparam_">The lparam</param>
       /// <returns><c>true</c> to keep enumerating</returns>
      public delegate bool EnumWindowsProc(int hwnd_, int lparam_);
    // Z_DOT typedef EnumWindowsProcIntPtrIntPtr(IntPtr hwnd_, IntPtr lparam_):int ::UtilsWin32::UtilsCL:UtilsWin32.cs  z.3908448500234277.2011.06.16.12.14.08|+*,
       /// <summary>
       /// Delegate for EnumWindowsProcIntPtrIntPtr
       /// </summary>
       /// <param name="hwnd_">The window</param>
       /// <param name="lparam_">The lparam</param>
       /// <returns><c>true</c> to keep enumerating</returns>
      public delegate int EnumWindowsProcIntPtrIntPtr(IntPtr hwnd_, IntPtr lparam_);
    //;
    #endregion
    //#+*@, public static const members
      //;
  //#+@, public const     members
    //;
  //;
//#%, protected    members
  //;
  //#%*, protected static     members
    //;
    //#%*@, protected static const members
      //;
  //#%@, protected const     members
    //;
  //;
</code>```

The //; is the expansion macro point mentioned above.

Body:
I use a template that creates what you might called "structured comments" when I start a file, this provides a section (analogous to the C# #regions) for each classification of member, so the breakdown is like

internal members
  internal static members
  internal constant members
private members
  //etc
protected members
  //etc
public members
  //etc

then repeat above with properties

then the constructors

then repeat above with

commands:pub,prt,pvt (fns that return void)
event handlers
functions:pub,prt,pvt

end of class

This forces you to think of and remember the role a member has, before and after its creation. As development proceeds, I generally put new functions at the bottom of the proper section until they mature, then migrate them to a position in the section that is dependency or functionally based.

Once you have that in place, make some macros so you can quickly jump to the end of a section, I use a popup menu -

internal,public,protected,private
 |[static,const]
   |members,properties,ctors,commands,functions

so the keystrokes are alt-q, (popup), 1,3,2 -- to take me to internal const properties

(sorry about the lingo, a const property is simply one with no setter)

To add to this, I create an expansion macro that will popup a dialog asking for name, params and retval -- then it creates the stub according to the section you are in.

I have found that this type of boundary grouping works best, compared to clusters of members or some other scheme -- it forces you to think about architecture.

Here is a snippet of what it looks like in real life

//#+, public    members
  //;
  //#+*, public static     members
    // ReSharper disable UnaccessedField.Local
    // ReSharper disable InconsistentNaming
     /// <summary>
     /// Public Static Members
     /// </summary>
    private static object __UtilsWin32_public_static_members;
    // ReSharper restore InconsistentNaming
    // ReSharper restore UnaccessedField.Local
    #region "public_static_members"
    // Z_DOT typedef EnumWindowsProc(int hwnd_, int lparam_):bool ::UtilsWin32::UtilsCL:UtilsWin32.cs  z.1711900400436177.2009.05.18.07.08.11|+*,
       /// <summary>
       /// Delegate for EnumWindowsProc
       /// </summary>
       /// <param name="hwnd_">The window</param>
       /// <param name="lparam_">The lparam</param>
       /// <returns><c>true</c> to keep enumerating</returns>
      public delegate bool EnumWindowsProc(int hwnd_, int lparam_);
    // Z_DOT typedef EnumWindowsProcIntPtrIntPtr(IntPtr hwnd_, IntPtr lparam_):int ::UtilsWin32::UtilsCL:UtilsWin32.cs  z.3908448500234277.2011.06.16.12.14.08|+*,
       /// <summary>
       /// Delegate for EnumWindowsProcIntPtrIntPtr
       /// </summary>
       /// <param name="hwnd_">The window</param>
       /// <param name="lparam_">The lparam</param>
       /// <returns><c>true</c> to keep enumerating</returns>
      public delegate int EnumWindowsProcIntPtrIntPtr(IntPtr hwnd_, IntPtr lparam_);
    //;
    #endregion
    //#+*@, public static const members
      //;
  //#+@, public const     members
    //;
  //;
//#%, protected    members
  //;
  //#%*, protected static     members
    //;
    //#%*@, protected static const members
      //;
  //#%@, protected const     members
    //;
  //;

The //; is the expansion macro point mentioned above.


问:
What are your experiences selling on the Android Market? 1 year on
Follow up to this question

So a lot has changed in the smartphone market in the last year (Specifically Androids market share, OS updates and marketplace updates). Given these changes I think it is appropriate to ask this question again.

I would love to quit my job and write Android apps fulltime. :-)

Is this yet feasible for the average lone developer? What have volumes been like?

(Happy to turn this into a community wiki before all the Grinch's start moaning but looks like I don't have the option)

答:
Maxim,

You should check this link, this, and finally this one from the same blog if you are interested in know how some developers are getting some cash from Android Market.

OwnerDisplayName: Maxim Gershkovich


答:
Jason Lewis is spot-on regarding the two significant issues of single sign on (or user management issues) and data integration.

+1 for ...heavy customization on a per-client basis.  Depending on what you are offering, your integration options will vary dramatically between clients, and often even between departments at a single client. I'm at a SaaS vendor, and we see completely different requirements from the clients' side on integration: "Give me a web form where I can manually upload our data export." or "Dedicated circuit to your facility, please." or redundant automatically verified PGP-encrypted SFTP transfers. (Yes, a lot of our integration is simply batch transfers.)

If a customer is considering a SaaS solution, then they are open to outsourcing, and they may have outsourced other key bits of their IT, often to multiple vendors. You'll need flexibility to accomodate those.

A deal with a client who is not particularly security sensitive may be dead in the water if the client-side development required is hefty. Or vice versa, a client with stringent security requirements may not approve a solution that can't pass compliance audits. We make sure that we can easily develop client interfaces for our customers as well as support them if they want to design their interface.

This is all from the point of view of a small shop, focused on our offering's quality  over quantity of sales, so your mileage might vary, but SaaS deals are often big elephants, and I think most providers are going with flexibility over sales volume.

Title: How to provide SaaS integration with enterprise systems (from the SaaS provider perspective)?

Body:
I'm doing some general research for a potential SaaS project.  The solution we are considering creating will need data integration capabilities with various enterprise systems.

I understand that SaaS adds complexity to enterprise integration since it lives in the cloud and outside of the firewall.

I've read a few articles that describe approaches for enterprises to integrate data with SaaS solutions.  Integration approaches range from the primitive FTP transfers, custom point to point integration, to a vast and growing range of commercial solutions (appliance, cloud-based, and EAI).

These articles are focused on the customer perspective.  In other words they are intended to help enterprises better understand their options for integrating with SaaS providers.

Can anyone provide some insight and advice from the SaaS provider perspective when it comes to making their solution as easily integratable as possible?

I assume the SaaS provider needs to create and publish web services API's and RESTful interfaces.  Any other advice or resources would be most appreciated.

PS: I realize saying "need to integrate with various enterprise systems" is incredibly vague.


问:
CPU Architecture and floating-point math
I'm trying to wrap my head around some details about how floating point math is performed on the CPU, trying to better understand what data types to use etc.

I think I have a fairly good understanding of how integer math is performed. If I've understood correctly, and disregarding SIMD, a 32-bit CPU will generally perform integer math at at least 32-bit precision etc.

Is it correct that floating-point math is dependent on the presence of a FPU? And that the FPU on the x86 is 80-bit, so floating point math is performed at this precision unless using SIMD? What about ARM?

答:
You do not need floating point hardware to use floating point math.

IEEE-754 has a number of floating point lengths 80, 64, 32 and now a 16.  There are other non-ieee floating point formats.  The IEEE format/standard is very painful, almost all of the features are wasted, few know them, and few or none of the languages give you the ability to use them.  With compliant hardware you can still fail to meet the spec because the software/operating system is part of it.  You are required to provide different answers depending on whether exceptions are trapped for example.  You would find non-IEEE floating point formats in DSP's for speed, processor size, etc.  They were more closely tuned with what you really used the fpu for and not everything we could ever want and the kitchen sink approach that the IEEE standard uses.

Not every hardware fpu supports every length.

fpu bugs are often solved by not using the hardware for the broken instruction, or the broken instruction is wrapped by software to fix any problems.  Hardware may have gotten better in the last 5-10 years but it was difficult to find a hardware fpu without any bugs.  To avoid the pentium embarrassment all over again you would need or at least want to fix the bugs in software.  the difficulty of the IEEE spec is why it is rare to find a system that completely meets the spec.  fixing the bug in software gets into compilers and operating systems, unless you control all three (hardware, compiler, operating system) you are likely to fail that as well.

Normally you compile your program knowing what you expect to run against, at least with ARM you compile for hard float or soft float.  It is certainly possible to have the floating point library detect and then use the appropriate solution from there on out so that one binary will work on both.  You have to examine each compiler separately to know what the solutions/rules are.  Compilers tend to know what platforms normally dont support it and build for soft float by default and other platforms that normally or always have an fpu and normally build for a hardware fpu for example.

Trying to decide when to use it?  As a general rule, avoid it unless you really, really, need it.  When you do use it there are many many ways to use it wrong, understand how to use it without wasting it, or without getting the wrong answer.  You might have been better off with integer math or keeping track of the decimal place yourself.


问:
Meaningful concise method naming guidelines
Recently I started releasing an open source project, while I was the only user of the library I did not care about the names, but know I want to assign clever names to each methods to make it easier to learn, but I also need to use concise names so they are easy to write as well.

I was thinking about some guidelines about the naming, I am aware of lots of guidelines that only care about letters casing or some simple notes. Here, I am looking after guidelines for meaningful but yet concise naming.

For example, this could be part of the guidelines I am looking after:

Use Add when an existing item is going to be added to a target, Use
Create when a new item is being created and added to a target.

Use Remove when an existing item is going to be removed from a target,
Use delete when an item is going to be removed permanently.

Pair AddXXX methods with RemoveXXX and Pair CreateXXX methods with
DeleteXXX methods, but do not mix them.

As the above samples show,I would like to find some online material helping me with naming methods and other item complying with English grammar and word meanings.

The above guidance may be intuitive for native English speakers, but for me that English is my second language I need to be told about things like this.

答:
Naming. One of the hardest things about software development :)

When I name something, here is my set of priorities:

Follow the idioms of the language. Ruby likes underscores. JavaScript likes camel case. Whatever language you're in is the convention to follow.

Reveal the intent of the API. It's not "send_http_data" it's "post_twitter_status".

Avoid leaking implementation details. Say, prefixing a variable with a type.

Do not use more characters than necessary without breaking the previous  guidelines.

Obviously this is a rather simplistic approach. Naming is nuanced.

For further research, I would recommend reading The Art of Readable Code, as it provides some excellent, succinct advise on method naming. For even more research I cannot more highly recommend Bob Martin's Clean Code.


问:
Porting library, what to do with JavaDoc comments/credits
I ported a library to Java, but am wondering what to do with the JavaDoc comments. The original library used javadoc comments too, so do I leave the @author tags from the original code? And how do I give myself credit as the person who ported it over?</p>

答:
I'm no expert, but basically I believe you are the author of the code you have written, as long as it's not a copy, and you were allowed to look at the code in the first place. The original code is just your inspiration. Best practice is to clearly mention who wrote the original code though.

To elaborate I believe copyright does not protect code if it is re-written in a different language, even if it is pretty close to the original. If the solution represented by the software is patented however you can't reproduce it in any language.

The only question as far as I can see is if a port is to be considered derived work, and if the particular licence protects this.

Edit:

It seems like most people disagree with me, and consider re-writes in a different language to be derived work: https://stackoverflow.com/questions/1919010/does-porting-count-as-derivative-work

The accepted answer here however says otherwise - that only the actual lines of code in the original software are protected: https://stackoverflow.com/questions/77044/licensing-a-rewrite-from-gpl-to-mit