问:
Command-Query-Separation and multithreading safe interfaces
I like the command query separation pattern (from OOSC / Eiffel - basically you either return a value or you change the state of the class - but not both). This makes reasoning about the class easier and it is easier to write exception safe classes.

Now, with multi threading, I run into a major problem: the separation of the query and the command basically invalidates the result from the query as anything can happen between those 2.

So my question is: how do you handle command query separation in an multi-threaded environment?

Clarification example:

A stack with command query separation would have the following methods:

push (command)

pop (command - but does not return a value)

top (query - returns the value)

empty (query)

The problem here is - I can get empty as status, but then I can not rely on top really retrieving an element since between the call of empty and the call of top, the stack might have been emptied. Same goes for pop & top. If I get an item using top, I can not be sure that the item that I pop is the same.

This can be solved using external locks - but that's not exactly what I call threadsafe design.

答:
Short answer is use synchronization for all access to shared data.

Locks allow synchronization and using locks is a threadsafe design.  It's not a design that does the locking for you or that prevents errors in your locking code, but it is a design that allows you to write correct multithreaded code.

Note that synchronization isn't just needed to sequence commands.  A query can return a corrupt value, or a command can corrupt your data structure.  In a multithreaded situation, all accesses to shared data should be synchronized.  Locking is a valid way to do this and Aybx's StackAndLock struct is a standard technique.  There are lower-level techniques, such as CAS, but even with locks, you have to write code that uses the locks correctly.  Higher level techniques involve using libraries (or better yet, languages) that implement things like STM, Actors, CSP, or other sorts of message passing.


问:
Is using nested try-catch blocks an anti-pattern?
Is this an antipattern? It is an acceptable practice?</p>

```<code>    try {
        //do something
    } catch (Exception e) {
        try {
            //do something in the same line, but being less ambitious
        } catch (Exception ex) {
            try {
                //Do the minimum acceptable
            } catch (Exception e1) {
                //More try catches?
            }
        }
    }
</code>```

答:
I've seen this pattern in network code, and it actually makes sense.  Here's the basic idea, in pseudocode:

```<code>try
   connect;
catch (ConnectionFailure)
   try
      sleep(500);
      connect;
   catch(ConnectionFailure)
      return CANT_CONNECT;
   end try;
end try;
</code>```

Basically it's a heuristic.  One failed attempt to connect could just be a network glitch, but if it happens twice, that probably means the machine you're trying to connect to really is unreachable.  There are probably other ways to implement this concept, but they'd most likely be even uglier than the nested tries.

ContentLicense: CC BY-SA 3.0

Body:
I've seen this pattern in network code, and it actually makes sense.  Here's the basic idea, in pseudocode:

try
   connect;
catch (ConnectionFailure)
   try
      sleep(500);
      connect;
   catch(ConnectionFailure)
      return CANT_CONNECT;
   end try;
end try;

Basically it's a heuristic.  One failed attempt to connect could just be a network glitch, but if it happens twice, that probably means the machine you're trying to connect to really is unreachable.  There are probably other ways to implement this concept, but they'd most likely be even uglier than the nested tries.


问:
How important is it for a programmer to have an online presence?
I've noticed more and more mentions (both in posts here and in actual job descriptions) of programmers' "portfolios" - typically their public profiles on sites such as this, GitHub, etc.

How important is this, and would companies (startups in particular) reject (or immediately discard without even interviewing) otherwise outstanding candidates who don't have an online presence?

Personally, I prefer to keep a very low profile online. My name here cannot identify me, and I have other handles for other sites. I have a very spartan (and completely private) Facebook page. I do code on my own, but the code lives in local repositories. In general, the less information online about me, the better.

I could see a designer needing some sort of online portfolio, but for a programmer, is this really a big negative when job-searching?

答:
Depends on what's meant by "online presence"

No presence

Github (because it is hard to associate a real person with a nick).

Bad presence

Facebook (reviewers uses Facebook for reject candidates)

Twitter (candidates are considered that likes to skip the work)

Online videogames (ditto)

Good presence

Personal website (professional and focused in computer and software)

Sites done by you (customers sites), i.e. "hey, i do this site"

Excellent presence

Get a Microsoft MVP.

Be a renowned beta tester of some popular technology (Java,PHP,C#..)


答:
Something else to bear in mind is the Fake Candidate.

Some unscrupulous recruitment agencies pose as candidates in order to get details of a job going. They'll create a great looking CV, farm it out on job boards and wait to get an interview. Once they have the details of the interview and the company that's hiring, they'll cancel the interview for a variety of reasons (already got an offer/changed mind/couldn't find the office/etc).

Having an online presence is a sure fire way to check if a candidate is real, so for me, it is essential that someone has either linkedin (with more than a couple of connections), twitter, a blog, facebook, stack overflow. If they have none of those, alarm bells start ringing and I'm immediately on my guard.

Not having a profile online won't stop me looking at the CV and interviewing, but it certainly doesn't help.

Title: How important is it for a programmer to have an online presence?

Body:
I've noticed more and more mentions (both in posts here and in actual job descriptions) of programmers' "portfolios" - typically their public profiles on sites such as this, GitHub, etc.

How important is this, and would companies (startups in particular) reject (or immediately discard without even interviewing) otherwise outstanding candidates who don't have an online presence?

Personally, I prefer to keep a very low profile online. My name here cannot identify me, and I have other handles for other sites. I have a very spartan (and completely private) Facebook page. I do code on my own, but the code lives in local repositories. In general, the less information online about me, the better.

I could see a designer needing some sort of online portfolio, but for a programmer, is this really a big negative when job-searching?


答:
would companies (startups in particular) reject (or immediately discard withouth even interviewing) otherwise outstanding candidates who don't have an online presence?

I would not want to work at a company, startup or otherwise, that rejected otherwise outstanding candidates on that basis. It seems like a foolish thing to do.

If I get a resume that says that the candidate is a StackOverflow user, or co-authored a paper, or worked on such-and-such a project, then I might check out their user page, or download the paper, or go to the web page for the project to learn a bit about it. These things help me streamline the interview process, so that I am not completely ignorant when I ask the question "So, tell me about the such-and-such project that you worked on."

I would not, however, do a general web search of a candidate's name in the hopes of learning more about them, for three reasons. First, names are not unique identifiers. Second, I'm unlikely to learn anything that will help me make a hiring decision. And third, and most importantly, I do not want to expose the company making the hiring decision to legal liability. If during my web search I accidentally learn that the candidate is married/unmarried/has children/is childless/is in the military/was once arrested/was once charged with a crime/was once sued/has a medical condition/etc, and then the candidate ends up not being hired, then the candidate potentially has an opportunity to bring an unfair hiring practices lawsuit.

In short: I wouldn't worry too much about it. It can help, but I don't think a lack of online presence will hurt you much.


答: It is definitely good to have an online presence, as most companies will look you up. It's probably good to have some rep on SO or Programmers, or be active in another social community, as that is just another way to showcase your skills. Be careful about having too much of a presence here, as companies most likely would not like to hire someone who is on SO 24/7, also, be careful what you ask, as that may show some flaws in your knowledge-base. Definitely be active on github as well, that will not only help your career chances, but will also make you a better programmer.</p>


问:
is jargon related to a frameWork (concept)
If this is not the right place to ask this question please inform where it would belong, to change it...

I have a doubt for the correct word or concept in english language [not my native], about the relationship of

language to framework

for example i work with

objective C, with the cocoa touch frame work || python with the django frame work

My comparison is between natural languages and formal languages,

So would be in a natural language

english  and the frame work a [computer, it]jargon?

Does this make sense?

Or what other concept would be the relationship between natural language - framework?

答:
Frameworks are like sets of idioms leading up to a full culture in your terms. For instance you might have American English or Australian English with distinct customs, habits, slangs and so forth. Jargons would be a part of that but not a full equivalent. Java for instance has been referred to as the Kingdom of Nouns with a very different culture than something like Lisp.

Some languages have cultures that are very open and free-wheeling, others are more constrained or "buttoned down". Indentation is very important in Python Culture but much less so in most other language cultures. Some are very open while others are more insular and isolationist. Some are older than others but still less complex or developed. Some tend toward simplicity over time with better tools and more efficient coding whilst others stay just as obtuse as the day they were first released. Trade languages like English or Indonesian tend to be much less complex than languages that are more isolated like Navajo or Finnish.

Which leads me to my point. Many people talk about the ideal programming language without any heed for its culture. Pick a language for its culture, not for the language itself.


问:
How can a large, Fortran-based number crunching codebase be modernized?
A friend in academia asked me for advice (I'm a C# business application developer).

He has a legacy codebase which he wrote in Fortran in the medical imaging field. It does a huge amount of number crunching using vectors. He uses a cluster (30ish cores) and has now gone towards a single workstation with 500ish GPUS in it.

However where to go next with the codebase so:

Other people can maintain it over next 10 year cycle

Get faster at tweaking the software

Can run on different infrastructures without recompiles

After some research from me (this is a super interesting area) some options are:

Use Python and CUDA from Nvidia

Rewrite in a functional language. For example, F# or Haskell

Go cloud based and use something like Hadoop and Java

Learn C

What has been your experience with this? What should my friend be looking at to modernize his codebase?

UPDATE: Thanks @Mark and everyone who has answered. The reasons my friend is asking this question is that it's a perfect time in the projects lifecycle to do a review.  Bringing research assistants up to speed in Fortran takes time (I like C#, and especially the tooling and can't imagine going back to older languages!!)

