问:
Naming conventions: camelCase versus underscore_case ? what are your thoughts about it?
I've been using underscore_case for about 2 years and I recently switched to camelCase because of the new job (been using the later one for about 2 months and I still think underscore_case is better suited for large projects where there are alot of programmers involved, mainly because the code is easier to read).

Now everybody at work uses camelCase because (so they say) the code looks more elegant .

What are you're thoughts about camelCase or underscore_case

p.s. please excuse my bad english

Edit

Some update first:

platform used is PHP (but I'm not expecting strict PHP platform related answers , anybody can share their thoughts on which would be the best to use , that's why I came here in the first place)

I use camelCase just as everibody else in the team (just as most of you recomend)

we use Zend Framework which also recommends camelCase

Some examples (related to PHP) :

Codeigniter framework recommends underscore_case , and honestly the code is easier to read .

ZF recomends camelCase and I'm not the only one who thinks ZF code is a tad harder to follow through.

So my question would be rephrased:

Let's take a case where you have the platform Foo which doesn't recommend any naming conventions and it's the team leader's choice to pick one. You are that team leader, why would you pick camelCase or why underscore_case?

p.s. thanks everybody for the prompt answers so far

答:
At first, I agree with dafmetal. It is of the upmost importance, that you do not mix different programming styles. Doing this in one and the same file is the worst you can do IMHO. Across different files, it is distracting, but not fatal.

The next thing you have to do, is at naming rules that are popular for the language that you are writing in. My C++ code for instnace, will look different than something for Python obviously (PEP8 is a nice guide here)

You can also use different naming conventions to refer to different things, as much as you probably use UPPER_CASE for constants (this only applies to certain languages of course), you can use this_style for local variable names, whereas you use camelCase for instance/member variables. This may not be needed when you have things such as self or this however.

Update

Let's take a case where you have the
  platform Foo witch doesn't recomend
  any naming conventions and it's the
  team leader's choice to pick one . You
  are that team leader , why would you
  pick camelCase or why underscore_case.

There are no advantages for one over the other really. This matter is very subjective and once agreed upon, it will not make a difference. There are always these religuous wars about these small things. But once you have gotten adjusted to either, the discussions seems to be entirely superfluous.

To quote Alex Martelli on a very similar matter:

Sure, I do get weary, in Ruby, of
  typing the silly "end" at the end of
  each block (rather than just
  unindenting) -- but then I do get to
  avoid typing the equally-silly ':'
  which Python requires at the
  start of each block, so that's almost a wash:-).  Other syntax
  differences such as '@foo' versus
  'self.foo', or the higher significance
  of case in Ruby vs Python, are really
  just about as irrelevant to me.

