答:
A day will come when your beautiful, perfectly crafted, well structured and readable code won't work. Or it won't work well enough. Or a special case will arise where it doesn't work and needs adjusting.

At that point, you will need to do something that changes things so it works correctly. Particularly in the case where there are performance problems, but also often in scenarios where one of the libraries, APIs, web services, gems or operating systems you are working with doesn't behave as expected, you can end up making suggestions that are not necessarily inelegant, but are counter-intuitive or non-obvious.

If you don't have some comments to explain why you have chosen that approach there is a very good chance that someone in future ( and that someone may even be you ) will look at the code, see how it could be "fixed" to something more readable and elegant and inadvertently undo your fix, because it doesn't look like a fix.

If everyone always wrote perfect code then it would be obvious that code that looks imperfect is working around some tricky intervention from the real world, but that isn't how things work. Most programmers often write confusing or somewhat tangled code so when we encounter this it is a natural inclination to tidy it up. I swear my past self is an actual idiot whenever I read old code I have written.

So I don't think of comments as an apology for bad code, but maybe as an explanation for why you didn't do the obvious thing. Having // The standard approach doesn't work against the 64 bit version of the Frobosticate Library will allow future developers, including your future self, to pay attention to that part of the code and test against that library. Sure, you might put the comments in your source control commits too, but people will only look at those after something has gone wrong. They will read code comments as they change the code.

People who tell us that we should always be writing theoretically perfect code are not always people with a lot of experience of programming in real-world environments. Sometimes you need to write code that performs to a certain level, sometimes you need to interoperate with imperfect systems. That doesn't mean that you can't do this in elegant and well written ways, but non-obvious solutions need explanation.

When I am writing code for hobby projects that I know nobody else will ever read I still comment parts that I find confusing - for example, any 3D geometry involves maths which I'm not entirely at home with - because I know when I come back in six months I will have totally forgotten how to do this stuff. That's not an apology for bad code, that's an acknowledgement of a personal limitation. All I would do by leaving it uncommented is create more work for myself in future. I don't want my future self to have to relearn something unnecessarily if I can avoid it now. What possible value would that have?


问:
On concatenating adjacent string literals
C and C++ compiles adjacent string literals as a single string literal. For example this:

```<code>"Some text..." "and more text"
</code>```

is equivalent to:

```<code>"Some text...and more text"
</code>```

In other C-family languages like C# or Java, this is a syntax error (which is perfectly fine BTW).

What is the rationale/historical reason for C and C++ to do this?

答:
The original C language was designed in 1969-1972 when computing was still dominated by the 80 column punched card. Its designers used 80 column devices such as the ASR-33 Teletype. These devices did not automatically wrap text, so there was a real incentive to keep source code within 80 columns. Fortran and Cobol had explicit continuation mechanisms to do so, before they finally moved to free format.

It was a stroke of brilliance for Dennis Ritchie (I assume) to realise that there was no ambiguity in the grammar and that long ASCII strings could be made to fit into 80 columns by the simple expedient of getting the compiler to concatenate adjacent literal strings. Countless C programmers were grateful for that small feature.

Once the feature is in, why would it ever be removed? It causes no grief and is frequently handy. I for one wish more languages had it. The modern trend is to have extended strings with triple quotes or other symbols, but the simplicity of this feature in C has never been outdone.

ContentLicense: CC BY-SA 3.0


问:
Is it possible to modify a native executable and change (dynamic) library it depends on?
Say I compile a simple application called myproggy that depends on the libfoo dynamic library. Assuming I have another dynamic library libbaz that implements absolutely the same interface (in other words it has definitions of the same functions as libfoo), is it possible to modify the myproggy to depend upon libbaz without the need for rebuild?

I can easily do this in the case when I can dynamically load the library, but what if I can't, and I also can't re-compile the library?

I am also aware of the security issues related to this.

答:
If it really does implement exactly the same interface,m then a simple rename should be sufficient.

Otherwise, yes you can - using a binary editor, you can find the location of the system calls to the dll and modify them to call the new library. Hackers do this (or similar techniques) all the time to remove copy-protection mechanisms.

In addition, Microsoft has a tool (Fakes) that is used for unit testing by rewriting the binary to call different methods at runtime, so you can slip in a modified stub for a real library call for testing purposes. This uses their tool Detours that:

contains utilities to attach arbitrary DLLs and data segments (called
  payloads) to any Win32 binary

I used to use a tool called Purify that instrumented (ie edited the binary) of running applications to inject performance and quality-checking code.


问:
What's wrong with comments that explain complex code?
A lot of people claim that "comments should explain 'why', but not 'how'". Others say that "code should be self-documenting" and comments should be scarce. Robert C. Martin claims that (rephrased to my own words) often "comments are apologies for badly written code".

My question is the following:

What's wrong with explaining a complex algorithm or a long and convoluted piece of code with a descriptive comment?

This way, instead of other developers (including yourself) having to read the entire algorithm line by line to figure out what it does, they can just read the friendly descriptive comment you wrote in plain English.

