问:
Git: rebasing on top of a refactor that affects the target rebase branch
Let's say I have a feature (topic) branch that I keep rebased on top of my development branch. During the course of the project (before merging in my feature branch), I decide that I need to make a large refactor to my project (for example, after updating a 3rd part module).

So I do this large refactoring on my development branch. Now I want to rebase my feature branch so I can take advantages of my refactoring.

The problem

There are still things in my feature branch that need refactored to match the changes I made in my development branch.

Should I:

Go back through my feature branch's history trying to edit commits (with rebase -i) to make the branch look as though all of the work had been done after the refactoring.

The advantage to this is that it keeps the history clean.

The disadvantage is that this can take a whole lot of time if the changes made in the development branch cause a lot of changes to need to be made in the feature branch.

Fix the things that need to be refactored in my feature branch and make a commit for this.

The advantage here is that it will be much easier to identify and fix things that need to be fixed

The disadvantage is that now the tree will have two commits in it for the refactor. One for the refactor done for the entire development branch, and a smaller commit done for the feature branch, once merged in it will look a little funny.

Which strategy should I go with?

An Example

Lets say on the development branch I rename functionA to functionB.

Now In my feature branch I've never modified the file containing functionA (now functionB in development). So when I run rebase development while on my feature branch it rebases cleanly.

The problem is if I've ever made a call to functionA in my feature branch, it's going to fail now since it was renamed functionB.

Now, should I just do a find and replace for functionA -> functionB and make one commit on the feature branch (option 2). Or should I go back through my history, finding where I introduced the call to functionA and rewrite the commit so it is introduced as calling functionB (option 1)?

答:
Neither

Option 1 sounds like a lot of unnecessary work. Why do you wan't to hide the fact that this code was written before the refactoring of dev?

Another disadvantage with option 2: After the rebase you will have a lot of possibly non-working commits before the 2nd refactoring commit. This will give you problems when bisecting since those commits might be untestable.

Option 3: Merge dev branch into feature branch.

Pro: you will get the rectoring from dev and may refactor the rest of the feature branch in the merge to get a working project.

Pro: No commit gets untested. (assuming the commits already made is tested).

Con: You will not be able to continue rebasing onto dev branch.


问:
Branches/decision count in an example
Having read SO, just found this question:

```<code>if (x > y)
     print (x)
else if (x < y)
     print (y)
else
     print (x,y)
</code>```

How many branches and decisions are there? It mentiones there should be 3 decision and 5 branches, yet I cannot see how. For me I can only imagine 4 branches (2 Ifs with two possible results).

Original question here

答:
I think it depends a bit on how you would define decision and branch. From a logical perspective I would say that there are 3 branches, because of the 3 calls to print. Since two ifs are used, there are two decisions made.

On a machine level this might look different, because the compiler will generate code that might involve more branches and decisions. For example the compiler could generate code for the test x==y.

ContentLicense: CC BY-SA 3.0

Title: Branches/decision count in an example


问:
How to name a variable when the word is both a noun and a verb
I have run into a corner-case problem with the general guidance of:

nouns for variables

verbs for functions

Specifically, I have a case where the word is ambiguous - it can be either a verb or a noun.  And in some cases when we're discussing the application, it will be used both ways in the same sentence.

My intent is to make sure the program will remain readable to future developers as well as myself when I return to sections of code months later.

One of the examples is with a battery.  A battery has a charge and you can also charge() a battery.

I think that having both Battery.Charge and Battery.Charge(value) will be confusing to future developers.

My current solution is to simply pick a different word for one or both of those cases (the variable and the function).  My problem with that approach is the Battery object's variable and function for charge won't align with design discussions involving the Battery.

My question is if there is another / better way to handle this conflict in naming convention?

Some additional reading on the subject.  None really addressed the particular of my question.

Meaningful concise method naming guidelines

Naming conventions for variables

The selected answer from https://softwareengineering.stackexchange.com/questions/14169/what-naming-guidelines-do-you-follow

答:
Prepend them with verbs that will make them a verb or a noun.</p>

```<code>Battery.doCharge()

Battery.getCharge()
</code>```

Body:
Prepend them with verbs that will make them a verb or a noun.

Battery.doCharge()

Battery.getCharge()


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

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

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