Others no doubt base their choice of
  programming languages on just such
  issues, and they generate the hottest
  debates -- but to me that's just an
  example of one of Parkinson's Laws in
  action (the amount on debate on an
  issue is inversely proportional to the
  issue's actual importance).

Source

If you are the team leader, you just go with one. Since one doesn't have any advantages over the other, you can just throw dice or pick what you like more.


问:
Incorporating web designer's into a rails app
I have a designer who has great knowledge of HTML, CSS and JavaScript (Not jQuery or AJAX though).

He gives me his designs in those files and I have to incorporate it into my apps.

The site is not static so I have trouble incorporating it.

When the site was static I used to save the HTMLs in my app/views directory and the other CSS, JS, fonts in the public/... dir. The files are directly linked from the HTML is read just fine.

But now, I have to replace HTML tags with .erb ones <% --rails-- %> when some dynamic action needs to be performed. Even this seems harder than it sounds

Anyone developer experienced with this? How did you solve your problem?

OR should I ditch this designer and get a designer who has good knowledge of rails?

答:
I have worked with many designers, some who can work within Rails apps and others who can't.  I highly recommend that you only hire designers who are capable enough to integrate directly into the project itself.  You will be surprised how valuable a good designer can be once they can integrate their work with the team.

Integration will require a little teaching and continual guidance before you will see results.  For a short term project I don't think it's worth it -- in those cases hire a different designer.  But for a longer term project its worth the time investment if you're working with a designer already skilled in HTML/CSS/Javascript.

Integrating a Web Designer into a Rails Project:

1. Set up the Designer's IDE

Non-programmers are easily overwhelmed by compatibility issues, so it's best to make sure their dev environment is aligned properly from the get go with tools they need to use to develop for Rails. A very good way to onboard a designer quickly for a Rails project is to install this installation script by Thoughtbot.  This will install nearly every dependency they will need to work on most Rails apps in local development.

An alternative approach is to use contained IDE for development to keep everybody synced, using tools such as Nitrous.io

Next, make sure they are hooked up to all of the relevant config settings needed to boot the app, such as having a working database.yml

2. Teach them basic Git

Manually implementing mockups from a designer is a gigantic waste of time.  If you want them to be able to use Rails, then is imperative they can also integrate that work easily with yours by using a version control system.  This is essential for seemlessly integrating their changes with the project, sparing you time, and enabling faster change/deployments.

Your designer should set out on learning how to become comfortable using basic git commands such as understanding branches, how to push, pull and commit.  If merge conflicts happen you might be better off handling them yourself (these should not occur to much for the designer if most of their work is separate from your changes).

There are great GUI tools such as SourceTree that make learning and using Git much easier if you don't want to learn how to use git from the command line.

3. Explain the Rails file/folder system where relevant

In a Rails app, your designer does not need to know too much about a Rails filesystem to get working.  They just need to know what part of the file system to focus on:

app/views: Where HTML files are stored. Here some concepts they need to know to get working is:

Data portions of the html can be spotted because they use ERB tags: <% --rails-- %>.  Tell them this is usually the part they should avoid changing when manipulating the HTML.
(In your views it may help to use comments to explain to your designer where important data fields are showing up so they can design HTML/CSS targeting them properly)

Partials are snippets of HTML that can be detected because they have an underscore in their name.  E.g. _edit.html.erb is a partial.  index.html.erb is not.

The main app layout is found within app/views/layout.  Explain the <%= yield %> ERB tag is what loads the other parts of the app's views for each page.

For front-end javascript/stylesheets/images:

app/assets or app/public:

Inside asset pages (e.g. home.css.scss) correspond to the name of every view folder's title.

From here, you can even go farther by helping them gain a little knowledge about how stylesheet precedence is handled by the asset pipeline in Rails (and compiles into a single application.css files). If they have knowledge of sass or less, it may also be useful to explain how these files compile down to css e.g. home.css.scss -> home.css

4. Teach them How to Start a Rails Server

To work within Rails a designer needs to learn basic command line actions to at least enough proficiency to be able to boot Rails once the app is set up.

This means a designer will need to learn how to navigate the command line filesystem using cd and cd .., including how to get to the Rails projects root from their Path.

Inside a basic rails app project path, they just need to follow this workflow to get started:

git pull in latest changes from the rails app root directory.

bundle install

bundle exec rake db:migrate  [you may need to tell them to e.g. bundle exec rake db:drop db:create db:migrate db:seed to fix database issues occasionally]

rails s to start the server.

And then to visit http://localhost:3000 to load the app's webpage.

Now they're done! Also remind them to use ctrl + c in the command line to stop the server if they are pulling in new changes.

By this point, your designer should have enough knowledge now to make html/css changes directly inside your Rails app comfortably within your existing project.

It's likely you will need to still help them out when complications arise (such as their database getting out of sync, or needing special account powers to work in a restricted part of your site), but the time savings you will gain will still make pursuing integration worth it.

ContentLicense: CC BY-SA 3.0


问:
Why Java is a factor 2-3 slower than equivalent C++ program?
I know there is an opinion that programs written in Java and running under JVM as as fast as C++ programs, after introducing just-in-time (JIT). I see many cases when Java is terribly slow for simple programs compared to C++, i.e. about factor 2-3 slower than equivalent C++ programs.

Just give you a small example: This is simple benchmark code to merge particles in clusters:

https://github.com/chekanov/hepjet

Go to "scjet_cpp" and type "make; make run". This runs C++ code.
 Then go to "scjet_java" and type "make; make run". This runs the same
 code written in Java.

Th first C++ code finishes merging particles within 50 msec (i7 desktop). Exactly the same Java code finishes for 170 ms. There is nothing special about the code, i.e. identical implementation in C++ and Java.

Any comment?

答:
There is no one answer to this, largely because it's not always true. In fact, arguably it's never really true. You can't measure the speed of a language, only the speed of some particular implementation (and rarely even of the implementation as a whole, only of its execution speed on some particular piece(s) of code.

Java code can be slower than C++ code--sometimes by a factor much larger than 2 or 3.

Java code can also be competitive with C++ code--but often requires substantially more memory to do so.

For a few, very specific, things Java can be faster than C++ that's written similarly.

That said, yes, on average code written in Java will run slower than (roughly) equivalent code written in C++. If your primary concern is with execution speed, Java has a number of disadvantages.

The main one is that it depends heavily on a JIT compiler for optimization--but since the user is waiting while the JIT compiler runs, most JIT compilers don't include the most expensive optimizations. Since a C++ compiler typically runs with only a developer waiting (or nobody waiting, in the case of server-based builds with CI systems and such) it's much more reasonable for the compiler to include every optimization in the book.

A second factor is closely related: C++ vendors see their customers as being extremely concerned with speed. Java vendors almost certainly see their customers as being more concerned with things like features and fast development than with achieving absolutely the highest possible execution speed. That's not to say they can or do neglect execution speed entirely, just that they don't emphasize it to nearly the same degree as C++ vendors.

Garbage collection can have an effect as well. Java (normally) uses a concurrent, copying collector. This works reasonably well across a wide variety of work loads, and most JVMs have some "tuning knobs" to help out when the default setting aren't optimum.

Nonetheless, testing seems to indicate that a JVM requires substantially more memory than equivalent C++ code to even hope to run at (approximately) the same speed. Especially when you're running in a memory-constrained situation, the overhead from garbage collection can increase substantially. This typically stems less from how often the garbage collector runs (in itself), than from the fact that when it runs, many objects are still "alive". A copying collector works by copying "live" (reachable) objects into a new location, so ideally you want nearly all objects to be "dead" (unreachable) before it runs. With less memory, it not only runs more often, but each iteration takes longer because fewer objects have aged enough to "die", and more objects remain reachable (and therefore need to be copied).

There's also a difference in the amount of work that's done at run time vs. compile time. C++ places a high emphasis on doing as much as possible at compile time. For example, all the cool template "stuff" happens entirely at compile time (at the expense of horribly long compile times in some cases). Despite similar syntax, much (most?) of Java's enforcement of types in its generics system happens at run-time. Java also includes (and many Java programs use) such things as reflection, which simply aren't present in C++.

Java also adds a number of convenience features such as auto-boxing that make it fairly easy to add quite a bit of overhead to seemingly simple operations in ways that aren't immediately apparent. C++ has some of these as well, but (it seems to me) they're both fewer in number, and their detrimental effects are typically somewhat less drastic (but my opinion on that may well be affected by the fact that I know C++ quite a bit better, so to me, similar problems may seem much more obvious in C++ than in Java).

Bottom line: it's difficult to point to a single, specific reason that Java programs are slower than C++ programs. Although it's true much more often than not, the reasons for its happening vary widely, and in many cases it seems to be more the "death of a thousand nicks" than being the result of a single factor.


问:
What are the languages, objects, data types, operations and features for lower levels in a multilevel model of a computer system?
From Structural Computer Organization by Tanenbuam

In a certain sense, a computer with n levels can be regarded as n different virtual machines, each one with a different
  machine language. We will use the terms ‘‘level’’ and ‘‘virtual machine’’ interchangeably. However, please note that like many terms
  in computer science, ‘‘virtual machine’’ has other meanings as well.

There is an important relation between a language and a virtual machine. Each machine has a machine language, consisting
  of all the instructions that the machine can execute. In effect, a
  machine defines a language. Similarly, a language defines a
  machine—namely, the machine that can execute all programs written in
  the language.

The machine languages of levels 1, 2, and 3 are numeric. Programs in them consist of long series of numbers, which are fine
  for machines but bad for people. Starting at level 4, the
  languages contain words and abbreviations meaningful to people.

What are the terminologies/names for the machine languages of level
0, 1 and 3? (The languages for the other levels are apparent to me)

In summary, the key thing to remember is that computers are designed as a series of levels, each one built on its predecessors.
  Each level represents a distinct abstraction, with different
  objects and operations present. By designing and analyzing computers in this fashion, we are temporarily able to suppress
  irrelevant detail and thus reduce a complex subject to something
  easier to understand.

The set of data types, operations, and features of each level is called its architecture. The architecture deals with
  those aspects that are visible to the user of that level.
  Features that the programmer sees, such as how much memory is available, are part of the architecture.

What are the "objects", "operations", "data types", "operations" and
"features" for level 0, 1 and 3?

Thanks!

答:
Level 0 is the digital logic level, or basically all of the circuitry.  Operations are on-off switches, data types are boolean values and numbers.  Features are logic gates, clocks, traces, semiconductor wafers, and so forth.  The machine language is simple binary.

Level 1 is the Micro-Architecture level. If you look at a micro photograph of the die in an Intel microprocessor (actual size is about the size of the nail on your little finger), you start to see higher-level features or "modules" on the landscape:

The data types are numbers, specifically integers having a width corresponding to the architecture (e.g. 32 bit numbers or 64 bit numbers), although communication can still occur between modules that is strictly binary.  Operations are defined by the boundaries between modules, and by the functions of the modules themselves.  The machine language is still pure binary, although the makings of a microcode language that implements the instruction set become apparent at this level.

Level 3 is the Operating System Machine Level.  Tanenbuam defines the OSM level as the “complete set of instructions available to the application programmer.” The machine language contains nearly all the ISA level (2) instructions and new instructions for “system calls”.  Data types are expanded to include strings, floating point numbers, binary images and user-defined types.  Operations include process control, memory control, file control and device control.  Operating systems can contain many features which hopefully are obvious, but include some sort of user interface, configuration management, device drivers, etc.

Further Reading

Microarchitecture on Wikipedia

Notes on the Operating System Machine Level

Presentation on the Operating System Machine Level


问:
git strategy on merging/rebasing feature that was abandoned but is being revived
Say we have this situation:

```<code>* master
|
* a
|
* b
      ... a lot has happened
*
      ... a lot has happened
* z
|
|  * aa (want to rebase onto master or merge into master but having too many conflicts)
|  |
|  * bb
....
|  |
|  * yy
|  |
|  * zz
| /
* parent
</code>```

parent to master has extensive code refactoring done
parent to aa has extensive code refactoring done, but different refactoring

I need to merge aa into master.  Or rebase aa onto master, in order to bring aa back into business.

I tried doing both, and both seem painful.  I have about 13 rebase fixes to do if I go the rebase route. and as I go step by step, something breaks because of the different refactoring done on either branches.  So I in a way re-refactor and amend things when I rebase.

When I do the merge, at least I know what I need to fix right away, as all conflicts are shown immediately.  Except the aa feature was done so long ago I can't readily wrap my head around all the conflicts.  I could say that rebase, at least, gives it to me step by step.

But both seem quite difficult and I know that git has an excellent reputation when it comes to merges.  So maybe I am struggling for naught?  Is there a better way?

My goal is to bring parent to aa path back into my master.

答:
While git is great, merging/rebasing an out-of-date feature branch is always going to be a painful experience. There is no magic bullet (of which I am aware) that will make this headache go away.

In my experience, I prefer rebasing over merging in these situations for the reasons you mentioned: you can resolve the errors in each commit one at a time, and ensure that everything builds and your tests pass before moving on to the next commit.

In extremely difficult rebases, I have actually reimplemented the feature using the commit diffs from the feature branch as a guide. As crazy as it might sound, it can actually be much quicker to quickly add a few classes and tests to the current codebase than to resolve conflicts for a feature that was a designed for a very different and out-of-date codebase.


答:
As to why Java can be slower well:-

The JVM needs to interpret pseudo machine code, C++ blindly executes
native machine code.

The JVM manages memory, C++ its up to the programmer to manage memory
which is more efficient but also more error prone.

The JVM needs to start up, then load and interpret the various
classes; with a C++ program load is basically copying the
instructions from disk to memory, in many cases (with DLL, .so, shared
libraries etc.) the program will have already been loaded and is sitting
in memory ready to go. This is actually the biggest performance hit
with Java and makes the language totally unsuitable for short running
independent executions.

While java may be up to three times slower it is often almost as fast as C++. You have to ask yourself if this really matters when you are running on a 3ghz processor which is spending most of its time waiting for memory to be loaded (or worse disk IO).

The other side of the equation (highly subjective, but, backed by years of experience) is that Java programs can be developed up to three times faster. The toolsets are more functional, there is a vast selection of really good libraries to choose from, and a limited number of gotchas to look out for (no if (a = b), no mixing up pointers with the pointed to).

Personally where I feel the need for speed I code in plain C. Its a language I know well and the performance constrained parts of a system tend to be small and well defined.

So its C for speed. Java for production code. Groovy or Python for everything else!

Title: Why Java is a factor 2-3 slower than equivalent C++ program?

Body:
I know there is an opinion that programs written in Java and running under JVM as as fast as C++ programs, after introducing just-in-time (JIT). I see many cases when Java is terribly slow for simple programs compared to C++, i.e. about factor 2-3 slower than equivalent C++ programs.

Just give you a small example: This is simple benchmark code to merge particles in clusters:

https://github.com/chekanov/hepjet

Go to "scjet_cpp" and type "make; make run". This runs C++ code.
 Then go to "scjet_java" and type "make; make run". This runs the same
 code written in Java.

Th first C++ code finishes merging particles within 50 msec (i7 desktop). Exactly the same Java code finishes for 170 ms. There is nothing special about the code, i.e. identical implementation in C++ and Java.

Any comment?


问:
How should calculations be handled in a document database
Ok, so I have a program that basically logs errors into a nosql database. Right now there is just a single model for an error and its stored as a document in the nosql database.

Basically I want to summarize across different errors and produce a summary of the "types" of errors that occured.

Traditionally in a SQL database the this normalization would work with groupings, sums and averages but in a NoSQL database I assume I need to use mapreduce.

My current model seems unfit for the task, how should I change the way I store "models" in order to make statistical analysis easy? Would a NoSQL database even be the right tool for this type of problem?

I'm storing things in Google AppEngine's BigTable, so there are some limitations to think of as well.

答:
Try to look at Hadoop wikipedia

Dunno if it works with you DB.

Maybe this post will be helpful:Mail archive

ContentLicense: CC BY-SA 2.5


答:
To avoid speaking on false premise here, I would like to see at least part of the disassembly generated from the hot spots (tight loops where the CPU spends most of the time) from the two programs, before I would say anything substantial here.

For Oracle JVM, the following option can be used to save a copy of the machine code generated from JIT:

https://wikis.oracle.com/display/HotSpotInternals/PrintAssembly

For C++ running on x86, I recommend AMD CodeAnalyst on Windows, and objdump on Linux.

One should take close look at:

The function calls (those that haven't been inlined)

The loops (to see how they are nested, and how many times they are executed)

The use of floating point instructions

Whether it uses the old x87 stack or the new SSE2 scalar/vector floating point instruction.

Use of expensive floating point instructions, and evidence of any optimization techniques done manually by each program's original author.

Use of library calls for handling math functions

If you do not already know the hot spots of the program, use a Low Overhead CPU Profiler to identify them first. Make sure not to confuse with high-overhead profilers. They are meant for different purposes.


问:
C# if statements
I am currently working on a C# checkers game for a university project in programming. But i have came to the point where i need to check whether a piece can be moved, or jump, but i feel like i'm using lots of code that isn't necessary to get true or false answers.

```<code>if (arrayX == 0)
{
    if (board.GetBoard(arrayX + 1, arrayY - 1).Piece == null)
    {
        return true;
    }
}
else if (arrayX == 7)
{
    if (board.GetBoard(arrayX - 1, arrayY - 1).Piece == null)
    {
        return true;
    }
}
</code>```

For example, is there a more efficient way of doing these if statements? In the code i have more if statements branching off other if statements.
So in summary, is there a way you can check loads of parameters, efficiently, without using loads of if statements branching off of one another?

答: It looks like you are testing edge cases.  You can often cut way down on the edge case testing by removing the edges from the problem.  Instead of the 8x8 board of checkers, internally make the board 12x12.  (Note that this would be easier in a language like Pascal that permits non-standard array bounds.)  Now you don't have to worry about most edge case testing--there's enough space out there that the destination of any possible move exists.  You still need to reject moves that would go off the edge of the board but even this can be done with a single statement (have an array of good and bad squares, if the prospect cell is a bad cell reject the move.)</p>

Title: C# if statements


问:
What's best for a client library: userland code or schema files?
I'm building a client library that consumes a collection of OpenStack API services. I know that as time goes on more services will be added - so I want to come up with a clean and neat way of structuring my client library to minimize development time (for future new services) and avoid duplication.

So far, I've thought of two solutions:

Implement userland code from scratch. Each service uses an underlying HTTP client, and for every API operation there is a concrete method in a concrete class that encapsulates logic. This is your standard application where everything exists in concrete code. Advantages are that it is straightforward and obvious for new contributors; disadvantages is that writing code is slow and there is a risk of duplicating boilerplate code.

Implement some kind of service description layer - similar to WADLs but lighter and written in JSON. Each description document would act similar to Google's Discovery API where the API's resources are defined using JSON Schemas; HTTP operations are defined with all their parameters, URIs, verb types, expected status codes, etc.; authentication is also defined. Advantages are that it takes less time to write, it avoids duplication, and it forms an explicit contract which is useful for end-user documentation. Disadvantages are that it's quite meta-like and difficult to understand for newcomers.

There are a number of popular client libraries that use this kind of schema pattern, but I'm trying to weigh up its positives and negatives. I'm leaning towards using schemas because I think they'll save time developing and avoid duplication. OpenStack APIs seem to be also moving towards json-schema.

Are there any strong reasons why relying on schemas is a bad idea for a client library, and/or why userland code is a better approach?

答:
Given the way the question is phrased, there obviously cannot be the correct answer, but you are asking for pros and cons. Here I argue solely for concrete code.

My first argument against schema comes along as a question: why not WADL? You want it more lightweight and in JSON! Are you sure you know where to cut the weight on WADL without later learning that you missed some points? Why JSON and not XML? The difference is superficial. My hunch is that you feel that WADL is not the right way to do these things and you think that its problems are weight and XML, but they may be deeper. You give a good arguments yourself: "difficult to understand for newcomers." That means your colleagues cannot help out shortly and you will not understand it anymore after leaving it alone for half a year --- "difficult to maintain" I would call it.

Language design is difficult: You are up to designing a formal language to describe the services you want to attach to. Getting a formal language right is a difficult task, as can be seen in how all programming languages initially have their quirks and evolve over time. There is a good chance that your first design is, well, suboptimal.

Risk of code duplication in my opinion is not an argument against concrete code. Instead of investing up-front in the super-duper all encompassing service description, why not investing just a bit of time constantly in refactoring. Only after having coded some services will you know where the boilerplate code really is that you can factor out into your own support library. As time goes, this support library may do for you what your service description is intended to do --- and better: speed up development of further services.

Spring may be kind of a counter argument. When they started, a lot of coding migrated from Java into XML files and was called configuration. What they actually had was a kind of interpreted, untyped programming language based on XML syntax, including the disadvantage that code brakes in production instead of in the compiler. Then some time ago the new hype was that Spring can now do without XML.

Jetty and Tomcat are similar examples and I guess that Spring was inspired by the XML configuration of Java Servlet applications. But finally Tomcat came out with an "embedded" version where the servlet application can be constructed in pure Java, no external XML configuration required, all concrete code. And Jetty seems to have started with Java-only, concrete code as a design goal.

Bottom line: before moving logic out of your code and into some home-baked description language, think twice, then think it over, then go for concrete code first.-)

It would be interesting to hear after a year how things turned out.


问:
How can I ask my boss (in a polite way) to comment his code?
I am being taught by my boss (I just finished school and he wanted someone with a little programming experience, so he chose me to train me on what that company specializes in) and started working with ASP.NET MVC applications, some HTML and CSS. I'm fine with the web design stuff he gives me (it is pretty simple to understand without clarification).

But for instance, he gives me a task to do with ASP.NET MVC, he explains it really well. But he doesn't explain anything in the code he has just given me. (We use source control in Visual Studio 2013), so it's literally hundreds of lines of code, without any background on what it is supposed to do. The kind of code that I'm seeing is code I've never seen before, so it is really difficult to try and figure out.

I would try and ask him more questions, but he is always working (it's his own business), and I feel as though he might get annoyed with all these questions I have on my hands.

So just something that will help my out until I get a grip on things, how can I ask my boss to put comments into his code that he gives me, but politely?

答:
This is more than just a personal request.  You are trying to change habits / culture, and that is not easy.  It's certainly not something that can be accomplished by a hallway conversation or an e-mail.  It's going to take some effort on your part.

Be the change that you wish to see in the world.

The quote may be falsely attributed to Mahatma Gandhi, but it's applicable advice.  As you try to puzzle out the codebase, write the comments that you would like to have seen, to the best of your ability, and commit them, after being reviewed by your boss.  Advantages:

You're being proactive, rather than nagging.

You're setting a good example.  In the best case, your boss / team will see the benefits and follow suit.

Some of the comments will probably say /* Mystery parameter 3 */ or /* 2015-02-09 AidanQuinn: Is this code ever called? */ — those are opportunities for your colleagues to either document the code properly or fix latent bugs.

If, during the pre-commit review, it is discovered that a comment you wrote is inaccurate, then your colleagues now know that the code was unclear.

Refrain from any rewriting or refactoring as you do this, and the introduction of comments should be nearly risk-free.  If you do rewrite anything, keep those changes as separate commits.

(Before you embark on this project, though, be sure that your expectations for comments are reasonable.  If your idea of well-commented code is outside the norm (Example 1, Example 2), then you'll only be making a fool of yourself.)


问:
Are there any easy-to-follow/reliable methods for simplifying code?
There is a problem with the way I code. Regardless of how much of a plan I write beforehand, the code becomes overcomplicated quickly.

Reading books on good practice and attempting to adhere to their principles isn't working.

Is there some surefire/proven way of auditing code to simplify it, other than being more thorough and dedicated in the planning stage?

答:
There are indeed techniques for gradually simplifying code and improving design by doing so. The general technique is known as "refactoring". Note that this term is used both informally (to mean "anything that changes how code is designed without changing what it does") and formally (to mean "following a specific refactoring discipline"). I am referring to the latter definition here.

In particular, this problem has been much studied by Martin Fowler, and his book "Refactoring: Improving the design of existing code" is one of the classic books of software engineering, and is well worth reading in this area.

The general technique that the book suggests is:

1) Write very detailed tests for the section of code you intend to refactor.

2) Make a specific SMALL change to the code. For example, inline a method, rename a class, extract some code into a new method, extract a superclass from an existing class, etc. (Fowler has detailed lists of many such small transformations in his book, along with suggestions on how/when to do them. Most of the names of existing "automatic refactoring" features such as those in Eclipse, IntelliJ, etc. were taken from those used in his book. Essentially, these are like "design patterns" but are used for modifying existing code rather than for designing it in the first place.)

3) Re-run your tests, to verify that you haven't broken anything yet.