English is 'designed' to be easily understood by humans. Java, Ruby or Perl, however, have been designed to balance human-readability and computer-readability, thus compromising the human-readability of the text. A human can understand a piece of English much faster that he/she can understand a piece of code with the same meaning (as long as the operation isn't trivial).

So after writing a complex piece of code written in a partly human-readable programming language, why not add a descriptive and concise comment explaining the operation of the code in friendly and understandable English?

Some will say "code shouldn't be hard to understand", "make functions small", "use descriptive names", "don't write spaghetti code".

But we all know that's not enough. These are mere guidelines - important and useful ones - but they do not change the fact that some algorithms are complex. And therefore are hard to understand when reading them line by line.

Is it really that bad to explain a complex algorithm with a few lines of comments about it's general operation? What's wrong with explaining complicated code with a comment?

答:
I forget where I read it but there is a sharp and clear line between what should appear in your code and what should appear as a comment.

I believe you should comment your intent, not your algorithm. I.e. comment what you meant to do, not on what you do.

For example:

```<code>// The getter.
public <V> V get(final K key, Class<V> type) {
  // Has it run yet?
  Future<Object> f = multitons.get(key);
  if (f == null) {
    // No! Make the task that runs it.
    FutureTask<Object> ft = new FutureTask<Object>(
            new Callable() {

              public Object call() throws Exception {
                // Only do the create when called to do so.
                return key.create();
              }

            });
    // Only put if not there.
    f = multitons.putIfAbsent(key, ft);
    if (f == null) {
      // We replaced null so we successfully put. We were first!
      f = ft;
      // Initiate the task.
      ft.run();
    }
  }
  try {
    /**
     * If code gets here and hangs due to f.status = 0 (FutureTask.NEW)
     * then you are trying to get from your Multiton in your creator.
     *
     * Cannot check for that without unnecessarily complex code.
     *
     * Perhaps could use get with timeout.
     */
    // Cast here to force the right type.
    return (V) f.get();
  } catch (Exception ex) {
    // Hide exceptions without discarding them.
    throw Throwables.asRuntimeException(ex);
  }
}
</code>```

Here there is no attempt to state what each step performs, all it states is what it is supposed to do.

PS: I found the source I was referring to - Coding Horror: Code Tells You How, Comments Tell You Why

Body:
I forget where I read it but there is a sharp and clear line between what should appear in your code and what should appear as a comment.

I believe you should comment your intent, not your algorithm. I.e. comment what you meant to do, not on what you do.

For example:

// The getter.
public <V> V get(final K key, Class<V> type) {
  // Has it run yet?
  Future<Object> f = multitons.get(key);
  if (f == null) {
    // No! Make the task that runs it.
    FutureTask<Object> ft = new FutureTask<Object>(
            new Callable() {

              public Object call() throws Exception {
                // Only do the create when called to do so.
                return key.create();
              }

            });
    // Only put if not there.
    f = multitons.putIfAbsent(key, ft);
    if (f == null) {
      // We replaced null so we successfully put. We were first!
      f = ft;
      // Initiate the task.
      ft.run();
    }
  }
  try {
    /**
     * If code gets here and hangs due to f.status = 0 (FutureTask.NEW)
     * then you are trying to get from your Multiton in your creator.
     *
     * Cannot check for that without unnecessarily complex code.
     *
     * Perhaps could use get with timeout.
     */
    // Cast here to force the right type.
    return (V) f.get();
  } catch (Exception ex) {
    // Hide exceptions without discarding them.
    throw Throwables.asRuntimeException(ex);
  }
}

Here there is no attempt to state what each step performs, all it states is what it is supposed to do.

PS: I found the source I was referring to - Coding Horror: Code Tells You How, Comments Tell You Why


问:
Would you still use Java in your next project, despite the whole mess in JCP
It seems that there is a whole mess around current JCP.

Quite of number of highly respected guys like Doug Lea, Tim Peierls had quit JCP.

Reference :

Is JCP dead? and Final results of the JSR Review Ballot for JSR #336

This put Java in an unfavorable future. As a Java developer, will you still consider using Java in your next project?

答:
As a pragmatist, yes I would consider using it in my next project.

However, I'd also consider other languages / platforms that had the right technical attributes AND a more open and community oriented approach to governance.

And I would also consider participating in a well organized effort to produce such a language and platform.

ContentLicense: CC BY-SA 2.5


问:
Which one is better?Change sprint dates or one team member is not attend sprint plans for 4 months
We have an agile team and nearly running 80. sprint.Our sprint  starts wednesday and finish Tuesday 10 days after.One of our team member,developer, will attend to a university course every Wednesday during 4 months.Which one is better should we take sprint days Tuesday to Monday,total sprint day will not change still 10,or one member will not attend to sprint plans and team will give commitment for her.</p>

答: I'd recommend changing sprint ceremony day if feasible. The team member in question will only have to catch up on a day's work of the rest of the team instead of catching up on the whole user story discussion and explanation, retrospective, task decomposition, etc.</p>


答:
What's wrong with explaining a complex algorithm or a long and convoluted piece of code with a descriptive comment?

Nothing as such. Documenting your work is good practice.

That said, you have a false dichotomy here: writing clean code vs. writing documented code - the two are not in opposition.

What you should focus on is simplifying and abstracting complex code into simpler code, instead of thinking "complex code is fine as long as it is commented".

Ideally, your code should be simple and documented.

This way, instead of other developers (including yourself) having to read the entire algorithm line by line to figure out what it does, they can just read the friendly descriptive comment you wrote in plain English.

True. This is why all your public API algorithms should be explained in the documentation.

So after writing a complex piece of code written in a partly human-readable programming language, why not add a descriptive and concise comment explaining the operation of the code in friendly and understandable English?

Ideally, after writing a complex piece of code you should (not an exhaustive list):

consider it a draft (i.e. plan to re-write it)

formalize the algorithm entry points/interfaces/roles/etc (analize and optimize interface, formalize abstractions, document preconditions, postconditions and side effects and document error cases).

write tests

cleanup and refactor

None of these steps are trivial to do (i.e. each can take a few hours) and the rewards for doing them are not immediate. As such, these steps are (almost) always compromized on (by developers cutting corners, managers cutting corners, deadlines, market constraints/other real world conditions, lack of experience etc).

[...] some algorithms are complex. And therefore are hard to understand when reading them line by line.

You should never have to rely on reading the implementation to figure out what an API does. When you do that, you are implementing client code based on the implementation (instead of the interface) and that means your module coupling is already shot to hell, you are potentially introducing undocumented dependendencies with every new line of code that you write, and are already adding technical debt.

Is it really that bad to explain a complex algorithm with a few lines of comments about it's general operation?

No - that is good. Adding a few lines of comments is not enough though.

What's wrong with explaining complicated code with a comment?

The fact that you shouldn't have complicated code, if that can be avoided.

To avoid complicated code, formalize your interfaces, spend ~ 8 times more on API design than you spend on the implementation (Stepanov suggested spending at least 10x on the interface, compared with the implementation), and go into developing a project with the knowledge that you are creating a project, not just writing some algorithm.

A project involves API documentation, functional documentation, code/quality measurements, project management and so on. None of these processes are one-off, fast steps to make (they all take time, require forethought and planning, and they all require that you come back to them periodically and revise/complete them with details).

Title: What's wrong with comments that explain complex code?

Body:
A lot of people claim that "comments should explain 'why', but not 'how'". Others say that "code should be self-documenting" and comments should be scarce. Robert C. Martin claims that (rephrased to my own words) often "comments are apologies for badly written code".

My question is the following:

What's wrong with explaining a complex algorithm or a long and convoluted piece of code with a descriptive comment?

This way, instead of other developers (including yourself) having to read the entire algorithm line by line to figure out what it does, they can just read the friendly descriptive comment you wrote in plain English.

English is 'designed' to be easily understood by humans. Java, Ruby or Perl, however, have been designed to balance human-readability and computer-readability, thus compromising the human-readability of the text. A human can understand a piece of English much faster that he/she can understand a piece of code with the same meaning (as long as the operation isn't trivial).

So after writing a complex piece of code written in a partly human-readable programming language, why not add a descriptive and concise comment explaining the operation of the code in friendly and understandable English?

Some will say "code shouldn't be hard to understand", "make functions small", "use descriptive names", "don't write spaghetti code".

But we all know that's not enough. These are mere guidelines - important and useful ones - but they do not change the fact that some algorithms are complex. And therefore are hard to understand when reading them line by line.

Is it really that bad to explain a complex algorithm with a few lines of comments about it's general operation? What's wrong with explaining complicated code with a comment?


答:
If the code is trivial, it doesn't need an explanatory comment.  If the code is non-trivial, the explanatory comment will most likely also be non-trivial.

Now, the trouble with non-trivial natural language is that many of us are not very good at reading it or writing it.  I'm sure your written communication skills are excellent, but nevertheless someone with a lesser grasp of written language might misunderstand your words.

If you try very hard to write natural language that cannot be misinterpreted you end up with something like a legal document (and as we all know those are more verbose and difficult to understand than code).

Code should be the most concise description of your logic, and there shouldn't be much debate about the meaning of your code because your compiler and platform have the final say.

Personally I wouldn't say that you should never write a comment.  Only that you should consider why your code needs a comment, and how you might fix that.  This seems to be a common theme in answers here.


问:
How 'child proof' should i write code as a solo programmer?
In our company there once were multiple programmers, now i am the last man standing. I have inherited all the code and i maintain, rewrite, extend (,fix) it.

I always run into this behaviour that i try to make stuff fool proof so that a dummie co-worker couldnt mess up the code. But there are limits to what i can do. I cannot prevent that someone holds a reference to an object. Even java/android system classes give you an object that you are not supposed to hold on to but just use it locally and thats it.

In our company a lot went wrong and i am kind of a burned child, i see possibilities how someone could do the wrong thing and the code keeps crashing and I am asked "why do you write stuff like that"...

Right now i am the only programmer but in the future maybe we have more (again), but right now i kinda restrain myself by spending too much time on trying to figure out how i could write my stuff so that the least amount of mistakes can be made with it. Even tho I would be the one who had to make the mistake.

Like everyone i do make mistakes ofc. So i null-check etc and write limits into the java-docs to remind myself what values i may pass etc. those simple checks are not what im talking about. I am talking about that often i could write a method in a simple and good way but some voice in my head says "oh no, what if SOMEONE would pass a wrong parameter or did this and that with it" and suddenly i find myself encapsulating logic and making stuff more complicated only to add some sort of protection against... dummie programmers with me being the only one possible.

I am NOT working on any open API or shared stuff. There will (most likely) never be any code audits etc. I am the only one using the code and it will stay like that for a long time.

So how do i stop myself from doing this fool-proof coding that costs me too much time and brainpower.

EDIT:
i read the other question + answers.
I understand the whole 'defensive programming' but i wonder when am i taking it too far ? And thats more my problem.

答:
Okay, so what I understand you are trying to get at (maybe understand), is that you need to make sure that no-one messes up your code? (because if they messed up the code things would break).
Maybe the solution to your over-worrying is not making your code child proof, but instead, increasing redundancy, you should consider using subversion.
Subersion basically allows you to save a project to a repository (repo), then when you want to make changes to the code, you 'branch' the project, meaning that you (or any other programmer) can make changes to the code in this branch without it affecting the 'trunk' (main copy) so if the code does get messed up, it is only in the branch and not actually in the real version, but if significant improvements are made to the code then you can merge your branch with your trunk meaning that the changes take place in the real working copy! So as long as these 'dummie' programmers are only working on the branch, then nothing gets messed up. Another cool function is if it does get messed up in the trunk, you can just go back in time to a time when those changes weren't made. Subversion really is a life-saver, consider beanstalk as your repo-base and TortoiseSVN as your subversion software. </p>


答:
The best way to make code child-proof is to make it decoupled into modules, then each module can have its API documented, and can be designed to do 1 thing well.

This will not stop a child taking your network module and putting it into DVD slot, but it will allow you to tell them off afterwards for not using it as it was intended - as proven by the documentation.

This does mean you have to spend more time designing your classes and modules and the interface boundaries, but its time well spent.

Title: How 'child proof' should i write code as a solo programmer?

Body:
In our company there once were multiple programmers, now i am the last man standing. I have inherited all the code and i maintain, rewrite, extend (,fix) it.

I always run into this behaviour that i try to make stuff fool proof so that a dummie co-worker couldnt mess up the code. But there are limits to what i can do. I cannot prevent that someone holds a reference to an object. Even java/android system classes give you an object that you are not supposed to hold on to but just use it locally and thats it.

In our company a lot went wrong and i am kind of a burned child, i see possibilities how someone could do the wrong thing and the code keeps crashing and I am asked "why do you write stuff like that"...

Right now i am the only programmer but in the future maybe we have more (again), but right now i kinda restrain myself by spending too much time on trying to figure out how i could write my stuff so that the least amount of mistakes can be made with it. Even tho I would be the one who had to make the mistake.

Like everyone i do make mistakes ofc. So i null-check etc and write limits into the java-docs to remind myself what values i may pass etc. those simple checks are not what im talking about. I am talking about that often i could write a method in a simple and good way but some voice in my head says "oh no, what if SOMEONE would pass a wrong parameter or did this and that with it" and suddenly i find myself encapsulating logic and making stuff more complicated only to add some sort of protection against... dummie programmers with me being the only one possible.

I am NOT working on any open API or shared stuff. There will (most likely) never be any code audits etc. I am the only one using the code and it will stay like that for a long time.

So how do i stop myself from doing this fool-proof coding that costs me too much time and brainpower.

EDIT:
i read the other question + answers.
I understand the whole 'defensive programming' but i wonder when am i taking it too far ? And thats more my problem.


问:
Decorating a class that calls its own public methods
I've written a system that calculates discounts for a shopping cart based on a set of rules. Each rule is implemented with the following interface (C#):

```<code>interface IRule
{
   bool IsActive();
   bool IsApplicableTo(IShoppingCart cart);
   decimal CalculateDiscount(IShoppingCart cart);
}
</code>```

A concrete implementation might look something like this:

```<code>class Rule : IRule
{
   bool IsActive() { return true; }

   bool IsApplicableTo(IShoppingCart cart)
   {
       if (!IsActive())
          return false;

       return TestIfApplicable(cart);
   }

   decimal CalculateDiscount(IShoppingCart cart)
   {
       if (!IsApplicableTo(cart))
          return 0m;

       return CalculateStuff(cart);
   }
}
</code>```

Now I'm trying to introduce some logging to the system. To keep things clean, I don't want to jam it into the Rule class. So I thought I'd make a Decorator for IRule, which handles the logging:

```<code>class LoggingRule : IRule
{
    IRule decoratedRule;

    bool IsActive()
    {
        LogImportantThings();

        return decoratedRule.IsActive();
    }

    //And so on.
}
</code>```

The issue that I'm running into here, is that the Rule class actually calls the IsActive and IsApplicableTo methods itself. When that happens, the decorator is simply passed by, and nothing is being logged.

I suppose I could make the LoggingRule a subclass of Rule. It would mean that I would have to make a LoggingRule variant for every IRule implementation. That could potentially cause a lot of duplication.

I could also put the logging into a base class, and use the Null object pattern when I don't want to log anything. But then again, 99 out of 100 times I don't want to log anything. And when these methods are called many many times, is it worth the potential overhead?

So neither solution seems particularly elegant, and I'm struggling to find a better alternative... Any suggestions?

答:
Can a Rule be active but not apply to a shopping cart?  Yes, right?  Can a Rule apply to a shopping cart and not be active?  Again, yes.  So as I see it, IsApplicableTo method is (or at least should be thought of as ) its own property independent of IsActive.  If IsApplicableTo calls IsActive, fine, though as a general rule, if it is public, it is meant to be called, and therefore it will be called twice.

In this way, the one who handles IRule should be calling both, thus the responsibility is not up to IRule to return false if IsApplicableTo would otherwise return true and IsActive returns false.  Likewise, don't feel like you need to call IsApplicableTo from within CalculateDiscount, since it is the caller's responsibility.  The caller would likely have something similar to the following:

```<code>for each rule:
    if rule.IsActive() and rule.IsApplicableTo(shoppingCart):
        total *= (1.0 - rule.CalculateDiscount(shoppingCart));
</code>```

Should IsApplicableTo return false because IsApplicableTo is calling IsActive and IsActive returns false, the result is ultimately the same.  In this way, LoggingRule can decorate another rule, only derive from IRule, and it would work perfectly fine.  Just don't make the mistake of adding LoggingRule and the encapsulated rule itself in the same list.

Hope that helps!

Body:
Can a Rule be active but not apply to a shopping cart?  Yes, right?  Can a Rule apply to a shopping cart and not be active?  Again, yes.  So as I see it, IsApplicableTo method is (or at least should be thought of as ) its own property independent of IsActive.  If IsApplicableTo calls IsActive, fine, though as a general rule, if it is public, it is meant to be called, and therefore it will be called twice.

In this way, the one who handles IRule should be calling both, thus the responsibility is not up to IRule to return false if IsApplicableTo would otherwise return true and IsActive returns false.  Likewise, don't feel like you need to call IsApplicableTo from within CalculateDiscount, since it is the caller's responsibility.  The caller would likely have something similar to the following:

for each rule:
    if rule.IsActive() and rule.IsApplicableTo(shoppingCart):
        total *= (1.0 - rule.CalculateDiscount(shoppingCart));

Should IsApplicableTo return false because IsApplicableTo is calling IsActive and IsActive returns false, the result is ultimately the same.  In this way, LoggingRule can decorate another rule, only derive from IRule, and it would work perfectly fine.  Just don't make the mistake of adding LoggingRule and the encapsulated rule itself in the same list.

Hope that helps!


问:
Is MongoDB appropriate for systems that will be likely to change?
I've been using MongoDb (mainly with Meteor) and for me, it has been a great way to mock up prototypes and proof of concepts quickly.

I'm just wondering, after building the initial product, if your product is likely to grow and change, is it a good idea to stick with mongoDb?

Cause it seems like with MongoDb, you need to know a lot about how you're going to use the data upfront. From my experience only, I seemed to constantly be trying to decide whether a datatype should be a document in its own right or a sub-document.

Making it a document gives it flexibility, but if you have all your datatypes as documents, well then you pretty much just have an SQL database with foreign keys that have no foreign key constaints.

Making it a subdocument makes things perform better whilst being convenient - you don't need to join tables (which you seem to have to do manually) - but the problem seems to be if you need to query that datatype outside the context of the parent, it's very hard.

So for example, if I'm building a website with chatrooms, I might have two datatypes - chatrooms and textEntries.

Chatroom will be its own document. But textEntries can either be a document in its own right or a subdocument within Chatroom.

If I make TextEntries a document, then I would need to manually keep track of the relationship between chatroom and textEntries which defeats the purpose of using mongoDB at all.

If I make TextEntries a subdocument, this will make things easier but what if later on, I have a new requirement where I want to search across all TextEntries in all chatrooms for a particular word?

With a prototype, I know exactly what I'm building so these decisions tend to be based on just getting the product working. But longer term, I wouldn't know how or in what way I'm going to want to query the data so in light of that, would I be better off just moving to an SQL database?

答:
Since MongoDB has no schema many people would argue that it is more appropriate to systems which are likely to change, although I completely agree with you that you need to carefully structure the data appropriately for your specific use case.

Regarding the use case you mention, it may be worth keeping in mind the maximum size for an individual document - 16MB I think, though admittedly that would be one busy chat room -

It may be my advanced age but I feel that the current shift to NoSql first is probably mistaken. It can be a lot simpler mapping object graphs to Document Databases but there are some significant compromises which come with NoSql and personally I feel that using an RDBMS until you start hitting the performance limits that it imposes (or have some specialised need an RDBMS cannot fill) is probably a safer bet.


答:
I don't believe there's anything wrong with comments in code. The idea that comments are somehow bad in my opinion is due to some programmers taking things too far. There's a lot of bandwagoning in this industry, particularly towards extreme views. Somewhere along the way commented code became equivalent to bad code and I'm not sure why.

Comments do have problems - you need to keep them updated as you update the code they refer to, which happens far too infrequently. A wiki or something is a more appropriate resource for thorough documentation about your code. Your code should be readable without requiring comments. Version control or revision notes should be where you describe code changes you made.

None of the above invalidates the use of comments, however. We don't live in an ideal world so when any of the above fail for whatever reason, I'd rather have some comments to fall back.


问:
Line break before or after binary operator?
While Sun's Java code convention suggests to put line break before the operator, many other guidelines disagree with it. I do not see any obvious pros and cons. Are there advantages of using one of these styles over the other?

String longVarName = a + b + c + d +
        e + f;
```
<p>vs</p>
<pre class="lang-java prettyprint-override"><code>String longVarName = a + b + c + d
        + e + f;
</code>```

答:
I normally follow the most commonly used style guidelines or a certain coding standard tools. The advantage of using a commonly used style brings benefits when you are reading other people's code or involved in a open source project where a style guidelines are set.

The most common styles that I have seen is the second style in the question. See the below for the list of them:

Google Style Guide:

When a line is broken at a non-assignment operator the break comes before the symbol.

Sun Coding Convention:

Break before an operator

Checkstyle Operator Wrap check's default value is nl:

The operator must be on a new line

ContentLicense: CC BY-SA 4.0


答:
Often we have to do complicated things. It's certainly right to document them for future understanding. Sometimes the right place for this documentation is in the code, where the documentation can be kept up to date with the code. But it's definitely worth considering separate documentation. This can also be easier to present to other people, include diagrams, colour pictures, and so on. Then the comment is just:

```<code>// This code implements the algorithm described in requirements document 239.
</code>```

or even just

```<code>void doPRD239Algorithm() { ...
</code>```

Certainly people are happy with functions named MatchStringKnuthMorrisPratt or encryptAES or partitionBSP. More obscure names are worth explaining in a comment. You could also add bibliographic data and a link to a paper that you've implemented an algorithm from.

If an algorithm is complex and novel and not obvious, it's definitely worth a document, even if only for internal company circulation. Check the document into source control if you're worried about it getting lost.

There is another category of code which isn't so much algorithmic as bureaucratic. You need to set up parameters for another system, or interoperate with someone else's bugs:

```<code>/* Configure the beam controller and turn on the laser.
The sequence is timing-critical and this code must run with interrupts disabled.
Note that the constant 0xef45ab87 differs from the vendor documentation; the vendor
is wrong in this case.
Some of these operations write the same value multiple times. Do not attempt
to optimise this code by removing seemingly redundant operations.
*/
</code>```

Body:
Often we have to do complicated things. It's certainly right to document them for future understanding. Sometimes the right place for this documentation is in the code, where the documentation can be kept up to date with the code. But it's definitely worth considering separate documentation. This can also be easier to present to other people, include diagrams, colour pictures, and so on. Then the comment is just:

// This code implements the algorithm described in requirements document 239.

or even just

void doPRD239Algorithm() { ...

Certainly people are happy with functions named MatchStringKnuthMorrisPratt or encryptAES or partitionBSP. More obscure names are worth explaining in a comment. You could also add bibliographic data and a link to a paper that you've implemented an algorithm from.

If an algorithm is complex and novel and not obvious, it's definitely worth a document, even if only for internal company circulation. Check the document into source control if you're worried about it getting lost.

There is another category of code which isn't so much algorithmic as bureaucratic. You need to set up parameters for another system, or interoperate with someone else's bugs:

/* Configure the beam controller and turn on the laser.
The sequence is timing-critical and this code must run with interrupts disabled.
Note that the constant 0xef45ab87 differs from the vendor documentation; the vendor
is wrong in this case.
Some of these operations write the same value multiple times. Do not attempt
to optimise this code by removing seemingly redundant operations.
*/


问:
Separation of concerns between objects
I have two objects which work together to provide interaction with HIDs on a machine.  One object is responsible for the communication (read/write) to the HID and the other object is responsible for modelling the HID.  Information is read and written to the HID as byte arrays.

As a contrived example:

```<code>class Hid
{
  private HidComms comms;

  public DateTime? GetPropertyB()
  {
    return comms.GetPropertyB();
  }
}

class HidComms
{
  public DateTime? GetPropertyB()
  {
    // request property B from HID
    // get 1 or more byte[] in response
    return new DateTime();
  }
}
</code>```

Which of these two objects should be responsible for encoding/decoding the byte arrays, or should a third object be responsible for this?  Meaning the Hid object only knows about state and the HidComms object only knows how to read/write with a third object responsible for the conversion?

答:
The best way to think of this is: what if you change your HID.

If your comms class handled the awkward aspects of translating a generic description into the byte arrays, then you only have 1 class to change. However, your Hid class might well be the primary object that interacts with the HI, and the hidcomms is solely there as a helper class to transfer the byte stream.

So.. it depends. From looking at the code in your question, I'd let the hid generate the byte arrays as it seems to encapsulate the entire HID.

Title: Separation of concerns between objects


问:
Possible design patterns for base function with possible additions
I have various interfaces i have to implement. Let's assume ITypeA, ITypeB. They have following methods:

```<code>ITypeA
  Connect
  Disconnect
  GetData
  SetData
  ClearData

ITypeB
  Connect
  Disconnect
  GetData
  SetData
  Start
  Pause
  Stop
</code>```

They have some base functionality: Connect, Disconnect, GetData and SetData. If I want to add ITypeC in the future, it will have these base functionality too.

I want to access to the base functionality and if there is additional functionality, I want to get this too. What design patterns are available that are capable of this situations?

I found one here: Extension Interface. In this, you create a base interface and  multiple extension interfaces that are implementing the additional functions. In the base interface you can ask for the available extension interfaces of the component. But this approach seems complicated: I have to create interfaces for each type, factories for the interfaces, I need some tables to save what Interface belongs to what Factory...

What is the basic solution for this problem? Extension Interfaces? Are there any other possible alternatives for my problem?

答:
It may be me but I can't see the difference between your problem and the description of the inheritance concept wich work with interfaces the same way it work with class.

So the basic solution to this problem seems to be inheritance (an interface being in fact a purely abstract class without any method implementation or attribute).

If your problem is that you want to define an interface on wich you can call potential additionnals methods not defined at the compilation time, then you are looking for dynamic typing wich is a language feature. (for research purpose look also for the term "duck-typing")

Look at Ruby, Python or Perl for exemple.


问:
How do I keep my classes in MVC from becoming bloated?
I'm not sure how I should have worded the question.

If I have a Student and Classes database, and I have queries that involve both.  Where do I put my queries?  In one case, someone wants student information, and I query Students and Classes in my Student class, if I put it in Classes, I cross over to the Students, [edit] violating single responsibility.

I thought I should only have queries for Students and queries for Classes in each class of this part of the Model layer, each utilized by services.

Also, What do I do when I need new queries?  I have this set of queries, then someone comes along and wants some special query.  I then copy and paste and change one thing or add an if then or a switch, this gets multiplied across the class in my model layer in multiple objects, giant switch statements, etc.  That does not seem to be what Model layers should be composed of, giant Models with code everywhere, violating DRY.

I have a service in one object in Students, findAllClassesByStudent($student_id) I call in my View perhaps, and another in Classes, findAllStudentsInAParticularClass($class_id).  Those are pretty close.

I realize I can abstract yet more layers and isolate logic in some other layer, but I can't abstract forever, sooner or later I have what appears as some violation of OOP's encapsulation. ViewModel View, Abstracted Data Access Layer, the services, etc. and so on.  If I do too little, then my objects are anemic.

I've been reading a lot and while there is a lot of interpretations, I'm assuming I'm leaving all the business logic in the Model layer, not on the controller or the View.

Pseudo examples:

```<code>class Student extends Model {

private $student

public function __construct() {

}

public function getStudentByID($student_id){
...SQL
}

public function getStudentClasses($student_id){  //first time

}

}

class Classes extends Model {

public function __construct(){

}

public function findAllStudentsInAParticularClass($class_id){  //feels like bloat
...SQL
}

}
</code>```

This seems like duplication to me.  Perhaps I haven't thought it through enough.  I just know from experience there's always someone that wants slightly different queries, and I end up copying and pasting.

答:
Your question is a bit confusing, but from what I understood, you need to refactor the code and find time to pay off the technical debt.

someone wants student information, and I query Students and Classes in my Student class, if I put it in Classes, I cross over to the Students, [edit] violating single responsibility.

Writing code is just easier part of software development. You have to think of who's responsibility is it (of Classes or Student), and implement it. Again, if you break something (like this OO principle), then try to find time and fix it.

I then copy and paste and change one thing or add an if then or a switch, this gets multiplied across the class in my model layer in multiple objects, giant switch statements, etc. That does not seem to be what Model layers should be composed of, giant Models with code everywhere, violating DRY.

Very bad approach. The solution is again refactoring. Do not let the copied code stay there. Do go back, and implement it properly.

How do I keep my classes in MVC from becoming bloated?

Again, refactoring. And proper design. But changing requirements do not affect only code. Refactoring also means fixing design and architecture problems.

If a class is getting bloated, that usually means that the design was either bad, or it wasn't adapted to the change(s).


答:
You cannot commit for someone else.

So check with the customer. It will probably have an impact on other planned meetings (sprint review, retrospective, ...) and if it is OK with him, change the day. Explain why you want to change the day. It is always better to have the entire team on board for the planning meeting.

Title: Which one is better?Change sprint dates or one team member is not attend sprint plans for 4 months

Body: We have an agile team and nearly running 80. sprint.Our sprint  starts wednesday and finish Tuesday 10 days after.One of our team member,developer, will attend to a university course every Wednesday during 4 months.Which one is better should we take sprint days Tuesday to Monday,total sprint day will not change still 10,or one member will not attend to sprint plans and team will give commitment for her.</p>


问:
In-memory datastore in Haskell
I want to implement an in-memory datastore for a web service in Haskell. I want to run transactions in the STM monad.

When I google hash table steam Haskell I only get this: Data. BTree. HashTable. STM. The module name and complexities suggest that this is implemented as a tree. I would think that an array should be more efficient for mutable hash tables.

Is there a reason to avoid using an array for an STM hashtable?
Do I gain anything with this steam hash table or should I just use a steam ref to an IntMap?

答:
The problem with a hash table implementation based directly on an array is that some of operations on it will inevitably require linear time array resizing (i.e., creating a bigger/smaller array and copying all data to it). There are multiple standard algorithms that approach this problem, like Linear Hashing or Cuckoo Hashing.

Not so long ago another algorithm named Hash Array Mapped Trie emerged, which gained a great popularity across functional languages like Clojure, Scala and, of course, Haskell (with the "unordered-containers" and "hamtmap" libraries) due to support of persistent data structures.

Not long ago I released an STM-specialized containers library based on that algorithm named "stm-containers", which should fit your task perfectly. You can also check out an introductory blog post, covering a motivation behind the library and providing benchmarks.

Title: In-memory datastore in Haskell


问:
Whether to store all numbers or just their ranges in database for this application
I'm developing a (PHP MySQL) Web App which will sell dynamically generated real time cell phone numbers for cellular companies. A company will ask for, say, a thousand numbers and this app will check for available numbers and provide them.

The number will be an 8 digit figure. The first two digits of the number will mostly be fixed as specific codes for a particular company, rest of the digits will be dynamically generated.

My question is whether

a) I should store all the sold numbers in database, if yes then:
   i)  Separate number in separate row or
   ii) All the numbers in a single row