I liked the suggestion of keeping the pure number crunching in Fortran, but wrapping it in something newer. Perhaps Python as that seems to be getting a stronghold in academia as a general-purpose programming language that is fairly easy to pick up.

See Medical Imaging and a guy who has written a Fortran wrapper for CUDA, Can I legally publish my Fortran 90 wrappers to Nvidias' CUFFT library (from the CUDA SDK)?.

答: I've been told that in many contexts, MATLAB is replacing FORTRAN for scientific computing application. Not only is it modern and high-level, it's also pretty fast at what it does. A lot of developers working on medical imaging software use MATLAB already, so it has several libraries dedicated to medical imagining. This means you will find both tools and domain-expert support if you go with MATLAB.</p>


问:
Linux distro for software development support?
I've spent too much time on setup & maintain a development server, which contains following tools:

Common services like SSH, BIND, rsync, etc.

Subversion, Git.

Apache server, which runs CGit, Trac, Webmin, phpmyadmin, phppgadmin, etc.

Jetty, which runs Archiva and Hudson.

Bugzilla.

PostgresSQL server, MySQL server.

I've created a lot of Debian packages, like my-trac-utils, my-bugzilla-utils, my-bind9-utils, my-mysql-utils, etc. to make my life more convenient. However, I still feel I need a lot more utils. And I've spent a lot of time to maintain these packages, too.

I think there maybe many developers doing the same things. As tools like subversion, git, trac are so common today. It's not to hard to install and configure each of them, but it took a long time to install them all. And it's time consuming to maintain them. Like backup the data, plot the usage graph and generate web reports. (gitstat for example)

So, I'd like to hear if there exist any pre-configured distro for Development Server purpose, i.e., something like BackTrack for hackers?

答:
As a Noob who has played in a number of software development environments, it can be quite a headache configuring and maintaining new systems.  Especially as you are adopting and learning, seeing what works for you, and then moving on.

A developer base package with the basics set up:  IDE or IDE's, Web Server, DB Server of choice (or option to select during setup), text editor/s of choice, etc.

A really nice option is if something like Ubuntu One or some other cloud solution was available to save a user's configuration so that it could be restored, or ported over to multiple machines or virtual machines.

I have seen virtual machine distros for specific languages/solutions...Drupal's Quickstart comes to mind.

At any rate, I wanted to give the two cents of a noob developer.


问:
Is there a language that transpiles to C, with better syntax?
CoffeeScript is a language that transpiles to JavaScript, with a clean syntax, inspired by Ruby. Is there a similar language that transpiles to C, allowing for more readable code without compromising on performance? If nothing like that exists, is there a good reason for not creating it?</p>

答: Vala and Genie are both languages that compile into C.  haxe compiles into C++, but I'm not sure that's what you want.</p>

ContentLicense: CC BY-SA 4.0


答:
CoffeeScript compiles to JavaScript for a very simple reason, JavaScript is the de facto client side language and it would be unreasonable to expect browser vendors to natively support CoffeeScript, when all it offers is an alternative syntax.

In a very similar manner, the main point of high level language to C translators is immediate portability, as there's a C compiler for almost every platform and an abundance of C libraries. Vala, for example, was designed to:

be a compiler for the GObject,