4) Repeat until you are satisfied with the results.

Thus, large changes to the code can be made by accumulating multiple small changes, with testing between each change.

Obviously, if you are in the habit of writing and retaining detailed tests for your code in the first place (a unit test suite, regression test suite, etc.), the above process will be much easier than if you have to write the tests immediately before you start refactoring. Also, it will be much easier to do this if the part of your test suite that you are re-running between each change is capable of running quite quickly.

Note that refactoring code in this way is a DISCIPLINE. It is not the same as simply randomly going around changing code. The frequent testing during the process is essential for ensuring that any inadvertent changes that you make to the program's behavior are quickly caught, while you can still remember what you did. For this reason, it is also often a good idea to do refactoring separately from other development which adds or changes the behavior of the program, since those sorts of changes are likely to invalidate existing tests. You could, for instance, alternate phases: Add a feature, then refactor a bit, then add another feature, then refactor some more, then fix a bug, then refactor, etc.

If you are consistent in programming using these techniques to simplify your code, the overall trend of your code over time will be that it gradually becomes simpler and easier to read, rather than the reverse (which is, sadly, more common in industry).

You may also find that some of the community around the Agile and/or XP software development methodologies may be helpful as to how/when/what to refactor, since continuous refactoring in this manner is considered a required feature of many such methodologies.