b) Should store range of numbers i.e 32500001-32510000
```

Keeping performance and ease of handling the algorithm in mind, kindly suggest me your solution.

答:
a) ii) is pure idiotic, evil stupidity. Don't.

a) is better if you want to code the simplest possible thing (which is usually a very big 'want').

b) is better if you're pressed for database space or absolutely have to minimize DB access time, and don't care about the additional logic your code needs to retrieve the numbers. (Cell phone numbers aren't that big a name space, so it's unlikely that you need to optimize that much, but that can't be decided from a distance.)


答:
You may have more joy dividing your interfaces by behaviour and deciding on the types later.

```<code>interface IConnectable
    Connect
    Disconnect

interface IDataTransferrable
    GetData
    SetData

interface IPlayable
    Start
    Pause
    Stop

class TypeA : IConnectable, IDataTransferrable
class TypeB : IConnectable, IDataTransferrable, IPlayable
</code>```

And then how can discover if your object supports these interfaces?

here's one way:

```<code>if (ob is IPlayable)
{
    Playback(ob);
}
</code>```

where you have a function:

```<code>void Playback(IPlayable ob)
</code>```

Title: Possible design patterns for base function with possible additions

Body:
I have various interfaces i have to implement. Let's assume ITypeA, ITypeB. They have following methods:

```<code>ITypeA
  Connect
  Disconnect
  GetData
  SetData
  ClearData