build native executables (through the machine's C compiler),

automate reference counting, and

still be accessible to GNOME C programmers

GNOME is a traditionally C oriented project and GObject specifically is written in C, Vala wouldn't probably find much love amongst GNOME developers if it compiled to machine code, regardless of it's friendlier nature (and syntax). Not everyone seemed to like the syntax, to the point that another language, Genie, was build to improve upon it.

For a C++ example, Facebook developed HipHop, a PHP to C++ translator. They were trying to solve a very specific issue, CPU usage, without having to replace all their PHP code and re-train their engineers (or worst, replace them). This is a far more specific example, as Facebook scalability issues are, well, unique, and again having access to the intermediate C++ code can be useful, as PHP extensions are written in C and C++.

So a translator from a high level language to another is a good idea mostly when you access to the intermediate code is required. For CoffeeScript, the JavaScript code is necessary because of its wide browser adoption, and for Vala, Genie and HipHop because of the existing codebase. Obviously having access to the intermediate code means that you can further optimize it if need be.

But generally speaking, it wouldn't be such a good idea to build a language that translates to C, or any other language, if you didn't have any use of the resulting code. There are so many languages out there, if you can't cope with C, just pick an other. Coincidentally the first C++ compiler written by Bjarne Stroustrup, CFront, was a C with Classes to C translator, but that was mainly because as a new language, it was impossible to bootstrap C with Classes.

Title: Is there a language that transpiles to C, with better syntax?

Body: CoffeeScript is a language that transpiles to JavaScript, with a clean syntax, inspired by Ruby. Is there a similar language that transpiles to C, allowing for more readable code without compromising on performance? If nothing like that exists, is there a good reason for not creating it?</p>


问:
Checking preconditions or not
I've been wanting to find a solid answer to the question of whether or not to have runtime checks to validate input for the purposes of ensuring a client has stuck to their end of the agreement in design by contract. For example, consider a simple class constructor:

```<code>class Foo
{
public:
  Foo( BarHandle bar )
  {
    FooHandle handle = GetFooHandle( bar );
    if( handle == NULL ) {
      throw std::exception( "invalid FooHandle" );
    }
  }
};
</code>```

I would argue in this case that a user should not attempt to construct a Foo without a valid BarHandle. It doesn't seem right to verify that bar is valid inside of Foo's constructor. If I simply document that Foo's constructor requires a valid BarHandle, isn't that enough? Is this a proper way to enforce my precondition in design by contract?

So far, everything I've read has mixed opinions on this. It seems like 50% of people would say to verify that bar is valid, the other 50% would say that I shouldn't do it, for example consider a case where the user verifies their BarHandle is correct, but a second (and unnecessary) check is also being done inside of Foo's constructor.

答:
A quote I've heard on this is:

"Be conservative in what you do and liberal in what you accept."

Which boils down to following the contracts for arguments when you call functions, and checking all the inputs before acting when you write functions.

Ultimately it depends on the domain.  If you're doing an OS API, you'd better check every input, don't trust all incoming data as valid before you start acting on it.  If you're doing a library for others to use, go ahead, let the user screw themselves (OpenGL comes to mind first for some unknown reason).

EDIT: in the OO sense, there seems to be two approaches- one that says an object should never be malformed (all its invariants must be true) for the entire time that an object is accessable, and another approach that says you have a constructor which doesn't set all invariants, then you set a few more values and have a second initialization function that finishes init.

I kind of like the former better since it doesn't require magic knowledge or rely on current documentation to know what parts of initialization the constructor doesn't do.

OwnerDisplayName: Robert Dailey

Title: Checking preconditions or not


问:
On improving commit practices
I was thinking about ways to improving my commit practices.

Is there any co-relation between no. of source code lines and no. of commits?

In a recent project that I was involved in, I was going at 30 commits per 1000 lines.

One typical file from the project has these stats

```<code>language: JavaScript
total commits that include this file: 32

total lines: 1408
source lines: 1140
comment lines: 98

no. of function declarations: 28
other declarations: 8
</code>```

Another file has these...

```<code>Language: Python
total commits that include this file: 17

total lines: 933
source lines: 730
comment lines: 80

classes: 1
methods: 10
</code>```

I also think that no. of commits is more related to no. of features or no. of changes to the code and less to the no. of lines.

The general git community motto is make short commits and commit often.

So, do you really think about you commit strategy before you start the project. For that matter, is there anything like commit strategy? If so, what's yours?

答:
For posterity, commit all files related to a bug/feature in one revision.  This will help you immensely later when you need to know what files were touched to fix a bug.

It will make it easier to go back and see what you did to see 5 files checked in under bug #783, instead of trying to track down 5 commits (one for each file).  This can be alleviated if you have better source control/workflow integration which matches a check-in to a job/bug/feature/backlog item.  Still commit frequently, but put related files/features in the same check-in every time.

If you have your CI set up for "build every commit" then that will help you do this.

Title: On improving commit practices


答: Virtual Machines may be a good solution for you: once you've setup a baseline environment in the VM to your liking, just create a snapshot of it and you can then go back and reuse it again and again. Personally I've used the free VirtualBox software with good results running Ubuntu. This method is invaluable also for testing.</p>

Title: Linux distro for software development support?

Body:
I've spent too much time on setup & maintain a development server, which contains following tools:

Common services like SSH, BIND, rsync, etc.

Subversion, Git.

Apache server, which runs CGit, Trac, Webmin, phpmyadmin, phppgadmin, etc.

Jetty, which runs Archiva and Hudson.

Bugzilla.

PostgresSQL server, MySQL server.

I've created a lot of Debian packages, like my-trac-utils, my-bugzilla-utils, my-bind9-utils, my-mysql-utils, etc. to make my life more convenient. However, I still feel I need a lot more utils. And I've spent a lot of time to maintain these packages, too.

I think there maybe many developers doing the same things. As tools like subversion, git, trac are so common today. It's not to hard to install and configure each of them, but it took a long time to install them all. And it's time consuming to maintain them. Like backup the data, plot the usage graph and generate web reports. (gitstat for example)

So, I'd like to hear if there exist any pre-configured distro for Development Server purpose, i.e., something like BackTrack for hackers?


问:
Readability of || statements
On HTML5 Boilerplate they use this code for jQuery:

```<code><script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/libs/jquery-...
</code>```

What's more readable:

```<code>if (!window.jQuery) document.write(...);
</code>```

or

```<code>window.jQuery || document.write(...);
</code>```

答:
I prefer

```<code>if (!window.jQuery)
    document.write( -local jQuery- );
</code>```

because it makes it obvious that the document.write() depends on some condition. With the second option, you are abusing short-circuit evaluation, so most developers will have to think harder to understand what you are doing.

I generally don't expect to see code that creates output to be used with a boolean operator like that.

Title: Readability of || statements

Body:
I prefer

if (!window.jQuery)
    document.write( -local jQuery- );

because it makes it obvious that the document.write() depends on some condition. With the second option, you are abusing short-circuit evaluation, so most developers will have to think harder to understand what you are doing.

I generally don't expect to see code that creates output to be used with a boolean operator like that.


答:
I'm going to cover a few points Yannis Rizos didn't in his otherwise great answer.

Yes, many languages exist. C is a common target for compiler back-ends as it's incredibly portable and heavily optimized, although with LLVM there's not much point to it.

A few implementations I know that do this are:

C++ (At least in the early days)

GHC Haskell (Although the main code generator is C--)

Gambit/Chicken/Bigloo Scheme

ECL (Common Lisp)

Perl

Vala & Genie

as fast as original C programs

No, just because it uses C as an intermediate language doesn't mean you will reach its speed. The reason C is fast is because of the method of writing the code which is obviously different for other languages. It's just a portable assembly, nothing special.


问:
Do enterprises use TIOBE ratings for programming languages?
Does the  TIOBE rating of programming language play a prominent role in the selection of programming language in enterprise computing?</p>

答:
TIOBE is not a meaningful indicator of anything.  Most specifically the claim that "TIOBE lists languages that are most popular in the industry" is not a conclusion that can be drawn.

All that TIOBE tells you is which programming languages have the most documents on the web written about them.  It is a huge leap of logic to conclude that that is an indicator of how much the languages are used in the real world.


问:
Are project managers useful in Scrum?
There are three roles defined in Scrum: Team, Product Owner and Scrum Master. There is no project manager, instead the project manager job is spread across the three roles.

For instance:

The Scrum Master: Responsible for the process. Removes impediments.

The Product Owner: Manages and prioritizes the list of work to be done to maximize ROI. Represents all interested parties (customers, stakeholders).

The Team: Self manage its work by estimating and distributing it among themselves. Responsible for meeting their own commitments.

So in Scrum, there is no longer a single person responsible for project success. There is no command-and-control structure in place. That seems to baffle a lot of people, specifically those not used to agile methods, and of course, PM's.

I'm really interested in this and what your experiences are, as I think this is one of the things that can make or break a Scrum implementation.

Do you agree with Scrum that a project manager is not needed? Do you think such a role is still required? Why?

答:
I'd be fair and say that in my view what works for me is the Scrum master acting as the Project manager as well. Being a Scrum master isnt a full time job - once the team is mature the scrum master doesnt even need to attend the daily stand ups.

There are more and more vacancies that I see for a Project Manager/ Scrum Master where companies do not want to differentiate these roles - rather have the same person handle both roles - ie: an Agile project manager.

ContentLicense: CC BY-SA 2.5

Title: Are project managers useful in Scrum?


问:
Why do we need private variables?
Why do we need private variables in classes?

Every book on programming I've read says this is a private variable, this is how you define it but stops there.

The wording of these explanations always seemed to me like we really have a crisis of trust in our profession. The explanations always sounded like other programmers are out to mess up our code. Yet, there are many programming languages that do not have private variables.

What do private variables help prevent?

How do you decide if a particular property should be private or
not? If by default every field SHOULD be private then why are there
public data members in a class?

Under what circumstances should a variable be made public?

答:
All variables should be private unless they absolutely need to be public (which is almost never, you should use properties/getters and setters).

Variables largely provide the state of the object, and private variables prevent others from going in and changing the state of the object.

Title: Why do we need private variables?


答:
Private variables help prevent people from depending on certain parts of your code. For example, say you want to implement some data structure. You want users of your data structure to not care how you implemented it, but rather just use the implementation through your well defined interface. The reason is that if no one is depending on your implementation, you can change it whenever you want. For example, you can change the back-end implementation to improve performance. Any other developers who depended on your implementations will break, while the interface users will be fine. Having the flexibility to change implementations without effecting the class users is a huge benefit that using private variables (and more broadly, encapsulation) gives you.

Also, it's not really a "trust crisis". If you make a piece of data public, you cannot ensure that no one is depending on it. It's often very convenient to depend on some implementation-specific variable, instead of going through the public interface, especially in the heat of a deadline. Further, developers won't always realize that they are depending on something that might change.

So this sort of answers your other questions, I hope. All your implementation details should be private, and the public part should be a small, concise, well-defined interface for using your class.

Title: Why do we need private variables?

Body:
Why do we need private variables in classes?

Every book on programming I've read says this is a private variable, this is how you define it but stops there.

The wording of these explanations always seemed to me like we really have a crisis of trust in our profession. The explanations always sounded like other programmers are out to mess up our code. Yet, there are many programming languages that do not have private variables.

What do private variables help prevent?

How do you decide if a particular property should be private or
not? If by default every field SHOULD be private then why are there
public data members in a class?

Under what circumstances should a variable be made public?


答:
It's not so much a matter of trust, but rather one of managing complexity.

A public member can be accessed from outside the class, which for practical considerations means "potentially anywhere". If something goes wrong with a public field, the culprit can be anywhere, and so in order to track down the bug, you may have to look at quite a lot of code.

A private member, by contrast, can only be accessed from inside the same class, so if something goes wrong with that, there is usually only one source file to look at. If you have a million lines of code in your project, but your classes are kept small, this can reduce your bug tracking effort by a factor of 1000.

Another advantage is related to the concept of 'coupling'. A public member m of a class A that is used by another class B introduces a dependency: if you change m in A, you also have to check usages of m in B. Worse yet, nothing in class A tells you where m is being used, so again you have to search through the entire codebase; if it's a library you're writing, you even have to make sure code outside your project doesn't break because of your change. In practice, libraries tend to stick with their original method signatures as long as possible, no matter how painful, and then introduce a block of breaking changes with a major version update. With private members, by contrast, you can exclude dependencies right away - they can't be accessed from outside, so all dependencies are contained inside the class.

In this context, "other programmers" include your future and past selves. Chances are you know now that you shouldn't do this thing X with your variable Y, but you're bound to have forgotten three months down the road when a customer urgently needs you to implement some feature, and you wonder why doing X breaks Y in obscure ways.

So, as to when you should make things private: I'd say make everything private by default, and then expose only those parts that absolutely have to be public. The more you can make private, the better.

Title: Why do we need private variables?


问:
Biggest mistake you've ever made
Similar to the question I read on Server Fault, what is the biggest mistake you've ever made in an IT related position. Some examples from friends:

I needed to do some work on a production site so I decided to copy over the live database to the beta site. Pretty standard, but when I went to the beta site it was still pulling out-of-date info. OOPS! I had copied the beta database over to the live site! Thank god for backups.

And for me, I created a form for an event that was to be held during a specific time range. Participants would fill out the form for a chance to win, and we would send the event organizers a CSV from the database. I went into the database, and found ONLY 1 ENTRY, MINE. Upon investigating, it appears as though I forgot an auto increment key, and because of the server setup there was no way to recover the lost data.

I am aware this question is similar to ones on Stack Overflow but the ones I found seemed to receive generic answers instead of actual stories :)

What is the biggest coding error/mistake ever…

答:
Issuing a SQL UPDATE with a 'bad' WHERE Clause that matched everything.

Lesson Learned: Always issue a SELECT first to see what will be changed.

Title: Biggest mistake you've ever made


答:
The keyword here is Encapsulation. In OOP you want to use private variables in order to enforce proper encapsulation of your objects/classes.

While other programmers are not out to get you, they do interact with your code. If you do not make a variable private, they may well refer to it in their own code without wanting to do any harm at all. However, if you need to get back to your class and change something, you no longer know who uses which variable and where. The goal of encapsulation is to make the external interface of the class explicit so that you know only these (typically) methods could have been used by others.

Hence, private variables ensure that the corresponding variable remains in the defining class only. If you need to change it, the change is local to the class itself.

In traditional lanugages like C++ or Java, you usually make everything private and only accessible by corresponding getters and setters. No need to decide much really.

Sometimes, f.ex. in a C++ struct, you need a class only as a way to group several things together. For example, consider a Vector class which has an x and a y attribute only. In those cases, you may allow direct access to these attributes by declaring them public. In particular, you must not care if some code outside modifies an object of your class by directly writing new values into x or y.