I have seen many projects gradually become so crufty and complicated that nobody understood them and they eventually had to be discarded, because maintaining them eventually took more effort than rewriting them would. Refactoring is a way to avoid this problem.


答:
I have been in a very similar situation to yours roughly a year ago. I started working with little programming experience (though I knew a bit of OO and some other languages to begin with) and the one person teaching me had very little time. He was always helpful, but I felt like I wouldn't want to ask every single question I had.

Others have already suggested extremely helpful stuff here (writing unit tests for example, but from my own experience, that is something that would have gone a bit 'too far' for me from scratch; or commenting parts of the code yourself, but that may be difficult depending on the first point/question I'll be asking you in a minute). The following points sum up what I did and what helped me, but it depends a lot on where exactly your problems lie.

Also, I have to agree with @AK_ who said that you don't really need comments in C#. That may not be 100% correct (I feel there's areas where comments definitely help, e.g. Reflection-heavy code) but in essence it is. If you write really 'clean code' with well-named methods and variables, and have lots of small 'bites' of code, they will be almost totally unnecessary. Everytime I felt the need for comments when reading code so far, then after I understood what it did, I was very unhappy with the way it was done and thought it could have been way clearer in the first place by good refactoring.
Edit: I'm specifically talking about C# comments here, not documentation (be it separate documentation or XML comments), as I think that documentation is always important.

Identify what exactly your problems are and if you can categorize them. That is, do you still have problems with the language itself or don't understand a specific syntax (e.g. lambda expressions and LINQ in general, or Reflection)? If you don't understand lines of code, you won't understand what the whole method/block does, so commenting it yourself will be hard. Rather, get a good book ('C# in a Nutshell' it was for me, but I heard 'C# in Depth' is spectacular as well) and read up on the things you encounter. Categorizing these problems beforehand makes this easier, as you can fill 'bigger gaps' at once, or even ask your boss about it, as it's not lots of questions anymore, but rather explaining a single subject or the most commonly used constructs so that you can get a huge 'boost' in this area quickly.

Parallel to the above, I tried making myself familiar with 'clean coding' and best general practices (not language specific). The effect of this may not be immediate, but it will pay off sooner or later, either when you have to extend existing stuff or wonder why someone created so many small methods instead of one where everything is contained ;-)

Get a grasp of common design patterns. They may be appearing here and there in the code you're reading, and if you recognize them it will immediately give you an a-ha moment. Even if you understand what the code you see there does, it may make you wonder why it is done this way, and figuring this out all by yourself is often not that easy.

Please don't take the above text as me making assumptions about your 'skill', I often accidentally switch between talking about my experiences and talking 'to you'. It's mostly meant as what I encountered, and what I did.
As others have said, this can be a very good experience and it's pretty much the standard in the job to read code that's not your own and that you don't know much about beforehand. But it can be really satisfying to finally grasp what's going on there and recognize yourself getting better at this particular 'skill'. Take this as an opportunity to learn a lot in really short time, good luck! :)

Title: How can I ask my boss (in a polite way) to comment his code?

Body:
I am being taught by my boss (I just finished school and he wanted someone with a little programming experience, so he chose me to train me on what that company specializes in) and started working with ASP.NET MVC applications, some HTML and CSS. I'm fine with the web design stuff he gives me (it is pretty simple to understand without clarification).

But for instance, he gives me a task to do with ASP.NET MVC, he explains it really well. But he doesn't explain anything in the code he has just given me. (We use source control in Visual Studio 2013), so it's literally hundreds of lines of code, without any background on what it is supposed to do. The kind of code that I'm seeing is code I've never seen before, so it is really difficult to try and figure out.