ITypeB
  Connect
  Disconnect
  GetData
  SetData
  Start
  Pause
  Stop
</code>```

They have some base functionality: Connect, Disconnect, GetData and SetData. If I want to add ITypeC in the future, it will have these base functionality too.

I want to access to the base functionality and if there is additional functionality, I want to get this too. What design patterns are available that are capable of this situations?

I found one here: Extension Interface. In this, you create a base interface and  multiple extension interfaces that are implementing the additional functions. In the base interface you can ask for the available extension interfaces of the component. But this approach seems complicated: I have to create interfaces for each type, factories for the interfaces, I need some tables to save what Interface belongs to what Factory...

What is the basic solution for this problem? Extension Interfaces? Are there any other possible alternatives for my problem?

Body:
You may have more joy dividing your interfaces by behaviour and deciding on the types later.

interface IConnectable
    Connect
    Disconnect

interface IDataTransferrable
    GetData
    SetData

interface IPlayable
    Start
    Pause
    Stop

class TypeA : IConnectable, IDataTransferrable
class TypeB : IConnectable, IDataTransferrable, IPlayable

And then how can discover if your object supports these interfaces?

here's one way:

if (ob is IPlayable)
{
    Playback(ob);
}

where you have a function:

void Playback(IPlayable ob)


答:
Depends on a few more details you don't give, eg expected size of data. But in general I would most likely go for a)i)

a)ii) would only be an option if you would talk about some database system that has special features to store and query this like some NoSQL databases (and maybe Postgres to some degree), having the option to actually query this data and not requiring to define thousands of columns which would be foolish.

a)i) has the slight advantage that you store the data as it is actually used and do not need to duplicate information that belongs to a "batch" (like owner) many times. If you store single numbers than there should at least be a "batch-header" table and the single number rows are in relation to this.

Query complexity should be mostly similar. It's really not that much a difference in the resulting SQL. (I would expect queries mostly to be of the kind if a certain range is still free or who owns a specific number.)

Title: Whether to store all numbers or just their ranges in database for this application

Body:
I'm developing a (PHP MySQL) Web App which will sell dynamically generated real time cell phone numbers for cellular companies. A company will ask for, say, a thousand numbers and this app will check for available numbers and provide them.

The number will be an 8 digit figure. The first two digits of the number will mostly be fixed as specific codes for a particular company, rest of the digits will be dynamically generated.

My question is whether

a) I should store all the sold numbers in database, if yes then:
   i)  Separate number in separate row or
   ii) All the numbers in a single row

b) Should store range of numbers i.e 32500001-32510000
```