答:
Maya scripting is done in Python. Therefore, any animation, special effects or or videogame studio that uses Maya extensively (and that's most of them) will also likely use Python elsewhere in its "pipeline", which is industry-speak for the in-house information system that manages the production.

A Django or Flask web service that gets consumed by Maya plugins is not an uncommon architecture at these shops.

Title: How is Python used in the real world?


问:
In MVC, can/should basic data retrieval from the Model be done in the View?
Given the concept of 'skinny controllers, fat models' and the general acceptance that Views can directly call on Models when requiring data for output, should one consider handling the 'get and display' parts of requests within the Views and not the Controller? For example (attempted to keep code fairly generic):

Controller

```<code><?php

class Invoice extends Base_Controller {

    /**
     * Get all the invoices for this month
     */

    public function current_month() {

        // as there's no user input let's keep the controller very skinny,
        // DON'T get data from the Model here, just load the view

        $this->load->view('invoice/current_month');

    }

}
</code>```

View

```<code><?php

// directly retrieve current month invoices here

$invoices = $this->invoice_model->get_current_month();

// get some other display-only data, e.g. a list of users for a separate list somewhere on the page

$users = $this->user_model->get_users();

?>

<h1>This month's invoices</h1>

<ul>
<?php foreach ($invoices as $invoice) { ?>

<li><?php echo $invoice['ref']; ?></li>

<?php } ?>
</ul>
</code>```

To me, this makes at least some sense in the cases where a request is essentially just a View. Why should the Controller have to collect and pass on the data to the View when it can just retrieve it itself? This leaves the Controller open for purely 'Application level' processing (e.g. handling GET/POST requests, managing access rights and permissions etc.) as well as keeping the Models reusable and all the other good stuff.

If this example was extended to allow a user to filter the results, the Controller would just handle the POST from the form and pass the filters to the View, which would then request the data again, this time with the filters.

Is this a valid approach to developing an MVC application? Or am I overlooking an important part of the role a Controller should play?

答:
Another thing to consider is that you appear to have autoloaded the user_model and invoice_model to allow the the view to access them. For this to work reliably, you probably autoload all of your models (because $this->load->model() just looks wrong in a view, doesn't it...)

Doing this unnecessarily bloats your stack by loading a bunch of stuff that may never get used. Part of the reason for having multiple models is to allow you to encapsulate related logic and load only what you need for a given task.

This looks like CodeIgniter. I've done a lot of CI development and I can share from personal experience that you really don't want to autoload more than you really have to. Try adding $this->output->enable_profiler(TRUE); in a controller's constructor and fiddle with autoloads (including helpers like database): you'll likely see a significant change in load and execution times, but especially in memory allocation.


问:
Sockets intricacies in TCP and UDP
I am quite familiar with TCP and UDP. I understand the process by which TCP establishes connections and other theoretical facts about TCP but when reading up about TCP hole punching for NAT Transversal, I have become stumped by how connect(), accept() and listen() is done in TCP. Is it a single or multiple sockets that are used for all this in TCP and is is this done the same way in UDP</p>

答:
Your question is about sockets, but I think you might be confused about what a NAT does.

For an incoming connection from a WAN computer to a NATted computer to work, the NAT has to be told, via a configuration mechanism, to forward packets from the WAN destined for a particular port to a port on one of the NATted computers.

For a connection originated on either side of the NAT, the NAT stores the packet's 5-tuple (source IP address, source port, protocol, destination IP address, destination port) and uses this information to determine where to forward packets

For packets destined for the WAN, the NAT rewrites the source address so that all responses are sent to it.

Because the NAT is acting like a transparent "man in the middle", all the socket functions work completely normally.

Title: Sockets intricacies in TCP and UDP


问:
How can I update a large legacy codebase to meet specific quality standards?
There is a lot of information about tools and techniques for improving legacy codebases, but I haven't come across any successful real world case studies.  Most advice is on the micro level, and while helpful, doesn't convince many people because of a lack of evidence it can help at the macro level.

I am looking specifically for incremental improvements that have been proven to be a success in the real world when updating a large legacy codebase to meet today's quality standards, and not a complete rewrite.

Before:

Large: greater than 1MLOC

Legacy: no automated tests

Poor quality: high complexity, high coupling, high escaped defects

After

Automated tests

Easier updates/maintenance

High quality: lowered complexity, decoupled code, few escaped defects

What kind of incremental steps have been proven in the real world to update a large legacy codebase successfully to meet above quality standards, without going through a total rewrite?

If possible, include an example company or case study of a large legacy project that has gone through a "successful" quality improvement process in your answer to back it up.

答:
I've actually been through a fairly significant refactoring three times in my career.  Code has a tendency to decay, so if your code base is around long enough, a large refactor is pretty much unavoidable.  All my examples were on private code bases, which might explain why public examples are hard to find.

The first time was an application which, believe it or not, had a fundamental architecture that made it only work with dot matrix printers.  When my company could no longer find a vendor to supply the ribbons, they assigned me to make it work with a laser printer.

The second time was a migration of several hundred automated test scripts from C to Java, partly because we needed better cross platform capability, and partly because it was getting difficult to hire new C developers.

The third time I am still in the middle of, which is modularizing a huge monolithic application to allow unit testing by reducing coupling, and for cross platform purposes.

I compare the effort to climbing a mountain.  You have this huge goal ahead of you, but you don't tackle it at the macro level.  You take it one handhold at a time, always having a close fallback position, never disconnecting the previous safety until the next one is in place.  You start out just making small incremental improvements, and after a while you turn around and there's suddenly this beautiful view.

Let's say you have 60,000 files of highly coupled code, for example.  You want to start putting it under unit test, but the dependencies make it impossible.  How do you fix it?  You decouple one file.  You add automated tests.  You get back to stable ground before moving on.  Repeat 59,999 times.

If that sounds simple, that's because it is simple.  It's not easy, but it's simple.  It's hard to notice any progress at first.  We are two years into what seemed an impossible refactor, and likely have years ahead of us until we're finished, but looking back we suddenly realize how much better the code has gotten already, and we have been able to continue to deliver new functionality to our customers in the mean time.

The other two times worked the same way.  You find the smallest safe step you can take, and you take it, always keeping the application in a working state.  You only worry about the big picture to make sure you're heading in the right direction.  All your actions are small, steady, and incremental.


问:
Delphi Build Server - Do I need to check in .dres files?
We're using final builder to build a Delphi project and the person managing the build server noticed that projects with no .dres files were not building because they're not in SVN and because they're not in SVN they're not on the build machine.

So he put them in SVN.

I'm a little skeptical about the necessity of putting them in SVN though.  For one thing, if they're needed by the build server then they're not being built by the build server and we're not really creating the build in one step since we're using pre-compiled code (I might as well just check in my DCU's, tear off my beard and return my Delphi-4-Ever allegiance card).

I see in Delphi after compiling a project:

  c:\program files (x86)\embarcadero\rad studio\9.0\bin\cgrc.exe -c65001 "PROJResource.rc" -foPROJ.dres

Those files are produced by brcc32 compiling an RC file.  I'd say, well just add that line to the build server, but PROJResource.rc isn't in SVN either!

PROJResource.rc is automatically generated by Delphi from adding things using the project manager and I never noticed it so I never added it to SVN and no one else complained (I think the .dproj file is behind this).  The RC files that I wrote myself are in SVN though.

So... what's the best way to fix this, just check in the PROJResource.rc or is there something else we can be doing to streamline this?

答:
If you are using FinalBuilder 7.0.0.1864 or later, on the Delphi Action Properties dialog, switch to the Resource Compiler page, and turn on "Compile Project Resources (D2009 or later)" - this will recompile the dres file during the build and you should not need to add it to svn (you do need the dproj though). </p>

<p>(I tried to post a screenshot but aparently I might be a spammer and I'm not allowed to do that yet!).</p>

Body:
If you are using FinalBuilder 7.0.0.1864 or later, on the Delphi Action Properties dialog, switch to the Resource Compiler page, and turn on "Compile Project Resources (D2009 or later)" - this will recompile the dres file during the build and you should not need to add it to svn (you do need the dproj though).

(I tried to post a screenshot but aparently I might be a spammer and I'm not allowed to do that yet!).


问:
How safe are hidden AJAX requests that fake performance?

What is a hidden AJAX request?

I've noticed an increase in the usage of hidden AJAX requests designed to make a user's action appear to happen immediately. I'll refer to this type of AJAX request as non-blocking. It's an AJAX request made without the user being aware it's happening, it's performed in the background and it's operation is silent (there is no verbose to indicate a successful completion of the AJAX call). The goal is to make the operation appear that it has happen immediately when it really has not finished.

Here are examples of non-blocking AJAX request;

User clicks delete on a collection of emails. The items disappear immediately from their inbox, and they can continue with other operations. Meanwhile, an AJAX request is processing the deletion of the items in the background.

User fills out a form for new records. Clicks save. The new item appears in the list immediately. The user can continue to add new records.

To clarify, here are examples of blocking AJAX request;

User clicks delete on a collection of emails. An hourglass cursor appears. The AJAX request is made, and when it responds the hourglass cursor is turned off. The user has to wait a second for the operation to complete.

User fills out a form for new records. Clicks save. The form turns grey with an AJAX loader animating. A message is shown "Your data was saved", and the new record appears in the list.

The difference between the two above scenarios is that a non-blocking AJAX setup does not provide feedback of an operating performing, and a blocking AJAX setup does.

The Risk Of Hidden AJAX Requests

The biggest risk of this style of AJAX request is that the web application could be in a completely different state when the AJAX request fails.

For example, a non-blocking example;

User selects a bunch of emails. Clicks the delete button. The operation appears to happen immediately (the items just disappear from the list). The user then clicks the compose button and starts typing a new email. It's at this time that the JavaScript code discovers the AJAX request failed. The script could show an error message, but it really is pointless at this time.

Alternately, a blocking example;

User selects a bunch of emails. Clicks the delete button. Sees an hour glass, but the operation fails. They get an error message saying "error. blah blah blah". They are returned back to the list of emails, and they still have the emails they wanted to delete selected. They could attempt to delete them again.

There are also other technical risks for performing non-blocking AJAX requests. The user could close the browser, could navigate to another website and they could navigate to another location in the current web that makes the context of any error response meaningless.

So Why Is It Becoming So Popular?

Facebook, Google, Microsoft, etc.. etc.. all these large domains are increasingly using non-blocking AJAX requests to make operations appear that they are performed instantly. I've also seen an increase in form editors that have no save or submit button. As soon as you leave a field or press enter. The value is saved. There is no your profile has been updated message or saving step.

AJAX requests are not a certainty, and shouldn't be treated as successful until they have completed, but so many major web applications are operating just like that.

Are these websites that use non-blocking AJAX calls to simulate responsive applications taking an unnecessary risk at the cost of appearing fast?

Is this a design pattern that we should all be following in order to remain competitive?

答:
You can compromise between the two options. For example, if the user deletes an email, you could mark it red or grey it out until you get a confirmation back from the server, and only then remove it from the list. The user can still do other things while one action is pending, so it's not blocking, but it still leaves a little reminder for the user that their actions haven't been committed yet.

Amazon AWS takes this approach: when you stop/start an instance, the checkbox that allows you to select it turns into a spinner (so you can't do anything to it for a few seconds), but this doesn't block you from interacting with other instances.


问:
Under which area of Artificial Intelligence is my knowledge store?
I've a maturing idea regarding a knowledge store.

For the purposes of this question, the store would be used by a police force for the recording and querying of crimes.  I believe that historically, police forces used to hold vast index card systems, allowing cross-correlation and querying.

The knowledge store would contain a collection of known facts, collated in a way that supports unknown future questions.

Obviously if I knew the future questions "how many crimes this month", "what tool is most commonly used for breaking and entering" it would be fairly straightforward to store, collate, and present the data.

My requirement for unknown future questions presents the problem.

I imagine a series of authors collating details of crimes. They'd submit details, making heavy use of relationships: "crime occurred in the evening", "burglar used a brick", "crime committed by Person_A".  The when considering a crime, the user would enter "brick" and be presented with collated knowledge related to that concept.

frequently used at night

frequently used in opportunist burglary

frequently used in in assault

most common entry object used in Neighbourhood D

most used object by Person_A, Person_B

The user would then browse/wander through the information set learning more about past crimes.

The underlying information store seems close to that in a Graph Database - but I don't want to "sleepwalk" into using one of those if there's a more natural, AI based solution that not only solves the storage/retrieval problem but which also provides expert-system style deductions.

答:
Description Logic is fine for this job. So using OWL and a reasoner is a good approach. In a simplified explanation, OWL full is almost as powerful as first order logic and so you won't need more. The question is which OWL version is suitable for your task, e.g., powerful enough and at the same time very efficient for interference with a reasoner.

Take care that using OWL and a reasoner is still a young topic. The tools seem to me a bit like in beta. (hard to find up to date information. you cool tool can be discontinued in 5-6 months). You will need to be very familiar with logic (first order and description logic) to make anything that will work. just a warning :-)

Prolog is not so popular any more (unfortunately so or not?), so I guess it is harder to find up-to date material and tools for Prolog for this task. (although Prolog is very good! really!)

EDIT regarding comment:

Running queries on relations is not so interesting, as it is not a big improvement over relational data bases. RDF and sparql is just a a nice way to combine different sources of data around the web.

Her is one example in pseudo logic/code:

```<code>Forall x element burglers :
used_brick(x) and left_fingerprints(x) => opportunist_burgler(x)
</code>```

(the above rule would be stored in some OWL format)

So if a burgler used a brick left fingerprints, this implies that he is a opportunistic burgler.

So if your data store has the following information:

```<code>used_brick(john).
left_fingerprints(john).
</code>```

then you run your OWL reasoner (e.g., at night if you have a lot of data).
this will result in the following data being added to your data store:

```<code>opportunist_burgler(john).
</code>```

Now if you query your data set "give me all opportunist burglers", as a result "john" will pop up. In your data set, it is not stored that 'john' is a opportunist, this is inferred from you OWL rules.

Now you can solve the same problem in the statistic software R, and use descriptive statistics as well as statistics test, e.g., clustering, principal components, anova, etc., and hook the R software to your web app. Then you could also use 'Bayesian interference' and 'Bayesian graphs' in R, and this would be closer to artificial intelligence the other options. But the maths behind it is quite difficult.

Body:
Description Logic is fine for this job. So using OWL and a reasoner is a good approach. In a simplified explanation, OWL full is almost as powerful as first order logic and so you won't need more. The question is which OWL version is suitable for your task, e.g., powerful enough and at the same time very efficient for interference with a reasoner.

Take care that using OWL and a reasoner is still a young topic. The tools seem to me a bit like in beta. (hard to find up to date information. you cool tool can be discontinued in 5-6 months). You will need to be very familiar with logic (first order and description logic) to make anything that will work. just a warning :-)

Prolog is not so popular any more (unfortunately so or not?), so I guess it is harder to find up-to date material and tools for Prolog for this task. (although Prolog is very good! really!)

EDIT regarding comment:

Running queries on relations is not so interesting, as it is not a big improvement over relational data bases. RDF and sparql is just a a nice way to combine different sources of data around the web.

Her is one example in pseudo logic/code:

Forall x element burglers :
used_brick(x) and left_fingerprints(x) => opportunist_burgler(x)

(the above rule would be stored in some OWL format)

So if a burgler used a brick left fingerprints, this implies that he is a opportunistic burgler.

So if your data store has the following information:

used_brick(john).
left_fingerprints(john).

then you run your OWL reasoner (e.g., at night if you have a lot of data).
this will result in the following data being added to your data store:

opportunist_burgler(john).

Now if you query your data set "give me all opportunist burglers", as a result "john" will pop up. In your data set, it is not stored that 'john' is a opportunist, this is inferred from you OWL rules.

Now you can solve the same problem in the statistic software R, and use descriptive statistics as well as statistics test, e.g., clustering, principal components, anova, etc., and hook the R software to your web app. Then you could also use 'Bayesian interference' and 'Bayesian graphs' in R, and this would be closer to artificial intelligence the other options. But the maths behind it is quite difficult.


问:
Is there a supported way to run .NET 4.0 applications natively on a Mac?
What, if any, are the Microsoft supported options for running C#/.NET 4.0 code natively on the Mac? Yes, I know about Mono, but among other things, it lags Microsoft. And Silverlight only works in a web browser. A VMWare-type solution won't cut it either.

Is there any semi-authoritative answer to why Microsoft just doesn't support .NET on the Mac itself? It would seem like they could Silverlight and/or buy Mono and quickly be there. No need for native Visual Studio; cross-compiling and remote debugging is fine.

The reason is that where I work there is a growing amount of Uncertainty about the future which is causing a lot more development to be done in C++ instead of C#; brand new projects are chosing to use C++. Nobody wants to tell management 18–24 months from now "sorry" should the Mac (or iPad) become a requirement. C++ is seen as the safer option, even if it (arguably) means a loss in productivity today.

答:
If you want to develop for an OS then use the right tools. There are no truly professional apps written in mono for the Mac. There is on the other hand a lot of non-professional developers using a lot of tools creating a lot of garbage. Look at the mono app reviews that have been written for OSX. The developers are writing using an incomplete framework hacked to match the OSX platform. Start out write - if you have used C# Objective C is a quick learn.

Professional developers for the mac use C++, Objective C, Cocoa, and Xcode. I develop on several platforms and each has their own best tools. Use Xcode for the Mac and iOS.

Just as a side note Xcode is no Visual Studio it is not as stable and is a disgrace to apple in comparison, but it works well when you get used to he quirks. It is very difficult to beat Microsofts tools - but they were written for Windows not Linux, iOS, OSX, AIX etc.


问:
Can we technically un-blur images?
Since there is an algorithm to blur images, so that part of it cannot be recognised, can we reverse the algorithm and unblur part of than image?

Is there a program that already does that, is that even possible, even in a near future?

答: If the convolution function is continuous then it should be possible. But since we pass through it to a band limited filter, the function cannot be continuous, some information is lost. But you can still find a close approximation.</p>

Title: Can we technically un-blur images?


问:
How have you made unit testing more enjoyable?
If you've always loved unit testing, good for you! But for the unfortunate ones who weren't born with a liking for it, how have you managed to make this task more enjoyable ?

This is not a "what is the right way to unit test" question. I simply want to know little personal tricks that reduce the boredom (dare I say) of writing unit tests.

答: I don't know. What definitely makes unit testing more enjoyable to me is the thought of all the frustrating, lengthy, boring and unrewarding debugging I will not have go through every time I make a change in the software :)</p>

ContentLicense: CC BY-SA 2.5


问:
What can I do to strengthen up my pen and pencil coding skills?
I want to better write code with pen and paper. Whether it'll be in pseudocode or real code, doesn't matter.

Could you kindly advise me sources for this?

答:
turn off the computer, grab pencils, paper, and an eraser, and get writing code.

Then, review it rigorously using references and try to prove its correctness.

Only when that's all done, sit down, type it in, compile and run to verify you got it right.

There is no other way.


答:
People usually do this in an interview when they want to see how you think.

Always make sure you have plenty of paper available, since you can't correct mistakes the way you usually would. Be prepared to rewrite your program after making a rough draft.

I've also found that using diagrams like structure charts, or Warnier-Orr diagrams, helps me clarify my though processes.

If you want to try this with some simple programs to get some practice, I suggest Project Euler as a source of such program exercises. They are usually mathematically interesting!

Oh, and add lots of comments. More than you usually would. Remember, the potential employer is trying to see how you think - try to give them insight into your thought processes.

Title: What can I do to strengthen up my pen and pencil coding skills?

Body:
I want to better write code with pen and paper. Whether it'll be in pseudocode or real code, doesn't matter.

Could you kindly advise me sources for this?


问:
How is a "Software Developer" different from a "Software Consultant"? What makes a consultant?
I have seen a lot of people claiming themselves to be a "software consultant". These consultants do what a normal software developer does, write code, estimate tasks, fix bugs and attend meetings etc. The only difference being the financials, consultants end up earning more. Then how is a software developer different from a "consultant"?

In addition to the main question, I would like to know how can a software developer become a consultant? Are there any specific guidelines for a consultant? Do they need to amass certifications and write up research papers? Please do not confuse the software consultant with a management consultant. Software consultants I have seen are not managers.

答:
I find it interesting the several answers begin "A software consultant is not an employee..." - they are an employee somewhere! And in particular, the OP is interested in how to become a consultant, which is certainly something that should be presented from the employee's perspective.

I work in the consultancy field and I would suggest the primary characteristic one needs to succeed is to be highly personable. This derives from the constant need to be in contact with customers. Anyone who is a "software consultant" but is not directly involved with customers on a near-daily basis is simply a software developer.

In my experience, software consultants are also programmers. However, sometimes they are not quite as talented as their software developer counterparts - mostly because they've had to hone other skills as well, including presenting and proposal writing. Of course, this varies between consultants.

I've also hired consultants who were previously software developers. After an interview or two, I can easily check their software development talents are up to scratch. I then have to focus on whether they are sociable enough (even presentable enough) to represent the company in front of customers. To some extent, you need to look good in a suit, as shallow as that sounds. You need to be able to present confidently in front of customers and field awkward questions. These are skills that only some software developers have.

Finally, I would add that I love my job as a software consultant. It's not because it pays well, although I won't complain about that. It's because I'm involved in many customer projects with a wide variety of problems to solve and technologies to use. That, for me, will always beat working on the next release...


答:
Do it more often!

Coding, whether with a computer or pen and paper, is one of those skills which is learned best by doing it more often. I'd start with working through problems on sites like Project Euler or Code Chef.


问:
LINQPad still being used much out there?
I'm trying to guage how popular and how used LINQPad is today.  I'm just wondering if it's still a useful tool or not as VS and other tools have gotten better.

Furthermore, I am coding over LLBGen by working with LINQ to SQL.  I see there is a plug-in for LLBGen and LINQPad.  Still I wonder if LINQPad is really worth it or what benefits it can give me or if it's still highly suggested out there for ORMs, etc.

答:
The main reason I use LINQpad is because my main code base has Code Analysis (FxCop) and Source Analysis (Style Cop) and all Warnings as errors enabled. When I need to quickly prototype or proof-of-concept something it isn't always practical to do it on the main code base as it can take too long to get the code to a state where it builds.

Once I'm happy, if needed then I can copy the code into my main code base and refactor to meet the project's guidlines and rules.


问:
Upcoming Google interview, looking for some preparation advice
Well I've been hitting the books wherever I can. I have an interview coming up, first one via phone, for a software engineer position. I've read all the blog posts, I've read all the accounts of interviews (some pretty old), and Google itself even suggested a reading list of books, none of which would surprise anyone here. Still, after some time preparing, I can't shake that feeling that there is such a large ground to cover, and I'm never sure whether to go with depth or breadth. I've found myself re-learning a whole area of compsci, only to forget most of the nitty details as I move on to another.

So, I don't know that there's a good answer to this question, but I'm looking for any practical advice on how to tackle the remaining weeks in advance of the interview. Part of my brain is tired from cramming, and of course the rest of it has to be utilized for some tough problems at my current place of employment.

答:
Borrowed the following article from http://get-that-job-at-google.blogspot.in/

Coding Knowledge C/C++ and Java are the preferred programming languages for Google Interviewers. You must know at least one of them really well. You will be expected to write code in the phone screen interviews and in the onsite interviews as well.

Recommended books for CS interviews:
Introduction To Algorithms - By Cormen

Programming Interviews Exposed

Cracking the Coding Interviews

Algorithms for Interviews

Recommended websites for coding practice: InterviewStreet, Topcoder

Big-O This should be the starting point in preparing for an algorithmic interview. You must not struggle with basic complexity analysis, as it will guarantee not being hired. You should be familiar and understand the O, Θ and Ω notations. I recommend reading section on complexity analysis from Data Structures and Algorithms book.

Sorting You should be able to write algorithms O(n*lgn) like QuickSort and MergeSort with ease. Compare and understand the best, worst and average case complexities. I found this table on wiki to be very handy; it lists important properties of all sorting algorithms. Don’t neglect the basic O(n^2) algorithms like Bubble sort or Insertion sort, since other algorithms improve over these. Interviews are more about improving a basic idea, sorting algorithms will help with this process.

Hash Tables When in doubt, think of hash tables. They are useful in most of the problems and frequently help us improve the time complexity of some problems by caching results.

Trees Go through basic tree construction, traversal and manipulation algorithms. You should be able to implement algorithms based on binary search trees. You should be familiar with balanced trees although you are not expected to write code for them in the interview: AVL trees, Red-Black trees, Trie, n-ary trees etc. Thorough knowledge about inorder, postorder and preorder traversals is necessary, because we can solve many tree problems by doing simple modifications to one of these traversals.

Graphs
Graphs are a very important concept in Computer Science. Practice the three basic representation of graphs (objects and pointers, matrix, and adjacency list) and familiarize yourself with their pros & cons.
There is not much time during the interview so you should not expect something very complex. However, basic graph traversal algorithms (DFS and BFS) are a must, you should implement them in all basic representations.
You should be able to implement the Dijkstra or Floyd-Warshall algorithms as well as minimum spanning tree algorithms (Kruskal and Prim). Learn about topological sorting, since it is surprisingly very useful in many ordering problems.

Dynamic Programming This is probably the most important subject as the implementations are small. You should be able to implement 2-3 dynamic algorithms during a 35-40 minutes time. As you’ll check the resources on this blog or on the web, you’ll find that you should expect at least one dynamic programming question per interview.

Operating Systems Learn about processes, threads and concurrency issues. Know about mutexes, semaphores, monitors and how they work. Understand what deadlock and livelock are and how to avoid them. Learn about context switching, scheduling etc.

Mathematics You should familiarize yourself with counting, combinatorics and probability.

Google's publications Read up Google's path-breaking publications listed below if you have time.
Google File System

Google Bigtable

Google MapReduce


问:
Why doesn't "object reference not set to an instance of an object" tell us which object?
We're launching a system, and we sometimes get the famous exception NullReferenceException with the message Object reference not set to an instance of an object.

However, in a method where we have almost 20 objects, having a log which says an object is null, is really of no use at all. It's like telling you, when you are the security agent of a seminar, that a man among 100 attendees is a terrorist. That's really of no use to you at all. You should get more information, if you want to detect which man is the threatening man.

Likewise, if we want to remove the bug, we do need to know which object is null.

Now, something has obsessed my mind for several months, and that is:

Why doesn't .NET give us the name, or at least the type of the object reference, which is null?. Can't it understand the type from reflection or any other source?

Also, what are the best practices to understand which object is null? Should we always test nullability of objects in these contexts manually and log the result? Is there a better way?

Update:
The exception The system cannot find the file specified has the same nature. You can't find which file, until you attach to the process and debug. I guess these types of exceptions can become more intelligent. Wouldn't it be better if .NET could tell us c:\temp.txt doesn't exist. instead of that general message? As a developer, I vote yes.

答:
Cromulent hit the nail on the head I think, however there is the obvious point too that if you're getting a NullReferenceException you have uninitialised variable(s).  The argument that you have circa 20 objects being passed into a method cannot be said to be a mitigation: as the creator of a chunk of code you have to be responsible for its doings, that includes its compliance to the rest of a codebase, as well as proper and correct utilisation of variables etc.

it is onerous, tedious and sometimes dull, but the rewards at the end are worth it: many are the times when I have had to trawl through log files weighing in at several gigabytes, and they are almost always helpful.  However before you get to that stage, the debugger can help you, and before that stage good planning will save a lot of pain(and I do not mean a fully engineered approach to you code solution either: simple sketches and some notes can and will be better than nothing).

In regards to the Object reference not set to an instance of an object the code cannot guess at values we may like: that's our job as programmers, and it simply means you have passed an uninitialised variable in.


问:
How can a Right-Brainer Deal with Massive Left-Brainer Code?
I'm an artist, mostly, though I describe myself as a artist/physicist.  While I can do math, deal with  words, and the "logical" stuff considered left-brain, it's an effort and I make mistakes, whereas I do well with and most of the time think in terms of those things associated with right-brain thinking - spatial relations, holistic big-picture context, etc.  Of course all that is fuzzy, as the right-left brain theory is oversimplified and no mental activity is so simple.   Yet I do sense that I fit in fine with artists, video directors, chefs, and other non-verbal thinking, creative types, while most people in "IT" or hardcore software engineers have minds that work differently, with attention to detail, holding many details in mind at one time, and strong rational and verbal capabilities.

So here I am in a job being paid to fix fussy and obscure bugs in a massive swarm of C++ software, very heavy on OO, and any one line of code makes no sense unless I hold in mind about twenty other class and method names, relations between them, the flow of execution (very spaghetti-like) and other detail.

Besides that,  I'm also rather strongly against much of contemporary C++ and OO styles.  Those who wrote this code really drank the deep OO and Modern C++ kool-ade.  I find it actually makes code much harder to follow, much harder to decide where to fix or change something.   I don't know if this is part of the left/right differnce (or whatever you want to call it) or not.

But work on the C++ I must - people depend on me for my income.  What are tips and techniques to deal with this situation, to be as effective as possible for my employer?

答:
Trust your intuition. If you are a good professional, it means regardless of your "brainness" - left or right - things that left-brainers do consciously you can do intuitively. In the end it's the same thing. Unfortunately we don't control our subconsciousness, but it does the job faster than our consciousness, if it does it at all. These intuitive insights coming out of nowhere are exactly the results of subconscious calculations.

Oh, and you may fail, it's too unreliable. But since you asked... ;)


问:
Branches/decision count in an example
Having read SO, just found this question:

```<code>if (x > y)
     print (x)
else if (x < y)
     print (y)
else
     print (x,y)
</code>```

How many branches and decisions are there? It mentiones there should be 3 decision and 5 branches, yet I cannot see how. For me I can only imagine 4 branches (2 Ifs with two possible results).

Original question here

答:
Investigating this a bit more, I concluded that the statement about this code having 5 branches is incorrect.
This code definitely has only 4 branches - 4 edges to traverse.
As IF has always two branches (one for true and one for false), with two IFs there are 4 branches in the code.
The diagram of this case (IF, ELSE IF, ELSE) is as follows. You can easily see only four branches:

Title: Branches/decision count in an example


问:
Changing __class__ in a factory?
I'm parsing a set of XML files of different kinds (these kinds are known in advance).

These are my requirements:

I want an object to represent each XML document (object-xml mapping)

I'd rather have a different class for each kind, so that identifying the type of the XML file is equivalent to looking at the class of the instance

I don't know the kind in advance

I want some specific behaviour for each object

But for the sake of simplicity, let's consider, I just need to open different numbers, of two know kinds:

even number

odd number

In term of design pattern, I use a variation of the factory design pattern, where the afctory is in the __init__ of the top level class, and I set the correct implementaion by a changing __class__ dynamically

```<code>class Number():
    def __init__(self, val):
        # common implementation (in case of XML, I do the recursion of xml imports)
        self.value = val

        # This is also the point where I discover the type of my object
        # Hence, the constuctor is also a factory of the appropriate type
        if val % 2 == 0:
            self.__class__ = EvenNumber
        elif val % 2 == 1:
            self.__class__ = OddNumber
        else:
            # keep the default Number implementation
            pass

class EvenNumber(Number):
    def half(self):
        '''
        specific behaviour for even numbers
        '''
        return self.value / 2

class OddNumber(Number):
    def next_int(self):
        return self.value

if __name__ == '__main__':
    for x in (Number(2), Number(3)):
        '''
        In the main algorithm, the processing depends on the type of the object
        '''
        if isinstance(x, EvenNumber):
            print(x.half())
        elif isinstance(x, OddNumber):
            print(x.next_int())
</code>```

What do you think about this approach?

I knew __class__ could be read, and was very surprised it can also be written.
What do you think of  changing __class__ dynamically?

Is this a well-known design pattern (it is not the factory pattern nor the state pattern nor the strategy pattern, even if it seems related to all of them)

Edit My real use-case

I want to open  a XBRL taxonomy, which is made of XML linkbases. Except the generic XML Linkbase, I want to handle more precisely some of them:

XML Label linkbase

XML Definition linkbase

etc.

In substance, here is what I have done:

```<code>class Linkbase(etree.xml.ElementTree):
    '''
    Generic linkbase
    '''
    def __init__(self, filename):
        # parse XML
        if self.type == 'definition':
            self.__class__ = DefinitionLinkbase
        elif self.type == 'label':
            self.__class__ = LabelLinkbase

     @property
     def type(self):
        return self.find('//xpath/expression').tag

class LabelLinkbase(Linkbase):
   @property
   def labels(self):
     # find all appropriate elements and returns a list of Labels

class DefintionLinkbase(Linkbase):
   @property
   def definitions(self):
      # returns all definitions
</code>```

Alternatively, I could have used a factory. I can think of something like this, but it doesn't look as elegant as the first approach.

```<code>class Linkbase(etree.xml.ElementTree):
    '''
    Generic linkbase
    '''
    def __init__(self, tree):
        self.tree = tree

     @property
     def type(self):
        return get_type(self.etree)

class LabelLinkbase(Linkbase):
   @property
   def labels(self):
     # find all appropriate elements and returns a list of Labels

class DefintionLinkbase(Linkbase):
   @property
   def definitions(self):
      # returns all definitions

def build_Linkbase(file):
    tree = etree.parse(file)
    if get_type(tree)== "defintion"
       return DefintionLinkbase(tree)
    elif get_type(tree) == "label":
       return LabelLinkbase(tree)
    else:
       return Linkbase(tree)
def get_type(tree):
    return tree.find('//xpath/expression').tag
</code>```

答:
Given your example, I would certainly recommend to define odd/even as properties. Now for the sake of answering the question, I would do the following:

```<code>class Number():
    def __init__(self, val):
        # common implementation (in case of XML, I do the recursion of xml imports)
        self.value = val

class EvenNumber(Number):
    def half(self):
        '''
        specific behaviour for even numbers
        '''
        return self.value / 2

class OddNumber(Number):
    def next_int(self):
        return self.value

# this is your factory
function buildNumber(val):
    if val % 2 == 0:
        return EvenNumber(val)
    else:
        return OddNumber(val)
</code>```

This is closer to the factory design pattern. If you want to make buildNumber a member of a configurable NumberFactory class, you can.

Edit

Beauty and elegance is in the eye of the beholder, but I find your second approach better. This is a judgement call, but I think the first one fail to follow the principle of least surprise because the constructor returns an object of a different type (which is unexpected in most languages, including python).

The second one, however, show a sane structure:

a class hierarchy exposing functionality

a function used to generate the appropriate objects from a source

This leads to a better separation of responsibility, and more flexibility regarding the source of data. This in turns leads to easier maintenance: if you have to add one more type, it won't affect the existing code. This is known as the open/close principle, and is a good thing.

The first approach makes the base class aware of its implemeters, which is a very (very) bad thing, because abstract objects should not depend on implementation details.

Title: Changing __class__ in a factory?

Body:
Given your example, I would certainly recommend to define odd/even as properties. Now for the sake of answering the question, I would do the following:

class Number():
    def __init__(self, val):
        # common implementation (in case of XML, I do the recursion of xml imports)
        self.value = val

class EvenNumber(Number):
    def half(self):
        '''
        specific behaviour for even numbers
        '''
        return self.value / 2

class OddNumber(Number):
    def next_int(self):
        return self.value

# this is your factory
function buildNumber(val):
    if val % 2 == 0:
        return EvenNumber(val)
    else:
        return OddNumber(val)

This is closer to the factory design pattern. If you want to make buildNumber a member of a configurable NumberFactory class, you can.

Edit

Beauty and elegance is in the eye of the beholder, but I find your second approach better. This is a judgement call, but I think the first one fail to follow the principle of least surprise because the constructor returns an object of a different type (which is unexpected in most languages, including python).

The second one, however, show a sane structure:

a class hierarchy exposing functionality

a function used to generate the appropriate objects from a source

This leads to a better separation of responsibility, and more flexibility regarding the source of data. This in turns leads to easier maintenance: if you have to add one more type, it won't affect the existing code. This is known as the open/close principle, and is a good thing.

The first approach makes the base class aware of its implemeters, which is a very (very) bad thing, because abstract objects should not depend on implementation details.


答:
While I applaud you for your ambitious(odd) dedication, I'm not so sure that pen and paper are the best solution for programming mastery. I would suggest learning to code in MS Notepad though. This is just my opinion, obviously, but I learned HTML/CSS/JavaScript in notepad and everything became muscle memory very fast. I actually got a contract job simply for putting ht/cs/js (using notepad) on my resume. I have also done 'some' C#.Net in notepad using the command-line compiler, and it's not so bad. Don't recommend it though. </p>

<p>My two cents. </p>

Body:
While I applaud you for your ambitious(odd) dedication, I'm not so sure that pen and paper are the best solution for programming mastery. I would suggest learning to code in MS Notepad though. This is just my opinion, obviously, but I learned HTML/CSS/JavaScript in notepad and everything became muscle memory very fast. I actually got a contract job simply for putting ht/cs/js (using notepad) on my resume. I have also done 'some' C#.Net in notepad using the command-line compiler, and it's not so bad. Don't recommend it though.

My two cents.


答:
Try getting more into the design side of things where being comfortable with the fuzziness is a strength would be my suggestion in terms of career progression.  As someone that likes to be creative, working on maintenance may not be a great fit whereas working on new stuff may be better if that is possible.

While there is nothing wrong with wanting some pride in one's work, wanting to not get bogged down in the details may be something that you may have to find a new approach to improve.  Rather than look at it as getting down and dirty, there may be another perspective that could make it fun somehow.

Support and maintenance likely have their fans as some people would prefer to tweak existing systems than put in a new system.  I know I tend to work better with an existing system that I'm changing rather than trying to pull something out of the ether.

What you may try to do is to note when people are wanting ideas for dealing with various trouble spots and brainstorm solutions as this is part of what you like.  It isn't about knowing which lines of code to change but rather if you can tell someone, "Did you look in that object and see if it is doing more than it claims?" kind of thing.

Another point is knowing what you want to create: Graphics, applications, websites, processes or systems?  These are all slightly different things that in wanting to create, you could be asked for "Create what?"

Title: How can a Right-Brainer Deal with Massive Left-Brainer Code?

Body:
I'm an artist, mostly, though I describe myself as a artist/physicist.  While I can do math, deal with  words, and the "logical" stuff considered left-brain, it's an effort and I make mistakes, whereas I do well with and most of the time think in terms of those things associated with right-brain thinking - spatial relations, holistic big-picture context, etc.  Of course all that is fuzzy, as the right-left brain theory is oversimplified and no mental activity is so simple.   Yet I do sense that I fit in fine with artists, video directors, chefs, and other non-verbal thinking, creative types, while most people in "IT" or hardcore software engineers have minds that work differently, with attention to detail, holding many details in mind at one time, and strong rational and verbal capabilities.

So here I am in a job being paid to fix fussy and obscure bugs in a massive swarm of C++ software, very heavy on OO, and any one line of code makes no sense unless I hold in mind about twenty other class and method names, relations between them, the flow of execution (very spaghetti-like) and other detail.

Besides that,  I'm also rather strongly against much of contemporary C++ and OO styles.  Those who wrote this code really drank the deep OO and Modern C++ kool-ade.  I find it actually makes code much harder to follow, much harder to decide where to fix or change something.   I don't know if this is part of the left/right differnce (or whatever you want to call it) or not.

But work on the C++ I must - people depend on me for my income.  What are tips and techniques to deal with this situation, to be as effective as possible for my employer?


问:
How to find a 'good' seed page for a web crawler?
I started building a web crawler and read somewhere that it's a very hard problem to find a good seed page for the crawler. Can anyone explain me if there is any pre-defined procedure/ guidlines of finding a good seed page? or how you say that a particular page is a good seed page?</p>

答:
A good seed page needs to have

As many links as possible

For as many different topics as possible

That's all, really. The first things that come to mind would be Wikipedia and the Open Directory Project.


问:
Design pattern for polymorphic behaviour while allowing library separation
Let's say I have a hierarchy of Item classes: Rectangle, Circle, Triangle. I want to be able to draw them, so my first possibility is add a virtual Draw() method to each:

```<code>class Item {
public:
   virtual ~Item();
   virtual void Draw() =0;
};
</code>```

However, I want to split the drawing functionality to a separate Draw library while the Core library contains only the basic representations. There's a couple of possibilities I can think of:

1 - A DrawManager that takes a list of Items and has to use dynamic_cast<> to work out what to do:

```<code>class DrawManager {
  void draw(ItemList& items) {
    FOREACH(Item* item, items) {
       if (dynamic_cast<Rectangle*>(item)) {
          drawRectangle();
       } else if (dynamic_cast<Circle*>(item)) {
          drawCircle();
       } ....
    }
  }
};
</code>```

This isn't ideal as it relies on RTTI and forces one class to be aware of all items in the hierarchy.

2 - The other approach is to defer drawing responsibility to an ItemDrawer hierarchy (RectangleDrawer, etc):

```<code>class Item {
   virtual Drawer* GetDrawer() =0;
}

class Rectangle : public Item {
public:
   virtual Drawer* GetDrawer() {return new RectangleDrawer(this); }
}
</code>```

This achieves the separation of concerns between the base representation of the Items and the code for drawing. The problem though is that the Item classes are dependent on the drawing classes.

How can I separate out this drawing code into a separate library? Is the solution for the Items to return a factory class of some description? However, how can this be defined so that the Core library isn't dependent on the Draw library?

答:
The split you describe - into two parallel hierarchies - is essentially the bridge pattern.

You worry that it makes the refined abstraction (Rectangle etc.) dependent on the implementation (RectangleDrawer), but I'm not sure how you could avoid that entirely.

You can certainly provide an abstract factory to break that dependency, but you still need some way to tell the factory which subclass to create, and that subclass still depends on the specific refined implementation. That is, even if Rectangle doesn't depend on RectangleDrawer, it still needs a way to tell the factory to build one, and RectangleDrawer itself still depends on Rectangle.

It's also worth asking whether this is a useful abstraction. Is drawing a rectangle so hard that it's worth putting in a differnt class, or are you really trying to abstract the graphics library?


答:
Since I believe generalistic web search should be now considered a solved problem with a single provider that has such an headstart, and momentum, that it's unpractical, unconvenient, and kinda lame to even consider outrunning it, I believe you might prefer focusing your search efforts on a specialized domain.

e.g.: U.S. law, E.U. law, local laws of certain foreign countries,
  documents in a certain language, fishing, hunting, the military,
  ambientalism, indian car manifacturers, south american team games,
  russian motorsports...

Specializing your domains is all about finding the appropriate seeds for the given domain. (Also, IMHO, a handul of selected, unknowing, specialized forums should also be considered as a starting point) So once you have you domain, if you dig it well, (or at least the one you're working with/for does) the seeds should come natural.

Otherwise head for dmoz.org like Google did some 15 years ago. (And don't forget to weight in yahoo.com for good measure) Give your crawler another 15 years and you should have a good link base to search upon.

Ok, ok, if you really really must take this hard and pointeless route
  also consider: reddit.com, twitter.com, and  (why not) the
  stackexchange.com constellation.

Title: How to find a 'good' seed page for a web crawler?

Body: I started building a web crawler and read somewhere that it's a very hard problem to find a good seed page for the crawler. Can anyone explain me if there is any pre-defined procedure/ guidlines of finding a good seed page? or how you say that a particular page is a good seed page?</p>


问:
Should I return from a function early or use an if statement?
I've often written this sort of function in both formats, and I was wondering if one format is preferred over another, and why.

public void SomeFunction(bool someCondition)
{
    if (someCondition)
    {
        // Do Something
    }
}
```

<p>or</p>

<pre class="lang-java prettyprint-override"><code>public void SomeFunction(bool someCondition)
{
    if (!someCondition)
        return;

    // Do Something
}
</code>```

I usually code with the first one since that is the way my brain works while coding, although I think I prefer the 2nd one since it takes care of any error handling right away and I find it easier to read

答:
The conditions on the top are called "preconditions". By putting if(!precond) return;, you are visually listing all preconditions.

Using the large "if-else" block may increase indent overhead (I forgot the quote about 3-level indents).


问:
DDD - Aggregate Roots - Dealing with Efficiency and Concurrency
First off, I'll admit that I'm a newbie to DDD and need to read the "blue book".

I'm building a system that has an AggregateRoot of type "Match". Each Match can have a collection of "Votes" and also has a readonly "VoteCount" property which gets incremented when a user up-votes or down-votes a Match.

Since many users could be voting on a Match at the same time, Votes have to be added/removed from the Match and the VoteCount has to be incremented/decremented as one atomic operation involving write locks (with locks handled by the DB). (I need VoteCount as a static value in the database to be queried on efficiently by other processes/components.)

It seems to me that if I were adhering to strict DDD, I would be coding this operation as such:

An application service would receive a vote request object

The service would then retrieve the Match object from a Match Repository

The service would then call some sort of method on the Match object to add the Vote to the collection and update VoteCount.

The Repository would then persist that Match instance back to the DB

However, this approach is not feasible for my application for 2 main reasons, as I see:

I'm using MongoDB on the backend and cannot wrap this read-write operation into a transaction to prevent dirty reads of the Match data and its associated Votes and VoteCount.

It's highly inefficient. I'm pulling back the entire object graph just to add a Vote and increment VoteCount. Although this is more efficient in a document db than in a relational one, I'm still doing an unnecessary read operation.

Issues 1 & 2 are not a problem when sending a single Vote object to the repository and performing one atomic update statement against Mongo.

Could Vote, in this case be considered an "aggregate" and be deserving of its own repository and aggregate status?

答:
Yes, you can model Vote as an aggregate unto itself.  In the real world, often people vote for several things at once.  The aggregate would then be called a Ballot instead of vote.  You just have a special case where there is only one item to vote for at a time.

I can't speak for MongoDB (perhaps someone else can) - but you would have a very easy time doing this in RavenDB with something like:

```<code>public class Match
{
    public string Id { get; set; }
    public string Name { get; set; } // or whatever
}

public class Vote
{
    public string Id { get; set; }
    public string MatchId { get; set; }
    public string UserId { get; set; }
    public bool YeaOrNay { get; set; } // or whatever
}
</code>```

Then you would just build a map/reduce index over your votes to tally the results.

Body:
Yes, you can model Vote as an aggregate unto itself.  In the real world, often people vote for several things at once.  The aggregate would then be called a Ballot instead of vote.  You just have a special case where there is only one item to vote for at a time.

I can't speak for MongoDB (perhaps someone else can) - but you would have a very easy time doing this in RavenDB with something like:

public class Match
{
    public string Id { get; set; }
    public string Name { get; set; } // or whatever
}

public class Vote
{
    public string Id { get; set; }
    public string MatchId { get; set; }
    public string UserId { get; set; }
    public bool YeaOrNay { get; set; } // or whatever
}

Then you would just build a map/reduce index over your votes to tally the results.

OwnerDisplayName: Matt Johnson


答:
Could Vote, in this case be considered an "aggregate" and be deserving
  of its own repository and aggregate status?

I think this might be the right answer. An aggregate should be a transactional consistency boundary. Is there a consistency requirement between votes on a match? The presents of a Vote collection on a Match aggregate would suggest that there is. However, it seems like one vote has nothing to do with the next.

Instead, I would store each vote individually. This way you can use the aggregate functionality of MongoDB to get the count, though I'm not sure whether it is still slow. If it is, then you can aggregate using the Map/Reduce functionality.

More generally, this may not be a best fit for DDD. If the domain doesn't consist of complex behavior there is hardly a reason to try to adapt the DDD tactical patterns (entity, agreggate) to this domain.

Title: DDD - Aggregate Roots - Dealing with Efficiency and Concurrency

Body:
First off, I'll admit that I'm a newbie to DDD and need to read the "blue book".

I'm building a system that has an AggregateRoot of type "Match". Each Match can have a collection of "Votes" and also has a readonly "VoteCount" property which gets incremented when a user up-votes or down-votes a Match.

Since many users could be voting on a Match at the same time, Votes have to be added/removed from the Match and the VoteCount has to be incremented/decremented as one atomic operation involving write locks (with locks handled by the DB). (I need VoteCount as a static value in the database to be queried on efficiently by other processes/components.)

It seems to me that if I were adhering to strict DDD, I would be coding this operation as such:

An application service would receive a vote request object

The service would then retrieve the Match object from a Match Repository

The service would then call some sort of method on the Match object to add the Vote to the collection and update VoteCount.

The Repository would then persist that Match instance back to the DB

However, this approach is not feasible for my application for 2 main reasons, as I see:

I'm using MongoDB on the backend and cannot wrap this read-write operation into a transaction to prevent dirty reads of the Match data and its associated Votes and VoteCount.

It's highly inefficient. I'm pulling back the entire object graph just to add a Vote and increment VoteCount. Although this is more efficient in a document db than in a relational one, I'm still doing an unnecessary read operation.

Issues 1 & 2 are not a problem when sending a single Vote object to the repository and performing one atomic update statement against Mongo.

Could Vote, in this case be considered an "aggregate" and be deserving of its own repository and aggregate status?

OwnerDisplayName: eulerfx


答:
Take a look at the visitor pattern.

Its intention is to separate an algorithm (in your case drawing) from an object structure on which it operates (items).

So a simple example for your problem would be :

```<code>class Item
{
public:
    virtual void visit(Visitable v)
    {
        v.accept(*this)
    }
};

class Rectangle : public Item
{
public:
    virtual void visit(Visitable v)
    {
        v.accept(*this)
    }
};

class Circle : public Item
{
public:
    virtual void visit(Visitable v)
    {
        v.accept(*this)
    }
};

class Visitable
{
public:
    virtual void accept(Rectangle& r);
    virtual void accept(Circle& c);
};

class Drawer : public Visitable
{
public:
    void accept(Rectangle& r)
    {
        // draw rectangle
    }
    void accept(Circle& c)
    {
        // draw circle
    }
};

int main()
{
    Item* i1 = new Circle;
    Item* i2 = new Rectangle;

    Drawer d;
    i1->visit(d); // Draw circle
    i2->visit(d); // Draw rectangle

    return 1;
}
</code>```

Title: Design pattern for polymorphic behaviour while allowing library separation

Body:
Let's say I have a hierarchy of Item classes: Rectangle, Circle, Triangle. I want to be able to draw them, so my first possibility is add a virtual Draw() method to each:

```<code>class Item {
public:
   virtual ~Item();
   virtual void Draw() =0;
};
</code>```

However, I want to split the drawing functionality to a separate Draw library while the Core library contains only the basic representations. There's a couple of possibilities I can think of:

1 - A DrawManager that takes a list of Items and has to use dynamic_cast<> to work out what to do:

```<code>class DrawManager {
  void draw(ItemList& items) {
    FOREACH(Item* item, items) {
       if (dynamic_cast<Rectangle*>(item)) {
          drawRectangle();
       } else if (dynamic_cast<Circle*>(item)) {
          drawCircle();
       } ....
    }
  }
};
</code>```

This isn't ideal as it relies on RTTI and forces one class to be aware of all items in the hierarchy.

2 - The other approach is to defer drawing responsibility to an ItemDrawer hierarchy (RectangleDrawer, etc):

```<code>class Item {
   virtual Drawer* GetDrawer() =0;
}

class Rectangle : public Item {
public:
   virtual Drawer* GetDrawer() {return new RectangleDrawer(this); }
}
</code>```

This achieves the separation of concerns between the base representation of the Items and the code for drawing. The problem though is that the Item classes are dependent on the drawing classes.

How can I separate out this drawing code into a separate library? Is the solution for the Items to return a factory class of some description? However, how can this be defined so that the Core library isn't dependent on the Draw library?

Body:
Take a look at the visitor pattern.

Its intention is to separate an algorithm (in your case drawing) from an object structure on which it operates (items).

So a simple example for your problem would be :

class Item
{
public:
    virtual void visit(Visitable v)
    {
        v.accept(*this)
    }
};

class Rectangle : public Item
{
public:
    virtual void visit(Visitable v)
    {
        v.accept(*this)
    }
};

class Circle : public Item
{
public:
    virtual void visit(Visitable v)
    {
        v.accept(*this)
    }
};

class Visitable
{
public:
    virtual void accept(Rectangle& r);
    virtual void accept(Circle& c);
};

class Drawer : public Visitable
{
public:
    void accept(Rectangle& r)
    {
        // draw rectangle
    }
    void accept(Circle& c)
    {
        // draw circle
    }
};

int main()
{
    Item* i1 = new Circle;
    Item* i2 = new Rectangle;

    Drawer d;
    i1->visit(d); // Draw circle
    i2->visit(d); // Draw rectangle

    return 1;
}


问:
How we call an RPC that not only calls external functions but also updates data structures?
I have a simple C++ RPC that lets you have remote class instances that support live members (data structures) update as well as method calls. For example I had a class declared like this (pseudocode):

```<code>class Sum{
public:
    RPC_FIELD(int lastSum);
    RPC_METHOD(int summ(int a, int b))
    {
     lastSum = a + b;
     return lastSum;
    }
};
</code>```

On machine A I had its instance. On machines B and C I had created its instances and connected them to machine A. So now they actually do all processing on machine A but machines B, C get lastSum class field updates automatically (and can subscribe to update event).

How to call (Nice Name) such a functionality when we have binding over network done automatically by RPC library? How RPC library creator can announce such feature?

答:
Not sure what kind of name you're looking for, but I have called what you're describing by the following in the past (dependent on who required reports/descriptions):

RAU: Remote Auto-Updates

RSF: Remotely Synchronised Fields

CSF: Centrally Synchronised Fields

AFS: Automatic Field Synchronisation

SFF: Server Fed Fields

SUF: Server Updated Fields

CUF: Centrally Updated Fields

Although if you are looking for a definitive name, I am not entirely sure one exists, if there is I would be happy to find out though.


问:
Renaming long named method in C#
I'm working on a project where exist one method with title

```<code>string ValidateNewPasswordExpireCurrentPasswordAndCreateNewPassword(...)
</code>```

I'm sure the method name must be changed. But can't found good and descriptive alternative.
Also I can't separate method in multiple methods, like ValidateNewPassword(), ExpireCurrentPassword() and CreateNewPassword().

How can I rename the method and the same time to not lose self describing ability ?

答:
```<code>string ChangePassword(...)
{
    if(ValidateNewPassword(...))
    {
        ExpireCurrentPassword();
        CreateNewPassword();
        return ... //Method signature is string?
    }
    else
    {
        //Handle invalid password
    }
}
</code>```

Much cleaner IMO!

Title: Renaming long named method in C#

Body:
string ChangePassword(...)
{
    if(ValidateNewPassword(...))
    {
        ExpireCurrentPassword();
        CreateNewPassword();
        return ... //Method signature is string?
    }
    else
    {
        //Handle invalid password
    }
}

Much cleaner IMO!


答: As mentioned by others I would go with UpdatePassword or RenewPassword as both imply that a password mus exist and that actions are being carried out on it which may or may not change it.  The best approach for me personally in such situations has been to rename the function then wrap the function in the old name as well, leaving legacy compatibility in place for a while, and having a log message outputting the new name of the modernised function.  That way you can allow programmers time to get accustomed to the new Name without breaking the codebase, and coincidentally saving you having to make plenty of refactoring code changes yourself.

Title: Renaming long named method in C#

Body:
I'm working on a project where exist one method with title

```<code>string ValidateNewPasswordExpireCurrentPasswordAndCreateNewPassword(...)
</code>```

I'm sure the method name must be changed. But can't found good and descriptive alternative.
Also I can't separate method in multiple methods, like ValidateNewPassword(), ExpireCurrentPassword() and CreateNewPassword().

How can I rename the method and the same time to not lose self describing ability ?


答:
I expect this method to call three other methods:

```<code>public string ValidateNewPasswordExpireCurrentPasswordAndCreateNewPassword(string password)
{
    AccountManager.ValidatePassword(password);
    AccountManager.ExpirePasswordForAccount(this.CurrentAccount);
    AccountManager.AssignPasswordToAccount(this.CurrentAccount, password);
}
</code>```

When a method aggregates different things, it's done because:

Either it's too cumbersome to call those different things in order every time you need them, i.e. the caller don't want to remember that the password should be validated, then the old one should be expired and only then the new one should be assigned.

The caller probably needs to know what's happening under the hood, since the same caller can call those three methods separately. You can try to shorten the method name, but not too much: sadly, you still need to be very specific and detailed.

You can also move the hint that the password is validated to the password argument itself.

```<code>public string ExpireAndReplacePassword(string passwordToValidate)
{
    AccountManager.ValidatePassword(passwordToValidate);
    AccountManager.ExpirePasswordForAccount(this.CurrentAccount);
    AccountManager.AssignPasswordToAccount(this.CurrentAccount, passwordToValidate);
}
</code>```

Or you don't trust the caller: what if the caller just assigns an invalid password?

In this case, the caller doesn't have to know the internals, so be short. You don't need to specify that there is input validation: you're expected to validate inputs from an unstrusted caller.

```<code>public void ReplacePassword(string newPassword)
{
    Contract.Requires(AccountManager.IsPasswordValid(newPassword));

    AccountManager.ExpirePasswordForAccount(this.CurrentAccount);
    AccountManager.AssignPasswordToAccount(this.CurrentAccount, newPassword);
}
</code>```

or, if there is still a reason to tell that the old password will expire:

```<code>public string ExpireAndReplacePassword(string newPassword)
{
    Contract.Requires(AccountManager.IsPasswordValid(newPassword));

    AccountManager.ExpirePasswordForAccount(this.CurrentAccount);
    AccountManager.AssignPasswordToAccount(this.CurrentAccount, newPassword);
}
</code>```

Or business-wise, separately, those actions don't make sense.

In the third case, if only the aggregation makes sense business-wise, you can simply use the verb which is used in this domain. For example, if the users don't expire their passwords, nor validate them, nor assign them, but simply change them, the change implying the validation, the expiration and the assignment, call the method simply:

```<code>public string ChangePassword(string password)
{
    Contract.Requires(AccountManager.IsPasswordValid(password));

    AccountManager.ExpirePasswordForAccount(this.CurrentAccount);
    AccountManager.AssignPasswordToAccount(this.CurrentAccount, password);
}
</code>```

Title: Renaming long named method in C#

Body:
I expect this method to call three other methods:

public string ValidateNewPasswordExpireCurrentPasswordAndCreateNewPassword(string password)
{
    AccountManager.ValidatePassword(password);
    AccountManager.ExpirePasswordForAccount(this.CurrentAccount);
    AccountManager.AssignPasswordToAccount(this.CurrentAccount, password);
}

When a method aggregates different things, it's done because:

Either it's too cumbersome to call those different things in order every time you need them, i.e. the caller don't want to remember that the password should be validated, then the old one should be expired and only then the new one should be assigned.

The caller probably needs to know what's happening under the hood, since the same caller can call those three methods separately. You can try to shorten the method name, but not too much: sadly, you still need to be very specific and detailed.

You can also move the hint that the password is validated to the password argument itself.

public string ExpireAndReplacePassword(string passwordToValidate)
{
    AccountManager.ValidatePassword(passwordToValidate);
    AccountManager.ExpirePasswordForAccount(this.CurrentAccount);
    AccountManager.AssignPasswordToAccount(this.CurrentAccount, passwordToValidate);
}

Or you don't trust the caller: what if the caller just assigns an invalid password?

In this case, the caller doesn't have to know the internals, so be short. You don't need to specify that there is input validation: you're expected to validate inputs from an unstrusted caller.

public void ReplacePassword(string newPassword)
{
    Contract.Requires(AccountManager.IsPasswordValid(newPassword));

    AccountManager.ExpirePasswordForAccount(this.CurrentAccount);
    AccountManager.AssignPasswordToAccount(this.CurrentAccount, newPassword);
}

or, if there is still a reason to tell that the old password will expire:

public string ExpireAndReplacePassword(string newPassword)
{
    Contract.Requires(AccountManager.IsPasswordValid(newPassword));

    AccountManager.ExpirePasswordForAccount(this.CurrentAccount);
    AccountManager.AssignPasswordToAccount(this.CurrentAccount, newPassword);
}

Or business-wise, separately, those actions don't make sense.

In the third case, if only the aggregation makes sense business-wise, you can simply use the verb which is used in this domain. For example, if the users don't expire their passwords, nor validate them, nor assign them, but simply change them, the change implying the validation, the expiration and the assignment, call the method simply:

public string ChangePassword(string password)
{
    Contract.Requires(AccountManager.IsPasswordValid(password));

    AccountManager.ExpirePasswordForAccount(this.CurrentAccount);
    AccountManager.AssignPasswordToAccount(this.CurrentAccount, password);
}


问:
CSS Classes for semantics vs. styles in general cases
The W3C spec on the class attribute says

There are no additional restrictions on the tokens authors can use in the class attribute, but authors are encouraged to use values that describe the nature of the content, rather than values that describe the desired presentation of the content.

Reference

I work on a massive website that has many disparate pages.  We have a default stylesheet that is shared across practically all pages.  I find it useful to have CSS rulesets such as these:

```<code>.center { text-align: center; }
.red { color: red; }
</code>```

However, these classes do not semantically describe content.

I'm sure you can understand that there are an enumerable number of cases where I need to center text or color it red, and each of these specific instances may have nothing to do with one another.  For example, the class warning may be useful in one spot, but in another it may just be aside.  I wouldn't necessarily want all warnings to be red either.

I realize that this is a hyper-technical question, but I do want the hyper-technical answer.  Is there any correct way to reconcile having general style rules that express no semantics with the HTML spec?  Is this a case for shudder inline styles?

答:
First of all this is a good question, I don't think that is is hyper technical and it makes a lot of sense.

encouraged is a key word here.

What you are doing is very common practice, it is extremely hard to do this sort of styling without this technique using CSS.  CSS is there to describe what we want the element to look like, it is our styling language and it really only hooks effectively to ids, class names and tag names (all other selectors are considerably slower last I checked). Out of these three classes make the most sense. This is because IDs are unique and tag names are even more descriptive of what an element is and not how it should be displayed.

I understand the W3C's argument, in programming most of the time classes describe of what type and object is and how it behaves and not how it should be presented.

One alternative is using a more robust templating language such as SASS and use mixins (see example on home page). This would let you give classes descriptive classes and share a 'center' mixin. I don't like this though since it involves embedding another technology to your code. LESS is also such an alternative.

Yes, you can inline the styles, you can also do so programmatically (use classes and have a script embed the styles on the back end). I really do not see the benefit of doing that though except of adhering more closely to the W3C's recommendation.

You can keep doing what you're doing. Which works but does not adhere to the W3C's encouragement.

When you inline styles you're also going to have the following issues:

elements with IDs will have their style values overridden by the inline style. An ID selector takes precedence over a class selector but inline styling beats both. This is not a problem if your styles are all of the sorts of 'center' but it is worth keeping in mind. You'd be surprised how much broken code exists on the web that fails for that reason.

Even classes 'center' might have a different meaning in some scenarios, you might want to also set the additional properties and not just the text-align and still be center. With center and red it's not that big of a problem though

Here is what I think you should do:

Try SASS or LESS, if these work for you they can end up saving you a lot of time. If that doesn't work I would continue using classes as a form of the mixin pattern to share properties across elements.

I do agree that the name 'class' for something that describes how an object should be displayed and not how it actually is is confusing, classes double today both for the presentation logic in CSS and it's code logic in JavaScript.

Good luck!


问:
Copyright notice in CSS or XML files
I'm currently working on an open-source project. Currently, we put our copyright notice at the top of every Java source file.

I was wondering whether it was advisable or common practice to put copyright notices in CSS or XML files.

答:
CSS yes, XML not so much

The purpose of a copyright notice is to inform readers that the material has a certain level of protection against unauthorised reuse. For creative works, such as CSS styling or source code, this makes sense.

In the case of XML it seems redundant because the XML should be acting as a data carrier rather than a creative work in and of itself. Of course, as Benjamin Gruenbaum has noted in the comments, if the XML is carrying a copyrighted work then that should carry a copyright notice within it.

On the whole, try to keep your copyright notice as small and unobtrusive as possible since people on tight bandwidth limits don't want to download more data than is necessary.

Title: Copyright notice in CSS or XML files


答:
Using more semantical class-names really comes in handy if you are designing more than one style, for example a mobile version. They may share lots of code, but sometimes 'center' shouldn't be centered anymore in the mobile version. Or something is put on a different background and therefor should use maroon rather than red. Restyling things like 'center{ text-align: right;}' is just confusing.

So I would encourage semantical meanings and style them. To avoid redundant coding of styles that keep recurring (for example 'font-weight: bold; text-align: center; color: red;' for several warnings and other red text Sass or Less could be very handy.

However, I would not spend ages renaming all your classes if you don't have multiple styles and the layout isn't subject to change. It is after all only for your own convenience (and the developers after you, if there are any.) Browsers do nothing with the semantical value, if anything use role-attributes.

I wouldn't use inline styles too much, but they can be useful. For example when the styling comes from a tool and is generated. It's just not productive to jump through hoops to rewrite the generated code to classes only to style them. (Especially when changing the settings of the tool will allow for easy change.)

Title: CSS Classes for semantics vs. styles in general cases

Body:
The W3C spec on the class attribute says

There are no additional restrictions on the tokens authors can use in the class attribute, but authors are encouraged to use values that describe the nature of the content, rather than values that describe the desired presentation of the content.

Reference

I work on a massive website that has many disparate pages.  We have a default stylesheet that is shared across practically all pages.  I find it useful to have CSS rulesets such as these:

```<code>.center { text-align: center; }
.red { color: red; }
</code>```

However, these classes do not semantically describe content.

I'm sure you can understand that there are an enumerable number of cases where I need to center text or color it red, and each of these specific instances may have nothing to do with one another.  For example, the class warning may be useful in one spot, but in another it may just be aside.  I wouldn't necessarily want all warnings to be red either.

I realize that this is a hyper-technical question, but I do want the hyper-technical answer.  Is there any correct way to reconcile having general style rules that express no semantics with the HTML spec?  Is this a case for shudder inline styles?


问:
Perforce workflow
So, we have just migrated from SVN to Perforce.

I'm having a little trouble trying to figure out the best workflow.

For Subversion, I did the following (via TortoiseSVN):

Check out repo

Do work

Update repo

Resolve conflicts, if any.

Commit my code.

Do work..

What is the best approach for P4? I know that you must open files for edit before actually editing them. With this in mind I am currently doing the following (via P4V):

Sync to head

Open entire project for editing

Do work

Revert unchanged files

Submit i.e. commit pending changes.

Open entire project for edit, again.

Do work..

Is this a practical approach? or is there one that is more in tune with Perforce best practices?

答:
Your step two of "Open entire project for editing" may contribute less than clear communication in the team.

One of the important aspects of working as a team is communication.  Perforce can show who has a file opened in a change set.  If I am working on a file and I see someone else also editing the file, this is of potential interest to me - we may have a collision.

On the other hand, if I am only checking out files that I need to open as I need them, my team mates will not be as confused about what I am working on (I'm not potentially touching every file in the project).

Furthermore, consider that the server is also maintaining the information on what every client spec has checked out.  By opening all the files in large projects this will tax the server a bit more (probably not much more, but it is still some).

Opening every file limits the use of the 'p4 opened' command.

It is one thing to see all "you are the only one to check out this file" checks in your pending changelist.  It is quite another to see every file also checked out by other people.

As you get used to perforce, you will get to the point where every time you start working on a file, you check it out first.

Once you check out the files, ideally you would place these open files in a named change list rather than leaving this in the default change list.  This is again to aid in communication between team members ("you've got xyz.java open in a change list named 'fix abc bug'").  This also facilitates working on two things at once by grouping the files in different change lists as you need them.

In p4v this is done by right clicking on the files and selecting 'move to another changelist'.

Unless you lock the files (there are pros and cons to this), you may need to resolve conflicts in the submit too - but you will know before you submit that you need to merge, and the server won't let you do the checkin of the changelist (this is an atomic operation).  This will show up with a question mark in the file icon.

A more 'advanced' p4 concept is that of jobs within p4.  These integrate with mylyn within eclipse as tasks.

With a job, one would associate changelists to a job.  You can then go back to look at a job and see what changes were checked into fix this particular item.

Furthermore, with p4 defect tracking gateway one can link p4 to your favorite bug tracking system.  This will link p4 jobs to bugs so that changes to one show up in the other (including p4 changelist checkins against jobs being described in the defect tracking system).

I've seen a huge bug tracking database built on top of p4 jobs.

You might find the p4 tutorials a useful resource.

Do <s>check out</s> look at p4 sandbox - it is interesting and you may find the private local branching (think DVCS) to fit how you work (and you can get the repository on a thumb drive and work off line).

Title: Perforce workflow


答:
First of all, DDD is really about creating a model where reading the code is like how the actual domain experts would be talking about the domain.

Second, they way DDD describes an aggregate root, the child objects on the aggregate root are merely properties on the aggregate root itself, and you shouldn't be able to access the child elements directly, only through the aggregate root.

So seen from a DDD perspective, if votes are children to the aggregate root "match", then the act of adding a vote to a match is actually an act of modifying the match.

Though you have not given enough information for me to fully understand the domain, it doesn't seem to me that this would be the natural way to see things, but I imagine that it has some similarities to StackExchange?

On any StackExchange site, if I open my user page, I can see a list of votes I have cast, including if it is an up- or a downvote, and the time when I cast the vote.  This is a direct query on votes I have cast. Thus, if you were to make a DDD model of StackExchange, then questions and answers could NOT be considered aggregate roots containing votes.

In this case, votes would be entities themselves.

Note that here I'm very focused on the way that "the blue book" describes aggregates, mainly because you mentioned it, and you focus on DDD in the question description. That doesn't mean that this is the only/correct way of dealing with aggregates.

p.s. If you havn't read the book yet, this presentation touches a lot of the subject matter: http://www.infoq.com/presentations/model-to-work-evans (part1) http://www.infoq.com/presentations/strategic-design-evans (part2)


答:
I work on a massive website that has many disparate pages. We have a default stylesheet that is shared across practically all pages. I find it useful to have CSS rulesets such as these:

```<code>.center { text-align: center; }
.red { color: red; }
</code>```

This is commonly done, but in my opinion it is a very poor practice.  It's only a teeny tiny bit better than just putting all the styles inline.  The only advantage you get is that you can choose a different shade of red.
It's so antithetical to the idea of CSS that it would be a candidate for thedailywtf.com, if only it weren't such a common practice.

Instead of

```<code><div class="warning">Do not cross the streams!</div>
</code>```

You have

```<code><div class="warning red center">...</div>
</code>```

and elsewhere:

```<code><span class="red">...</span>

<div class="center">Some heading or caption or whatever</div>
<div class="warning bold black">A different kind of warning?</div>
</code>```

What are you going to do when your client wants to change all the warnings to black text in a yellow filled box with a black border, floated right?  A task that should take ten minutes instead takes ten hours.

Sure, it's more work now to assign semantic class names to all your content, but doing so makes it very easy to adjust the look of the site in the future. The bigger the web site, the more important it is to do this properly.  If you are familiar with word-processing applications, think about adjusting the subsection headings in a 50-chapter book where no paragraph styles were used.

If you want some "warnings" red, and other "warnings" not red, then you need two separate classes, e.g. "warning" and "serious-warning".

I recommend Transcending CSS: The Fine Art of Web Design by Andy Clarke, Molly E. Holzschlag, Aaron Gustafson and Mark Boulton.  It's a beautiful book, and does a great job of explaining how and why to separate the semantic content from the presentation.

Body:
I work on a massive website that has many disparate pages. We have a default stylesheet that is shared across practically all pages. I find it useful to have CSS rulesets such as these:

.center { text-align: center; }
.red { color: red; }

This is commonly done, but in my opinion it is a very poor practice.  It's only a teeny tiny bit better than just putting all the styles inline.  The only advantage you get is that you can choose a different shade of red.
It's so antithetical to the idea of CSS that it would be a candidate for thedailywtf.com, if only it weren't such a common practice.

Instead of

<div class="warning">Do not cross the streams!</div>

You have

<div class="warning red center">...</div>

and elsewhere:

<span class="red">...</span>

<div class="center">Some heading or caption or whatever</div>
<div class="warning bold black">A different kind of warning?</div>

What are you going to do when your client wants to change all the warnings to black text in a yellow filled box with a black border, floated right?  A task that should take ten minutes instead takes ten hours.

Sure, it's more work now to assign semantic class names to all your content, but doing so makes it very easy to adjust the look of the site in the future. The bigger the web site, the more important it is to do this properly.  If you are familiar with word-processing applications, think about adjusting the subsection headings in a 50-chapter book where no paragraph styles were used.

If you want some "warnings" red, and other "warnings" not red, then you need two separate classes, e.g. "warning" and "serious-warning".

I recommend Transcending CSS: The Fine Art of Web Design by Andy Clarke, Molly E. Holzschlag, Aaron Gustafson and Mark Boulton.  It's a beautiful book, and does a great job of explaining how and why to separate the semantic content from the presentation.