As an additional point, notice that this matter is regarded slightly different in other languages. For example, languages that are strongly rooted in functional programming emphasize data immutability, i.e. data values cannot be changed at all. In such cases, you do not have to care what other programmers (or rather their code) do to your data. They simply cannot do anything that could affect your code, because all data is immutable.

In those languages, you therefore get something called uniform access principle, where one deliberatly does not distinguish methods like getters and setters, but provides direct access to the variable/function. So you may say that private declarations are quite a lot more popular in the object-oriented scenarios.

This also shows how broadening your knowledge to include other fields makes you view existing concepts in a whole new way.

Title: Why do we need private variables?


答:
The OOP concept has inheritance has one of its features (Java or C++). So if we going to inherit (meaning we are going to access the variables of the inherited class), there's the possibility of affecting those variables. So we have to decide whether the variables can be changed or not.

For this purpose only, we are using access modifiers in OOP. One of the modifiers is private which means it can be accessed only by that class. Any other class can't affect those variables.

As we know, protected means it can be accessed by the class that is going to inherit.

Why there's a modifier concept in OOP, is due to these reasons (any class can access other class variables using the OOP concept). If there's no modifier concept, it means it would have been difficult while inheriting classes or using  other OOP concepts.

Title: Why do we need private variables?


答:
Private variables ensure that later references outside the scope of an object or function won't inadvertently affect other variables. For large programming projects, this can help avoid a lot of interesting problems (that are usually not caught by compiler).

For example, prototypical languages like Javascript can allow users to plaster on variables as they see fit:

```<code>function SomeObject() {
    this.a = 2; //Public (well, actually protected) variable

    this.showA = function() {
        alert(this.a);
    }
}

//Some lines down...

var obj = new SomeObject();
obj.a = 3;
obj.showA(); //Will alert 3. Uh oh!
</code>```

If that variable was private, it wouldn't be able to be changed from the outside:

```<code>function SomeObject() {
    var a = 2; //Private variable

    this.showA = function() {
        alert(a);
    }
}

//Some lines down...

var obj = new SomeObject();
obj.a = 3;
obj.showA(); //Will alert 2
</code>```

That said, not all variables need to be private and excessive use of private variables can actually make code more cumbersome. Trivial fields that don't seriously impact an object don't need get() and set() methods.

Private variables also make it easier to expand code in the future, without relying on heavy documentation as to what the many public variables do. There's less of a threat of accidentally breaking functionality if less variables can be overwritten.

Public variables should be used when an object/function will be accessing other objects/functions, since as a rule, private variables can't do this. You may have anywhere from a few to quite a few public variables, and it's not a bad thing to use them if they're used correctly.

Title: Why do we need private variables?

Body:
Private variables ensure that later references outside the scope of an object or function won't inadvertently affect other variables. For large programming projects, this can help avoid a lot of interesting problems (that are usually not caught by compiler).

For example, prototypical languages like Javascript can allow users to plaster on variables as they see fit:

function SomeObject() {
    this.a = 2; //Public (well, actually protected) variable

    this.showA = function() {
        alert(this.a);
    }
}

//Some lines down...

var obj = new SomeObject();
obj.a = 3;
obj.showA(); //Will alert 3. Uh oh!

If that variable was private, it wouldn't be able to be changed from the outside:

function SomeObject() {
    var a = 2; //Private variable

    this.showA = function() {
        alert(a);
    }
}

//Some lines down...

var obj = new SomeObject();
obj.a = 3;
obj.showA(); //Will alert 2

That said, not all variables need to be private and excessive use of private variables can actually make code more cumbersome. Trivial fields that don't seriously impact an object don't need get() and set() methods.

Private variables also make it easier to expand code in the future, without relying on heavy documentation as to what the many public variables do. There's less of a threat of accidentally breaking functionality if less variables can be overwritten.

Public variables should be used when an object/function will be accessing other objects/functions, since as a rule, private variables can't do this. You may have anywhere from a few to quite a few public variables, and it's not a bad thing to use them if they're used correctly.


问:
Converting Fortran 77 code to C#
I'm trying to convert a Fortan77 program to C#. I have a subroutine with about 650 lines of code and horrific GOTO statements all over the place. I'm having a lot of trouble even starting to visualise the flow of the subroutine to figure out what it does.

Is there anybody with experience in this sort of thing who could give me any advice on how to get an overview of this subroutine? Are there some tools available to speed up or facilitate this type of conversion?

答:
The best way without doubt is to first rewrite/refactor the FORTRAN code into a better structured and logical way. This will force you to understand the original logic before attempting to port it to C#.

Here's how I would approach it:

Understand the existing code and if necessary refactor and even rewrite it in FORTRAN so you can test easily that it works.

Port the refactored code to C#

Don't waste your time with an automatic code converter which will just end up with the same mess of goto statements as the original FORTRAN since C# supports gotos and labels, just as C does.

Title: Converting Fortran 77 code to C#


问:
Catching an error?
Is catching an error with try ... catch a better practice than catching an error with proper analysis/error check? For instance, removing from an empty list: Does surround with a try catch clause considered as a more efficient way than testing if the list is empty beforehand?Or is it the same? Thanks.

P.S: If a similar question was previously asked on the forum please feel free to refer it.

答:
Much of what exception handling helps with is larger systems. In particular, code that detects an error may be several layers away (and written entirely separately from) the code that knows how to react to that error.

For a typical example, let's consider code for opening a file that's buried in some library. Just for simplicity, let's assume it's opening a file for logging. If the log can't be opened, that library code doesn't (and mostly shouldn't) know what to do. It should certainly detect the problem, but it has no idea whether (for example) you want to send out an email, display a MessageBox or NSAlert, etc. By throwing an exception, it let's the code that uses it to make the decision about how the problem is communicated to the user.

As for using an if statement and (for example) return value instead, we run into a similar problem. If we go this route, every layer from deep in the library where the file is opened, on up to the point that we display something to the user, has to cooperate in checking the error code and transmitting it up to a higher level if it something it can't handle itself. Unfortunately, in most cases, it's easier to do the wrong thing (make the call without even checking the return value) than the right one. Just for grins, let's say there are six layers of code between where the problem is detected and where the problem should be communicated to the user. Let's further assume there's a 90% of the programmer doing the right thing at each level. In that case, we get .96 = .53, or only a 53% chance that the error will actually be handled correctly. Even with (in my estimation) above average coding practices (I think 70-80% is probably closer to average) the chances of it being handled correctly are barely better than 50:50.

By contrast, with exceptions, code at intermediate levels doesn't have to do anything for the exception to be transmitted on up to where it can be handled (well, unless you're using Java checked exceptions, but if you do that, you deserve all the problems you get). Exceptions propagate by default instead of being "eaten" by default. We can simplify all the intermediate layers of code because the right thing happens by default.

Title: Catching an error?


问:
Duck checker in Python: does one exist?
Python uses duck-typing, rather than static type checking.  But many of the same concerns ultimately apply: does an object have the desired methods and attributes?  Do those attributes have valid, in-range values?

Whether you're writing constraints in code, or writing test cases, or validating user input, or just debugging, inevitably somewhere you'll need to verify that an object is still in a proper state--that it still "looks like a duck" and "quacks like a duck."

In statically typed languages you can simply declare "int x", and anytime you create or mutate x, it will always be a valid int.  It seems feasible to decorate a Python object to ensure that it is valid under certain constraints, and that every time that object is mutated it is still valid under those constraints.  Ideally there would be a simple declarative syntax to express "hasattr length and length is non-negative" (not in those words.  Not unlike Rails validators, but less human-language and more programming-language). You could think of this as ad-hoc interface/type system, or you could think of it as an ever-present object-level unit test.

Does such a library exist to declare and validate constraint/duck-checking on Python-objects?  Is this an unreasonable tool to want? :)

(Thanks!)

Contrived example:

```<code>rectangle = {'length': 5, 'width': 10}

# We live in a fictional universe where multiplication is super expensive.
# Therefore any time we multiply, we need to cache the results.

def area(rect):
    if 'area' in rect:
        return rect['area']
    rect['area'] = rect['length'] * rect['width']
    return rect['area']

print area(rectangle)
rectangle['length'] = 15
print area(rectangle) # compare expected vs. actual output!

# imagine the same thing with object attributes rather than dictionary keys.
</code>```

答:
It sounds like you want class invariants. That link (a deferred PEP) is the first Google search result for "class invariants in Python". The second is a link to an existing library: PyDBC. I haven't used it before, but it appears to do what you're after.</p>

```<code>import os
os.environ['PY_DBC'] = 'true'
import dbc

class Rect:
    __metaclass__ = dbc.DBC
    def __init__(self, length, width):
        self.length = length
        self.width = width
        self.area = length*width
    def __invar(self):
        if hasattr(self, "area"): # __invar gets called during __init__ too :(
            assert self.area == (self.length * self.width)

r = Rect(4, 5)
r.length = 123
</code>```

Title: Duck checker in Python: does one exist?

Body:
It sounds like you want class invariants. That link (a deferred PEP) is the first Google search result for "class invariants in Python". The second is a link to an existing library: PyDBC. I haven't used it before, but it appears to do what you're after.

import os
os.environ['PY_DBC'] = 'true'
import dbc