Keeping performance and ease of handling the algorithm in mind, kindly suggest me your solution.


答:
One point not yet mentioned is that sometimes commenting precisely what a piece of code does can be helpful in cases where a language uses a particular syntax for multiple purposes.  For example, assuming all variables are of type float, consider:

```<code>f1 = (float)(f2+f3); // Force result to be rounded to single precision
f4 = f1-f2;
</code>```

The effect of explicitly casting a float to float is to force the result to be rounded to single precision; the comment could thus be viewed as simply saying what the code does.  On the other hand, compare that code to:

```<code>thing.someFloatProperty = (float)(f2*0.1); // Divide by ten
</code>```

Here, the purpose of the cast is to prevent the compiler from squawking at the most efficient way of accurately computing (f2/10) [it's more accurate than multiply by 0.1f, and on most machines it's faster than dividing by 10.0f].

Without the comment, someone who was reviewing the former code might think the cast was added in a mistaken belief that it would be needed to prevent the compiler from squawking and that it wasn't needed.  In fact, the cast serves the purpose of doing exactly what the language spec says it does: force the result of the computation to be rounded to single-precision even on machines where the rounding would be more expensive than keeping the result in higher precision.  Given that a cast to float can have a number of different meanings and purposes, having a comment specify which meaning is intended in a particular scenario can help make clear that the actual meaning lines up with intent.

Body:
One point not yet mentioned is that sometimes commenting precisely what a piece of code does can be helpful in cases where a language uses a particular syntax for multiple purposes.  For example, assuming all variables are of type float, consider:

f1 = (float)(f2+f3); // Force result to be rounded to single precision
f4 = f1-f2;

The effect of explicitly casting a float to float is to force the result to be rounded to single precision; the comment could thus be viewed as simply saying what the code does.  On the other hand, compare that code to:

thing.someFloatProperty = (float)(f2*0.1); // Divide by ten

Here, the purpose of the cast is to prevent the compiler from squawking at the most efficient way of accurately computing (f2/10) [it's more accurate than multiply by 0.1f, and on most machines it's faster than dividing by 10.0f].

Without the comment, someone who was reviewing the former code might think the cast was added in a mistaken belief that it would be needed to prevent the compiler from squawking and that it wasn't needed.  In fact, the cast serves the purpose of doing exactly what the language spec says it does: force the result of the computation to be rounded to single-precision even on machines where the rounding would be more expensive than keeping the result in higher precision.  Given that a cast to float can have a number of different meanings and purposes, having a comment specify which meaning is intended in a particular scenario can help make clear that the actual meaning lines up with intent.


答:
I believe the line should start with the highest symbol in the parse tree of the statement you want to break.  It highlights the operator that is most important in the expression.  It is the same reason why you put an else at the begin of a line and not at the end of the previous line.

In the following example, scanning the left margin, you see the structure of the statement as an OR of 3 expressions.

```<code>if (ch>='A' && ch<='Z'
    || ch>='a' && ch<='z'
    || ch>='0' && ch<='9')
{...}
</code>```

Below, the || operators are less highlighted.  It is less obvious it is an || of expressions.  Especially if the lines were diffent lengths.

```<code>if (ch>='A' && ch<='Z' ||
    ch>='a' && ch<='z' ||
    ch>='0' && ch<='9')
{...}
</code>```

And just for reference, this is very wrong.  The || operators are not highlighted at all.

```<code>if ( ch>='A' && ch<='Z' || ch>='a'
     && ch<='z' || ch>='0' && ch<='9')
{...}
</code>```

I even like to put commas at the beginning of the line, even though I seldom see that.  I refrain from doing that on shared code.

```<code>var note:Object =
    { key: key
    , type: 'P'
    , text: someLongProcedureCallGettingTheUserInitials()
       + ": " + getTheTextThatWasTyped()
    };
</code>```

Title: Line break before or after binary operator?

Body:
While Sun's Java code convention suggests to put line break before the operator, many other guidelines disagree with it. I do not see any obvious pros and cons. Are there advantages of using one of these styles over the other?

String longVarName = a + b + c + d +
        e + f;
```
<p>vs</p>
<pre class="lang-java prettyprint-override"><code>String longVarName = a + b + c + d
        + e + f;
</code>```

Body:
I believe the line should start with the highest symbol in the parse tree of the statement you want to break.  It highlights the operator that is most important in the expression.  It is the same reason why you put an else at the begin of a line and not at the end of the previous line.

In the following example, scanning the left margin, you see the structure of the statement as an OR of 3 expressions.

if (ch>='A' && ch<='Z'
    || ch>='a' && ch<='z'
    || ch>='0' && ch<='9')
{...}

Below, the || operators are less highlighted.  It is less obvious it is an || of expressions.  Especially if the lines were diffent lengths.

if (ch>='A' && ch<='Z' ||
    ch>='a' && ch<='z' ||
    ch>='0' && ch<='9')
{...}

And just for reference, this is very wrong.  The || operators are not highlighted at all.

if ( ch>='A' && ch<='Z' || ch>='a'
     && ch<='z' || ch>='0' && ch<='9')
{...}

I even like to put commas at the beginning of the line, even though I seldom see that.  I refrain from doing that on shared code.

var note:Object =
    { key: key
    , type: 'P'
    , text: someLongProcedureCallGettingTheUserInitials()
       + ": " + getTheTextThatWasTyped()
    };


问:
Where to put sample data in project structure
I am working on a Scala project and I want to include some sample data somewhere in the project.  Specifically, my Scala project includes code that performs various natural language processing tasks on text data.  I want to include a sample set of text files that the user can use to test out the program somewhere in the project structure. Right now I am putting this sample data in the resources folder (mostly because it is the only location within the project that I know how to read from).  But I was wondering if this is the best location? In general what is the best practice regarding where to put sample data within the project?  Alternatively, would it be a better idea to simply provide this data separately (i.e external to the project)?</p>

答:
The data should be provided in the project, but outside the library/binary.

That is the data should be provided as part of the source archive the user downloads (unless very large; large data should be provided separately), but they should take no part in the build process. So they'd go in sample or something and the user will load that data just the way they would load their own data placed anywhere on disk (following instructions in appropriate quick start document).

Additionally you could provide an automated integration test that would load those data and exercise main functions of the program. These would start the application similarly to how the user would, load the sample data and check the behaviour, still using only the end-user interface. Easiest done with shell if you have command-line interface, but there are tools for testing a GUI too.


问:
Beginning a sentence with a function name?
Occasionally while typing something up that relates to a case-sensitive programming language I end up starting a sentence with a function name. Now the rules of English state that the first word in a sentence needs to be capitalized; the function name is lowercase, though. If you are wondering what could I be saying that would result in the first word being a function name, take this example:

Your fread implementation is broken. fread needs to return how many bytes were read.

I understand that I could change the second instance of fread to It but I want to know the best way of handling this other than just rewriting the sentence. Should I capitalize the function name? The only way I would like to hear "rewrite the sentence" as an answer is if starting the sentence with a function name violates some English rule that I am not aware of.
Edit: I really thank everyone for these answers. They have changed and improved my insight into the issue. I have learned quite a bit from this. I am very surprised that I did not think of these simple but good solutions.