I would try and ask him more questions, but he is always working (it's his own business), and I feel as though he might get annoyed with all these questions I have on my hands.

So just something that will help my out until I get a grip on things, how can I ask my boss to put comments into his code that he gives me, but politely?


问:
What to do when time estimation goes wrong?
Let’s say you estimated time for a case to be 3 days.
In day two you notice that the case is growing and new scenarios are popping up which were not counted when the time estimation where done.  The new finding leads to 2 days extra (total 5 days). This is a typical problem that you will face sooner or later as developer.

Which strategy can be used when you are going to notify project leader the new time of delivery?

Often you get the question why? How do you motivate the new time of delivery?

The fact is that many projects don’t put much time on analysis & design during SDLC.

EDIT:
In very complex projects no matter how much reasonable time you put on Analysis & Design there are always surprises since the business rules are too complex. However in such cases I believe the project leader must be aware of the complexity and have right attitude when unexpected surprises comes up. The question is how to tackle project leaders who don’t understand the complexity.

答:
As soon as you see the estimate being wrong you need to raise the alarm bell. Inform those who expect the delivery about the delay.

Ask for help from team-mates if possible. Make sure that you still deliver as high quality software as possible.

A short-cut will most likely do more harm in the end, and everyone involved should know this. Or atleast should it be possible to explain it to them.


问:
Why is the 'out' keyword used in two seemingly disparate contexts?
In C#, the out keyword can be used in two different ways.

As a parameter modifier in which an argument is passed by reference

```<code>class OutExample
{
    static void Method(out int i)
    {
        i = 44;
    }
    static void Main()
    {
        int value;
        Method(out value);
        // value is now 44
    }
}
</code>```

As a type parameter modifier to specify covariance.

```<code>// Covariant interface.
interface ICovariant<out R> { }

// Extending covariant interface.
interface IExtCovariant<out R> : ICovariant<R> { }

// Implementing covariant interface.
class Sample<R> : ICovariant<R> { }

class Program
{
    static void Test()
    {
        ICovariant<Object> iobj = new Sample<Object>();
        ICovariant<String> istr = new Sample<String>();

        // You can assign istr to iobj because
        // the ICovariant interface is covariant.
        iobj = istr;
    }
}
</code>```

My question is: why?

To a beginner, the connection between the two doesn't seem intuitive. The use with generics doesn't seem to have anything to do with passing by reference.

I first learned what out was in relation to passing arguments by reference, and this hindered my understanding of the use of defining covariance with generics.

Is there a connection between these uses that I'm missing?

答:
There is a connection, however it is a little loose. In C# the keywords ´in´ and ´out´ as their name suggest stand for input and output. This is very clear in the case of output parameters, but less clean what it have to do with template parameters.

Lets take a look at the Liskov substitution principle:

...

Liskov's principle imposes some standard requirements on signatures
  which have been adopted in newer object-oriented programming languages
  (usually at the level of classes rather than types; see nominal vs.
  structural subtyping for the distinction):

Contravariance of method arguments in the subtype.

Covariance of return types in the subtype.

...

See how contravariance is associated with input and covariance is associated with output? In C# if you flag a template variable with out to make it covariant, but please note you can only do this if the mentioned type parameter only appears as output (function return type). So the following is invalid:

```<code>interface I<out T>
{
  void func(T t); //Invalid variance: The type parameter 'T' must be
                  //contravariantly valid on 'I<T>.func(T)'.
                  //'T' is covariant.

}
</code>```

Similary if you flag a type parameter with in, that means you can only use it as input (function parameter).  So the following is invalid:

```<code>interface I<in T>
{
  T func(); //Invalid variance: The type parameter 'T' must
            //be covariantly valid on 'I<T>.func()'.
            //'T' is contravariant.

}
</code>```

So to summarize, the connection with the out keyword is that with function parameters it means that it is an output parameter, and for type parameters it means that the type is only used in output context.

System.Func is also a good example what rwong mentioned in his comment. In System.Func all input parameters ar flaged with in, and the output parameter is flaged with out. The reason is exactly what I described.

Body:
There is a connection, however it is a little loose. In C# the keywords ´in´ and ´out´ as their name suggest stand for input and output. This is very clear in the case of output parameters, but less clean what it have to do with template parameters.

Lets take a look at the Liskov substitution principle:

...

Liskov's principle imposes some standard requirements on signatures
  which have been adopted in newer object-oriented programming languages
  (usually at the level of classes rather than types; see nominal vs.
  structural subtyping for the distinction):

Contravariance of method arguments in the subtype.

Covariance of return types in the subtype.

...

See how contravariance is associated with input and covariance is associated with output? In C# if you flag a template variable with out to make it covariant, but please note you can only do this if the mentioned type parameter only appears as output (function return type). So the following is invalid:

interface I<out T>
{
  void func(T t); //Invalid variance: The type parameter 'T' must be
                  //contravariantly valid on 'I<T>.func(T)'.
                  //'T' is covariant.

}

Similary if you flag a type parameter with in, that means you can only use it as input (function parameter).  So the following is invalid:

interface I<in T>
{
  T func(); //Invalid variance: The type parameter 'T' must
            //be covariantly valid on 'I<T>.func()'.
            //'T' is contravariant.

}

So to summarize, the connection with the out keyword is that with function parameters it means that it is an output parameter, and for type parameters it means that the type is only used in output context.

System.Func is also a good example what rwong mentioned in his comment. In System.Func all input parameters ar flaged with in, and the output parameter is flaged with out. The reason is exactly what I described.


答:
Post your code to Code Review, and let someone else simplify it for you.  ☺

In seriousness, if you study the simplifications recommended among the thousands of Code Review answers, you'll find that the range of techniques is far too broad to summarize in an answer.  Just off the top of my head, I can think of:

Don't reinvent the wheel.  Don't write code at all, if possible.

Pick the right programming language for the job.  (Joining two datasets is vastly easier in SQL than in Java, for example.)

Write code that is idiomatic for the chosen language.  (For example, in Python, take advantage of itertools and list comprehensions.)

Use an appropriate framework or library where possible.

Pick the right algorithm.  (Sometimes there will be a speed / simplicity trade-off, though.)

Avoid premature optimization.

KISS and YAGNI

Pick the right data structure.

Use recursion / iteration where appropriate.  Use OOP / functional programming where appropriate.

Use design patterns that fit your problem.

Refactor relentlessly.

… and more…

Basically, as @RobertHarvey says, Practice.  But now I've given you a resource where you can take advantage of other programmers' experience.

Title: Are there any easy-to-follow/reliable methods for simplifying code?

Body:
There is a problem with the way I code. Regardless of how much of a plan I write beforehand, the code becomes overcomplicated quickly.

Reading books on good practice and attempting to adhere to their principles isn't working.

Is there some surefire/proven way of auditing code to simplify it, other than being more thorough and dedicated in the planning stage?


问:
Secure Form Submission
This is probably a no brainer, but I've not been able to find an answer that is definitive.

I have a Codeigniter site running on Apache with mod_rewrite (to get rid of index.php) and mod_ssl for HTTPS.  My question is.....

If at https://example.com/form.php I have a form like this...

```<code><form action="/process.php">
.....
</form>
</code>```

Will that form be submitted to HTTPS, or is it going over HTTP?  Do I have to explicitly say HTTPS in the action?

答:
If you have a link (or form action) with a relative URI (without a scheme and hostname), then the URI will be completed with the scheme and hostname of the page containing the link.

This means that, if you are on the page "https://example.com/form.php", then the link/action "/process.php" will result in a request for the URI "https://example.com/process.php".
Similarly, that link on the page "http://nowhere.example.com/form.php" will go to "http://nowhere.example.com/process.php".

Title: Secure Form Submission


问:
Game architecture - connecting different parts of the game
I do a bit of solo game development and always get stuck on some part of the architecture where I can't decide what the best way to tackle a problem is. I've just run into a good architecture problem, and I'm hoping I'll be able to use lessons learned from it down the road.  I'll abstract it down a bit to a theoretical problem:

Say my game has two abilities, "Heal Player" and "Stun Enemies". Each of the abilities is reusable with a cooldown. The game will need a separate button to activate each of the abilities.

The core class for gameplay is called GameplayCore. My GUI is all contained in an HUD class, and the enemies are all controlled by an EnemyManager. The Player class contains the player's health. GameplayCore creates and stores the HUD instance, EnemyManager instance, and Player instance.

Obviously I want to separate the UI code from the functionality code. So say on the GUI side I've got HealButton, StunButton, and HealthBar classes that define the appearance and behavior of those controls. On the functionality side, I've got the Player class with a health property, an AbstractAbility class that defines shared ability behavior including cooldown, and the HealAbility and StunAbility classes that extend it to define concrete implementations.

To keep GameplayCore from getting too bloated, I make an AbilitySet class to create and manage the HealAbility and StunAbility instances, and make an instance of AbilitySet in GameplayCore.

Here's where things start to fall apart. I want to be able to change the appearance of the buttons as their cooldowns elapse. I want the cooldown code to be self-contained in AbstractAbility, so HealAbility and StunAbility need references to their corresponding buttons. Now I need to pass those references back from HUD to GameplayCore and then into the constructor of AbilitySet so they can be passed into the constructors for the ability buttons. HealAbility needs references to the HealthBar (in HUD) and the Player (in GameplayCore). StunAbility needs a reference to EnemyManager so it can retrieve the collection of enemies to loop through and stun them. But HUD needs references to the HealAbility and StunAbility so it can call them when the buttons are pressed.

Everything has gotten pretty tangled; there is too much coupling and I'm honestly not sure where the best place to construct the ability classes is. I'm very tempted to merge all of the ability code into the ability buttons, which would greatly simplify everything, but then I'd have important functionality code mixed into a UI class.

What's a good organizational approach to this problem? What are some good architectural strategies I could use to keep the code from getting too tangled? Is my entire approach heavily flawed?

edit: I should note this particular project is in ActionScript 3, which does include an event system (with its own quirks and limitations).

答:
As Stephen suggested in his comment, you could use the observer Pattern to connect the different parts of your application.

However, this is a rather static approach, and you will have to implement interfaces everywhere and the dependencies are still strong. Since this is  a game, your structure, logic and gameplay might will change over time.

I'd recommend using an event-based approach. It works similar to the Observer, with the difference that neither the sender nor the receiver know about each other (no explicit "notify").

You'd simply fire an "HealthChanged"-event, and every component that is interested will just act accordingly.
You can achieve this by using an Event bus.

If you want to make the program really un-coupled and flexible, you might consider using the event mechanics together with an Entity system

It's a component-based approach: Instead of having a health attribute in the player class, the player would be defined by it's components : Health, Attack and Position (or whatever else).

Since I'm not sure if this might be too much overhead for a free-time-project like yours, I won't go into much detail here. But you can check the above link and more detail here


问:
HTTP keep alive and TCP persistent connection
What's the relationship between the two concepts?

Is one HTTP Keep-Alive connection always over a long persistent TCP connection? When the HTTP connection is closed, will the TCP connection be closed at the same time?

Or can multiple HTTP requests, including Keep-Alive ones, run over a single TCP connection?

答:
Is one http keepalive connection always over a long persistent tcp connection

There is no such thing as a "persistent" TCP connection. All TCP connections persist from connection start to close.

When the http connection closed , will the tcp connection be closed at the same time?

There is no concept of "close connection" for HTTP. HTTP knows only requests and responses and an exchange is done the request is fully send and the response is fully received. With keep-alive you can have multiple such exchanges inside a single TCP connection.

Close of TCP connection means close of HTTP connection, but there is no explicit close of the HTTP connection.


问:
How much to "automatically" do?
I'm reading Code Complete 2, and I'm at the chapter where it says to (paraphrasing) "avoid programming through the interface."  Why is it bad to program "through" the interface?

A more concrete example: if I have a method of a class that submits a funny picture, what's wrong with it logging me in also?  Should I simply provide more "helper" methods that do it automatically?

Would it be preferred to break it up into:

set_login(username, password)

login()

submit_picture(funny_picture)

easy_submit(funny_picture) # where it will log in (if not already) and submit

答: Wrong or correct it depends on the level which that code is going to be used of. What will happen, if you want to submit more than one picture? On this example, I would divide it into two levels, say, core and application. The core level provides basic facilities (login(u, p) and submit_data(data, type)), and the application layer provides helper methods. And would use them appropriately depending on the context.

Title: How much to "automatically" do?


答:
Even if there is a way to ask this politely, there are two possibilities as to what your boss will think about comments in his code:

Either that comments in his code would be a good thing to have, or

That comments in his code would not be a good thing to have.

If your boss thinks that comments in his code would not be a good thing to have, (and there are very good arguments for this, i.e. the code is supposed to be the documentation, and no documentation will ever stipulate something as precisely and as unambiguously as the code that actually does it,) then nothing will happen.

Now, if by any chance your boss thinks that comments in his code would be a good thing to have, then there is a considerable chance that he will tell you to study his code, understand how it works, and proceed to add comments to his code yourself. (There are very good arguments for this too, i.e. you need to learn, and his time is by definition much more valuable than yours.)

So, unless you are prepared to have to do this, you might be better off not saying anything.


问:
Feasibility Study Format on SDLC
Is there a specific format for a feasibility study in SDLC? If so, do you know any sources where I can find more information about this? or can you show me at least an outline of what it should contain?</p>

答:
I would have thought a feasibility study is part of your project management. Once that is completed you would start on your SDLC with analysis, design..etc. Or you may include pm in your SDLC according to company practice.

further to an answer, a feasibility study might include all project related costs, user acceptance, affects on company image, your ability to complete the project, time related risks etc..

Title: Feasibility Study Format on SDLC


问:
What is the rule for nested loop code?
I am new to programming and currently learning Java from Stanford free learning course.  There was this assignment that I had trouble translating my algorithm into code.  I feel like I have a misconception about nested loops.

My question in this code:

```<code>while (frontIsClear()) {   //LET THIS REFER AS BOOLEAN 1
  putBeeper();             //LET THIS REFER AS STAT 1
  if (frontIsClear()) {    // LET THIS REFER AS BOOLEAN 2
    move();                //LET THIS REFER AS STAT 2
  }
}
</code>```

If BOOLEAN 1 is TRUE but BOOLEAN 2 is FALSE  then will STAT 1 work or will it terminate everything?

I understand STAT 2 won't work because BOOLEAN 2 is false but I just don't get this loop inside condition etc.

答:
It Depends... If your putBeeper() method has any impact on this condition; frontIsClear(), it will not call to move() method if the conditional statement becomes false.

In your given example, there are no nested loops.
For example:

```<code>int i = 0;
while (frontIsClear()) {
 putBeeper();
 while (i<3) {
  move();
 }
}
</code>```

So you'll move 3 steps when frontIsClear().

Title: What is the rule for nested loop code?

Body:
It Depends... If your putBeeper() method has any impact on this condition; frontIsClear(), it will not call to move() method if the conditional statement becomes false.

In your given example, there are no nested loops.
For example:

int i = 0;
while (frontIsClear()) {
 putBeeper();
 while (i<3) {
  move();
 }
}

So you'll move 3 steps when frontIsClear().


问:
Changing a directive's template based on state
I'm trying to figure out the best patter for applying when writing a particular type of Angular directive. In this scenario, I want it to display a login form if a user is logged out, and then switch to a different view once logged in.

This isn't my complete app, so it's not a redirect as far as I can see. The specific example at the moment is that up in the top right of the page will be a last.fm login form, which will switch over to a last.fm widget if the user successfully logs in.

I could put both in the template and change them dynamically with CSS, but this somehow feels a little off. Can I swap a directive's entire template and recompile? Should I use two divs with ng-if statements?

I'm sure there are many ways of doing it, but is there a particularly Angular way of handling the situation?

答:
I'd use 2 different divs as you say with ng-if.  That is the desired behavior anyway... you essentially have 2 "mini views" (one logged in and one not) with separate functionality for this widget.

I wouldn't try to get fancy here for no reason.


问:
How do I enforce 'referential transparency' in this program?
Below is the python program written to follow the rule of thumb in functional programming.

The simple rule of thumb is: if you can replace any expression, sub-expression or subroutine call with the return value of that expression, sub-expression or subroutine call anywhere in the program, without the program changing its meaning, then you have referential transparency. And what this means, practically speaking is that you can't have any I/O, can't have any mutable state, can't have any side-effects. In every expression, the value of the expression must depend solely on the values of the constituent parts of the expression. And in every subroutine call, the return value must depend solely on the arguments.

```<code>def identity(k):
    return k

def cube(k):
    return pow(k, 3)

def summation(n, term):
    total, k = 0, 1
    while k <= n:
        total, k = total + term(k), k + 1
    return total

def sum_naturals(n):
    return summation(n, identity)

def sum_cubes(n):
    return summation(n, cube)

if __name__ == '__main__':
    sum = sum_naturals(4)
    print(sum)
</code>```

In above program, objects pointed by total and k maintain immutability of state and I/O is not used except in driver code to just confirm the results.

How do I enforce 'referential transparency' in my program for all the expressions/sub-expressions used in this program?

答:
You already said in your question how you can tell whether your program is referentially transparent or not: if you can replace a expression with its value, without changing the meaning of the program, it is referentially transparent. If you cannot do that, it is not.

So, let's just try and replace some expressions with their values!

in your summation method, in the first line, you set total to 0. So, if your program is referentially transparent, we should be able to replace any occurrence of total with 0. For example, like this:

```<code>def summation(n, term):
    total, k = 0, 1
    while k <= n:
        total, k = 0 + term(k), k + 1
    return total
</code>```

or like this:

```<code>def summation(n, term):
    total, k = 0, 1
    while k <= n:
        total, k = total + term(k), k + 1
    return 0
</code>```

The same goes for k:

```<code>def summation(n, term):
    total, k = 0, 1
    while k <= n:
        total, k = total + term(k), 1 + 1
    return total
</code>```

or here:

```<code>def summation(n, term):
    total, k = 0, 1
    while k <= n:
        total, k = total + term(1), k + 1
    return total
</code>```

or here:

```<code>def summation(n, term):
    total, k = 0, 1
    while 1 <= n:
        total, k = total + term(k), k + 1
    return total
</code>```

let's put that all together:

```<code>def summation(n, term):
    total, k = 0, 1
    while 1 <= n:
        total, k = 0 + term(1), 1 + 1
    return 0
</code>```

Also, what is the return value of the while loop? The while loop doesn't have a return value, it returns nothing. According to the rules of referential transparency, we should be able to replace any expression with its return value without changing the meaning of the program, ergo, we should be able to replace the entire while loop with nothing:

```<code>def summation(n, term):
    total, k = 0, 1
    return total
</code>```

Again, if your program were referentially transparent, this shouldn't change the result.

Note that a loop simply cannot possibly be referentially transparent. Referential transparency can also be interpreted as "if I do the same thing, the same thing happens". But in a loop, we do the same thing over and over again, yet, we expect something different to happen every time, or at least once: the loop stops.

Here's an example of how to implement summation without breaking referential transparency:

```<code>def summation(n, term):
    if n == 0:
        return term(n)
    else:
        return term(n) + summation(n - 1, term)
</code>```

And here is an implementation in a tail-recursive fashion using the standard "introduce an accumulator" trick:

```<code>def summation(n, term):
    def summation_rec(n, total):
        if n == 0:
            return total
        else:
            return summation_rec(n-1, total + term(n))
    return summation_rec(n, 0)
</code>```

(Unfortunately, that won't help, since Python doesn't implement Proper Tail Calls, not even Proper Tail Recursion. So, this will still blow the stack for larger n. But in a language with proper implementation of tail recursion or even proper tail calls, this will run in O(1) stack space.)

Body:
You already said in your question how you can tell whether your program is referentially transparent or not: if you can replace a expression with its value, without changing the meaning of the program, it is referentially transparent. If you cannot do that, it is not.

So, let's just try and replace some expressions with their values!

in your summation method, in the first line, you set total to 0. So, if your program is referentially transparent, we should be able to replace any occurrence of total with 0. For example, like this:

def summation(n, term):
    total, k = 0, 1
    while k <= n:
        total, k = 0 + term(k), k + 1
    return total

or like this:

def summation(n, term):
    total, k = 0, 1
    while k <= n:
        total, k = total + term(k), k + 1
    return 0

The same goes for k:

def summation(n, term):
    total, k = 0, 1
    while k <= n:
        total, k = total + term(k), 1 + 1
    return total

or here:

def summation(n, term):
    total, k = 0, 1
    while k <= n:
        total, k = total + term(1), k + 1
    return total

or here:

def summation(n, term):
    total, k = 0, 1
    while 1 <= n:
        total, k = total + term(k), k + 1
    return total

let's put that all together:

def summation(n, term):
    total, k = 0, 1
    while 1 <= n:
        total, k = 0 + term(1), 1 + 1
    return 0

Also, what is the return value of the while loop? The while loop doesn't have a return value, it returns nothing. According to the rules of referential transparency, we should be able to replace any expression with its return value without changing the meaning of the program, ergo, we should be able to replace the entire while loop with nothing:

def summation(n, term):
    total, k = 0, 1
    return total

Again, if your program were referentially transparent, this shouldn't change the result.

Note that a loop simply cannot possibly be referentially transparent. Referential transparency can also be interpreted as "if I do the same thing, the same thing happens". But in a loop, we do the same thing over and over again, yet, we expect something different to happen every time, or at least once: the loop stops.

Here's an example of how to implement summation without breaking referential transparency:

def summation(n, term):
    if n == 0:
        return term(n)
    else:
        return term(n) + summation(n - 1, term)

And here is an implementation in a tail-recursive fashion using the standard "introduce an accumulator" trick:

def summation(n, term):
    def summation_rec(n, total):
        if n == 0:
            return total
        else:
            return summation_rec(n-1, total + term(n))
    return summation_rec(n, 0)

(Unfortunately, that won't help, since Python doesn't implement Proper Tail Calls, not even Proper Tail Recursion. So, this will still blow the stack for larger n. But in a language with proper implementation of tail recursion or even proper tail calls, this will run in O(1) stack space.)


答:
@Gábor has already explained the connection (contravariance for all that goes "in", covariance for all that goes "out"), but why re-use keywords at all?

Well, keywords are very expensive. You cannot use them as identifiers in your programs. But there is only so many words in the English language. So, sometimes you run into conflicts, and you have to awkwardly rename your variables, methods, fields, properties, classes, interfaces, or structs to avoid clashing with a keyword. For example, if you are modeling a school, what do you call a class? You can't call it a class, because class is a keyword!

Adding a keyword to a language is even more expensive. It basically makes all code that uses this keyword as an identifier illegal, breaking backwards-compatibility all over the place.

The in and out keywords already existed, so they could just be reused.

They could have added contextual keywords which are only keywords within the context of a type parameter list, but what keywords would they have chosen? covariant and contravariant? + and - (like Scala did, for example)? super and extends like Java did? Could you remember off the top of your head which parameters are covariant and contravariant?

With the current solution, there's a nice mnemonic: output type parameters get the out keyword, input type parameters get the in keyword. Note the nice symmetry with method parameters: output parameters get the out keyword, input parameters get the in keyword (well, actually, no keyword at all, since input is the default, but you get the idea).

[Note: if you look at the edit history, you will see that I actually originally switched the two around in my introductory sentence. And I even got an upvote during that time! This just goes to show you how important that mnemonic really is.]

Title: Why is the 'out' keyword used in two seemingly disparate contexts?

Body:
In C#, the out keyword can be used in two different ways.

As a parameter modifier in which an argument is passed by reference

```<code>class OutExample
{
    static void Method(out int i)
    {
        i = 44;
    }
    static void Main()
    {
        int value;
        Method(out value);
        // value is now 44
    }
}
</code>```

As a type parameter modifier to specify covariance.

```<code>// Covariant interface.
interface ICovariant<out R> { }

// Extending covariant interface.
interface IExtCovariant<out R> : ICovariant<R> { }

// Implementing covariant interface.
class Sample<R> : ICovariant<R> { }

class Program
{
    static void Test()
    {
        ICovariant<Object> iobj = new Sample<Object>();
        ICovariant<String> istr = new Sample<String>();

        // You can assign istr to iobj because
        // the ICovariant interface is covariant.
        iobj = istr;
    }
}
</code>```

My question is: why?

To a beginner, the connection between the two doesn't seem intuitive. The use with generics doesn't seem to have anything to do with passing by reference.

I first learned what out was in relation to passing arguments by reference, and this hindered my understanding of the use of defining covariance with generics.

Is there a connection between these uses that I'm missing?


问:
What is the difference between ref and out in runtime?
C# provides the ref and the out keyword to make arguments to be passed by reference. The semantic of the two is very similar. The only difference is in the initialization of the flaged variable:

ref requires the variable to be initialized before passing it to the function, out does not.

out requires the variable to be initialized inside the function, ref does not.

The use cases of these two keywords are also almost the same, and their too frequent usage is I beleive considered a code smell (although there are valid use cases like the TryParse and TryGetValue patterns).

Because of this could someone explain, why there are two very similar tools in C# for so narrow use cases?

Also, on MSDN, it is stated that they have different run-time behavior:

Although the ref and out keywords cause different run-time behavior, they are not considered part of the method signature at compile time.

How is their run-time behavior different?

Conclusion

Both answers looks correct, thank you both. I accepted jmoreno's because it is more explicit.

答:
here's an interesting writeup on the topic that may answer your question:

http://www.dotnetperls.com/ref

point of interest:

"The difference between ref and out is not in the Common Language Runtime, but is in the C# language itself."

update:

the senior developer at my work just corroborated @jmoreno's answer, so make sure you read it!.


问:
Why Java is a factor 2-3 slower than equivalent C++ program?
I know there is an opinion that programs written in Java and running under JVM as as fast as C++ programs, after introducing just-in-time (JIT). I see many cases when Java is terribly slow for simple programs compared to C++, i.e. about factor 2-3 slower than equivalent C++ programs.

Just give you a small example: This is simple benchmark code to merge particles in clusters:

https://github.com/chekanov/hepjet

Go to "scjet_cpp" and type "make; make run". This runs C++ code.
 Then go to "scjet_java" and type "make; make run". This runs the same
 code written in Java.

Th first C++ code finishes merging particles within 50 msec (i7 desktop). Exactly the same Java code finishes for 170 ms. There is nothing special about the code, i.e. identical implementation in C++ and Java.

Any comment?

答:
I'm very glad that I see professional answers. You are all smart!
 Indeed, there is a small check you can do to test that this long runtime in case of Java is due to JIT compilation.  This is how to see this:

Envelope these lines inside scjet_java/KT.jet as

for (int i=0; i<1000; i++){
    KT KT = new KT(0.6, 1, -1, 5.0);
    KT.setDebug(true);
    KT.buildJets(list);
    KT.printJets();
}
```

This will run particle clustering 1000 times. You will see that first run takes about 75 msec (i7,64 bit), while the next ones take only 15 ns for one clustering step.  15 ns is exactly the time that is needed for C++ code inside scjet_cpp/main.cpp to run over the single event!

So, the runtime is similar in C++ and Java code. I do not care much about 10-20% difference, if any at this level.

Body:
I'm very glad that I see professional answers. You are all smart!
 Indeed, there is a small check you can do to test that this long runtime in case of Java is due to JIT compilation.  This is how to see this:

Envelope these lines inside scjet_java/KT.jet as

for (int i=0; i<1000; i++){
    KT KT = new KT(0.6, 1, -1, 5.0);
    KT.setDebug(true);
    KT.buildJets(list);
    KT.printJets();
}

This will run particle clustering 1000 times. You will see that first run takes about 75 msec (i7,64 bit), while the next ones take only 15 ns for one clustering step.  15 ns is exactly the time that is needed for C++ code inside scjet_cpp/main.cpp to run over the single event!

So, the runtime is similar in C++ and Java code. I do not care much about 10-20% difference, if any at this level.


问:
Naming conventions: camelCase versus underscore_case ? what are your thoughts about it?
I've been using underscore_case for about 2 years and I recently switched to camelCase because of the new job (been using the later one for about 2 months and I still think underscore_case is better suited for large projects where there are alot of programmers involved, mainly because the code is easier to read).

Now everybody at work uses camelCase because (so they say) the code looks more elegant .

What are you're thoughts about camelCase or underscore_case

p.s. please excuse my bad english

Edit

Some update first:

platform used is PHP (but I'm not expecting strict PHP platform related answers , anybody can share their thoughts on which would be the best to use , that's why I came here in the first place)

I use camelCase just as everibody else in the team (just as most of you recomend)

we use Zend Framework which also recommends camelCase

Some examples (related to PHP) :

Codeigniter framework recommends underscore_case , and honestly the code is easier to read .

ZF recomends camelCase and I'm not the only one who thinks ZF code is a tad harder to follow through.

So my question would be rephrased:

Let's take a case where you have the platform Foo which doesn't recommend any naming conventions and it's the team leader's choice to pick one. You are that team leader, why would you pick camelCase or why underscore_case?

p.s. thanks everybody for the prompt answers so far

答:
Depends on the programming language.

I consider using the case in the same boat of whether or not to use Hungarian notation:

Python: underscore_case, no Hungarian
notation

C++: camelCase, Hungarian
notation


问:
mySQL / PHP design pattern - one function multiple queries
So here's the gist of it. I'm looking for a design pattern where I can have one function, say queryHandler that gets the query and the parameters from a number of different functions and returns the said query results.

At the moment, I have a Core class which implements the singleton pattern for database object creation and so forth.

However, I want a design pattern that can handle different queries with different bind parameters. So, take these queries:

```<code>SELECT * FROM foo WHERE id = :bar

INSERT INTO foo (id, name, bar) VALUES (:id, :name, :bar)
</code>```

Etc.

For the first one, I would have a bindParam where :bar would be PDO::PARAM_INT, however, in the second case it would be multiple bindParams with both INT and STR types.

I want my functions to just have one variable, and one call to the queryHandler:

```<code>$query = 'SOME QUERY HERE'
$this->queryHandler($query, $params ... or something)
</code>```

Obviously, queryHandler would sort out how many params, their type, and do the query itself.

Any ideas? Thanks

答:
Use a multidimensional array like $key => $value, $key2 => $value2 and iterate?

```<code>$data = array( 'column_name' => 'value' );
querysorter ( 'tblname', $data );
function querysorter{
foreach($data)
//bindparam here
}
</code>```

Hope this helps, just had to do something similair.

Body:
Use a multidimensional array like $key => $value, $key2 => $value2 and iterate?

$data = array( 'column_name' => 'value' );
querysorter ( 'tblname', $data );
function querysorter{
foreach($data)
//bindparam here
}

Hope this helps, just had to do something similair.


问:
Where should documentation files be saved in SVN?
At the moment I am using one repository for project with the following "default" structure:

```<code>project
 - trunk
     - docs
 - branches
 - tags
</code>```

I would like to know if is a good practice store the docs outside trunk folder example:

```<code>project
 - docs
 - trunk
 - branches
 - tags
</code>```

答:
The (dis-)advantages of having your documentation inside the trunk of the repository depends on a number of factors. Some of the more important ones are:

Your branching strategy

How comparable the documentation lifecycle and the software lifecycle are

Your workflow for keeping the documentation up-to-date and the format of your documentation

If you create a new tag/branch for each release and the documentation gets released in tandem with the code, keeping the documentation inside the trunk has the advantage that it becomes easy to find the documentation that goes with a particular past release, as the documentation gets copied to the tag/branch together with the sources.

On the other hand, if your documents are released on a different cycle than the code (for example, the code gets tagged and released daily, but the documentation only once every 3 weeks), then there is no advantage to having the documentation inside trunk, as most software releases will then contain unreleased (and probably incomplete) documentation.

As a final possibility, if you regularly work on feature branches (and you are in the habit of updating the documentation as you write the code), then keeping binary documentation files inside trunk can cause you a lot of merge grief when merging the branch back to trunk. It should be noted that the fileformats used by the major wordprocessors are all binary (either proprietary or compressed XML).


答:
At the time this question was asked, the MSDN article was subtly incorrect (it has since been corrected).  Instead of "cause different behavior" it should be "requires different behavior".

In particular, the compiler enforces different requirements for the two keywords, even though the same mecanism (IL) is used to enable the behavior.

Title: What is the difference between ref and out in runtime?

Body:
C# provides the ref and the out keyword to make arguments to be passed by reference. The semantic of the two is very similar. The only difference is in the initialization of the flaged variable:

ref requires the variable to be initialized before passing it to the function, out does not.

out requires the variable to be initialized inside the function, ref does not.

The use cases of these two keywords are also almost the same, and their too frequent usage is I beleive considered a code smell (although there are valid use cases like the TryParse and TryGetValue patterns).

Because of this could someone explain, why there are two very similar tools in C# for so narrow use cases?

Also, on MSDN, it is stated that they have different run-time behavior:

Although the ref and out keywords cause different run-time behavior, they are not considered part of the method signature at compile time.

How is their run-time behavior different?

Conclusion

Both answers looks correct, thank you both. I accepted jmoreno's because it is more explicit.

ContentLicense: CC BY-SA 4.0


问:
Protected properties vs protected getters
If I have an abstract Animal class with a $name property and constructor like this:

```<code>abstract class Animal {

   protected $name;

   public function __construct($name) {
      $this->name = $name;
   }
}
</code>```

And the classes who are instance of the Animal class uses make use of the $name property like this:

```<code>class Cat extends Animal {

   public function makeNoise() {
      switch($this->name) {
        ....
      }
      return "Meow";
   }

   //More functions who will be using the $this->name property
}
</code>```

Is it  better to use an protected getter method in the class or stay with the protected property?

答:
There are points to keep in mind for each approach, and there may not be a clear winner.

Protected Field

If not constant, a protected field allows the subclass to modify parent class state directly. This means a subclass may be able to violate the parent's invariants or validations. State may be able to change at inopportune times, which may cause problems (or it may not).

In other words, this approach might cause a class to behave inconsistently, possibly in a bad way.

That being said, some state might be treated as volatile and it is okay for it to change whenever you want.

Getter

This is actually not much different. Methods can be overridden as long as they are not marked as un-overridable (e.g. final, non-virtual). The difference is while a field can be changed directly, a getter/setter combination can enforce invariants and validations on the field transparently.

Does the state represent a property of the base class directly, or does it happen to be that all subclasses need the state but it does not really belong to the base class? For example, let as assume that all animals can speak. Animal knows it can speak, but the how belongs in the subclass. Maybe an abstract getter method is appropriate: Animal can use it, but the actual implementation must be defined in each subclass.

If the state does not change, you may also be able to define a constant in the base class. Maybe the subclass passes a value to the base class constructor which then sets it in stone in that constant. This allows the base class to use the constant as well because it is defined in the base class.

There is no one way to do this, and understanding the right way for a given situation requires experience. Hopefully this helps explain why each option works and how they are different.


问:
Are there any easy-to-follow/reliable methods for simplifying code?
There is a problem with the way I code. Regardless of how much of a plan I write beforehand, the code becomes overcomplicated quickly.

Reading books on good practice and attempting to adhere to their principles isn't working.

Is there some surefire/proven way of auditing code to simplify it, other than being more thorough and dedicated in the planning stage?

答:
In my experience, if a software developer doesn't properly understand the system/domain he is writing the code for then the code is quite likely to become over-complicated.

The reason for this is fairly obvious. Simple code has a structure that mirrors the problem being solved or the domain being modelled. That way the code's behaviour tends to emerge from the structure, rather than being encoded as a large number of explicit cases.

Another way to spot this error is when you need a large number of test cases to check that the code is working properly and you discover failures in all sorts of edge cases. If the software had been designed well then there wouldn't be as many edge cases.

So work hard at trying to understand the problem domain or the system you are modelling. Don't just accept a specification or set of requirements from someone else and code to that. Break down barriers between the domain experts and the software engineers; become a domain expert yourself.


问:
How to design similar purpose static methods
I know that you cannot override static functions, but for what I'm looking to do, it seems like the logical way to design my class.

I have a method that is associated with my abstract class, that i want to work without the class being instantiated, but will work differently on different implementations of that abstract class(all statically)

Usually when this happens I am overlooking something, or there is a better way to approach the design, so hopefully someone here can set me on the right path.

Essentially I have a Content abstract class something like:

```<code>public abstract class Content{
   public virtual void copyAll();
   public virtual void VerifyContent();
   public static virtual Dictionary<int,Content> ProcessAllFromDT(DataTable dt) //Cannot exist
}
</code>```

And then an implementation of that Ringtone, and Wallpaper

```<code>public class Wallpaper:Content{
   public void CopyAll(){...}
   public void VerifyContent(){...}
   //Loads Wallpapers From DT
   public static Dictionary<int,Content> ProcessAllFromDT(DataTable dt){...} //content in this case is a wallpaper
}
</code>```

Finally it would be nice to have something like:

```<code>public void ProcessAllContent<T>() where T:Content{
    ...
    var dictionary = T.ProcessAllFromDT(dt); // Doesn't compile.
}
</code>```

Suggestions on a better design for what I'm trying to do here?

答:
If I understand you right (and I don't think I do) then you might...

You could create a static member for a generic static class that has the function for each subclass type. Just make each sub class have a static constructor that sets the appropriate action for how it does processing.

```<code>public static class ProcessDt<T>
{
    public Action ProcessAllFromDt { get; set; }
}

public class ZuberfizzContainer : AbstractContainer
{
    static ZuberfizzContainer()
    {
        ProcessDt<ZuberfizzContainer>.ProcessAllFromDt = () => ZuberfizzContainer.StaticZuberfizzMethod();
    }
}

public class GinghamContainer : AbstractContainer
{
    static GinghamContainer()
    {
        ProcessDt<GinghamContainer>.ProcessAllFromDt = () => GinghamContainer.StaticGinghamMethod();
    }
}
</code>```

then usage would be:

```<code>ProcessDt<ZuberfizzContainer>.ProcessAllFromDt(); // This will do the zuberfizz specific stuff
ProcessDt<GinghamContainer>.ProcessAllFromDt(); // This will do the gingham specific stuff
// or any other one that sets the processallfromdt method for its type
</code>```

Body:
If I understand you right (and I don't think I do) then you might...

You could create a static member for a generic static class that has the function for each subclass type. Just make each sub class have a static constructor that sets the appropriate action for how it does processing.

public static class ProcessDt<T>
{
    public Action ProcessAllFromDt { get; set; }
}

public class ZuberfizzContainer : AbstractContainer
{
    static ZuberfizzContainer()
    {
        ProcessDt<ZuberfizzContainer>.ProcessAllFromDt = () => ZuberfizzContainer.StaticZuberfizzMethod();
    }
}

public class GinghamContainer : AbstractContainer
{
    static GinghamContainer()
    {
        ProcessDt<GinghamContainer>.ProcessAllFromDt = () => GinghamContainer.StaticGinghamMethod();
    }
}

then usage would be:

ProcessDt<ZuberfizzContainer>.ProcessAllFromDt(); // This will do the zuberfizz specific stuff
ProcessDt<GinghamContainer>.ProcessAllFromDt(); // This will do the gingham specific stuff
// or any other one that sets the processallfromdt method for its type


问:
Best practice to include XSD in C# project
I have an XSD schema I need to include within my program, to validate some user input XML. The schema will need to be regularly updated. (By the programmer.)

My current method to include this is hold a reference to it within Resources.resx - however, this doesn't seem ideal as it requires me to duplicate all my enum's between the XSD and the C#.

I've also looked at converting the XSD file to a runtime class using xsd.exe - however, as I understand, this requires running a separate process outside of Visual Studio, which makes it more complex to update, and requires the process being detailed for future authors.

I can't imagine this is an unusual situation - is there a method by which this is commonly done, where I can remove the duplication in my current method, but still not have the need to manually process the schema on each update?

答:
The answer largely depends on how often you expect your types to change in a way that would force changes to the schema.

If changes occur rarely or not at all, the easiest thing to do from a maintainer's standpoint may very well be to duplicate the values in a static XSD document.

If changes occur frequently, you may be better off coming up with a way to generate the XSD as a build artifact.  This will eliminate duplication and ensure that it will be up-to-date, but there may be a significant up-front cost to put it together.


问:
How to handle exceptions that get absorbed by a 3rd party library?
I'm currently having an issue with a 3rd party control library provider. They have an exception occulting culture that gets in the way of my general fail-fast approach when developing software.

An example: their grid control proposes a RowValidating event in which it's possible to check user data input before it's committed to the underlying object. The event argument has a IsValid boolean property and an ErrorText string property. If the handler had  the IsValid property set to False, the grid will treat the row as invalid, present the error text followed by "Do you want to correct the value?" in a yes / no dialog box.

The problem is that if the handler throws an actual Exception during the validation process, the grid catches it and will behave exactly like described above - only it will use the caught exception's Message property as the validation error text. The exception instance, even though it's actually MY code that caused it, can't ever be caught afterwards. There's no way for me to handle it other than wrapping my validation code in a try/catch block that catches everything.

Of course I don't want my code to throw any exceptions, but hey... errare humanum est! If that ever happens, I'd much prefer having the app crash and burn than hiding the exception away! For these scenarios I have a global handler that will log the unhandled exception right before the app crashes. This is where I'd expect any of them to end up.

Since my company made a huge investment in this particular 3rd party provider (both from learning and actual code running with it), I can't just run to another vendor - much less making my own grid control.

I tried talking to the vendor so that this gets fixed but they won't do anything in fear of causing breaking changes for other customers (understandable). They also won't introduce any kind of boolean flag to circumvent the behavior (less understandable).

Right now I'm uncomfortable deploying an app in which I know there's a chance for it to run in a corrupted state. I also hate having to wrap my event code in a try/catch block that may encounter an Exception from which it's impossible to gracefully recover from.

What kind of solution can I use to prevent or fix this problem?

TL;DR: 3rd party vendor takes away Exception instances thrown from my own code, workarounds are ugly and unsatisfying, don't know what to do with this.

答:
What is there to do. In my view, the decision to turn an exception during validation into a failed validation is a correct way of handling such exceptions.

Letting the exception pass through and crash the application has a significant risk that you lose the work the user had been doing, even if the situation was caused by bad user-input and entirely correctable.

In a validation routine, you should only check if the input is valid and not make any changes to the state of the application. Therefore, if an exception gets thrown in a validation routine, there should be zero risk that the application state is corrupted.

If you are doing more than just validation in your handler, then it is your problem to ensure that there is no path out of it with an invalid application-state.