问:
Thoughts on web development architecture through integrating C++ in the future to a web application
I'm looking to build a website (it's actually going to be a commercial startup) I saw this question and it really shed some light on a few things that I was hoping to understand (kudos to the op). After seeing that, it would make sense that, unless the website were required to actually have millions of hits per day, it wouldn't be a viable solution to write a C++ backend on the server side.

But this got me thinking.

what if it in the (unlikely) events of the future, it does go that route? The problem is that, while I'm thinking of starting this all using .Net (in the beginning) just to get something quick and easy up without a lot of hassle (in terms of learning), and then moving towards something more Open Source (such as Python/Django or RoR) later to save money and to support OSS, I'm wondering IFF the website actually becomes big, will it be a good idea to integrate a C++ backend, and use Python ontop of C++ for a strong foundation, and then mitigate HTML/CSS/AJAX/etc ontop of the backend's foundation? I guess, what I'd like to know is that, given the circumstance, if this were to happen, would it be a proper approach in terms of architecture? I'd definitely be supporting MVC as that seems to be a great way to implement a website.

All in all, would one consider this rational, or are there other alternatives? I like .Net, and I'd like to use it in the beginning, because I have much more experience with that than, say, Python or PHP, and I prefer it in general, but I really do want to support OSS in the future. I suppose the sentence I'm looking for is, "is this pragmatic?"

答:
I don't think so.

C++ will always have its place in OS and driver development, but as far as web applications go, the bottleneck is rarely the server running it; it's all in the network bandwidth and the time it takes for a client machine to see updated information.