I do think my stance on alternating the sentence was too tough and now I realize due to these good answers that overall altering the sentence appears to be the best option for dealing with these cases be it adding parenthesis after the function or saying The function before the function name and if available using formatting for the function name.

答:
In typography this is generally handled by using a different rendering, whether or not it's the start of a sentence, to indicate that what's hitting the eye is not just a word in the sentence but a special entity.

Your fread implementation is broken. fread needs to return how many bytes were read.

Depending on how formal a document is, it can adopt the same approach. In any case doing so eliminates the issue you identify, so you may wish to use it for that reason alone.

In the plain text world (as noted by several in comments and other answers), appending parentheses to function names helps a bit, but since we also need to refer to entities that don't take parentheses, this has only limited value. In general, short of adopting a convention of surrounding the text with special characters like brackets and asterisks, in the plain text world there's little option but to sidestep the issue by restructuring the sentence.


问:
Why is Akka being marketed as reactive? Is Actor Model reactive?
As far as I understand the Actor Model and the Reactive Programming are separate concepts. Actor Model does not seem to be inherently reactive to me.

However the Akka framework which is an Actor Model implementation is being described as reactive:

"Java and Scala program logic lives in lightweight Actor objects,
  which send and receive messages in a reactive fashion."

"We Are Reactive"

Is it a case of misusing the term or they are completely correct? Is any actor model implementation (e.g. Erlang) already reactive? Is simply generating messages as a response to other messages considered reactive as well?

Some related reading where the approaches are contrasted:

StackOverflow: RX vs messaging queues like rabbitmq or zeromq?

CS.SE: How do Functional Reactive Programming and the Actor model relate to each other?

Lambda the Ultimate: Actors vs. Reactive Objects

答: They don't mean reactive as in functional reactive programming, they mean reactive as in the reactive manifesto, which is a more generic term for a movement to build software that is event-driven, scalable, and resilient.  It's a relative recent movement and the term hasn't really caught on.</p>


问:
Is randomly refactoring code allowed in scrum
Background

My team uses scrum

I have currently no task assigned

There are no more pending task in the backlog

Today is Labor Day for my client.

Not having many things to do today I wanted to start refactoring some code I keep on seeing in the project I am working on, but currently I am not assigned to any sprint task to do any large scale refactoring.

Is it OK in Scrum if I start randomly refactoring code that I have and have not written that always bother me but don't have time other days to fix it because of other days assignments?

What about other days that I have spare time between sprints.

I actually do and believe in continuous refactoring. I always do it on the pieces of code that I am working when assigned a story but what about some other code I see that is not currently related to what I am working on at that moment?

答:
I'd say no, it's not. This is regardless of the type of work (refactoring, etc).

At minimum, tasks should be created and pushed into your current sprint. The purpose of time tracking is to capture your velocity in order to effectively be able to plot out future sprints. If you're working on things without tracking them, you will impact the velocity and it will not get better over time as it's intended to with proper tracking (you will likely regularly not have enough work because your projected velocity is less than your real velocity).

As for refactoring work in itself, I can go on a tirade about that, but I won't as I don't think it's the core question you're trying to have answered.


问:
Phenotropic Program Design
I recently ran across an idea put forth by Jaron Lanier called "phenotropic programming."

The idea is to use 'surface' interfaces instead of single point interfaces in computer programs utilizing statistics to winnow out minor errors that would typically cause a "classical" program to catastrophically crash.

The two-line description is here:

According to Jaron, the 'real difference between the current idea of
  software, which is protocol adherence, and the idea [he is]
  discussing, pattern recognition, has to do with the kinds of errors
  we're creating' and if 'we don't find a different way of thinking
  about and creating software, we will not be writing programs bigger
  than about 10 million lines of code no matter how fast our processors
  become.'

The slightly longer explanation is here.
And the even longer explanation is here.

So, the question, looking past the obvious robot-overlord connotations that people tend to pick out, how would one actually design and write a "phenotropic program?"

答:
Here is a slide set for defining a Probabilistic Programming Language in Scala.

It is the first decent implementation example for some of the core components to the system that Jaron Lanier proposes.

Title: Phenotropic Program Design


答:
I am going to say no as well.  Re-factoring often leads to unintended bugs if it is not managed the right way.

As a GM, periodically I would put everyone on another project and spend a week doing code reviews / re-factoring / renaming and enforcing conventions on a project.  These re-factoring sprints would almost always be cosmetic in nature.  Any functional re-factoring would be planned ahead of time and involve the original developer.

Functional re-factoring should always be planned and coordinated as part of the scrum process so the time can be tracked and all necessary team members are available to validate the process.  One developer should not go off changing code written by another off track because most likely it is just going to mess up the current sprint for everyone.  Especially when it comes to code merge time.

If it is a project which you are the sole maintainer and it is your own free time then it can be different assuming you take steps to ensure that you don't cause unnecessary delays in your current sprint.

When in doubt, ask your manager.

EDIT: I also want to mention that a given piece of code you do not like may have a certain performance target associated with it.  You may not like it but it may be faster than anything you could build that suits how you want to use it.  Just another reason why functional re-factoring should always be a managed process.

Title: Is randomly refactoring code allowed in scrum

Body:
Background

My team uses scrum

I have currently no task assigned

There are no more pending task in the backlog

Today is Labor Day for my client.

Not having many things to do today I wanted to start refactoring some code I keep on seeing in the project I am working on, but currently I am not assigned to any sprint task to do any large scale refactoring.

Is it OK in Scrum if I start randomly refactoring code that I have and have not written that always bother me but don't have time other days to fix it because of other days assignments?

What about other days that I have spare time between sprints.

I actually do and believe in continuous refactoring. I always do it on the pieces of code that I am working when assigned a story but what about some other code I see that is not currently related to what I am working on at that moment?


问:
Long Keywords like `function` and `namespace`
In many English-based programming languages like C++ and JavaScript, there exist long keywords like function, namespace, exception (in OCaml languages) and such. Do you think shorter keywords like func should replace them? Why or why not? What about replacing them with digraph operators?

The long keywords we will be mainly talking about, but not limited to, are mainly from curly-brace imperative languages: function, namespace, implements, instanceof and synchronized (I always misspell that).
You should also show the examples from your favourite programming language.

答:
First of all, those languages of syntactical C ancestry abbreviate some keywords that are used often, while the longer keywords like "namespace" hardly matter... for example "int", "var".

Long keywords are universally understandable between languages. PL/SQL, for example, is not a curly-brace language, but the keywords spelled in full: function, procedure, package, etc.
For that reason, it should not be too hard to read a PL/SQL procedure even if you have never learned PL/SQL.

Once keywords are abbreviated, programs are only readable to those who know what each abbreviation means in that language. Ambiguities can arise. And programmers are encouraged to abbreviate their identifiers too, quid pro bono.


问:
A 'task' system which has an ending, to get ready for next task
I want to make a system, so that there are certain tasks. For example, let's talk about a game. I want to make it so there are 100+ tasks doing different things, but when the player's magic level is 5, it will do the magic task, if the player's fighting skill is level 5, it will fight. I have that already, however here is the catch. I want to make it so once the task executes, it will have an 'ending'. So, it will do something before it finally gets killed.

My code so far:

```<code>for (GameTask a : s.gameTasks) {
    if (a != null) {
        if (a.validate()) {
            a.execute();
        }
    }
}
</code>```

It will loop all the tasks and execute them, however how can I implement an 'ending' to it, so that it will get ready for the next task? I hope I have written it clearly as English is not my first language.

tl;dr, I want to add an 'end' to each task so that it can be killed and can be ready for next task.

答:
I'm not sure what you mean with ending a task and be ready for the next, but it looks to me that you just want a way of stopping each task so it can continue with the next one in the loop.

If that's the case then you probably wan't to make the GameTask class implement Runnable so you can execute them using the Executors class, something like this:

```<code>    ExecutorService executor = Executors.newFixedThreadPool(5);
    for (GameTask task : s.gameTasks) {
        executor.execute(task);
    }
</code>```

Then, depending on what each task does, it might be more or less tricky to implement the end task method, but in principle the simplest way is that each task has a loop with a boolean that determines if it should continue being executed. You could then implement an "endTask" method in the GameTask that would set to false that variable.

You can see an example in this other question: https://stackoverflow.com/questions/94011/how-to-abort-a-thread-in-a-fast-and-clean-way-in-java

Body:
I'm not sure what you mean with ending a task and be ready for the next, but it looks to me that you just want a way of stopping each task so it can continue with the next one in the loop.

If that's the case then you probably wan't to make the GameTask class implement Runnable so you can execute them using the Executors class, something like this:

    ExecutorService executor = Executors.newFixedThreadPool(5);
    for (GameTask task : s.gameTasks) {
        executor.execute(task);
    }

Then, depending on what each task does, it might be more or less tricky to implement the end task method, but in principle the simplest way is that each task has a loop with a boolean that determines if it should continue being executed. You could then implement an "endTask" method in the GameTask that would set to false that variable.

You can see an example in this other question: https://stackoverflow.com/questions/94011/how-to-abort-a-thread-in-a-fast-and-clean-way-in-java


问:
How do newly-created programming languages use Windows API features?
WinAPI is focused primarily on the C family, but how do new programming languages use those features without creating their own runtime/interpreter type thing?  Do they hook directly into the DLL files?  kernel32.dll contains most of those functions right?

Thanks.