class Rect:
    __metaclass__ = dbc.DBC
    def __init__(self, length, width):
        self.length = length
        self.width = width
        self.area = length*width
    def __invar(self):
        if hasattr(self, "area"): # __invar gets called during __init__ too :(
            assert self.area == (self.length * self.width)

r = Rect(4, 5)
r.length = 123


答: TIOBE is an index of how much "gossip" there is about a language. If you or someplace you work bases technical choices on gossip then .......</p>

Title: Do enterprises use TIOBE ratings for programming languages?

Body: Does the  TIOBE rating of programming language play a prominent role in the selection of programming language in enterprise computing?</p>


答: The if-statement is a statement and as such does not have a result. The or-expression has a result which is immediately thrown away. Therefore, the if-statement is less complex and should be preferred.

Title: Readability of || statements

Body:
On HTML5 Boilerplate they use this code for jQuery:

```<code><script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/libs/jquery-...
</code>```

What's more readable:

```<code>if (!window.jQuery) document.write(...);
</code>```

or

```<code>window.jQuery || document.write(...);
</code>```


答: It is a shell idiom imported in JavaScript (perhaps through perl where it is also idiomatic). If you have a team used to it, it doesn't hinter the readability (some may even find it is an improvement), but I'm far from sure that it is known by people without a perl or shell background.</p>

Title: Readability of || statements


问:
Is it sane to use Document based NoSQL for store big data tables
In Document based NoSQL to create tables (AFAIK) I need:

Create such many as many rows in table documents with same ID field (that will be table id) and each time need to set the columns (for each document).

Then you first search documents by id (table) and next search what you need in the selection.

Please correct if I understand it wrong... And is it sane? How could that be fast?

答:
Perhaps. Only real way to tell is to setup some test cases and measure. My suspicion would be that how you are accessing the data in terms of pattern and usage matters most.

That said, thinking of document DBs in terms of tables is generally self-defeating. Think in terms of documents.


问:
Adding a forum to an existing site
I've got a site with ~500 registered members, 300 of which are what you'd call "active". Site data is kept in a MySQL dbase.

I'd like to add a myBB forum to the site, but this question applies to any forum really.

What I very much want to avoid is requiring my users to register both on the site and on the forum because my userbase is not technically literate and this would confuse a lot of them.

However the forum software has its own registration, login, cookie, and password management system which naturally are different from the site's mechanics.

I envision the following possibilities:

install myBB into the existing database and customize the login code to unify the two systems. This would probably mean changing the site's code to use the myBB system as that would likely be less painful to refactor and wouldn't hurt future myBB upgrade ability.

install myBB into separate database and write a bridging script of some sort that auto-registers existing site users with the forum if they elect to participate. Also check new forum registrations against the site's username list to prevent newcomers from taking existing names.

run them fully separate and force users to re-register (easiest for ME, but least desirable for them)

I would like a suggested course of action from those who have trod this path before.

答:
Most forum engines have custom authentication feature.

This is the case of PHPBB, for example.

If MyBB doesn't have any, you can still implement your own by changing the source code of the forum engine.

Title: Adding a forum to an existing site


问:
How important is knowing functionality before coding?
I work for a software development company where the development work has been off shored to us. The on shore team handle the support and talk directly to the clients. We never talk to the clients directly we just talk people from the on shore team, who talk directly to the clients.

When requirements come, the on shore team talk to the clients and make requirement documents and inform us. We make design documents after studying the requirements (we follow the traditional waterfall model).

But there is one problem in the whole process: nobody in the either off-shore or on-shore team understand the functionality of the application completely. We just know its a big complex web app handling complex order processing, catalog management, campaign management and other activities. We struggle with the design document as the requirements would not be clear. It then goes into a series of questions/answers back and forth between the on shore team, off shore team and clients. We would often be told to understand functionality from the code. But that's usually not feasible as the code base is huge and even understanding a simple menu item take days if not weeks. We tried telling the clients to give us knowledge transfer about the application but to no avail. Our manager would often tell us to start coding even if the design document is not complete or requirements are not clear. We would start by coding the part of the requirements that seems clear and wait for the rest.

This usually would delay the deployment by a month. In extreme cases we would have very low errors in the development and production but the clients would say that's not what they asked. That would start a blame game and a series of change requests and we would end up developing something very different.

My question is how would you do development work if you don't know the functionality of the app fully?

UPDATE

The development methodology it isn't really my choice and I am not my team's lead. It is the way it began. I tried to tell people about the advantages of agile but to no avail. Besides I don't think my team has the necessary mindset to work in an agile environment.

答:
That's not the way it works is it. One of the subjects of my current education is that of analysis, and the relationship with a customer. The emphasis has alwyas been on clearly defining the project. Imagine this:

You order a building company to build a house but you don't know how you want it to look. You just customise the first floor, so the team builds a house up to the first floor. Then you want the ground floor to be layed out differently. Oops...

Unless you're very sure you can (partially) make correct foundations for the application, I would just tell the client there is no other way it's going to be done than with clearly defined goals and functionalities. Because if you just take a stab at what it might be, you'll risk throwing a lot of money and time down the drain.


答:
You are using exactly the wrong development methodology for the problems you are facing.

By using Waterfall you are committing to:

Getting the right requirements up front - this obviously isn't
working

Coding the requirements away from the customer - you aren't
able effectively check issues with the customer given you have
committed to developing to the requirements

The first chance the customer gets to see their functionality is during testing - this is
far too late given the issues you are having

Consider using, if it is possible, a different way of managing the project. Agile Software Development has several features that are designed to tackle the issues you are facing.

A decent comparison of Waterfall vs Agile was written a while back, lets take a couple of quotes from it that highlight your problems:

Missing the Mark:

Once a stage is completed in the Waterfall method, there is no going
  back, since most software designed and implemented under the waterfall
  method is hard to change according to time and user needs.  The
  problem can only be fixed by going back and designing an entirely new
  system, a very costly and inefficient method.

Tied Down...

Agile methods allow for specification changes as per end-user’s
  requirements, spelling customer satisfaction.  As already mentioned,
  this is not possible when the waterfall method is employed, since any
  changes to be made means the project has to be started all over again.

...and Unable to Move

To synopsise the difference between the two, one can say the classic
  waterfall method stands for predictability, while Agile methodology
  spells adaptability.  Agile methods are good at reducing overheads,
  such as, rationale, justification, documentation and meetings, keeping
  them as low as is possible.  And, that is why Agile methods benefit
  small teams with constantly changing requirements, rather more than
  larger projects.

Where you are now is bad; you are not delivering to the customer's requirements, and, if you are in the blame part of software development, productivity is going to go out of the window, distrust is going to rise, and things are likely to get worse, not better.

The relationship with the customer is critical; here, it sounds like you aren't able to effectively collect their issues and adapt to their changing requirements in the way you are currently working; therefore you need to look at ways of changing that.

Title: How important is knowing functionality before coding?

Body:
I work for a software development company where the development work has been off shored to us. The on shore team handle the support and talk directly to the clients. We never talk to the clients directly we just talk people from the on shore team, who talk directly to the clients.

When requirements come, the on shore team talk to the clients and make requirement documents and inform us. We make design documents after studying the requirements (we follow the traditional waterfall model).

But there is one problem in the whole process: nobody in the either off-shore or on-shore team understand the functionality of the application completely. We just know its a big complex web app handling complex order processing, catalog management, campaign management and other activities. We struggle with the design document as the requirements would not be clear. It then goes into a series of questions/answers back and forth between the on shore team, off shore team and clients. We would often be told to understand functionality from the code. But that's usually not feasible as the code base is huge and even understanding a simple menu item take days if not weeks. We tried telling the clients to give us knowledge transfer about the application but to no avail. Our manager would often tell us to start coding even if the design document is not complete or requirements are not clear. We would start by coding the part of the requirements that seems clear and wait for the rest.

This usually would delay the deployment by a month. In extreme cases we would have very low errors in the development and production but the clients would say that's not what they asked. That would start a blame game and a series of change requests and we would end up developing something very different.

My question is how would you do development work if you don't know the functionality of the app fully?

UPDATE

The development methodology it isn't really my choice and I am not my team's lead. It is the way it began. I tried to tell people about the advantages of agile but to no avail. Besides I don't think my team has the necessary mindset to work in an agile environment.


答:
Accidentally deleted the database that stored all our customer info, order history and invoices going back to the start of the company (several years worth).

To be fair, my employer has to share some of the blame though. They had the only copy of that database stored on the Mac SE (yes this was a long time ago) that they gave me (a brand new employee, first job out of college) as my workstation and had never even considered making a backup.

So, thinking it was a copy of the DB I dragged it to the trash can. Because of the size of the file it deleted it immediately. We eventually got it back after paying an ungodly amount to a data restoration service, but for about 5 days we couldn't fulfill or bill any orders, and had no way to access information about any customer. It pretty much brought the (3 person company) to a standstill.

Title: Biggest mistake you've ever made

Body:
Similar to the question I read on Server Fault, what is the biggest mistake you've ever made in an IT related position. Some examples from friends:

I needed to do some work on a production site so I decided to copy over the live database to the beta site. Pretty standard, but when I went to the beta site it was still pulling out-of-date info. OOPS! I had copied the beta database over to the live site! Thank god for backups.