Servers have come a long way, and are quite capable of running garbage languages [I won't point any fingers; you know who you are] without a client even noticing the performance hit.

PHP seems to be where it's at for many web applications, and with some of the new capabilities of the modern web and modern computers, it's also becoming more and more common to push more of the processing on to the client machine (as opposed to letting the server manage it all).

You very well may find a use for C++ on the server, though it may be simpler to just make a CGI script in a more modern, easier to code language.


问:
If I use locks, can my algorithm still be lock-free?
A common definition of lock-free is that at least one process makes progress. 1

If I have a simple data structure such as a queue, protected by a lock, then one process can always make progress, as one process can acquire the lock, do what it wants, and release it.

So does it meet the definition of lock-free?

1 See eg M. Herlihy, V. Luchangco, and M. Moir. Obstruction-free synchronization: Double-ended queues as an example. In Distributed Computing, 2003. "It is lock-free if it ensures only that some thread always makes progress".

答:
That's no definition for lock-free.

If you can guarantee progress then you have deadlock-free, and if you have the eventual completion of every request, then you have starvation-free, but not lock-free.

I question whether your simple example actually provides this anyway.  You need lock hierarchies and so on to actually make progress guarantees when multiple locks are involved.

ContentLicense: CC BY-SA 3.0


问:
How should I describe the process of learning someone else's code? (In an invoicing situation.)
Edit: Justin Cave made a good point that this sort of communication should be up front in my quoting / estimations.  Is this case, I'm still interested to know what sort of language people use to describe the 'existing code learning' activities.  Especially to a company who haven't dealt with software contractors before.  End edit

I have a contract to upgrade some in-house software for a large company.  The company has requested multiple feature additions and a few bug fixes. This is my first freelance style job.

First, I needed to become familiar with how the application worked - I learnt it as if I was a user.

Next, I had to learn how the software worked.  I started with broad concepts, and then narrowed down into necessary detail before working on each bug fix and feature.

At least at the start of the project, it took me a lot longer to learn the existing code than it did to write the additional features.

How can I describe the process of learning the existing code on the invoice?  (This part of the company usually does things in-house, so doesn't have much experience dealing with software contractors like me, and I fear they may not understand the overhead of learning someone else's code).  I don't want to just tack the learning time onto the actual feature upgrade, because in some cases this would make a 'simple task' look like it took me way too long.  I want break the invoice into relevant steps, and communicate that I'm charging for the large overhead of learning someone else's code before being able to add my own to it.

Is there a standard way of describing this sort of activity when billing for a job?

答:
I would invoice such tasks as "Review existing functionality" and/or "Review existing code".  Depending on the complexity of the new features I would add a "Design xxx" task which would include the time I spend figuring out the integration points into the existing code.

I think it's a good idea to make it clear to the customer that there is some overhead in bringing a new consultant up to speed--and that, if they are happy with the result, continuing to work with the same consultant will likely save them money.


问:
What conventions or frameworks exist for MVVM in Perl?
We're using Catalyst to render lots of webforms in what will become a large application. I don't like the way all the form data is confusingly into a big hash in the Controller, before being passed to the template. It seems jumbled up and messy for the template. I'm sure there are real disadvantages that I haven't described properly... Are there?

One solution is to just decide on a convention for the hash, e.g.:

```<code>{
  defaults => {
    type => ['a', 'b', 'c']
  },
  input => {
    type => 'a'
  },
  output => {
    message => "2 widgets found of type a",
    widgets => [ 'foo', 'bar' ]
  }
}
</code>```

Another way is to store the page/form data as attributes in a class (a ViewModel?), and pass a whole object to the template, which it could use like this:

```<code><p class="message">[% model.message %]<p>

[% FOREACH widget IN model.widgets %]
</code>```

Which way is more flexible for large applications?

Are there any other solutions or existing Catalyst-compatible frameworks?

答: HTML::FormHandler can render forms for you, using either the Simple or Table built in renderers. But you're not forced to use them. You can write your own, or leave them all out together (which is what I did, though I doubt that was a good decision). I've found it to be a very flexible module (it being built with Moose). You can also let it handle saving the data to the database with HTML::FormHandler::TraitFor::Model::DBIC, or roll your own.</p>


问:
Automating release management and CI on python projects under mercurial VCS
I have a set of Python projects which are under the mercurial VCS. I would like to automate the following tasks:

Run the test suite for every commit (CI).

Make a source distribution for every commit, which has a tag in mercurial. This is regarded as a new release.

Copy the distribution to a special repository.

There is Jenkins as a proposal for similar questions, but I'm not sure if it can handle the release management like intended.

答:
At a previous job, we had a locked down "central" server (I know, central server for a distributed RCS sounds funny) that didn't allow direct login except by admins.  Users could only clone / pull from it.  Admins did the pushing.  I'm not sure if hooks were used, but we sent automated emails and accomplished the permissions using the hgadmin tools.

If you set this up you could install your own hooks on that machine (see http://hgbook.red-bean.com/read/handling-repository-events-with-hooks.html) to perform the actions you're talking about - accept pushes that pass the tests, run a build script, and a copy it out if everything goes according to plan (see the changegroup hook).

Or you could install some continuous integration software on your server, but you'll end up paying for that.  We're about to start using Bamboo by Jira (see http://www.atlassian.com/software/bamboo/overview - they do have a free trial), but I can't speak for any at the moment.


问:
How do I balance program CPU reverse compatibility whist still being able to use cutting edge features?
As I learn more about C and C++ I'm starting to wonder: How can a compiler use newer features of processors without limiting it just to people with, for example, Intel Core i7's?

Think about it: new processors come out every year with lots of new technologies. However you can't just only target them since a significant portion of the market will not upgrade to the latest and greatest processors for a long time.

I'm more or less wondering how this is handled in general by C and C++ devs and compilers. Do compilers make code similar to if SSE is supported, do this using it, else do that using the slower way or do developers have to implement their algorithm twice, or what?

More or less how do you release software that takes advantage of newer processor technologies while still keeping a low common denominator?

答:
Your best choice as a developer nowadays is to choose tools that are smart enough to take advantage of special instruction sets such as SSD and SIMD when they are available on the processor directly and, when they aren't,  automatically fall back to software algorithms that emulate those features.  The compiler manufacturer can tell you in their specifications whether or not they support this.

From the Wikipedia article for the Intel C++ Compiler:

The compiler or library can make multiple versions of a piece of code,
  each optimized for a certain processor and instruction set, for
  example SSE2, SSE3, etc. The system includes a function that detects
  which type of CPU it is running on and chooses the optimal code path
  for that CPU.

Amusingly, that algorithm seems to favor Intel processors.

GCC has a "march" optimization for compiling to a particular microprocessor architecture.  The tradeoff is that some platform independence may be sacrificed.  See http://www.linuxjournal.com/article/7269?page=0,1

LLVM doesn't appear to have processor-specific optimizations; this makes sense, because LLVM seeks to generate a machine-independent intermediate code representation, and then turns that machine-independent representation into executable machine code.  So any code targeting a specific processor architecture would have to reside in that second step.


答:
I've used CCNet to do this kind of thing, with a config triggered by a commit that runs a few jobs (the tests are quite easy to add to this). It works nicely with mercurial; which is what I use in my scripts. It gets the latest version from the repo, builds it, then deploys the files using WebDeploy. I have used RoboCopy for this in the past.

See this post for full script:
http://www.the-wombat-speaks.co.uk/blog/post/2011/09/12/dry-cruisecontrolnet-config.aspx

Title: Automating release management and CI on python projects under mercurial VCS

Body:
I have a set of Python projects which are under the mercurial VCS. I would like to automate the following tasks:

Run the test suite for every commit (CI).

Make a source distribution for every commit, which has a tag in mercurial. This is regarded as a new release.

Copy the distribution to a special repository.

There is Jenkins as a proposal for similar questions, but I'm not sure if it can handle the release management like intended.


问:
What's shell script's advantage over interpreted programming languages?
(I'm not sure if it's a appropriate question here)

Shell scripts, like those written in bash, can do many things. They can call Unix programs, pipe their output, redirect I/O from/to files, control flow, check whether a file exists, etc.

But a modern programming language, e.g, python and ruby, can also do these things. And, they are (I think) more readable and maintainable.

bash enjoys wide spread adoption. But many distributions have installed python interpreter, too.

So what's the advantage of shell a script? If I could write python, ruby or perl, is it worth to learn bash?

答:
You should take a look at coffeescript.
Their words:

Underneath all those awkward braces and semicolons, JavaScript has
  always had a gorgeous object model at its heart. CoffeeScript is an
  attempt to expose the good parts of JavaScript in a simple way.

The golden rule of CoffeeScript is: "It's just JavaScript".

Well... here comes the super-beginner answer.

As an auto-learning beginner for the last 6 months, and tasting a little bit of C, C++, Javascript, and more Bashscript in the last days... I can tell you:

Shell scripts, like those written in bash, can do many things. They
  can call Unix programs, pipe their output, redirect I/O from/to files,
  control flow, check whether a file exists, etc.

and isn't this simple fantastic!? loops and variables? wow!

python and ruby, can also do these things. And, they are (I think)
  more readable and maintainable.

Please, tell me where you see this? I wrote bashscript in gedit even in geany and I can format, (tabs?) and I read my code in the speed of light using bashscript in comparision on other languages.

Does this languages have other tools to keep order? I know object-oriented save a LOT of code, but... people say bashscript is OO too! WOW 2 ! That's my point here. Going to:

the advantage of shell a script

is inside this question: How to do what this bashdamnthing can do in perl or phyton or ruby? It 's easy?

(bashdamnthing = xdotool)


答:
Shell scripting is an interpreted programming language. Here are a few reasons why I chose to write scripts in bash instead of perl or python or some other scripting language:

Works everywhere: More complex interpreters may not always be available, such as during system startup or on embedded systems. Bash is available even in busybox.

Works on the command line: If you're well-versed in shell-scripting, you can use those skills to do complex things in ad-hoc scripts right on the command line. I use this skill daily as a sysadmin.

Easier to write programs that call other programs: If what you're trying to do is chain several existing programs together in interesting ways, it can be simpler to do in a shell script than with a higher-level language.

If the program is 30 lines or less, I'll usually write it using shell scripting. If there is any complex manipulation or complex or analysis to deal with, I'll do it using python or perl.

Title: What's shell script's advantage over interpreted programming languages?

Body:
(I'm not sure if it's a appropriate question here)

Shell scripts, like those written in bash, can do many things. They can call Unix programs, pipe their output, redirect I/O from/to files, control flow, check whether a file exists, etc.

But a modern programming language, e.g, python and ruby, can also do these things. And, they are (I think) more readable and maintainable.

bash enjoys wide spread adoption. But many distributions have installed python interpreter, too.

So what's the advantage of shell a script? If I could write python, ruby or perl, is it worth to learn bash?


问:
Why is verbosity bad for a programming language?
I have seen many people around complaining about verbosity in programming languages. I find that, within some bounds, the more verbose a programming language is, the better it is to understand. I think that verbosity also reinforces writing clearer APIs for that particular language.

The only disadvantage I can think of is that it makes you type more, but I mean, most people use IDEs which do all the work for you.

So, What are the possible downsides to a verbose programming language?

答:
@frowing, I would suggest that one way to look at the verbosity issue is to realize that programming is always some mix of two rather different styles of finding and expressing a solution.

The first and more verbose style is language-oriented (linguistic) programming. This style combines noun-like words and verb-like words within sentence-like structures, and it is intended to be read and understood in much the same fashion as a well-written paragraph. Linguistic programming is the most universal style of programming since language itself is universal. For that same reason, long-term program support always needs a powerful linguistic component, since the first thing a new programmer will look for is as conceptual understanding of what is being done. As a general rule, the farther away you move from the context in which you created a program, the more important a linguistic style of programming will be for ensuring that your assumptions and concepts will not be misunderstood by the next person trying to understand your code. Your own example of using a more linguistic style of programming to reduce ambiguity in APIs is a good example of that principle.

The second and more concise style is math-oriented (mathematical) programming. This style of reasoning also relies on language, since for example variables are analogous to nouns and operators to verbs. However, mathematical reasoning leverages the amazing and highly parallel ability of our brains to do complex spatial transformations on objects that are within our line of vision. By representing nouns and verbs as compact, distinctive symbols that can be arranged into well-structured imaginary objects -- equations -- we can then use our highly parallel visual capabilities to perform rotations, replacements, movements, inversions, and other transformations on these imaginary objects. The result is an enormous amplification of the number of cases we can handle at once, since each symbol can represent entire classes of closely related objects.

Notice that to apply visual processing effectively, you need to keep your imaginary object as similar as possible in size and features to a real object. If the needed field of vision gets too wide, or the symbols can’t be used like movable marks on an object, or if you have to “read letters” and convert them into words, the ability to perform complex transformations reliably will fall off quickly even for a very good mathematician.

That is why people immersed deeply in the mathematical style of programming can get seriously unhappy if an equation is spread out and expressed in what they would call a “verbose” linguistic style. It’s not because the equation has been changed significantly, it’s because spreading it out like that can make it nearly impossible to apply a visual style of understanding to it. Yet at the same time, a new programmer who is not at all familiar with the short symbols is likely to prefer a more verbose version that provides more linguistic information for initially understanding what the code does.

So what would I recommend?

Use both styles, but pay careful attention to why you are using each style.

For example, anything that has a chance of interfacing with the outside world should be intensively verbose at some level, even if only in the form of inline comments mixed with the code, and should also include automated checks for correct usage. Cryptic and especially incompletely defined notations have no business in such interfaces, since they are almost guaranteed to get misunderstood at some point. The 1999 loss of the Mars Climate Obiter due to a failure to recognize whether software interface units were expressed in pounds or Newtons is a particularly pointed example of the dangers of relying too casually on raw numbers at software or hardware interfaces.

Conversely, any form of programming that is deeply algorithmic and mathematical in nature is a good candidate succinct programming that supports the mathematical style of reasoning. If someone new must maintain such code, it would usually be better for them to learn the mathematical notations instead of trying to transform the code into more verbose forms. There should of course at all times be documentation easily available to explain the mathematical parts the code available to such developers, but that is a separate issue.

In between these extremes are many cases where the programmer has considerable discretion. I would suggest looking at how the code will be maintained in the long term, and trying to accommodate the needs of the people most likely to be maintaining the code in the long term.


问:
Is it worth it to switch from home-grown remote command interface to using JMX
Without knowing too much about JMX, I've always assumed that it would be the best approach for building in remote management to our standalone Java server application. Our server application has some minimal remote control capability, using text commands sent via TCP/IP socket to it.

Using the home grown approach, it is fairly to add a new command. (Just create new command text, and the code to handle that in the message receiver).  On the other hand, we have hardly implemented any commands, even though there are many things we would like to be able to execute remotely.

I am trying to weigh the value of moving to incorporating JMX (learning it, and building the interfaces), versus just sticking with the home-grown approach. Does anyone have any experience or advice regarding changing an existing application to use JMX?

答:
Good question.

First of all answer is quite simple for me. Move to JMX for several reasons.

There are lots of stable proven JMX implementations  out there that you can simply use to bootstrap your application and you don't really have to maintain your code to be able to support different operations.

JMX is a very simple model where you have MBeanServer that hosts a bunch of services / MBeans that have properties and methods.

These services / MBean are exposed by MBeanServer in a protocol agnostic way.

If there is a need to connect to the MBeanServer using different protocol's its simply a matter of creating adapters.

To answer your other question, is it easy to migrate to JMX, the answer is it all depends. If fairly easy to migrate the implementations / services to MBean and expose only what you want to but the tricky part maybe how you connect to those services. So clients might have to rewrite some of the code.

Hope this help!

Good luck.


问:
Is there a canonical book on Ruby on Rails?
I'm an experienced developer with .NET, and understand core computing concepts well (OOP, design patterns, etc) but would like to also learn rails.

Is there a book out there that's the de-facto standard for describing best practices, design methodologies, and other helpful information on Ruby on Rails? What about that book makes it special?

答:
I would recommend The Rails 3 Way. I cannot say enough good things about it. It covers every part of Rails, including many of the essential gems you need to know about. And it works both as a read for a beginner and a reference guide for the intermediate Rails developer.

If you're feeling flush, I would also throw in The RSpec Book, for a good grounding in how to write in a BDD way, which I personally think is a near-essential for Rails devs.


问:
What's your favourite quote about programming?
What's your favourite quote about programming?

One quote per answer, and please check for duplicates before posting!

答:
In C++ it’s harder to shoot yourself in the foot, but when you do, you blow off your whole leg.

  — Bjarne Stroustrup

LastEditorDisplayName: Roger Pate

ContentLicense: CC BY-SA 2.5


答:
Because more code means more development times and more bugs.

If you write 100 lines of codes rather than 300 lines of codes. That means almost 1/3 development times you need and 1/3 potential bugs you may meet.

In most circumstances you need to balance efficiency and the conciseness, since write less codes means machine needs to do more things and it will decrease the efficiency.

Title: Why is verbosity bad for a programming language?

Body:
I have seen many people around complaining about verbosity in programming languages. I find that, within some bounds, the more verbose a programming language is, the better it is to understand. I think that verbosity also reinforces writing clearer APIs for that particular language.

The only disadvantage I can think of is that it makes you type more, but I mean, most people use IDEs which do all the work for you.

So, What are the possible downsides to a verbose programming language?


答:
Rather than go to a technical book, I revert to the Elements of Style* by Strunk and White.  The underlying concept is "Be precise" and "Don't say more than needed."  Everything else is commentary.

Applied to programming, it's about being very precise, but not having unneeded fluff.  The extra fluff can be syntax, but it could also be more words than required to convey meaning.  (Of course not too few to allow ambiguity either)

I cite the original version since it is the most concise.  :-)


问:
Should we encourage coding styles in favor of developer's autonomy, or discourage it in favor of consistency?
A developer writes if/else blocks with one-line code statements like:

```<code>if (condition)
   // Do this one-line code
else
   // Do this one-line code
</code>```

Another uses curly braces for all of them:

```<code>if (condition)
{
   // Do this one-line code
}
else
{
   // Do this one-line code
}
</code>```

A developer first instantiates an object, then uses it:

```<code>HelperClass helper = new HelperClass();
helper.DoSomething();
</code>```

Another developer instantiates and uses the object in one line:

```<code>new HelperClass().DoSomething();
</code>```

A developer is more easy with arrays, and for loops:

```<code>string[] ordinals = new string[] {'First', 'Second', 'Third'};
for (i = 0; i < ordinals.Length; i++)
{
    // Do something
}
</code>```

Another writes:

```<code>List<string> ordinals = new List<string>() {'First', 'Second', 'Third'};
foreach (string ordinal in ordinals)
{
    // Do something
}
</code>```

I'm sure that you know what I'm talking about. I call it coding style (cause I don't know what it's called). But whatever we call it, is it good or bad? Does encouraging it have an effect of higher productivity of developers? Should we ask developers to try to write code the way we tell them, so to make the whole system become style-consistent?

答:
This really depends a lot on the type of organization.

If you're a small group of superheroes, then any type of style is fine.  If everyone has their own style, and it's both good and internally consistent, then that's all the process you need.  The Superheroes will say, "Jane has brackets, so this is what she means" or "Jack uses camelCase for variables".

Universal standards tend to be best for making everyone a B+ player.  Your superheroes will get pulled down by this.  But if you want one A player and a half dozen B players and a half dozen C players to average up to the B+, then you want consistent standards.  In this instance, you want everyone doing things the same so that the one A player can walk through everyone's code as quickly as possible.

Many of you way, "But wait, why not do away with the B and C players?"

The reality is there aren't many Superheroes.  While it may pay to find and nurture them at Google, putting in a new billing system for Ma Bell may be more cost effective with the latter team.  (And if you really have Superheroes, 4 or 5 of them will be twice as expensive as a dozen juniors)


问:
Data Structures usage and motivational aspects
For long student life I was always wondering why there are so many of them yet there seems to be lack of usage at all in many of them. The opinion didn't really change when I got a job.

We have brilliant books on what they are and their complexities, but I never encounter resources which would actually give a good hint of practical usage. I perfectly understand that I have to look at problem , analyse required operations,  look for data structure that does them efficiently. However in practice I never do that, not because of human laziness syndrome, but because when it comes to work I acknowledge time priority over self-development.

Over time I thought that when I would be better developer I will automatically use more of them -  that didn't happen at all or maybe I just didn't. Then I found that the colleagues usually in the same plate as me - knowing more or less some three of data structures and being totally happy about it and refusing to discuss this matter further with me, coming back to conversations about 'cool new languages' 'libraries that do jobs for you' and the joy to work under scrumban etc.

I am stuck with ArrayLists, Arrays and SortedMap , which no matter what I do always suffice or either I tweak them to be capable of fulfilling my task. Yes, it might be inefficient but do we really have to care if Intel increases performance over years no matter if we improve our skills? Does new Xeon or IBM machines really care what we use? What if I like build things, but I am not particularly excited whether it is n log(n) or just n? Over twenty years the processing power increased enormously, which gives us freedom of not being critical about which one to use? On top of that new more optimized languages appear which support multiple cores more efficiently.

To be more specific: I would like to find motivational material on complex real areas/cases of possible effective usages of data structures. I would be really grateful if you would provide relevant resources. There is similar question ,but in the end the links again mostly describe or do dumb example(vehicles, students or holy grail quest - yes, very relevant) them and people keep referring to the "scenario decides the data structure to use". I want to know these complex scenarios to be able to identify similarities to my scenario and then use them. The complex scenarios where it really matters and not necessarily of quantitive nature. It seems that data structures only concern is efficiency and nothing else? There seems to be no particular convenience for developer in use one over another.

(only when I found scientific resources on why exactly simple carbohydrates are evil I stopped eating sugar and candies completely replacing it with less harmful fruits - I hope you can see the analogy)

答:
I think there are a few reasons why developers tend to only use a few data structures.

There are general data structures that work well enough most of the time so they become the primary choice of data structures for most problems.

I know hash tables and lists are my "goto" data structures. I even know that in some of the cases I used hash tables when Red Black Trees or even AVL Trees would have been better choices.  However, the hash table is more familiar to both me and my team. And choosing it doesn't impact the performance of our software very much.

Languages influence the choice by providing certain data structures as builtins leading to greater usage.

Whether it's arrays in C or hash tables in Perl and Python I see others (and myself) using these data structures more often because there more familiar and more readily available.

Programmers tend to head into one area during their careers and stay in that area.

I know database and filesystem implementers are much more familiar with B-Trees and tend to use that data structure in other things.

Depending on what you work on the choice of data structure may not matter that much within reason. Notice the "within reason".  I'm not talking about using a free form text string and full text search to contain numerically indexed data that should in an array.  The are reasons why it may not matter.

Your dealing with a small amount of data.

Your bottleneck is external to the code you control.

To me part of the criteria for journeyman and expert developers is knowing more than a couple of data structures, but more importantly being able to recognize when your "goto" data structures (or even the structures you know) aren't appropriate.  And then doing the work and research to find the appropriate structure and use it.


问:
Functions that only call other functions. Is this a good practice?
I'm currently working on a set of reports that have many different sections (all requiring different formatting), and I'm trying to figure out the best way to structure my code. Similar reports we've done in the past end up having very large (200+ line) functions that do all of the data manipulation and formatting for the report, such that the workflow looks something like this:

```<code>DataTable reportTable = new DataTable();
void RunReport()
{
    reportTable = DataClass.getReportData();
    largeReportProcessingFunction();
    outputReportToUser();
}
</code>```

I would like to be able to break these large functions up into smaller chunks, but I'm afraid that I'll just end up having dozens of non-reusable functions, and a similar "do everything here" function whose only job is to call all these smaller functions, like so:

```<code>void largeReportProcessingFunction()
{
    processSection1HeaderData();
    calculateSection1HeaderAverages();
    formatSection1HeaderDisplay();
    processSection1SummaryTableData();
    calculateSection1SummaryTableTotalRow();
    formatSection1SummaryTableDisplay();
    processSection1FooterData();
    getSection1FooterSummaryTotals();
    formatSection1FooterDisplay();

    processSection2HeaderData();
    calculateSection1HeaderAverages();
    formatSection1HeaderDisplay();
    calculateSection1HeaderAverages();
    ...
}
</code>```

Or, if we go one step further:

```<code>void largeReportProcessingFunction()
{
    callAllSection1Functions();

    callAllSection2Functions();

    callAllSection3Functions();
    ...
}
</code>```

Is this really a better solution? From an organizational point of view I suppose it is (i.e. everything is much more organized than it might otherwise be), but as far as code readability I'm not sure (potentially large chains of functions that only call other functions).

Thoughts?

答:
Breaking a function up into logical subfunctions is helpful, even if the subfunctions aren't reused -- it breaks it down into short, easily understood  blocks. But it has to be done by logical units, not just n # of lines.  How you should break it up will depend upon your code, common themes would be loops, conditions, operations on the same object; basically anything that you can describe as a discrete task.

So, yes, it's a good style -- this may sound strange, but given your describe limited reuse, I would recommend that you think carefully about ATTEMPTING reuse.  Be sure that the usage is truly identical, and not just coincidentally the same. Attempting to handle all cases in the same block is frequently how you end up with the large ungainly function in the irst place.


问:
How to speak to a computer
I am a self-taught, novice programmer. The language I chose was Objective-C, so that I can write Apple applications and software. I have learned the hard way that Objective-C has a steep learning curve, but I have forced myself to look at it over and over until I get it right.

I feel I am completing one major step, and that is becoming very comfortable with the syntax. Now as I enter the next big step - finding out what is possible with a computer programming language - I am thinking that all software is just developed within the confines of:

classes

loops

booleans

IF/OR statements

variables

etc.

Is that a true assessment? When thinking of software in my head do I just need to learn to convert it all to the above? Right?

Sorry if this question sounds funny, but I am just learning how to take the language in and talk (what I think is) the language of a computer. Is there a good book or tutorial that helps illustrate how to "speak as a computer would"?

答:
Fundamentally, computers can only do a few basic things:

They can perform simple arithmetic

They can execute instructions sequentially

They can branch to another instruction, based on a condition

They can loop (a variation of branching)

They can move data from one place to another

They can store data and retrieve it for later use.

That's about it.  Everything you see a computer do is just an elaborate abstraction over these simple operations.

Programming languages are one of those abstractions.  They allow us to speak the computer's language (technically, machine code), using a symbolic language that is closer to the language we humans use to communicate.  Programs called compilers translate programming languages into machine code, so that the machine can execute our instructions, just as we specified them.

There are many different computer languages, each optimized for a particular way of thinking or problem solving.  These ways of thinking are called paradigms; many programming languages support more than one paradigm.  Objective C is just one such language.

The way each computer programmer gets started is as individual as your fingerprints.  If you really want to "get" the idea of computers, my advice is to learn more than one language.  Study other languages; see how they differ.  See how they all have certain things in common; although they might solve a problem differently, at their core they still resolve down to the same fundamental operations.

Title: How to speak to a computer


问:
How do you quantify competency in terms of time (years)?
While looking for a job via agencies some time ago, I kept having questions from the recuitment agents or in the application forms like:

How many years of experience do you have in:

Oracle

ASP.NET

J2EE etc etc etc....

At first I answered faithfully... 5yrs, 7yrs, 2 yrs, none, few months etc etc..

Then I thought; I can be doing something shallow for 7 years and not being competent at it simply because I am just doing a minor support for a legacy system running SQL2000 which requires 10 days of my time for the past 7 years. Eventualy I declined to answers such questions.

I wonder why do they ask these questions anymore. Anyone who just graduated with a computer science can claim 3 to 4 years experience in anything they 'touched' in the cirriculum, which to me can be equivalent to zero or 10 years depending how you look at it.

It might hold true decades ago where programmers and IT skills are of very different nature. I might be wrong but I really doubt 'time' or 'years' are a good gauge of competency or experience anymore.

Any opinion/rebuttal are welcome!

答: If, for example, you started using ASP.NET in 2003, but have spent only 1/4 of your time doing projects with it since then, then you should claim only 7/4 or roughly 2 years of experience.</p>


问:
Use `using` in C++ or avoid it?
Discounting subtly different semantics due to ADL, how should I generally use using, and why? Is it situation-dependent (e.g. header which will be #included vs. source file which won't)?

Also, should I prefer ::std:: or std::?

Namespace-level using namespace:

```<code>using namespace std;

pair<string::const_iterator, string::const_iterator>
f(const string &s) {
    return make_pair(s.begin(), s.end());
}
</code>```

Being fully explicit:

```<code>std::pair<std::string::const_iterator, std::string::const_iterator>
f(const std::string &s) {
    return std::make_pair(s.begin(), s.end());
}
</code>```

Namespace-level using-declarations:

```<code>using std::pair;
using std::string;

pair<string::const_iterator, string::const_iterator>
f(const string &s) {
    return make_pair(s.begin(), s.end());
}
</code>```

Function-local using-declarations:

```<code>std::pair<std::string::const_iterator, std::string::const_iterator>
f(const std::string &s) {
    using std::make_pair;
    return make_pair(s.begin(), s.end());
}
</code>```

Function-local using namespace:

```<code>std::pair<std::string::const_iterator, std::string::const_iterator>
f(const std::string &s) {
    using namespace std;
    return make_pair(s.begin(), s.end());
}
</code>```

Something else?

This is assuming pre-C++14, and thus no return-type-deduction using auto.

答:
Avoid using using in headers, because that breaks the purpose of namespaces.

It is ok to use it in source files, but I would still avoid it in some cases (for example using std).

However if you got nested namespaces, it's ok :

```<code>namespace A {
namespace B {
namespace C {
class s;
} // C
} // B
namespace D{
using B::C::s;
} // D
} // A
</code>```

ContentLicense: CC BY-SA 4.0

Title: Use `using` in C++ or avoid it?

Body:
Avoid using using in headers, because that breaks the purpose of namespaces.

It is ok to use it in source files, but I would still avoid it in some cases (for example using std).

However if you got nested namespaces, it's ok :

namespace A {
namespace B {
namespace C {
class s;
} // C
} // B
namespace D{
using B::C::s;
} // D
} // A


问:
Are developers expected to have skills of business analysts?
Our business analyst has left the team. We are now expected to do the work which was previously done by the business analyst, and the management thinks that a task which is done in three months by a business analyst can be done in one month by a developer.

My experience is in programming only, and I'm not familiar to the business intelligence tools. To me this seems like maybe an unfair comparison or expectation, and might even trivialize the role of a business analyst.

Has anyone else encountered this situation? How to deal with it?

答:
I agree with gnat's comment. Also, the B.A. took 3 months not because she is not professional enough as a programmer. Most probably the time taken in analysis is significant because the amount of customer interaction required (which usually fits the customer timetable) and the time taken in writing down detailed documentation.

Most Business Analysis tools are not complex to learn for a programmer (given the right training). However, the business analysis concepts and the domain expertise can take time.

If the remaining work is not significant, maybe more than one developer could cooperate to finalize the work that has been done in a short time. But the rule set that if B.A. takes 3 months to do the job, then it takes the programmer 1 month is not valid as stated. It sounds like comparing a dentist work to a brain surgeon's work!

In any case, the project manager should flag this as a risk in the project.


问:
Multi-tenancy - single database vs multiple database
We have a number of clients, whose systems share some functionality, but also have quite a degree of diversity. The number of clients is growing - always a healthy thing! - and the diversity between their businesses is also increasing.

At present there is a single ASP.Net (Web Forms) Web Site (as opposed to web project), which has sub-folders for each tenant, with that tenant's non-standard pages. There is a separate model project, which deals with database access and business logic.

Which is preferable - and most importantly, why - between having (a) 1 database per client, with only the features associated with that client; or (b) a single database shared by all clients, where only a subset of tables are used by any one client.

The main concerns within the business are over:

maintenance of multiple assets - backups, version control and the like

promoting re-use as much as possible

How would you ensure these concerns are addressed, which solution is preferable, and why? (I have been also compiling responses to similar questions)

答:
Since the clients databases and functionality are diverging, then it means that at one point they will end up being different systems, so in this case I would recommend separate systems since the costs of maintaining the customizations for each client will outweigh the benefits of a single database system.

Single database systems are best for when the changes between different customers are merely configurations but not additional features for each client.


问:
Teacher demands excessive/unjustified use of Design Patterns
I study computer science and I have a class called "Programming Techniques". Its purpose is to teach (us) good object oriented design principles. During the semester we have homeworks, programs that we must write to demonstrate what we've learned.

The lab assistant demands for each of these homeworks that specific design patterns should be used. For example, the current homework is an application used for processing customer orders. We are demanded to use either "Factory Method" or "Abstract Factory" design patterns for this. It gets even worse: at the end of the semester we must write a program (something more complex) that must use at least one creational pattern, at least one structural pattern and at least one behavioural pattern.

Is it normal to demand this ? I mean, forcing us to design our programs in such a way that a specific design pattern makes sense is just beyond what I consider ok. If I'm a car mechanic and have a huge tool box, then I will use a certain tool from that box if and when the situation demands it. Not more, not less. If my design of the application doesn't demand at all the use of "Abstract Factory" (for example), then why should I implement it ?

I'm not sure yet if the senior lecturer agrees with what the lab assistant is demanding, but I want to talk to him about it and I need solid arguments to do so. How should I approach this problem with him ?

PS: I'm sure there must be a better way to teach us these things. Maybe making us each week read about 3 design patterns and the next week giving us a test with small but specific programming or architectural situations/problems. The goal in that test would be to identify what design patterns would make sense and how they could be implemented. This way, he can see if we understand them.

EDIT: These homeworks are not just 100-line programs, they have quite a lot of requirements and are fairly complicated. This is the reason we have about 2 - 3 weeks of deadline for each of them.

I agree that practicing this is the best way to learn. But shouldn't smaller programs/applications be used for this ? Something just for demonstrating purposes. Not big programs with lots of requirements/classes/etc.

答: It's sad if university is just about passing the subject these days regardless of what or how you learn. I feel for you because a few years ago I was in a similar situation, but I was given a specific project to implement where a factory was utterly irrelevant, but nevertheless we had to force one in. The problem with this kind of teaching is that it is very misleading to impressionable students. If teachings patterns out of context, teachers must make that point clear. Any good student should raise his concerns to the teacher...it's what learning should be about.</p>


问:
Why was Tanenbaum wrong in the Tanenbaum-Torvalds debates?
I was recently assigned reading from the Tanenbaum-Torvalds debates in my OS class. In the debates, Tanenbaum makes some predictions:

Microkernels are the future

x86 will die out and RISC architectures will dominate the market

(5 years from then) everyone will be running a free GNU OS

I was a one year old when the debates happened, so I lack historical intuition. Why have these predictions not panned out? It seems to me, that from Tanenbaum's perspective, they're pretty reasonable predictions of the future. What happened so that they didn't come to pass?

答:
For 2:
The CISIC instruction set has a big advantage: It's more compact, like compressed machine code. Nowadays it's very cheap to decode CISC instructions into micro-ops and it's very expensive to access the RAM. So CISC has the advantage of pushing more code in the L1/L2/L3 caches</p>


问:
Is there such a thing as a super programmer?
Have you come across a super programmer? What identifies him or her as such, compared to "normal" experienced/great programmers?

Also. how do you deal with a person in your team who believes he is a super programmer? Both in case he actually is or if he isn't?

Edit: Interesting inputs all round, thanks. A few things can be gleaned:

A few definitions emerged. Disregarding too localised definitions (that identified the authors or their acquaintance as super programmers), I liked a couple definitions:

Thorbjørn's definition: a person who does the equivalent of a good team consistently for a long time.

Free Electron, linked from Henry's answer. A very productive person, of exceptional abilities. The explanation is a good read.

A Free Electron can do anything when it comes to code. They can write a complete application from scratch, learn a language in a weekend, and, most importantly, they can dive into a tremendous pile of spaghetti code, make sense of it, and actually getting it working. You can build an entire businesses around a Free Electron. They’re that good.

Contrasting with the last definition, is the point linked to by James about the myth of the genius programmer (video). The same idea is expressed as egoless programming in rwong's comment. They present opposite opinions as whether to optimise for such a unique programmer or for a team.

These definitions are definitely different, so I would appreciate it if you have an input as to which is better. Or add your own if you want of course, though it would help to say why it is different from those.

答:
A superprogrammer is any person who can generate code faster than a speeding compiler, more powerful than a recursive function, and able to leap over FIFO stacks in a single bound.

The way you deal with a person in your team who believes he is a superprogrammer is by exposing him to his only weakness - sunlight.


问:
What makes C so popular in the age of OOP?
I code a lot in both C and C++, but did not expect C to be the second most popular language, slightly behind Java.

TIOBE Programming Community Index

I'm curious as to why, in this age of OOP, C is still so popular? Note that 4 out of the top 5 popular programming languages are "modern", object-oriented capable languages.

Now, I agree that you can use OOP in C to some extent, but it's sort of painful and inelegant (well at least compared to C++ I guess). So, what makes C so popular?  Is it efficiency; being low-level; the vast majority of libraries that already exist or something else?

答: Embedded systems and drivers are usually programmed in C. Aside from that there are tons of legacy C systems out there that are still maintained and extended.</p>


答:
Einstein got it right: "Make things as simple as possible, but not simpler."

This applies to code as well. If you can simplify code by removing repetitive and needlessly verbose elements, that is a good thing.

Also, some case studies suggest that programmer productivity measured in lines of code is more or less a constant. So is the number of bugs per LOC. So switching to a language that allows you to do more per line of code can be considered a productivity improvement, if all other things stay equal.

That being said, there is a tendency in this industry to over engineer and complicate what should be simple things. Simple things like stuffing contact details in a relational database. I've seen some ridiculously complicated and misguided solutions (cough MDA) for that particular problem. Languages like Scala and Ruby are good examples of powerful tools that in the hands of certain individuals result in unintelligible, overly complicated, and poorly maintainable code. Just because you can use multiple levels of indirection with a few key strokes doesn't mean you have to wack every nail in sight with that particular hammer.

When used properly, you get nice clean code that is both short and easy to understand. When used poorly, you are better off confining the individual in question to using visual basic or a similarly limited language to prevent further damage.

True skill lies in making complex things in a simple way, not in making simple things in a complicated way.


答:
I'm assuming that your business analyst is a subject matter expert - they understand the organization and the industry that the organization operates in extremely well, and they probably have a very good understanding of appropriate laws and regulations that apply to what the organization does.

I would expect a developer, especially one who has been with the organization for a while, to have begun to acquire some of the skills of a business analyst. Perhaps not necessarily how to use the tools they do, but at least the domain knowledge regarding the organization, the industry, and regulations. However, I wouldn't expect any developer to be a drop-in replacement for a business analyst, must less have the ability to perform work and have a higher productivity than a business analyst.

To me, the timetable sounds like a major project risk. In order for a developer to function as a business analyst, there must be time allocated to become much more familiar with the domain as well as the tools used before the developer can function at the same productivity as an equally dedicated and knowledgeable business analyst.

I would recommend sitting down with management - explain what you would need to do to become as familiar with the environment as the business analyst who left and estimate the time that it would take you to reach that level of familiarity. Only after that time can you do the work.

Title: Are developers expected to have skills of business analysts?

Body:
Our business analyst has left the team. We are now expected to do the work which was previously done by the business analyst, and the management thinks that a task which is done in three months by a business analyst can be done in one month by a developer.

My experience is in programming only, and I'm not familiar to the business intelligence tools. To me this seems like maybe an unfair comparison or expectation, and might even trivialize the role of a business analyst.

Has anyone else encountered this situation? How to deal with it?


答:
Firstly, you don't need OOP for everything, despite whatever dogmas regarding this have been popularized. Unlike Java, C allows function pointers and even closures which opens the door to functional programming and solves quite piece of the problem space OOP handles, because it provides the means of dependency injection. Also cautious use of macros can actually create some very nice things, as sglib proves.

In a weird way, one could see C as a good compromise between Java and C++. Please note I am not saying that C is in any way a mix of both. But in contrast to Java, it is rather powerful language while in contrast to C++ it has manageable complexity.

It is an old language, that has grown reliable and consistent, while not really growing more complicated. And all that aside, it has a giant eco-system and it simply runs everywhere.

Title: What makes C so popular in the age of OOP?

Body:
I code a lot in both C and C++, but did not expect C to be the second most popular language, slightly behind Java.

TIOBE Programming Community Index

I'm curious as to why, in this age of OOP, C is still so popular? Note that 4 out of the top 5 popular programming languages are "modern", object-oriented capable languages.

Now, I agree that you can use OOP in C to some extent, but it's sort of painful and inelegant (well at least compared to C++ I guess). So, what makes C so popular?  Is it efficiency; being low-level; the vast majority of libraries that already exist or something else?


问:
Continuous integration (with iOS and Android projects)
I'm trying to make some positive changes in my company and one of the changes is implementing continuous integration. We do mobile development (iOS/Android) so I need a CI that supports both types of projects. As you can tell I don't know a lot about CI but I've googled a little bit and I think that Jenkins and Hudson are the two most popular.

I have a two part questions.

Your thought on Jenkins?

Is there a way for CI to check if the project is compiling to the

coding standards (like loose coupling and so on)?

答:
Firstly you might want to go look at TeamCity as another option for your server.

In my view (though I've somewhat less experience with Jenkins than with TeamCity) both are excellent and very capable tools - I'd be happy in an environment using either.

Ok, to get to the meat of the problem i.e.

Is there a way for CI to check if the project is compiling to the coding standards (like loose coupling and so on)?

At the most fundamental level all that a CI server does is run a script and then interpret and present the results of running that script - so if you can script it then your CI server can probably run it and if you can format the output appropriately then the CI server can probably interpret and report on the result.

Of course the major build servers are already capable of talking to/integrating with a lot of popular tools - so really the question becomes what tooling are you using to check your coding standards and does that integrate with your choice of CI server.

Yes, the CI server brings a lot more to the game in terms of automation than just mindlessly running a script - but at the end of the day that's what its doing.

Just to be clear - I know that a build server does more than just run scripts, its the automation of the process (and in particular the integration with (D)VCS) that adds value - but in answering the "what do I need for a build server" question the answer is "a server and script" everything else flows from there.


答:
A few factors that contribute:

C is ubiquitous. Whatever the platform, C is probably available.

C is portable. Write a piece of clean C, and it compiles with minimal modifications on other platforms - sometimes it even works out-of-the-box.

C has been around for a while. Back in the days when UNIX conquered the world, C (the UNIX programming language of choice) shared in its world domination, and became the lingua franca of the programming world. Any serious programmer can be expected to at least make some sense of a chunk of C; the same can't be said about most other languages.

C is still the default language for UNIX and UNIX-flavored systems. If you want a library to succeed in open-source land, you need fairly good reasons not to use C. This is partially due to tradition, but more because C is the only language you can safely assume to be supported on any UNIX-like system. Writing your library in C means you can minimize dependencies.

C is simple. It lacks the expressivity of sophisticated OOP or functional languages, but its simplicity means it can be picked up quickly.

C is versatile. It is suitable for embedded systems, device drivers, OS kernels, small command-line utilities, large desktop applications, DBMS's, implementing other programming languages, and pretty much anything else you can think of.

C is fast. Most C implementations compile directly to machine code, and the programmer has full power over what happens at the machine level. There is no interpreter, no JIT compiler, no VM or runtime - just the code, a compiler, a linker, and the bare metal.

C is 'free' (in both the beer and the speech sense). There is no single company that owns and controls the standard, there are several implementations to choose from, there are no copyright, patenting or trademark issues for using C, and some of the best implementations are open-source.

C has a lot of momentum going. The language has been popular for decades, so there is an enormous amount of applications, libraries, tools, and most of all, communities, to support the language.

C is mature. The last standard that introduced big changes is C99, and it is mostly backwards-compatible with previous standards. Unlike newer languages (say, Python), you don't have to worry about breaking changes anytime soon.

C is compatible. Most languages have bindings to talk to C. This means one can develop a library in C using standard calling conventions, and feel confident that almost any other language can link against that library. To name a few popular languages in widespread use: C#, Java, Perl, Python, PHP can all link against C libraries without much trouble.

C is powerful: if the language cannot do something, all popular compilers allow embedding assembler code which can do anything the hardware can do. Transitively combined with the above point about compatibility, this means C can act as a liaison between higher level languages and the "bare metal" of assembly.


问:
Are there serious companies that don't use version-control and continuous integration? Why?
A colleague of mine was under the impression that our software department was highly advanced, as we used both a build server with continuous integration, and version control software. This did not match my point of view, as I only know of one company I which made serious software and didn't have either. However, my experience is limited to only a handful of companies.

Does anyone know of any real company (larger than 3 programmers), which is in the software business and doesn't use these tools? If such a company exists, are there any good reason for them not doing so?

答:
The last job I worked at without version control was in 2006 (I'm a Web developer, FWIW). The company only had about 2 or 3 developers before hiring me, but I was the first of 10 or so developers hired in just a couple of months. One of the first things I did when hired was introduce version control (CVS, because I didn't know at the time how badly it sucked!), but many of the developers hired after me couldn't get it to work on their dev environments, so didn't use it. Oh, did I mention that they didn't even have local instances of the application running? They hacked code on the server. And no automated tests, of course. I cringe when I think back on it.

Before that, I did some AS/400 programming work without version control.  I don't know if a decent VCS was even available for that environment.

Now I use Git for all my one-man projects, and my last several jobs have used it too.

CI is a different matter. It's great to have, and I encourage it, but it's less essential than version control, at least for smaller projects in interpreted languages. Most of my recent jobs have had CI servers, though; among other things, it means that no one can forget to run the full test suite before deploying.

OwnerDisplayName: daramarak


答:
I prefer to separate in my resume the experience in advanced and basic categories.

Over advanced there are all technologies I have been using most.

Over basic I introduce those languages and technologies I left in the past, or those I see less over time.

I'm not describing years in resume, except on my presentation letter.

Title: How do you quantify competency in terms of time (years)?

Body:
While looking for a job via agencies some time ago, I kept having questions from the recuitment agents or in the application forms like:

How many years of experience do you have in:

Oracle

ASP.NET

J2EE etc etc etc....

At first I answered faithfully... 5yrs, 7yrs, 2 yrs, none, few months etc etc..

Then I thought; I can be doing something shallow for 7 years and not being competent at it simply because I am just doing a minor support for a legacy system running SQL2000 which requires 10 days of my time for the past 7 years. Eventualy I declined to answers such questions.

I wonder why do they ask these questions anymore. Anyone who just graduated with a computer science can claim 3 to 4 years experience in anything they 'touched' in the cirriculum, which to me can be equivalent to zero or 10 years depending how you look at it.

It might hold true decades ago where programmers and IT skills are of very different nature. I might be wrong but I really doubt 'time' or 'years' are a good gauge of competency or experience anymore.

Any opinion/rebuttal are welcome!


问:
Mulitple processes aware of each other
Hope you can help me with this, I've searched a lot and I got really confused of what to do here.

I'm building a program in C and I need to run it multiple time as I need.

So it's going to be like below,

process 1 handle all rows on DB table test where process_flag=1

process 2 handle all rows on DB table test where process_flag=2

process 3 handle all rows on DB table test where process_flag=3

and so on

How can I make the processes aware of each other, so if process 3 goes down then processes 2 & 3 start working on process_flag=3?

答:
The best solution might be to keep all the processes unaware of each other and use a separate watchdog/supervising process to monitor them and automatically restart ones that go down. Examples are Supervisor or perp.

If you want it to behave exactly as you say, you could have each process store their pid in the database (or in a file), or send a heartbeat periodically (storing time of last activity in the database, or touching a file on disk). The table/file would also contain the process_flag. Then in between jobs the other processes could check this and see if any of the pids are for no longer running processes, or if the heartbeat hasn't been updated in a while. Then they could "claim" that process_flag and update the row/file atomically.

But... if you do all that you're basically making each process a process monitor. So to keep it simple you could split out that monitoring code into a separate process. But then you've basically written a replacement for one of the existing tools you could have been using.

A concern people have about using a watchdog is what to do if it crashes itself. One solution is to have a cron that periodically starts it up if it's no longer running.

Title: Mulitple processes aware of each other


问:
Why is verbosity bad for a programming language?
I have seen many people around complaining about verbosity in programming languages. I find that, within some bounds, the more verbose a programming language is, the better it is to understand. I think that verbosity also reinforces writing clearer APIs for that particular language.

The only disadvantage I can think of is that it makes you type more, but I mean, most people use IDEs which do all the work for you.

So, What are the possible downsides to a verbose programming language?

答:
Programmers tend to like languages with expressive power as it allows them to code up the simple things, which often have to be done frequently, in small pieces of code. Verbose languages tend to mean that many, many lines of code have to be used to do the same thing over and over again.
However, there can be something of a price to be paid with expressive languages as they may not be as fast to execute as simpler high level langauages.
If I can give an example in the contrast between C and C++. C++ gives more expressive power to code writers - they can encapsulate the idea of real world objects in classes. C programmers can achieve the same things but they do have the expressive power of the class construct to help them - so often they have to write longer, more complicated (to understand) code. But that code may well run faster (though this is highly dependent on compiler quality and so on) because it does not use C++'s "late binding" (ie run time refactoring) to execute the code. C just executes the compiled and linked code, C++ has to make a decision (in certain circumstances) at run time about which pieces of code to execute.</p>


问:
Can you point me to a nontrivial strategy pattern implementation?
We are faced implementing a registration workflow with many branches. There are three main flows which in some conditions lead to one another. Each flow has at least four different steps; some steps interact with the server, and every step adds more information to the state. Also the requirement is to have it persistent between sessions, so if the user closes the app (this is a mobile app), it will restore the process from the last completed step with the state from the previous session.

I think this could benefit from the use of the strategy pattern, but I've never had to implement it for such a complex case. Does anyone know of any examples in open source or articles from which I could find inspiration? Preferably the examples would be from a live/working/stable application.

I'm interested in Java implementation mostly; we are developing for Java mobile phones: android, blackberry and J2ME. We have an SDK which is quite well separated from platform specific implementations, but examples in C++, C#, Objective-C or Python would be acceptable.

答:
You should have a look at JHotDraw. It's sole purpose is to demonstrate patterns usage in real life.

jhotdraw.org is where it's at:

a Java GUI framework for technical and structured Graphics. It has been developed as a "design exercise" but is already quite powerful. Its design relies heavily on some well-known design patterns. JHotDraw's original authors have been Erich Gamma and Thomas Eggenschwiler...

JavaWorld published an introductionary article "Become a programming Picasso with JHotDraw". The accompanying example application JModeller - a simple UML editor built using JHotDraw - shows some of the described design patterns and demonstrates how to use and extend existing classes...

Besides the documentation which is included in the download package more information about the internal architecture of JHotDraw and guidance for using the JHotDraw can be found here:

A description of the design patterns used in JHotDraw in the form of a pattern language by Douglas Kirk. Especially, the pattern index in form of a clickable pattern map shows the relation of different patterns.

A case study about an older version of JHotDraw can be found in the dissertation of Dirk Riehle...


答:
I second the TeamCity recommendation -- it is a great product. I can't speak to android as I've got no seat time over there, but I have successfully got iOS projects running in CI thanks two articles (1 2).

The trickiest parts really had to do with getting the mac to run the automated build with the proper keychain and such so you could create a signed app that you could deploy to an iDevice rather than an emulator-only option.

Title: Continuous integration (with iOS and Android projects)

Body:
I'm trying to make some positive changes in my company and one of the changes is implementing continuous integration. We do mobile development (iOS/Android) so I need a CI that supports both types of projects. As you can tell I don't know a lot about CI but I've googled a little bit and I think that Jenkins and Hudson are the two most popular.

I have a two part questions.

Your thought on Jenkins?

Is there a way for CI to check if the project is compiling to the

coding standards (like loose coupling and so on)?


答: The same thing that makes a manual hammer popular in an age of pneumatic hammers (air hammers): C is still the right tool for certain jobs.</p>


答:
I believe that there is an answer to the question rooted in a more fundamental and theoretical issue than readibility and this answer is related to the algorithmic information theory founded by Gregory Chaitin:
http://en.wikipedia.org/wiki/Algorithmic_information_theory. Stated in few words, "the information content of a string is equivalent to the length of the shortest possible self-contained representation of that string", This implies that the shortest program (namely in terms of its lexicographic length) solving a given problem closely matches the intrinsic complexity of the problem to which it gives a solution and, thus, it depends more on the problem nature and less on the representation of the problem. </p>


问:
What was the first programming language written for computers?
Looking at so many programming languages we have today, each one being unique in it's own way, I've tried to figure out what the first programming language written for computers is.

Looking at the release date for the popular ones I got somewhat close but I didn't look at less obvious ones, programming languages which are either dead or very little use nowadays. Fortran is the closest thing I got but I don't know if it's real.

In a nutshell: What was the first programming language written for computers? Are there any languages that derived from that language?

答:
after assembly type things the first was Fortran  created by John Backus at IBM in 1957, Lisp was created in 1957 by John McCarthy at MIT, Cobol came out in '59.

Fortran influenced a bunch of other things and Lisp has influence in pretty much everything.


答:
According to this source, FORTRAN in 1954. FORTRAN is still used extensively in science and engineering though the language has been significantly modified.

There is some ambiguity in what is considered a programming language. Assembly might count, since it is an abstraction of the underlying binary codes, and has syntax.

Body:
Looking at so many programming languages we have today, each one being unique in it's own way, I've tried to figure out what the first programming language written for computers is.

Looking at the release date for the popular ones I got somewhat close but I didn't look at less obvious ones, programming languages which are either dead or very little use nowadays. Fortran is the closest thing I got but I don't know if it's real.

In a nutshell: What was the first programming language written for computers? Are there any languages that derived from that language?


答: The first "real" language was Assembly, unless you'd consider things like switches or punch cards a programming language.</p>

Title: What was the first programming language written for computers?


答: I've set up our company's build server and scripts before using Jenkins where we develop iOS apps. Like many said, CI server is pretty simple and I like Jenkins because it's free/open source and has many plugins like publising coverage reports or github integration. </p>


答:
It's difficult to answer that definitively, but Plankalkül was designed by Konrad Zuse between 1943 and 1945.  The linked Wikipedia article refers to it as "the first high-level non-von Neumann programming language to be designed for a computer".

See also.


答:
As VJovic indicates, do not use using in a header file. using in a header file affects the current compilation unit (the .cpp file) in ways that the source file may not be expecting.

using namespace is also to be avoided in a source file. This brings every symbol into the same scope as the source file. It is more clear to your readers what you are doing if you use specific symbols from the namespace.

Title: Use `using` in C++ or avoid it?

Body:
Discounting subtly different semantics due to ADL, how should I generally use using, and why? Is it situation-dependent (e.g. header which will be #included vs. source file which won't)?

Also, should I prefer ::std:: or std::?

Namespace-level using namespace:

```<code>using namespace std;

pair<string::const_iterator, string::const_iterator>
f(const string &s) {
    return make_pair(s.begin(), s.end());
}
</code>```

Being fully explicit:

```<code>std::pair<std::string::const_iterator, std::string::const_iterator>
f(const std::string &s) {
    return std::make_pair(s.begin(), s.end());
}
</code>```

Namespace-level using-declarations:

```<code>using std::pair;
using std::string;

pair<string::const_iterator, string::const_iterator>
f(const string &s) {
    return make_pair(s.begin(), s.end());
}
</code>```

Function-local using-declarations:

```<code>std::pair<std::string::const_iterator, std::string::const_iterator>
f(const std::string &s) {
    using std::make_pair;
    return make_pair(s.begin(), s.end());
}
</code>```

Function-local using namespace:

```<code>std::pair<std::string::const_iterator, std::string::const_iterator>
f(const std::string &s) {
    using namespace std;
    return make_pair(s.begin(), s.end());
}
</code>```

Something else?

This is assuming pre-C++14, and thus no return-type-deduction using auto.


答: Nothing. TIOBE is a worthless index. If you actually look at their measurement, it's an absolute guess- at best.</p>


答:
You probably wanted to ask why people use C instead of C++ despite the fact that when you have a C compiler, you also usually have C++ compiler.

C language is much simpler than C++. I don't know any company that uses the complete C++ standard in their coding convention. Take a look at Google's C++ code style as an example: http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml

C is much faster to compile. Thanks to the lack of hard to compile constructs.


答:
One advantage of using C over languages like C++ or Java is that there isn't a whole lot of magic happening under the hood.  No constructors are run when items are allocated, and no destructors are run when objects go out of scope.  There's no name mangling and no vtables.  Performance is easier to predict; you don't have to worry about a garbage collector interrupting a routine and throwing off its timing.

Constructors, destructors, name mangling, vtables, garbage collectors, etc., can ease some of the complexity in the code you author, but then that complexity becomes part of the language itself, where you have little to no control over it.  You may wind up with longer build times (annoying, but tolerable), larger runtime memory footprint (may or may not be tolerable) or slower performance. With C you can pare away some of that complexity until you're left with the functionality you need.

For example, the C++ string data type is light-years easier to work with than C-style strings, but it's a fairly heavyweight piece of code, and adds some heft to your image size.  I've rarely seen anyone make full use of string's capabilities in any one program.  C-style strings, while harder to work with, impose less of a penalty in terms of run time and image size, and for a particular problem may be more attractive for that reason.


答:
Simplicity, consistency and precision.

It is simple - you don't need a complex development environment, extensive libraries, or a virtual machine.

It is consistent - most C written 10 years ago could compile today.

Precision - it let's you get down to the level of the machine, knowing the memory locations as needed.  This is great for performance and embedded hardware.

It's not for everything, bit it's still a useful tool.


答:
C has an ABI(Application Binary Interface) C++ doesn't. This makes C more useful than C++ in certain instances.  If I am going to write a library and be able to ship binaries for other people's use C++ is the wrong tool for the job.  If I am going to write libraries that are going to be used by some other language again C is the right tool for the job.  I have never heard of a language that didn't support FFI(Foreign Function interface) to C, on the other hand C++ won't work with libraries written in C++ if different compilers are used.

Basically it boils down to C filling a role that C++ is unsuitable for.


问:
How to build a web service to detect content change(s) at an external website?
I'm researching ways to build a web service to periodically traverse a predetermined list of web pages (of another external website) to detect if a page's content has changed from

editing of the page, and

deletion of the page.

The end goal is to have this web service post push-notification events to mobile devices.

FYI, I've searched and read "Questions with similar titles" here.

Thank you for sharing your answers.

答: What about just reading the page with cURL? Maybe store a checksum of what you read and compare against that next time.</p>


答:
I've always tended to blame the popularity of C on the need for a universal assembly language. It's combination of specificity at the machine level, standardization, and extreme portability allow C to function as that de facto universal assembly language, and for that reason I suspect its role there will continue indefinitely.

I should mention that I'm always a bit surprised when OOP is presented in programming courses as a sort of "final model" that is the only possible endpoint for good programming. Like many other aspects of programming, the value of OOP is a compromise between many competing factors, including how human brains organized information, how societal groups support software over the long term, and in the case of object-oriented programming, some pretty deep aspects of how the universe itself works.

And that last point is worth hammering a bit. Read further if you are interested in a physics-level exploration of why certain programming styles exist, how they work together, and where the world may be heading in the future as we expand further on such concepts...

An object in physics is anything that maintains recognizable coherence over time. That in turn allows simple creatures like ourselves to get away with representing the object using only a small number of bits, without endangering our survival too badly. But in terms of physics in the large, the number of things you have to get exactly right to make that kind of simplification easy and common is remarkably large. As humans we don't think about all of that much because quite frankly, we wouldn't be here if it were not true.

Sound too abstract? It really isn't. Imagine for example trying to navigate the road to your friend's house if instead of cars you encountered rapidly oscillating plasma fields and momentary condensations of matter moving with an enormous range of velocities. Such a scenario might cut rather deeply into socialization opportunities, yes? We need objects, we are objects, and the existence of objects provides us with an enormous and critically important level of simplification of the environment around us.

So let's pull all of that back around to software. What do objects in the real world have to say about objects in terms of programming?

Well, for one thing it means that what defines a "good" object in software should really be whether or not the type of data you are handling readily supports the idea of recognizable persistence over time.

With the definition, the easiest forms of OOP are easy to recognized. They are the ones that cop out a bit by using only data that is already "attached" or defined by some real-world, truly physical object like a person, house, or car. Even today, this is still too often the only definition of objects that people get in software courses. That's too bad, because even trivial object-oriented programs need a broader definition than that.

The second and far more interesting category of objects consists of what I'll call immortalized real-world events. By "immortalized" I mean things that at least briefly exist as a well-defined entity or collections out in the real world, but which then disperse and ceases to exist as physically meaningful collections. A symposium is a great example: The symposium exists for a short while as a decently well-defined collection of places and people. But alas, even the best conferences must end, and the individual parts that made them up move on to other activities.

But by using computers and networks, we can make such a transient symposium seem like a long-term object by capturing and maintaining a memory of it as a software object. A great many of the things we do with computers and databases amount to this kind of immortalization of transient events, in which we in effect try to make our real universe richer by capturing and extending it in ways that cannot possibly exist physically. E.g., have you seen a real Pandora lately? Such captures and extensions of real-world pieces help enrich and extend our own lives, economies, and choices in remarkable ways. This to me is the heartland of object oriented programming, the place where it has had, and continues to have, the most remarkable impacts.

A final category of OOP consists of objects that have no close connection to external events, but are instead the infrastructure needed to support our continuing extension of reality using immortalized objects from the real world. This is where you can descend all the way down to the (semi)metal of the computer, creating pieces of persistent reality that like the chemical elements of the real world can be combined quickly and in interesting ways to build new internal worlds. Mobile computing has helped promote the growth of this kind of highly recombinatorial approach, one that again in many ways mimics the recombinatorial features of the physical world. It is also hard: What may seem like a good choice may prove over time to have been an unexpectedly bad one, usually because it ends up blocking diversity and expansion instead of supporting it.

This last category also points the risks of using just one model for programming, since just like the real world, programmed worlds also need processes that don't correspond well to relatively unchanging objects. Earth is full of objects, but the sun is full of highly dynamic energy flows that ultimately are needed to "drive" the objects and activities on lower-energy earth. Similarly, in creating computing worlds there are cases where you must deal with flows and transformations and rapidly changing contexts that, while not very object-like in themselves, are nonetheless absolutely critical to enabling the simpler, more human-friendly objects used at higher levels. It is no coincidence that much of the programming done at the kernel level is not conspicuously object-like, or that it tends to rely heavily on languages like C that are more processing oriented. These are the deeper domains that complement the fascinating diversity we see higher up in computer generated worlds. Trying to force them into pure object models can be a bit like telling the sun it needs to be re-organized as a few billion tidy fireplace objects so that we can understand and navigate more easily from our humans-first perspective.

The other area where OOP can go awry is focusing too much on old object concepts.

Objects in the real world, and especially living objects, have an absolutely astonishing level of ability to interact with their environments in complex and subtle ways. Composable widgets that look each other over, do some compatibility and sanity checks, and maybe even figure out some new ways to interact come a lot close to the real-world biological concept of objects than do the simple frameworks and simple inheritance schemes that we tend to focus on (usually by necessity!) at the code level. This is one of the growth areas for objects in the cyber world, the more "agent like" approaches where reactivity to environment is the norm even within programming itself.

And so much for my "critique" of OOP! Still, though, I hope I've pointed out why creating a richer cyberworld means encompassing diversity of programming styles, rather than assuming that "just one" is all that is needed. My feeling is that the really interesting stuff is yet to come, no matter how mundane much of what we do now is!


答:
Editing of the page can be checked by:

Check if the HTTP header last-modified is present. If it is, compare it to the previously stored value and you are done.

If the last-modified HTTP header is not present, store the page checksum or checksum of the important part of the page. Since some of the web pages contain randomly generated parts, you want to ignore these parts. You can define the 'important part' of the page using e.g. regular expression. Next time you will compare the stored checksum with new one.

Delete of the page can be checked simply by trying to connect to it.

Title: How to build a web service to detect content change(s) at an external website?

Body:
I'm researching ways to build a web service to periodically traverse a predetermined list of web pages (of another external website) to detect if a page's content has changed from

editing of the page, and

deletion of the page.

The end goal is to have this web service post push-notification events to mobile devices.

FYI, I've searched and read "Questions with similar titles" here.

Thank you for sharing your answers.


答:
Lots of Legacy Software

Many companies cannot change, instantly all their code to C++ or similar.

Many companies cannot afford to change their code.

Many companies can afford to change their code, but don't care, or are "cheap".

Many companies are in the process of migrating, but, not yet finished.

Hidden Object Orientation

(Non Object Oriented) C source code designed as Object Oriented C source code, applications that are modeled with Object Orientation, and coded with "pure C", or tools that translate from "C++" or other O.O. progr. lang into C.

I heard that some video games are done that way. Some cross platforms tools also, and the GTK (GObject, GLibrary) visual interface library for the GNome Linux O.S. distributions.


问:
Examples of continuous integration workflow using git
Can anyone provide a rough outline of their git workflow that complies with continuous integration.
E.g. How do you branch? Do you fast forward commits to the master branch?

I am primarily working with Rails as well as client and server side Javascript. If anyone can recommend a solid CI technology that's compatible with those, that'd be great. I've looked into Jenkins but would like to check out other good alternatives.

To put some context into this, I am planning on transitioning from working as a single developer into working as part of the team. I'd like to start standardizing my own personal workflow so that I can onboard new devs quickly.

答:
A simple workflow.

Central Git Repo used by the CI server

People push to a specific branch on that Repo (say Master)

CI Server detects changes in master branch or runs a timed build

CI Server runs unit tests

Depending on your rules, the CI server can
then tag the repository, and a myriad of other things.

There are countless ways to do this, do what fits your workflow the best.