答: Every language (even C!) has some kind of runtime. This runtime will usually provide bindings to C or have an API usable from C (or in the case of C: from assembler). Such C bindings can then be used to access libraries written for C. There will usually be a translation layer that converts between different data representations in C and in the target language.</p>


问:
How to manage data flow between UI components?
I have been trying to use classes that implement ActionListener to respond to user input.  I'm consistently noticing that for an action listener to communicate the event to other objects, it has to contain the object.  Like,

The object I want to get updated when action_src is clicked:

```<code>public class Display_Field {
    JTextField display;

    public Display_Field ( JButton action_src ) {
        action_src.addActionListener( new Open_Dialog_Click( this ) );
    }

    public void setText( String text ) {
        display.setText( text );
    }
}
</code>```

The ActionListener I plan to add to action_src:

```<code>public class Open_Dialog_Click implements ActionListener {
    private Display_Field display;

    public void actionPerformed( ActionEvent action ) {
        JFileChooser chooser = new JFileChooser();
        chooser.showOpenDialog( null );
        display.setText( chooser.getSelectedFile().getName() );
    }

    public Open_Dialog_Click( Display_Field display ) {
        this.display = display;
    }
}
</code>```

There is so many convolutions! Like, the display needs to be constructed with a button that adds an ActionListener that needs to be constructed with the display...

Is there a less convoluted way to allow data to flow between components?

I have considered making a central class that houses all the listeners, acting as wiring for any and all intercomponent communication, but that seems like the class is doing too much for its own good.  ...or is that how it is done after all?

答:
What I normally do is have a JPanel that holds a reference to all the elements involved. This JPanel implements ActionListener so you can just pass "this" to every element (JTextField, JButton, etc.) that you create.

This way you have access to all the objects (they are instance variables) and listen to all the events within the same class.

If things get too messy then the ActionListener could be an external class (a "controller") that could hold a reference to more than one JPanel.

Some code:

```<code>public class TestJPanel implements ActionListener
{
    private JButton button;
    private JTextArea textArea;
    private JCheckBox checkBox;

    public TestJPanel() {
        button = new JButton("I'm a button");
        button.addActionListener(this);

        checkBox = new JCheckBox();
        checkBox.addActionListener(this);

        textArea = new JTextArea();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == button)
        {
            textArea.setText("Button clicked");
        }
        else if (e.getSource() == checkBox)
        {
            textArea.setText("Checkbox clicked");
        }
    }
}
</code>```

Body:
What I normally do is have a JPanel that holds a reference to all the elements involved. This JPanel implements ActionListener so you can just pass "this" to every element (JTextField, JButton, etc.) that you create.

This way you have access to all the objects (they are instance variables) and listen to all the events within the same class.

If things get too messy then the ActionListener could be an external class (a "controller") that could hold a reference to more than one JPanel.

Some code:

public class TestJPanel implements ActionListener
{
    private JButton button;
    private JTextArea textArea;
    private JCheckBox checkBox;

    public TestJPanel() {
        button = new JButton("I'm a button");
        button.addActionListener(this);

        checkBox = new JCheckBox();
        checkBox.addActionListener(this);

        textArea = new JTextArea();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == button)
        {
            textArea.setText("Button clicked");
        }
        else if (e.getSource() == checkBox)
        {
            textArea.setText("Checkbox clicked");
        }
    }
}


答:
Here is one approach:  do both !

Refactoring is often error-prone or more time-consuming that originally estimated as @misterbiscuit points out.

So consider an attempt to do it a draft or a spike.  You don't ned to seek approval or advertise if at this stage.

Then, look to include it through one of two channels:

an existing ticket that touches the same code / functionality where you can reasonable wrap this in.  Reasonably as agreed on with fellow team members.

entire a ticket for review at the next ticket grooming (or weekly meeting, etc. if waterfall).  At that time you can make the case for it.

Once you get actual buy-in, you can look to apply or redo your spike and having the code actual get merged into the mainline (master, etc.) branch.

This will have several advantages:

All your code codes through the same process, gets tested, QA, in the release pipeline, etc.

You get formal buy-in, including from the product manager, that refactoring is part of the craft and not something that needs to be 'sneaked in' on a holiday.  Ask yourself why you aren't 'sneaking in' an actual feature may help for perspective.

You can ask for pairing, code review, qa, devops and all the other support that may be needed for the factoring code change.  It will all be official, according to Policy and Procedure and above board.

If you are a publicly traded company with SOX compliance you likely want/need to do this sort of formal process (i.e. document it and then follow it).

You get a better reputation with both the product manager (change was done quickly) and the development team (codebase was improved).

The organization is seeking to care about code quality which is good for productivity, morale, employee retention and many other reasons.

The effect on project velocity can be more easily tracked when all work is included.  It can be ok not to appoint any points as the presence itself can be used to affect velocity.

Developers are likely to see out tools that encourage easier code reviews such as Fisheye, Github, etc.

Developers are more likely to see out some basic standards (sometimes documented, sometimes not) that make sharing code and hence refactoring easier.  Sometimes a big part of refactoring is picking a style and then applying it broadly (replacing a mixture of approaches with one).

A final comment: Avoid the product manager hearing the word 'random'.  They may respond more favourably with 'targeted, strategic, performance enhancing' code upgrade.  Or application service pack.  Or whatever language gives you coverage.


问:
How 'child proof' should i write code as a solo programmer?
In our company there once were multiple programmers, now i am the last man standing. I have inherited all the code and i maintain, rewrite, extend (,fix) it.

I always run into this behaviour that i try to make stuff fool proof so that a dummie co-worker couldnt mess up the code. But there are limits to what i can do. I cannot prevent that someone holds a reference to an object. Even java/android system classes give you an object that you are not supposed to hold on to but just use it locally and thats it.

In our company a lot went wrong and i am kind of a burned child, i see possibilities how someone could do the wrong thing and the code keeps crashing and I am asked "why do you write stuff like that"...

Right now i am the only programmer but in the future maybe we have more (again), but right now i kinda restrain myself by spending too much time on trying to figure out how i could write my stuff so that the least amount of mistakes can be made with it. Even tho I would be the one who had to make the mistake.

Like everyone i do make mistakes ofc. So i null-check etc and write limits into the java-docs to remind myself what values i may pass etc. those simple checks are not what im talking about. I am talking about that often i could write a method in a simple and good way but some voice in my head says "oh no, what if SOMEONE would pass a wrong parameter or did this and that with it" and suddenly i find myself encapsulating logic and making stuff more complicated only to add some sort of protection against... dummie programmers with me being the only one possible.

I am NOT working on any open API or shared stuff. There will (most likely) never be any code audits etc. I am the only one using the code and it will stay like that for a long time.

So how do i stop myself from doing this fool-proof coding that costs me too much time and brainpower.

EDIT:
i read the other question + answers.
I understand the whole 'defensive programming' but i wonder when am i taking it too far ? And thats more my problem.

答:
As someone who started in Basic and C; I have a policy:

If it can explode, make sure it explodes.

Paranoia with error checking and defensive styles often create slower and more difficult to debug code. (And can introduce its own bugs)  The reality is that code must be documented and that you should expect a reasonable developer to use it.  If you are doing null checks all over the place then there is something wrong with the design in general.

The more you try to hide things the more you often hurt yourself or your team.  It comes back to bite you in the butt.


问:
Multithreaded Pre/Post Functions
I'm programming an application for an embedded device. We are using an RTOS that supports multi threading. The device is supposed to mimic an older project that was programmed in plain C (without threads).

The original project uses a stack and START / END functions at the beginning and end of each function that can be called throughout runtime. Each time START is called a constant number (identifying the function) will be put on the stack - END will remove it from the stack and check if the top is equal to the called function. If it is different something really bad has happened and the device will recover/reset.

This feature is great for debugging purposes as it fully displays how functions are called. It would be very lovely to have such a feature in the multi-threaded version.

I implemented START and END as a class in C++ using constructor and destructor which makes the handling fairly easy. Running this single-threaded works like a charm. Anything multithreaded will destroy the stack as the scheduler switches context and writing to one stack would not make sense.

The most basic solution in my mind would be having one START/END stack for each thread -> Problem each function has to know which threads it runs on. Is there a better solution to this problem?