And for me, I created a form for an event that was to be held during a specific time range. Participants would fill out the form for a chance to win, and we would send the event organizers a CSV from the database. I went into the database, and found ONLY 1 ENTRY, MINE. Upon investigating, it appears as though I forgot an auto increment key, and because of the server setup there was no way to recover the lost data.

I am aware this question is similar to ones on Stack Overflow but the ones I found seemed to receive generic answers instead of actual stories :)

What is the biggest coding error/mistake ever…


问:
How to deal with social login
In my new web app I'm going to allow social login through Twitter (maybe), Facebook and Google and I'm in search of the best way to do it.

Actually I'm using Rails with Devise + Omniauth and this is the problem:

Should I ask the user to choose a password so that he can login without a social network?

Or maybe the user should be able to set a password if he want (for example when editing his account?)

The second way seems the best one but since Twitter doesn't provide user email and google doesn't provide an username I'll probably have to ask the user for username/email when he log in so in that case I may also ask for the password...

waht do you think?

答: Social Login integration is the best possible way to make your site social and to bring maximum possible traffic to your site.Most of the site owners integrate single sign on systems these days.I have also used one such system its LoginRadius,enabling social login via around 21 open id providers.</p>

Title: How to deal with social login


答:
"pre-configured distro for Development Server purpose, i.e., something like BackTrack for hackers?"

In My Opinion BackTrac is not for hackers but for kids with flaming eyes.

And I totally can't understand you. What means "I've spent too much time on setup & maintain a development server" ? How often do you do it? And why so often? Usually servers are different and made once, work long.

I suggest to use Gentoo or Funtoo (Exherbo is to unstable yet) for Dev Server but not calculate or Sabayon. The goal is really high customization level so you can be sure that you can easy make job done with all your needs. You don't need compile whole system every time, just make your own Stage 4 after enough configuration. I know a lot of stable servers based on such solutions.

As well I think it does not such matters which distribution you pick. Anywhere you can find same tools for automation so any RHEL or RHEL based distribution must be fine. You must tell us exact troubles with "setup & maintain" to get objective solutions.


问:
Why do we need to put private members in headers?
Private variables are a way to hide complexity and implementation details to the user of a class. This is a rather nice feature. But I do not understand why in c++ we need to put them in the header of a class. I see two annoying downsides to this:

It clutters the header from the user

It force recompilation of all client libraries whenever the internals are modified

Is there a conceptual reason behind this requirement? Is it only to ease the work off the compiler?

答:
There are most likely several reasons. While private members can't be accessed by most other classes, they can still be accessed by friend classes. So at least in this case they may be needed in the header, so the friend class can see they exist.

The recompilation of dependent files may depend on your include structure. Including the .h files in a .cpp file instead of another header can in some cases prevent long chains of recompilations.


答:
It is because the C++ compiler must know the actual size of the class in order to allocate the right amount of memory at instantiation. And the size includes all members, also private ones.

One way to avoid this is using the Pimpl idiom, explained by Herb Sutter in his Guru of the Week series #24 and #28.

Update