答:
(Please note that in the comments above, the OP mentioned the "stack" we're talking about isn't the call stack, it's a separate, dedicated stack for the purpose of call tracking)

We've already covered the concept of Thread Local Storage (TLS) in the comments above.  If that's available and you want to use it, great.

Another approach is slightly more "roll your own", but I've used it with success.  For now I'm assuming we're only talking about task-level function call tracking, although this method can be extended to ISRs too.

Most RTOSes provide the opportunity to run user-defined callout functions, or "hooks", at specific points, like entering & exiting ISRs, context switching into and out of a task, the timer tick, etc.  For example, FreeRTOS provides a large set of [Trace Macros] (http://www.freertos.org/rtos-trace-macros.html) that let you instrument & trace your code (see traceTASK_SUSPEND(xTask) and traceTASK_RESUME(xTask), for example.)

Let's keep this simple.  I hate globals, they are a source bugs, break good encapsulation, etc.  That said, you could have a global variable:

```<code>FUNC_CALL_STK   *stack_ptr;
</code>```

or whatever.  Each time you switch into a task (using the RTOS' built in hook function), "stack_ptr" is set to the current task's "trace stack" position.  Each time you switch out of the task (again, via RTOS hook), you store stack_ptr into the task's private stack pointer.  Each task has its own private tracing stack & pointer into the current position.

Another alternative, which avoids using OS-supplied hook functions (I tend to favor this approach):

Each task would still have its own tracing stack & pointer, but this could be implemented as a lookup table of "stack pointers" (perhaps indexed by task ID or whatever), and just use those directly from task context to push & pop.  Each task's tracing stack & stack pointer would be initialized at task init, before entering the task's "infinite loop".  So for example, your START function would do something like:

```<code>PushCurrentFuncIdentifier(FuncId, GetCurrentTaskID());
</code>```

GetCurrentTaskID() is an OS API that would return an integer which uniquely identifies the currently-running task (every RTOS has such an API).  No matter if/when a context switch occurs, this should be thread-safe.

BTW, using your C++ class, the CTOR could save off the Task ID (TID) as a private member, and then the DTOR could use the cached TID instead of having to call the RTOS API again.

Title: Multithreaded Pre/Post Functions

Body:
(Please note that in the comments above, the OP mentioned the "stack" we're talking about isn't the call stack, it's a separate, dedicated stack for the purpose of call tracking)

We've already covered the concept of Thread Local Storage (TLS) in the comments above.  If that's available and you want to use it, great.

Another approach is slightly more "roll your own", but I've used it with success.  For now I'm assuming we're only talking about task-level function call tracking, although this method can be extended to ISRs too.

Most RTOSes provide the opportunity to run user-defined callout functions, or "hooks", at specific points, like entering & exiting ISRs, context switching into and out of a task, the timer tick, etc.  For example, FreeRTOS provides a large set of [Trace Macros] (http://www.freertos.org/rtos-trace-macros.html) that let you instrument & trace your code (see traceTASK_SUSPEND(xTask) and traceTASK_RESUME(xTask), for example.)

Let's keep this simple.  I hate globals, they are a source bugs, break good encapsulation, etc.  That said, you could have a global variable:

FUNC_CALL_STK   *stack_ptr;

or whatever.  Each time you switch into a task (using the RTOS' built in hook function), "stack_ptr" is set to the current task's "trace stack" position.  Each time you switch out of the task (again, via RTOS hook), you store stack_ptr into the task's private stack pointer.  Each task has its own private tracing stack & pointer into the current position.

Another alternative, which avoids using OS-supplied hook functions (I tend to favor this approach):

Each task would still have its own tracing stack & pointer, but this could be implemented as a lookup table of "stack pointers" (perhaps indexed by task ID or whatever), and just use those directly from task context to push & pop.  Each task's tracing stack & stack pointer would be initialized at task init, before entering the task's "infinite loop".  So for example, your START function would do something like:

PushCurrentFuncIdentifier(FuncId, GetCurrentTaskID());

GetCurrentTaskID() is an OS API that would return an integer which uniquely identifies the currently-running task (every RTOS has such an API).  No matter if/when a context switch occurs, this should be thread-safe.

BTW, using your C++ class, the CTOR could save off the Task ID (TID) as a private member, and then the DTOR could use the cached TID instead of having to call the RTOS API again.


问:
How do you get the usernames/passwords onto a STUN or TURN server for long-term credential authentication?
The STUN and TURN specifications allow for client authentication using usernames and passwords, and call this authentication via long-term credentials. In fact, TURN requires that clients authenticate by this means.

However, I would assume that almost all deployments run their STUN or TURN servers separately from their database server. For example, for a VOIP application that uses TURN servers, presumably all of the user data would be stored in a database, user account management might be primarily handled by a web server, while the clients would still need to be able to authenticate into a separate TURN server.

What's the best practice for the STUN/TURN server to access the usernames and passwords from the database to authenticate clients? If most deployments or your solution relies upon a particular STUN/TURN server implementation that supports specific features, any recommendations as to STUN/TURN servers would be appreciated as well.

答:
Given that:

Both of the original STUN authentication schemes (viz. short- and long-term credentials) involve the server knowing the plaintext password of every user;

The same authentication schemes are susceptible to offline dictionary attack, unless TLS/DTLS is used; and

There is a general principle that passwords should be handled with secrecy even if it causes great inconvenience for system implementors and operators:

Then it is desirable to keep the long-term passwords off the STUN/TURN server (even if DTLS is used to protect them on the wire), to minimize the attack surface for the database of all passwords.

The viable authentication schemes are therefore:

Authentication via short-term credentials, permitted by RFC-5766 section 4 because it's at least as strong as the long-term credential scheme.

DTLS and authentication with long-term credentials, where the STUN server would make remote calls to a central password store to perform all MESSAGE-INTEGRITY operations that require knowledge of passwords. The central password store must be one of the small number of systems subjected to detailed security auditing and control; it would need special new interfaces so that it could be used by the STUN servers.

General protocols for obtaining authorization credentials, e.g A REST API For Access To TURN Services, SAML, Diameter, or even slightly-misused OAuth.

DTLS and authentication with long-term credentials, where the passwords are assigned solely for the STUN service, and are supposedly unrelated to users' real passwords.

Of those four, the idea of STUN-specific passwords is the most likely to cause trouble because it will inspire revolt among users who have enough trouble remembering one good password.

The idea of long-term credentials, with special delegation to a central server, is undesirable because it needlessly increases the attack surface on that central server.

The short-term credential scheme is not completely specified; the STUN/TURN specs do not discuss how the credentials are generated or transported. Since it would be necessary to design a protocol to generate those credentials and transport them to the STUN client and STUN server, it would be far less effort to ignore the short-term credential scheme and instead to use one of the new federated protocols.

The choice of general protocol is not very important, but obviously it would be easier to deploy one that would be shared with other services. At the time of writing, however, A REST API For Access To TURN Services is the most complete specification.

Therefore, I recommend use of the REST API to obtain temporary usernames and passwords from an HTTPS server. The STUN/TURN server will validate the usernames and passwords using a secret that it shares with the HTTPS server.


问:
Mobile App Development-Architecture/Platform: Main performance concern: device/UI responsiveness
I am currently investigating different alternatives for building a mobile instant messaging application for iOS and Android, using an XMPP server (probably ejabberd) as the back-end. Main requirements are a nice UI and of course good performance on most devices.

I have identified three different alternatives, two of which include using the Marmalade SDK

Option A): Use Marmalade C++, creating the UI with Marmalade Libraries such as IwNUI/INUI. In this option, the UI is created in C++ code. My assumption is that this should be good in performance, however I am not sure how easy it is to achieve a nice, custom UI that has a good/modern feel to it, such as other high-quality apps. Another advantage: This would target iOS/Android with one code base.

Option B): Also Marmalade, using the C++ s3eWebView api to load local web pages packaged in the application package. UI would be designed in these web pages using HTML/CSS/JavaScript. For the application logic, JavaScript or C++ can be used, as there is a JavaScript Bridge (http://docs.madewithmarmalade.com/display/MD/The+Javascript+interface) to communicate between C++ and JavaScript code. Would also target iOS/Android in one go.

Option C): Non-Marmalade: Go with two code bases. Use Objective-C (i.e. "standard way") for iOS, and Google Android SDK for Android. Build the app twice.

I am currently leaning towards Option B, as this would allow for use of one code base, and leverage existing HTML5/CSS/JavaScript technologies (nice especially for UI), together with the ability to use C++. However, my concern is whether device/UI responsiveness will be acceptable with this. I have run some preliminary tests for simple things such as loading CSS3 dropdown menus into an s3eWebView via C++, and this seems fairly responsive (i.e. menu drops down quickly and smoothly).

答:
Regarding the code:

C++ is already commonly used cross platform for non UI code, there was a recent presentation on how dropbox accomplishes this:

http://oleb.net/blog/2014/05/how-dropbox-uses-cplusplus-cross-platform-development/

Since you intend on using C++, the non-UI code can be shared regardless of the UI decision.  That might make it easier to just make a decision about the UI.

Regarding the UI:

You should determine whether this tradeoff is acceptable with additional research.

The last mile of making a hybrid app mimic a native app is rarely worth putting effort into, as you will two problems: 1) finishing the app features, 2) hacking in all kinds of native functionality.

If you try apps made with mobile uis (this site[1]), apps made with mobile frameworks (ionic[2], ratchet[3], others...) and decide the performance is fine, then make a hybrid app.  If you feel you need to improve on it, even incrementally, just ship native controls instead.

Even if you end up intending on shipping native controls, you could prototype with HTML and later figure out the native UI, assuming that the non-UI code is decoupled.

[1] http://blog.stackoverflow.com/2011/07/mobile-stack-exchange/

[2] http://ionicframework.com/

[3] http://goratchet.com/


答: If there is an absolute requirement to start each sentence with a cap, then simply replace fread with "The fread function" wherever it starts a sentence.

Title: Beginning a sentence with a function name?

Body:
Occasionally while typing something up that relates to a case-sensitive programming language I end up starting a sentence with a function name. Now the rules of English state that the first word in a sentence needs to be capitalized; the function name is lowercase, though. If you are wondering what could I be saying that would result in the first word being a function name, take this example:

Your fread implementation is broken. fread needs to return how many bytes were read.

I understand that I could change the second instance of fread to It but I want to know the best way of handling this other than just rewriting the sentence. Should I capitalize the function name? The only way I would like to hear "rewrite the sentence" as an answer is if starting the sentence with a function name violates some English rule that I am not aware of.
Edit: I really thank everyone for these answers. They have changed and improved my insight into the issue. I have learned quite a bit from this. I am very surprised that I did not think of these simple but good solutions.

I do think my stance on alternating the sentence was too tough and now I realize due to these good answers that overall altering the sentence appears to be the best option for dealing with these cases be it adding parenthesis after the function or saying The function before the function name and if available using formatting for the function name.