Indeed, this (or more generally, the header / source file distinction and #includes) is a major hurdle in C++, inherited from C. Back in the days C++ C was created, there was no experience with large scale software development yet, where this starts to cause real problems. The lessons learned since then were heeded by designers of newer languages, but C++ is bound by backward compatibility requirements, making it really hard to address such a fundamental issue in the language.

Title: Why do we need to put private members in headers?

Body:
Private variables are a way to hide complexity and implementation details to the user of a class. This is a rather nice feature. But I do not understand why in c++ we need to put them in the header of a class. I see two annoying downsides to this:

It clutters the header from the user

It force recompilation of all client libraries whenever the internals are modified

Is there a conceptual reason behind this requirement? Is it only to ease the work off the compiler?


答:
Project manager: a role within a traditional organization or enterprise.

Scrum master: a role within a software development team using the Scrum methodology.

Talking about project manager vs. scrum master is really talking about apples and oranges because the roles have different contexts. I've never heard of an organization that has "Scrum master" as an official title or pay grade. And project managers on any project, Scrum or otherwise, are often somewhat removed from day-to-day software development activities.

Exactly what a project manager does and how much his/her role overlaps with that of a Scrum master or project owner depends heavily on the size and nature of the project, but there are certainly tasks normally attributed to a project manager that aren't specifically part of the Scrum master or project owner roles. On a small project it may be possible to expand the duties of the Scrum master or project owner roles to include those tasks (hiring, firing, purchasing, contract management, interfacing with higher-level executives, etc.). On a larger project, software development is just one part of project management, and the duties of the project manager and those of the Scrum master are unlikely to overlap much at all.

A project manager should be the Scrum master's interface to the organization. The Scrum master should be the project manager's interface to the team.

So, are project managers useful in Scrum? No, project managers are useful outside Scrum. They're not part of the Scrum software development methodology, but they provide the resources that allow Scrum to work.

Title: Are project managers useful in Scrum?

Body:
There are three roles defined in Scrum: Team, Product Owner and Scrum Master. There is no project manager, instead the project manager job is spread across the three roles.

For instance:

The Scrum Master: Responsible for the process. Removes impediments.

The Product Owner: Manages and prioritizes the list of work to be done to maximize ROI. Represents all interested parties (customers, stakeholders).

The Team: Self manage its work by estimating and distributing it among themselves. Responsible for meeting their own commitments.

So in Scrum, there is no longer a single person responsible for project success. There is no command-and-control structure in place. That seems to baffle a lot of people, specifically those not used to agile methods, and of course, PM's.

I'm really interested in this and what your experiences are, as I think this is one of the things that can make or break a Scrum implementation.

Do you agree with Scrum that a project manager is not needed? Do you think such a role is still required? Why?


答:
The class definition needs to be sufficient for the compiler to produce an identical layout in memory wherever you've used an object of the class. For example, given something like:

```<code>class X {
    int a;
public:
    int b;
};
</code>```

The compiler will typically have a at offset 0, and b at offset 4. If the compiler saw this as just:

```<code>class X {
public:
    int b;
};
</code>```

It would "think" that b should be at offset 0 instead of offset 4. When code using that definition assigned to b, code using the first definition would see a get modified, and vice versa.

The usual way to minimize the effects of making changes to the private parts of the class is usually called the pimpl idiom (about which I'm sure Google can give a great deal of information).

Body:
The class definition needs to be sufficient for the compiler to produce an identical layout in memory wherever you've used an object of the class. For example, given something like:

class X {
    int a;
public:
    int b;
};

The compiler will typically have a at offset 0, and b at offset 4. If the compiler saw this as just:

class X {
public:
    int b;
};

It would "think" that b should be at offset 0 instead of offset 4. When code using that definition assigned to b, code using the first definition would see a get modified, and vice versa.

The usual way to minimize the effects of making changes to the private parts of the class is usually called the pimpl idiom (about which I'm sure Google can give a great deal of information).


问:
F# performance vs Erlang performance, is there proof the Erlang's VM is faster?
I've been putting time into learning functional programming and I've come to the part where I want to start writing a project instead of just dabbling in tutorials/examples.

While doing my research, I've found that Erlang seems to be a pretty powerful when it comes to writing concurrent software (which is my goal), but resources and tools for development aren't as mature as Microsoft development products.

F# can run on linux (Mono) so that requirement is met, but while looking around on the internet I cannot find any comparisons of F# vs Erlang.  Right now, I am leaning towards Erlang just because it seems to have the most press, but I am curious if there is really any performance difference between the two systems.

Since I am used to developing in .NET, I can probably get up to speed with F# a lot faster than Erlang, but I cannot find any resource to convince me that F# is just as scalable as Erlang.

I am most interested in simulation, which is going to be firing a lot of quickly processed messages to persistent nodes.

If I have not done a good job with what I am trying to ask, please ask for more verification.

答:
You should read this post by Joe Armstrong: http://erlang.org/pipermail/erlang-questions/2012-February/064277.html

The short of it is that Erlang was not designed to be fast! It is reasonably fast in many cases but that is secondary to issues like fault tolerance and stability.

The truth is both Erlang and F# are nice languages, and while I have only taken a quick look at F# I have written a book on Erlang: Building Web Applications With Erlang and I can say that it is a fun language to work in.

I would also point out that there seems to be a boom in functional language books to be published in the next 6-9 months. I know of at least 4 on Erlang (including mine), One on Haskell, as well as Titles on OCaml, Clojure and F#.


答:
Short version:

Knowing what to do ≠ knowing your customer.

Imagine this: you're a company related to real estate development. You ask your partner to build a large complex. The partner says that despite all the documents you gave him, he also need to talk directly to the people who would purchase the flats in this complex. Seriously?

Long version:

It's always nice to know how a specific application will be used, because it's fun to learn things, but it is not always possible on large projects.

Some domains are just too complex. If you're just a developer and you are working on multiple applications from multiple domains, you just can't always understand what the end user is doing, because it would require you to spend five years learning accounting, ten years in medical school, six years in law school, etc.

On the other hand, a software product made with no understanding of the specific domain will be at best, well, a bit unusable.

That's why functional and non functional requirements must be written by people who fully understand the domain. In general, requirements gathering involve at the same time:

Technicians (for example developers who would tell that a specific feature is impossible, that this other one can be much better if done this way, and this one will cost thousands of dollars while there is a much cheaper alternative),

People specialized in project management,

People specialized in the domain of the customer, who have the full understanding of this domain and the precise needs of the customer. Of course, this may be the customer itself.

One functional and non functional requirements are written and are precise enough, you don't need anything else as a person whose work is to translate those requirements into code.

As for your specific case, you describe the cause of the problem yourself:

We struggle with the design document as the requirements would not be clear.

It's not the lack of knowledge about the customer which causes all the trouble, it's the low quality of the requirements. In a correctly managed project, the functional and non functional requirements must be perfectly clear and unambiguous. If the requirements document is not clear or if it tells you that "the visual design of the product must be attractive" or other stupidities like that, it's because it was written by people who don't know how to write it.

Knowing that, you have to act differently:

If you know that the team which gathers the requirements is desperate, and your own team have skilled people for requirements gathering, explain the situation to your superior and tell that the other team must be replaced by somebody competent, for example the people from yours.

Otherwise (i.e. if they are not desperate), try to determine their internal cause of those low requirements and persuade them that doing their job correctly will only reduce the overall cost of the project. Showing the statistics about how badly written requirements influenced the project by increasing the cost (how much?) and the risk of not being ready for the deadline is a good idea here.

Probably the requirements document is just incomplete. I see this all the time: inexperienced project managers are just convinced that one-page document is enough, and don't understand why they would ever write three to four hundred pages instead of one. If it's the case in your company, show that spending more time on requirements would decrease the costs.


问:
How important is it for a programmer to have an online presence?
I've noticed more and more mentions (both in posts here and in actual job descriptions) of programmers' "portfolios" - typically their public profiles on sites such as this, GitHub, etc.

How important is this, and would companies (startups in particular) reject (or immediately discard without even interviewing) otherwise outstanding candidates who don't have an online presence?

Personally, I prefer to keep a very low profile online. My name here cannot identify me, and I have other handles for other sites. I have a very spartan (and completely private) Facebook page. I do code on my own, but the code lives in local repositories. In general, the less information online about me, the better.

I could see a designer needing some sort of online portfolio, but for a programmer, is this really a big negative when job-searching?

答:
Here's an article on branding by Inc magazine.

Coming from an internet marketing background, it is the equivalent of "street cred" as far as branding who you are is concerned. Of course no large employer who is worth their salt would hire without passing you through a skills assessment and background check. But 75% of all employers look on Facebook regarding a candidate to see if he/she would be a good "fit" more of an asset or liability. When I hire coders (I am a one man show), what puts them on top of the short list is when I see that they are not novices and have exhibited knowledge and experience in forums and on the web..they have a web presence.

If your qualifications matched someone else's, or if it was even a little bit below another's, but had many notable associations to credible industry websites, you would look better than the next guy with no "branding". Think of it like Coca-Cola, do you want to buy a drink everyone is after or one that no one has heard of...

Also, keep a Facebook profile for you (personal-non searchable or restricted) and one for your business profile (searchable with relevant topics relating to your industry experience and testimonials from people you helped if applicable). Linkedin is good too... a huge runner up in business branding following facebook.

Being marketing savvy is a plus, not only by getting your visibility to prospective employers/jobs but an easy way to contact and/or refer you from potential clients and previous clientele.


答:
You should not handle the normal program flow via Exceptions. Exceptions should only be handled if you want to do something with it.
If removing an element of an empty list should throw an exception, you should let it throw. If you want to return a new empty list from this method,  you should do that.

There is not 1 absolute answer on this matter, you should check it per use-case.

Of course, it never hurts to do some defensive programming and making sure users don't see too much exceptions in the use of the application.
In the example you mentioned, I would probably do a null-check and depending on the method, maybe throw a new ArgumentNullException.
A try-catch in this situation just feels a little 'dirty' in my opinion, but in a bigger scenario it might make more sense.

Back in the days I've learned throwing exceptions is an expensive operation (random link, check bottom of the page), so avoid them if possible.

Another thing which I don't really like about catching errors is, if you don't narrow them down enough, you could potentially catch an error which doesn't have anything to do with the piece of code you really want to check.
For example, if your application is 6-layers and you are calling some method like:

```<code>try
{
  otherlayer.Method1();
}
catch(IOException ioEx)
{
  //DoSomething
}
</code>```

It is possible this IOException catches something which you didn't expect at first, so you will probably handle it wrong. (could happen if someone decides to change the other layers without your knowledge).

In summary:
I would advice against using a lot of try...catch blocks in your code, only when they are really necessary and they are adding something usefull, or make sure your program flow will continue to operate.

Title: Catching an error?

Body:
Is catching an error with try ... catch a better practice than catching an error with proper analysis/error check? For instance, removing from an empty list: Does surround with a try catch clause considered as a more efficient way than testing if the list is empty beforehand?Or is it the same? Thanks.

P.S: If a similar question was previously asked on the forum please feel free to refer it.

Body:
You should not handle the normal program flow via Exceptions. Exceptions should only be handled if you want to do something with it.
If removing an element of an empty list should throw an exception, you should let it throw. If you want to return a new empty list from this method,  you should do that.

There is not 1 absolute answer on this matter, you should check it per use-case.

Of course, it never hurts to do some defensive programming and making sure users don't see too much exceptions in the use of the application.
In the example you mentioned, I would probably do a null-check and depending on the method, maybe throw a new ArgumentNullException.
A try-catch in this situation just feels a little 'dirty' in my opinion, but in a bigger scenario it might make more sense.

Back in the days I've learned throwing exceptions is an expensive operation (random link, check bottom of the page), so avoid them if possible.

Another thing which I don't really like about catching errors is, if you don't narrow them down enough, you could potentially catch an error which doesn't have anything to do with the piece of code you really want to check.
For example, if your application is 6-layers and you are calling some method like:

try
{
  otherlayer.Method1();
}
catch(IOException ioEx)
{
  //DoSomething
}

It is possible this IOException catches something which you didn't expect at first, so you will probably handle it wrong. (could happen if someone decides to change the other layers without your knowledge).

In summary:
I would advice against using a lot of try...catch blocks in your code, only when they are really necessary and they are adding something usefull, or make sure your program flow will continue to operate.


问:
Open Source sponsored feature development
I am considering to sponsor a development of some particular features in some Open Source tools. I would like the results of the work to be available publicly, and if possible, to be included in the main product line. The features are usually something which is of general use, but not very critical, and no one has currently a plan to develop it. For illustration, imagine I would like to use MinGW for Win32 development, but I miss a post mortem debugging option, I would like this feature to be implemented and I am willing to pay $1000 for it.

Is there some common way how to proceed, or is this wildly per-project dependent? Are there some general guidelines how to contact the product developers, or are there some common meeting places where smart open source people who might interested to participate in such sponsored development meet, which I should visit to advertise the sponsoring option?

Are there some specific ways how to talk about the job to be more attractive to people participating in open source (e.g. it might be more interesting for them to participate in a contest than just to take a payed job, which might have a bit of mundane feel)?

Or perhaps is this something which you think has little chance to succeed, because perhaps money has very little value for open source developers?

Any tips and experiences from someone who has some experience of open source sponsorhip from any side (sponsor or the developer) are welcome.

答:
is this wildly per-project dependent?

Yes, it is. You will need to contact the project maintainers about his and see how they would like you to go about things.


答:
One of the main problems with the traditional project manager role is that it separates authority from responsibility. The PM has complete authority over the project organization - (s)he decides what tasks need to be done, by whom, in what order, etc. But (s)he's not held accountable for the completion of these tasks or the quality of software that is produced. The team members are the only ones responsible. This creates a huge communication overhead, as to put back authority and decision in sync with operational work, team members constantly have to report everything that is done to the PM in addition to the rest of the team. It also creates a feeling of dispossession, powerlessness and a loss of purpose with the team members, which is a large source of frustration and discouragement.

Agile somehow puts these notions back together - the authority over work organization is held by the team as a whole (through release, iteration and daily meetings) so that everyone feels like they can have a say in the matter, in return of which each of the team members has to take responsibility for producing quality software that works and make a strong commitment towards that goal. You could thus theoretically get rid of the project manager.

Once you've said that, there are still duties traditionally assigned to the PM which still need to be taken care of though - lunivore described them quite accurately.

As this article suggests, in truly multi-skilled teams, one thing you could do is discard the project manager role, redistribute its duties among the team members and have former PMs become regular team members.

Title: Are project managers useful in Scrum?


答: Use the right tool to do the right thing. Documents databases should be used to store documents, not tables.  If the documents have the same columns a relational database is more appropriate to store it or maybe a graph database. </p>

Title: Is it sane to use Document based NoSQL for store big data tables

Body:
In Document based NoSQL to create tables (AFAIK) I need:

Create such many as many rows in table documents with same ID field (that will be table id) and each time need to set the columns (for each document).

Then you first search documents by id (table) and next search what you need in the selection.

Please correct if I understand it wrong... And is it sane? How could that be fast?


问:
Compatibility Test and other testing method to use while building software
I will be adding a feature to the software and have to update or modify some of public API of the present open source software.

What are steps which could be taken to ensure the compatibility of  the software.
what are the testing methods which are used in open source world to test the newly added features??
Open Source program is: Xapian

答:
If there are existing tests (e.g. unit tests, integration tests) for this open source software, use them to verify you have not broken anything (i.e. no regressions). As well, add new tests that will test your new feature.

If there are no existing tests, consider adding some for your new feature as well as slowly adding some for the existing features. This will help to make the open source software better in general, even if no new features are added.


问:
What are some characteristics of Python that makes it unique as its own language?
What are some characteristics of Python that makes it unique as its own language? I'm looking for any sort of characteristics ranging from good to bad, useful to hindrance, syntax to real-world usage, but non-obscure observations would be the most useful for the average developer.

I'm a newb here, so intuitive things may need to be explained.....

答:
The thing is, Python is among very few languages with extremely low syntactic overhead giving it tremendous expressive powers: list/set/dict comprehensions, yield, decorators, eval, meta class programming, introspection, the optimized built-in data structures (lists, dicts, sets), all of those things conspire in a very nice way to give you (the developer) the power to express your thoughts in concise and elegant code almost as fast as you can think.
I can't really think of any other languages with this killer set of features combined together.</p>


答:
Generator Expressions

input() Let me explain, I have not seen a language (so far), where you can assign a value to a statement that prints something, it is like ruby's print/gets, but with a value assigned to the print, instead of: print "Foo" bar = gets

yield

Many types of datasets: ordereddict, namedtuple, array, list, tuple, dictionary

Body:
What are some characteristics of Python that makes it unique as its own language? I'm looking for any sort of characteristics ranging from good to bad, useful to hindrance, syntax to real-world usage, but non-obscure observations would be the most useful for the average developer.

I'm a newb here, so intuitive things may need to be explained.....


问:
How to implement Cache in web apps?
This is really two questions. Im doing a project for the university for storing baseball players statitics, but from baseball data I have to calculate the score by year for the player who is beign displayed. The background is, lets say 10, 000 users hit the player "Alex Rodriguez", the application have to calculate 10, 000 the A-Rod stats by years intead of just read it from some where is temporal saved. Here I go:

What is the best method for caching this type of data? Do I have to used the same database, and some temporal values on the same database, or create a Web Service for that?

What reading about web caching so you recommend?

答:
You could keep a cache in memory, if it's small enough.  Otherwise, you can store your cache in the same data base you use to keep the primary data.

You don't have to create a web service, unless you're using web services to access the primary data in your data base.

You can start reading about data base caching here.

Title: How to implement Cache in web apps?


答:
There are lots of options depending on the technologies you are using.

My first thought is that you could pre-calculate all the stats up front and store them in the database. If the database is under your control, then you can easily add to the database. If it is 3rd party, maybe you should create your own database which uses the 3rd party one as source data.

If the system will be updated over time, you could have a nightly process that recalculated all the stats each night. This way, the data will always be uptodate.

With this, your database essentially replaces the need for in application cache.

I'm not sure if you need a web service for this. That's an architectural decision that has little to do with your question about caching data somewhere in your app (at least to me it doesn't).

Title: How to implement Cache in web apps?

Body:
This is really two questions. Im doing a project for the university for storing baseball players statitics, but from baseball data I have to calculate the score by year for the player who is beign displayed. The background is, lets say 10, 000 users hit the player "Alex Rodriguez", the application have to calculate 10, 000 the A-Rod stats by years intead of just read it from some where is temporal saved. Here I go:

What is the best method for caching this type of data? Do I have to used the same database, and some temporal values on the same database, or create a Web Service for that?

What reading about web caching so you recommend?


问:
What should happen at the start of a software project startup?

A quick introduction

My college semesters include a 8 week project working for an actual company with a software need in order to get some much needed practical experience. I have just started such a project with 5 other students. We're required to spend roughly 40 hours a week per student on this project. We're working with SCRUM as the software development method, this was assigned by our teachers.

The question

Day one of the project just ended which has created some questions for me as to how to start a project in the 'real world'. Our first day included working on a project planning document (not sure what the English term is), creating a appointment with the company for an introduction and the opportunity to start specifying the requirements and setting up some standards for the behavior within the group.

However these items didn't take that long to finish. We've made some concrete plans for tomorrow and the day after we'll meet the company. This still leaves several hours of 'work-time' unspent. Is it usual not being able to fill every hour of a day for work at the start of a project or are we simply too inexperienced to see what work needs to be done at this stage of a project, or are we, perhaps, going through the above list too fast?

How does this work in the 'real world'? Do you spend your time wondering 'what should I do now', or do you have a clear view of what you're supposed to do at that moment?

答:
For the specific project there's not much you can do until you find out what the client wants. However, there are some things you can do now so your team is ready to go.

How are you going to handle version control?

Will you do code reviews?

When will the daily standup meetings be held? What are the rules?

What role does everyone play?

How are builds handled?

Where to put documents so everyone can have access?

Have the group work on a very simple project to test all of this out either in a required language or pick one familiar to the team.


答:
Set up your version control system and document its configuration

Set up an automated build system

Set up automated Unit tests that integrate with the build system

Set up a web server to serve up static content like automatically generated docs and reports from your Continuous Integration System.

Set up a Continuous Integration server to run your builds and tests and publish the results

Set up a Wiki to use for "live" documentation of the project and other things.

Determine what you are going to use to manage your backlog of features and tasks

Determine who is product owner and responsible for tracking all the work

Determine who is going to make sure the team stays focused on the committed work

Determine how often builds will be released to your product owner, and stick to this schedule.

Title: What should happen at the start of a software project startup?

Body:
A quick introduction

My college semesters include a 8 week project working for an actual company with a software need in order to get some much needed practical experience. I have just started such a project with 5 other students. We're required to spend roughly 40 hours a week per student on this project. We're working with SCRUM as the software development method, this was assigned by our teachers.

The question

Day one of the project just ended which has created some questions for me as to how to start a project in the 'real world'. Our first day included working on a project planning document (not sure what the English term is), creating a appointment with the company for an introduction and the opportunity to start specifying the requirements and setting up some standards for the behavior within the group.

However these items didn't take that long to finish. We've made some concrete plans for tomorrow and the day after we'll meet the company. This still leaves several hours of 'work-time' unspent. Is it usual not being able to fill every hour of a day for work at the start of a project or are we simply too inexperienced to see what work needs to be done at this stage of a project, or are we, perhaps, going through the above list too fast?

How does this work in the 'real world'? Do you spend your time wondering 'what should I do now', or do you have a clear view of what you're supposed to do at that moment?


问:
Using an actor model versus a producer-consumer model?
I'm doing some early-stage research towards architecting a new software application. Concurrency and multithreading will likely play a significant part, so I've been reading up on the various topics.

The producer-consumer model, at least how it is expressed in Java, has some surface similarities but appears to be deeply dissimilar to the actor model in use with languages such as Erlang and Scala. I'm having trouble finding any good comparative data, or specific reasons to use or avoid the one or the other.

Is the actor model even possible with Java or C#, or do you have do use one of the languages built for the purpose? Is there a third way?

答:
If you would like to try out the actor model in Java (and Scala) you might want
to take a look at Akka. Libraries are also being developed for C++ (see
the libraries listed on this wikipedia page).

So, it seems that the actor model need not be built-in in the programming
language.


问:
Why do we need private variables?
Why do we need private variables in classes?

Every book on programming I've read says this is a private variable, this is how you define it but stops there.

The wording of these explanations always seemed to me like we really have a crisis of trust in our profession. The explanations always sounded like other programmers are out to mess up our code. Yet, there are many programming languages that do not have private variables.

What do private variables help prevent?

How do you decide if a particular property should be private or
not? If by default every field SHOULD be private then why are there
public data members in a class?

Under what circumstances should a variable be made public?

答:
See this post of mine to a related question on SO.

The short of it is that variable scope allows you to show consumers of your code what they should and shouldn't be messing with. A private variable may hold data that has been "vetted" by using a property setter or a processing method to ensure the entire object is in consistent state. Changing the private variable's value directly may cause the object to become inconsistent. By making it private, someone has to work really hard, and have really high runtime permissions, in order to change it.

Proper member scoping is thus key in self-documenting code.

Title: Why do we need private variables?


问:
Submitting Java Code with Junit unit test
I have mostly worked on simple java programs and compiled and run them with Eclipse on Windows. So, I have no experience of using command prompt for compiling Java projects and do not have much info about what actually happens beneath the play button in Eclipse.

Now I have to submit a Java application which will have basic operation on XML. My project also will have (JUnit) Unit Test.

My question is related to submission of this Project.

Which files would be necessary to submit the code. So, it executes
properly?

Does choosing Eclipse as an IDE or junit as a unit testing framweork
produces any dependenices i.e the executor of the program should
have eclipse/libraries to execute the program on his machine?

答:
You can easily use the Eclipse "file->export->java->jar" function to create a compiled package of your code. You can select various options depending on your wishes, e.g. exporting the source with it. If you select "runnable jar file", you can easily select a run configuration which Eclipse will "embed" into the .jar file.

Using an IDE should not add dependencies to your code. Using a unit testing framework does of course add the testing framework as a dependency for running the tests (but does not add them as a dependency for your main code).

You might also want to look at Maven, which can automate dependency management and the creation of output (Maven calls them target) files.