答:
If Options was effectively cloneable (I mean, regardless of Cloneable interface), you could use prototype pattern - have one in builder and clone it in build().

If you don't use Cloneable interface, you would have to copy every field, so it would add another place where you need to add it, so at least for class with simple fields actualy using Cloneable would be good idea.

Title: Improvements to Joshua Bloch's Builder Design Pattern?

Body:
Back in 2007, I read an article about Joshua Blochs take on the "builder pattern" and how it could be modified to improve the overuse of constructors and setters, especially when an object has a large number of properties, most of which are optional. A brief summary of this design pattern is articled here.

I liked the idea, and have been using it since. The problem with it, while it is very clean and nice to use from the client perspective, implementing it can be a pain in the bum! There are so many different places in the object where a single property is reference, and thus creating the object, and adding a new property takes a lot of time.

So...I had an idea. First, an example object in Joshua Bloch's style:

Josh Bloch Style:

```<code>public class OptionsJoshBlochStyle {

    private final String option1;
    private final int option2;
    // ...other options here  <<<<

    public String getOption1() {
        return option1;
    }

    public int getOption2() {
        return option2;
    }

    public static class Builder {

        private String option1;
        private int option2;
        // other options here <<<<<

        public Builder option1(String option1) {
            this.option1 = option1;
            return this;
        }

        public Builder option2(int option2) {
            this.option2 = option2;
            return this;
        }

        public OptionsJoshBlochStyle build() {
            return new OptionsJoshBlochStyle(this);
        }
    }

    private OptionsJoshBlochStyle(Builder builder) {
        this.option1 = builder.option1;
        this.option2 = builder.option2;
        // other options here <<<<<<
    }

    public static void main(String[] args) {
        OptionsJoshBlochStyle optionsVariation1 = new OptionsJoshBlochStyle.Builder().option1("firefox").option2(1).build();
        OptionsJoshBlochStyle optionsVariation2 = new OptionsJoshBlochStyle.Builder().option1("chrome").option2(2).build();
    }
}
</code>```

Now my "improved" version:

```<code>public class Options {

    // note that these are not final
    private String option1;
    private int option2;
    // ...other options here

    public String getOption1() {
        return option1;
    }

    public int getOption2() {
        return option2;
    }

    public static class Builder {

        private final Options options = new Options();

        public Builder option1(String option1) {
            this.options.option1 = option1;
            return this;
        }

        public Builder option2(int option2) {
            this.options.option2 = option2;
            return this;
        }

        public Options build() {
            return options;
        }
    }

    private Options() {
    }

    public static void main(String[] args) {
        Options optionsVariation1 = new Options.Builder().option1("firefox").option2(1).build();
        Options optionsVariation2 = new Options.Builder().option1("chrome").option2(2).build();

    }
}
</code>```

As you can see in my "improved version", there are 2 less places in which we need to add code about any addition properties (or options, in this case)! The only negative that I can see is that the instance variables of the outer class are not able to be final. But, the class is still immutable without this.

Is there really any downside to this improvement in maintainability? There has to be a reason which he repeated the properties within the nested class that I'm not seeing?


问:
Finding co-maintainers for open source projects
I have a number of open-source projects that have gotten some significant usage and would like to find co-maintainers so that I am not a bottleneck when it comes to maintenance and support requests and to get other perspectives on how the project should evolve.

Where should I look for co-maintainers, what should I look for in a co-maintainer, and how should I go about bringing them up to speed on the code and maintainer responsibilities?

答:
Symmetry.

Are you contributing to someone else's projects?

That could be a very good place to find co-developers.

Alternatively, another way to perpetuate a project where I felt like I had made my big contributions might be to fold it into a competing project.

ContentLicense: CC BY-SA 3.0


问:
Git workflow for small teams
I'm working on a git workflow to implement in a small team. The core ideas in the workflow:

There is a shared project master that all team members can write to

All development is done exclusively on feature branches

Feature branches are code reviewed by a team member other than the branch author

The feature branch is eventually merged into the shared master and the cycle starts again

The article explains the steps in this cycle in detail:

https://github.com/janosgyerik/git-workflows-book/blob/small-team-workflow/chapter05.md

Does this make sense or am I missing something?

答:
You can get inspired to gitflow or Twgit.

gitflow summarizes its approach as:

Git extensions to provide high-level repository operations for Vincent
  Driessen's branching model.

Twgit describes itself as follows:

Twgit is a free and open source assisting tools for managing features,
  hotfixes and releases on Git repositories. It provides simple,
  high-level commands to adopt the branching model describes in our
  documentation. Supported OS: Debian/Ubuntu Linux, Mac OS X.

Both tools are available from github.

OwnerDisplayName: janos

Title: Git workflow for small teams


问:
Why some consider static analysis a testing and some do not?
Preparing myself also to ISTQB certification, I found they call static analysis actually as a static testing, while some engineering book distinct between static analysis and testing, which is the dynamic activity. I tent to think that static analysis is not a testing in the true sense as it does not test, it checks/verifies. But sure I would love to hear opinion of the true experts here.
Thank you</p>

答:
In many respects, your question is the corollary of a number of recent discussions, about where the line is drawn.

eg

Is verification and validation part of testing process?

Verfication vs validation again, does testing belong to verification? If so, which?

How to apply verification and validation on the following example

Quite simply, the line depends on which standard, and which lifecycle you are following.

Personally, as an advocate of ISO/IEC 12207, I put Static Code Analysis firmly in the Verification camp, as it is a review activity, whereas Dynamic Analysis is a testing activity, therefore a Validation phase.

As an aside, I had never heard SCA referred to as Static Testing, so I Googled... Wikipedia defines it, pretty much as a synonym of SCA. I prefer to use the terms Static Analysis, and restrict testing to cover the actual execution.

I'm not that familiar with ISTQB so I can't draw the specific line for that certification for you.


问:
Why does an unsigned int compared with a signed character turn out with an unexpected result?
Why does the following code output y>x when clearly 1>-1?

```<code>unsigned x=1;
signed char y=-1;

if(x>y){
    printf("x>y");
}
else {
    printf("y>x");
}
</code>```

Please explain this result.

答: Implicit type conversion is biting you. Because x is unsigned, y is cast to unsigned as well; because -1 doesn't fit in an unsigned char, it overflows and becomes 255 (the bit-wise unsigned char equivalent of -1), which obviously is larger than -1.


问:
Using 'new' in a projection?
I wish to project a collection from one type (Something) to another type (SomethingElse).  Yes, this is a very open-eneded question, but which of the two options below do you prefer?

Creating a new instance using new:

```<code>var result = query.Select(something => new SomethingElse(something));
</code>```

Using a factory:

```<code>var result = query.Select(something => SomethingElse.FromSomething(something));
</code>```

When I think of a projection, I generally think of it as a conversion.  Using new gives me this idea that I'm creating new objects during a conversion, which doesn't feel right.  Semantically, SomethingElse.FromSomething() most definitely fits better.  Although, the second option does require addition code to setup a factory, which could become unnecessarily compulsive.

答:
In .NET Framework, the most frequently used convention is:

```<code>something.ToSomethingElse();
</code>```

Examples:

37.ToString();

new [] { "Hello", "World" }.ToArray();

DateTime.Now.ToBinary();

Guid.Empty.ToByteArray();

etc.

Note that depending on the context, maybe you could simply use Enumerable.Cast:

```<code>var result = query.Cast<SomethingElse>();
</code>```

If you have a good reason to avoid this convention (for example if SomethingElse is a string), then use whatever convention you prefer from the ones you quoted in your question. They are both valid.

Another nice thing in C# is the implicit operator. For example, instead of:

```<code>var element = new XElement(new XName("section"), ...);
</code>```

you simply write:

```<code>var element = new XElement("section"); // Uses implicit conversion from string to XName.
</code>```

Title: Using 'new' in a projection?

Body:
In .NET Framework, the most frequently used convention is:

something.ToSomethingElse();

Examples:

37.ToString();

new [] { "Hello", "World" }.ToArray();

DateTime.Now.ToBinary();

Guid.Empty.ToByteArray();

etc.

Note that depending on the context, maybe you could simply use Enumerable.Cast:

var result = query.Cast<SomethingElse>();

If you have a good reason to avoid this convention (for example if SomethingElse is a string), then use whatever convention you prefer from the ones you quoted in your question. They are both valid.

Another nice thing in C# is the implicit operator. For example, instead of:

var element = new XElement(new XName("section"), ...);

you simply write:

var element = new XElement("section"); // Uses implicit conversion from string to XName.


答:
If you want to change one type to another type but dont want to above code every time .. use automapper .It does these translation and more code reuse can be possible through it.

http://www.automapper.org/

let me know if you need highlight on same.

Title: Using 'new' in a projection?

Body:
I wish to project a collection from one type (Something) to another type (SomethingElse).  Yes, this is a very open-eneded question, but which of the two options below do you prefer?

Creating a new instance using new:

```<code>var result = query.Select(something => new SomethingElse(something));
</code>```

Using a factory:

```<code>var result = query.Select(something => SomethingElse.FromSomething(something));
</code>```

When I think of a projection, I generally think of it as a conversion.  Using new gives me this idea that I'm creating new objects during a conversion, which doesn't feel right.  Semantically, SomethingElse.FromSomething() most definitely fits better.  Although, the second option does require addition code to setup a factory, which could become unnecessarily compulsive.


答: Personally I would either go with the first option if it's only used in one place, or create an extension method if it is used in multiple places.</p>

Title: Using 'new' in a projection?


问:
What diagrams, other than the class diagram and the workflow diagram, are useful for explaining how an application works?
I am working on a small Delphi project, composed of two units. One unit is for the GUI, and the other for data management, file parsing, list iterating and so on.. I've already made a class diagram, and my workflow looks like hell- it's too complex, even for anyone to read. I've considered making a dataflow diagram, but it would be even more complex. A use case diagram wouldn't be of use either. Am I missing some diagram type which could somehow represent the relationship between my two units? </p>

答:
My suggestion would be creating an architecture diagram to illustrate the high level idea of the whole project.

also if class diagram is too complex then break them units and show the interaction of units rather than all classes.


答:
This is a case where hopefully you are getting a compiler warning about the mixing of a signed and unsigned value. It may be even more specific where it talks about an unsigned lvalue and a signed rvalue.

This example underscores the hazards of C and to a lesser extent, C++ (which tends to be a little more strict about type checking, and which offers multiple kinds of casts).  If you want to write good quality C code several things can help:

As a basic precaution, use compiler options to generate the strictest warnings possible.

Very specifically, avoid mixing of signed and unsigned values in comparisons and most calculations. (signed = signed * unsigned OK, signed = signed + unsigned OK, most other mixing, bad).

Use printf(), trace(), or inspection of variables in a debugger to better understand where things go wrong.  If your program included a statement like printf("x=%d, y=%d/n", x, y); you would see that things went bad as -1 was assigned into y.

Study, study, study...  C is a demanding language and you should make yourself as expert as possible on the semantics and side-effects of signed and unsigned comparisons and calculations.  You also need a very high degree of attention to detail about the range of input values to equations, the possible range of equation results, and whether constants can actually fit into the variables to which they are assigned.

When appropriate, use defensive programming techniques like asserts to expose programming problems during development.

Title: Why does an unsigned int compared with a signed character turn out with an unexpected result?

Body:
Why does the following code output y>x when clearly 1>-1?

```<code>unsigned x=1;
signed char y=-1;

if(x>y){
    printf("x>y");
}
else {
    printf("y>x");
}
</code>```

Please explain this result.


问:
Android: Not able to experiment on own?
I have just started learning Android App Development a few days ago, with prior knowledge of C/C++, HTML and CSS.

This is the situation I am facing Repeatedly:

I am learning from a Video Tutorial Series, after each video, or each few videos, I say myself: Let's use what I have just learnt in the simple (and also "meaningless") app that I have made so far by watching the tutorials.

I start implementing it, but then after a few minutes, I realize that I cannot do it because I do not know a few other syntax related to the particular thing, (or) I do not know whether these things can be combined with these other things by the use of . (dot).

Whatever I try, I get either an error in eclipse or "Sorry...the app com.example.simple has stopped unexpectedly...." when the app runs.

Then I search StackOverflow, Google and learn that what I want to implement requires learning about a few more classes, syntax and creating a few more java classes.

I am not able to experiment on my own. Is it normal? Is it the HARD-WAY in which one is supposed to learn?

Should I first learn Java and then come back to Android - would that be helpful?

答:
I am really happy to see that you want to do Android programming, it is advised to learn Java before learning Android. It is something you don't know HTML but want to create a web page.

But on the start you can implement very simple hello world type of example and grasp the concepts before jumping into programming.

"Language does not matter, logic does". keep trying and don't give up on this.

Eclipse is quite powerful to debug and analyze errors. You could post some code errors might someone can give you right guidance.

Title: Android: Not able to experiment on own?


答:
@tdammers answer is correct, let me expand a bit.

The binary representation for negative values assumes the highest bit has value of 1. E.g., all negative 8-bit values look like 1xxx xxxx.

8-bit value for -1 is 1111 1111.

Hence, the very same binary 1111 1111 for unsigned is 255. So, the same binary value can be interpreted two different ways, depending if it is signed or not.

In your case, as @tdammers noticed, your -1 is stored into signed variable, but then implicitly interpreted as unsigned. Of course, 1 < 255, hence the result.

P.S. You should always check compiler warnings. All modern compilers would raise a warning on this matter.


答:
The problem with the second approach is that it requires a named (as opposed to an anonymous) type; otherwise, it would be impossible to pass something to a factory method. A large percentage of non-trivial LINQ queries use anonymous types, for example

```<code>query.Zip(otherQuery, (a, b) => new {First = a, Second = b}).Select(...)
</code>```

or

```<code>query.Select((v,i)=> new {Value=v, Index=i}).Where(...).Select(...)
</code>```

and so on. Having to define a named type for the anonymous type or using a generic Tuple<...> would solve the problem at the expense of readability.

Using new, on the other hand, lets you stay consistent even when you enter the territory of non-trivial LINQ queries. I would definitely recommend staying with new, and avoid making the matters that are already complex even more complex for no good reason.

Title: Using 'new' in a projection?

Body:
The problem with the second approach is that it requires a named (as opposed to an anonymous) type; otherwise, it would be impossible to pass something to a factory method. A large percentage of non-trivial LINQ queries use anonymous types, for example

query.Zip(otherQuery, (a, b) => new {First = a, Second = b}).Select(...)

or

query.Select((v,i)=> new {Value=v, Index=i}).Where(...).Select(...)

and so on. Having to define a named type for the anonymous type or using a generic Tuple<...> would solve the problem at the expense of readability.

Using new, on the other hand, lets you stay consistent even when you enter the territory of non-trivial LINQ queries. I would definitely recommend staying with new, and avoid making the matters that are already complex even more complex for no good reason.


答:
If you want to show static relationships between your components, then UML Component Diagram should help you. If you want to show interactions between these components, then try to use UML Sequence Diagram. You should also remember about staying at the same level of abstraction, e.g. don't go into details (like pressing checkbox), when you're trying to describe the system on the component level ("gui" vs "other" unit). Your workflow diagram doesn't have much sense right now, as it should focus on a specific scenario (e.g. loading a report) rather than trying to show all possible scenarios on a single diagram.

Also I think that you have more serious problem underneath, as you "other unit" is just doing too much work, and is clearly breaking the Single Responsibility Principle. You could think about splitting the "other unit" into more components, each of them taking just a specific responsibility (e.g. parsing files, generating reports, sorting reports).

Title: What diagrams, other than the class diagram and the workflow diagram, are useful for explaining how an application works?

Body: I am working on a small Delphi project, composed of two units. One unit is for the GUI, and the other for data management, file parsing, list iterating and so on.. I've already made a class diagram, and my workflow looks like hell- it's too complex, even for anyone to read. I've considered making a dataflow diagram, but it would be even more complex. A use case diagram wouldn't be of use either. Am I missing some diagram type which could somehow represent the relationship between my two units? </p>


答:
I agree, I do not view static analysis as testing. Static analysis is more powerful than testing because it is a formal proof that a certain piece of code matches its specifications. Therefore, it guarantees that a piece of code does what it should do, for all inputs. In other words, it can guarantee the absence of errors.

Testing, on the other hand, is done on a limited number of different inputs. Therefore, it can only indicate the presence of errors, not their absence. This is the biggest difference between static analysis and testing.

However, static analysis is very difficult, time-consuming and fundamentally impossible to perform for all programs due to the incompleteness of first-order logic.

Title: Why some consider static analysis a testing and some do not?

Body:
Preparing myself also to ISTQB certification, I found they call static analysis actually as a static testing, while some engineering book distinct between static analysis and testing, which is the dynamic activity. I tent to think that static analysis is not a testing in the true sense as it does not test, it checks/verifies. But sure I would love to hear opinion of the true experts here.
Thank you</p>


答:
Classic UML Diagram References

Two great references for UML and its many diagram types include Martin Fowler's UML Distilled in which each diagram is described in much the same way as you might expect a pattern to be described (it is named, described, the forces on it are enumerated, and the applicability is identified).  A more comprehensive reference is Grady Booch (et. all) in Object Oriented Analysis and Design with Applications.

Nested State Diagrams

You mention that your workflow looks like hell, and often the art of doing a good diagram is its level of detail.  The Booch reference has great material about nested state machines that knocked my socks off when I read it.  A state diagram can have a boat load of states and transitions, but by using their nested representation a lot of transitions that can happen from any state can be represented in an outer diagram and the transitions that are most specific to a locality of a few states can be represented by an inner diagram.

Activity Diagrams

Workflow might lend itself to being shown in an activity diagram.  Activity diagrams are superior to flow chart in several ways, but can represent some similar things like decisions and iteration.  One thing I like about them is that they show parallel activities, and sometimes represent the division of labor in the system using partitions or as they are more commonly called, swim lanes.  They can also represent synchronization with a synchronization bar that has one arc coming in and multiple arcs going out (fork) and multiple arcs coming in and a single arc going out (join).  Like state machines, UML also permits activity diagrams to be nested to better structure and to limit the level of detail.

Data Flow Diagrams

If you don't mind a blast from the past, one diagram from structured diagram that UML rejected but for which I believe UML has not given a fully satisfying replacement is the data flow diagram (DFD).  This type of diagram is beautifully simple in its use of four symbols to show a process, data store, data flow, and external entities.  External entities are show at the right and left sides of the diagram to show who or what provides inputs and outputs to the system, the data is labelled as it is passed from one data transforming process to another.  If data is sourced from or produced for storage, that too is shown, typically with the data stores located below the processes that consume/produce them.

Using Diagrams to Design Better

Many other diagrams are available.  Your favorite diagram editor might expand or limit your choices.  Ideally, diagrams should help you improve the consistency and completeness of your designs.  A complex hard to draw diagram might be telling you that your design is too complex, and may even show you some relationships that you can make simpler.


问:
How to do lazy loading in a SOA fashion?
For example, I've got a root object exposed in a SOA service, say Invoice (Invoice has line items as children).

Sometimes, I need to retrieve its detail line items. I'm thinking to make it lazy loading, because it's a traffic overhead to transfer line items every time Invoice is required. But in SOA fashion, it seems unlikely. Because all it can expose are Invoice POCOs, with contain no logic. Thus I cannot attach my lazy loading logic to Invoice to instruct it to load lines items when needed.

答:
What I would do is to implement a client library that interacts with that service and then use some proxy to provide lazy loading.

For example, your service could return Invoice POCOs and InvoiceLine POCOs in two separate calls.
Now, as the user/caller/client of that service, you can have your own client library that facilitates interacting with the service from your application code. In that client library you could have an Invoice class with a proxy method get_lines() that would call again to the service, get the InvoiceLine POCOs and return those (or some more functional InvoiceLine objects)

Update:
Obviously, you cannot guarantee that all systems calling your service will use that same client, so the Service should not rely or depend on having that specific client library doing the calls.
But for your own application, for your own client purposes, you can have whatever client functionality you want (just like many existing classes wrapping Google Analytics APIs, etc)


问:
Why does DirectX use a left-handed coordinate system?
I considered posting on Stack Overflow, but the question strikes me as being far too subjective since I can't think of a reasonable technical explanation for Microsoft's choice in this matter. But this question has bugged me for so long and the issue keeps coming up in one of my projects, and I have never actually seen an attempt at explaining this:

OpenGL uses a right-handed coordinate system, where the +Z part of the world coordinate system extends toward the viewer.

DirectX uses a left-handed system where the +Z part of the world coordinate extends into the screen, away from the viewer.

I never used the Glide API, so I don't know how it worked, but from what I can gather, it uses a left-handed system as well.

Is there a technical reason for this? And if not, is there some conceptual advantage to a particular handedness of a coordinate system? Why would one choose one over the other?

答:
They are both essentially equivalent, as one can be easily transformed into the other.  The only advantage I can find for the left-handed system is: as objects are farther away from the observer, in any direction (x, y, or z), the distance is a higher value. But I have no idea if this is why Microsoft chose one over the other.

POV-Ray also uses a left-handed corridnate system.

ContentLicense: CC BY-SA 2.5


问:
Pythonic use of the isinstance function?
Whenever I find myself wanting to use the isinstance() function I usually know that I'm doing something wrong and end up changing my ways.  However, in this case I think I have a valid use for it.  I will use shapes to illustrate my point although I am not actually working with shapes.  I am parsing XML configuration files that look like the following:

```<code><square>
  <width>7</width>
</square>
<rectangle>
  <width>5</width>
  <height>7</height>
</rectangle>
<circle>
  <radius>4</radius>
</circle>
</code>```

For each element I create an instance of the Shape class and build up a list of Shape objects in a class called the ShapeContainer.  Different parts of the rest of my application need to refer to the ShapeContainer to get certain shapes.  Depending on what the code is doing it might need just rectangles, or it might operate on all quadrangles, or it might operate on all shapes.  I have created the following function in the ShapeContainer class (the actual function uses a list comprehension but I have expanded it here for readability):

```<code>def locate(self, shapeClass):
  result = []
  for shape in self.__shapes:
    if isinstance(shape,shapeClass):
      result.append(shape)
  return result
</code>```

Is this a valid use of the isinstance function?  Is there another way I can do this which might be more pythonic?

答:
Use polymorphism and duck-typing before isinstance()

You generally define what you want to do with the shapes, then either use polymorphism to adjust how each shape responds to what you want to do, or you use duck typing; test if the shape at hand can do the thing you want to do in the first place. This is the invocation versus introspection trade-off, conventional wisdom states that invocation is preferable over introspection, but in Python, duck-typing is preferred over isinstance testing.

So you need to work out why you need to filter on class in the first place; why do you need to find all the rectangles? Perhaps they are the only type that implements a certain method, in which case you use duck typing to test for that method instead.

Or perhaps you need to process each type in a different way, because each type has to be handled just right for whatever you are doing with them. In that case, you need to give each shape the same method, but implement it differently for each type, placing the responsibility for adaptation in each object.

ABCs

With duck-typing, you may find that you have to test for multiple methods, and thus a isinstance() test may look a better option. In such cases, using a Abstract Base Class (ABC) could also be an option; using an ABC let's you 'paint' several different classes as being the right type for a given operation, for example. Using a ABC let's you focus on the tasks that need to be performed rather than the specific implementations used; you can have a Paintable ABC, a Printable ABC, etc.

Zope interfaces and component architecture

If you find your application is using an awful lot of ABCs or you keep having to add polymorphic methods to your classes to deal with various different situations, the next step is to consider using a full-blown component architecture, such as the Zope Component Architecture (ZCA).

zope.interface interfaces are ABCs on steroids, especially when combined with the ZCA adapters. Interfaces document expected behaviour of a class:

```<code>if IRectangleShape.providedBy(yourshape):
    # it's a rectangle
</code>```

but it also let's you look up adapters; instead of putting all the behaviours for every use of shapes in your shape classes, you implement adapters to provide polymorphic behaviours for specific use-cases. You can adapt your shapes to be printable, or paintable, or exportable to XML:

```<code>class RectangleXMLExport(object):
    adapts(IRectangleShape)
    provides(IXMLExport)

    def __init__(self, rectangle):
        self.rectangle = rectangle

    def export(self):
        return u'<rectangle><width>{0}</width><height>{0}</height></rectangle>'.format(
            self.rectangle.width, self.rectangle.height)
</code>```

and your code merely has to look up adapters for each shape:

```<code>for shape in shapebag:
    self.result.append(IXMLExport(shape).export())
</code>```

Body:
Use polymorphism and duck-typing before isinstance()

You generally define what you want to do with the shapes, then either use polymorphism to adjust how each shape responds to what you want to do, or you use duck typing; test if the shape at hand can do the thing you want to do in the first place. This is the invocation versus introspection trade-off, conventional wisdom states that invocation is preferable over introspection, but in Python, duck-typing is preferred over isinstance testing.

So you need to work out why you need to filter on class in the first place; why do you need to find all the rectangles? Perhaps they are the only type that implements a certain method, in which case you use duck typing to test for that method instead.

Or perhaps you need to process each type in a different way, because each type has to be handled just right for whatever you are doing with them. In that case, you need to give each shape the same method, but implement it differently for each type, placing the responsibility for adaptation in each object.

ABCs

With duck-typing, you may find that you have to test for multiple methods, and thus a isinstance() test may look a better option. In such cases, using a Abstract Base Class (ABC) could also be an option; using an ABC let's you 'paint' several different classes as being the right type for a given operation, for example. Using a ABC let's you focus on the tasks that need to be performed rather than the specific implementations used; you can have a Paintable ABC, a Printable ABC, etc.

Zope interfaces and component architecture

If you find your application is using an awful lot of ABCs or you keep having to add polymorphic methods to your classes to deal with various different situations, the next step is to consider using a full-blown component architecture, such as the Zope Component Architecture (ZCA).

zope.interface interfaces are ABCs on steroids, especially when combined with the ZCA adapters. Interfaces document expected behaviour of a class:

if IRectangleShape.providedBy(yourshape):
    # it's a rectangle

but it also let's you look up adapters; instead of putting all the behaviours for every use of shapes in your shape classes, you implement adapters to provide polymorphic behaviours for specific use-cases. You can adapt your shapes to be printable, or paintable, or exportable to XML:

class RectangleXMLExport(object):
    adapts(IRectangleShape)
    provides(IXMLExport)

    def __init__(self, rectangle):
        self.rectangle = rectangle

    def export(self):
        return u'<rectangle><width>{0}</width><height>{0}</height></rectangle>'.format(
            self.rectangle.width, self.rectangle.height)

and your code merely has to look up adapters for each shape:

for shape in shapebag:
    self.result.append(IXMLExport(shape).export())


问:
Windows Phone 8 development on Windows 7 - is it or will be possible?
I was trying to install Windows Phone 8 SDK on my Windows 7 machine and it hit me with the 'supported only on Windows 8' message. I actually wanted to develop Phone 7.5 apps on Visual Studio 2012, impossible thing with the 7.1 SDK, so I thought 8 SDK will do the job.

As if it was not enough that the 8 SDK was controversial upon release, now that it's generally available, to me it seems like a horrible decision to make it available only for Windows 8, because in my humble opinion, no serious and sane developer will install Windows 8 ever, or at least in the near future, just because of the Metro UI.

So, anyone knows any workarounds for developing Windows Phone 8 on Windows 7, or at least develop for 7.5 but using Visual Studio 2012?

答:
Nope, it's all Windows 8 unfortunately. A reason is the hypervisor in Windows 8 is used to emulate or virtualise Windows phone 8 machines. That and marketing of course.

Edit:

AS for developers using Windows 8, I use it on all my laptops now and like it. I run Visual Studio 2010 and 2012 under it with no issues.


答:
Certainly you want to reduce the number of round trips.  That's a realistic requirement of any SOA.  That means you probably have many use cases you want to code for:

```<code>interface IInvoice
{
    Guid InvoiceId { get; }
    string InvoiceNumber { get; }
    string CustomerName { get; }
    decimal TotalPrice { get; }
}
public IEnumerable<IInvoiceSummary> FindInvoices(IInvoiceCriteria criteria);

interface IInvoiceSummary : IInvoice
{
    int NumberOfLineItems { get; }
}

public IDetailedInvoice GetInvoice(Guid invoiceId);

interface IDetailedInvoice : IInvoice
{
    ReadOnlyCollection<IInvoiceLineItem> LineItems { get; }
}
</code>```

Of course if you have different use cases, you may want to change those.  Perhaps you want to get unpaid invoices for a customer, but in detailed format, so maybe you have another service point that returns that special case.

So, I recommend not building lazy loading into your SOA architecture.  Since lazy loading hides the number of round trips to the database, and round trips are something the programmer should always be paying attention to because they're expensive, then you shouldn't hide them.

Title: How to do lazy loading in a SOA fashion?

Body:
For example, I've got a root object exposed in a SOA service, say Invoice (Invoice has line items as children).

Sometimes, I need to retrieve its detail line items. I'm thinking to make it lazy loading, because it's a traffic overhead to transfer line items every time Invoice is required. But in SOA fashion, it seems unlikely. Because all it can expose are Invoice POCOs, with contain no logic. Thus I cannot attach my lazy loading logic to Invoice to instruct it to load lines items when needed.

Body:
Certainly you want to reduce the number of round trips.  That's a realistic requirement of any SOA.  That means you probably have many use cases you want to code for:

interface IInvoice
{
    Guid InvoiceId { get; }
    string InvoiceNumber { get; }
    string CustomerName { get; }
    decimal TotalPrice { get; }
}
public IEnumerable<IInvoiceSummary> FindInvoices(IInvoiceCriteria criteria);

interface IInvoiceSummary : IInvoice
{
    int NumberOfLineItems { get; }
}

public IDetailedInvoice GetInvoice(Guid invoiceId);

interface IDetailedInvoice : IInvoice
{
    ReadOnlyCollection<IInvoiceLineItem> LineItems { get; }
}

Of course if you have different use cases, you may want to change those.  Perhaps you want to get unpaid invoices for a customer, but in detailed format, so maybe you have another service point that returns that special case.

So, I recommend not building lazy loading into your SOA architecture.  Since lazy loading hides the number of round trips to the database, and round trips are something the programmer should always be paying attention to because they're expensive, then you shouldn't hide them.


问:
Is there an API for determining congressional districts?
I'm looking to determine the congressional district based on an address my user is providing. This will avoid having the user to look it up themselves.

Does an API of this sort exist?

Note

Through my attempts to find one, I've only come across these:

http://www.govtrack.us/developers/api

(not sure how to submit an an address or zip code however)

The following resources are available in the API

...Bills and resolutions in the U.S. Congress since 1973 (the 93rd Congress).

...A (bill, person) pair indicating cosponsorship, with join and withdrawn dates.

...Members of Congress and U.S. Presidents since the founding of the nation.

...Terms held in office by Members of Congress and U.S. Presidents. Each term corresponds with an election, meaning each term in the House covers two years (one 'Congress'), as President four years, and in the Senate six years (three 'Congresses').

...Roll call votes in the U.S. Congress since 1789. How people voted is accessed through the Vote_voter API.

...How people voted on roll call votes in the U.S. Congress since 1789. See the Vote API. Filter on the vote field to get the results of a particular vote...

http://www.opencongress.org/api

(seems to be a way to find congress information, but not districts)

This API provides programmers with structured access to all the data on OpenCongress, everything from official bill info to news and blog coverage to user-generated votes on bills and much more...

This API defaults to returning XML. All queries can also return JSON...

https://groups.google.com/forum/?fromgroups=#!topic/opendems-discuss/CeKyi_aANaE

(similar question, no resolution)

I've been looking over Open Dems, and seeing what's exposed at this
  point and what isn't.  I work with Democrats Abroad, and am interested
  in using stuff from the lab for their sites.

I quickly looked over the Precinct API, which does both more and less
  than what I'd need.  An ideal resource would be any way of translating
  addresses into CD at the very least (getting state district data would
  be good as well), since that would make it easier for DA's membership
  to make a difference in races like last month's NY26 race...

Update

I'm looking at the source for the govtrack.us website and the 'doGeoCode' function may be useful.

view-source:http://www.govtrack.us/congress/members

If no one has any suggestions, I will try to go off of what they are doing.

答:
Melissa Data makes tools for address verification that includes information on political districts.  I do not know if they have a public api; the link above will take you to an address look up page.  They offer a limited number of free look ups that can be increased with a subscription.  Please check their terms of use before putting this into a production application.

While their data is updated monthly, I have noticed that some of it does not reflect recent redistricting.

Many states have this information available, but I doubt that there is any consistency in their implementation.


答: I haven't used it, but a quick search brought me to Congress API from Sunlight Labs. Check out their districts.getDistrictsFromZip method -- it seems to be what you're looking for. You might get better (more accurate) results geocoding the address yourself and then using districts.getDistrictFromLatLong -- I'd assume that a given zip code could cross district boundaries.</p>

Title: Is there an API for determining congressional districts?

Body:
I'm looking to determine the congressional district based on an address my user is providing. This will avoid having the user to look it up themselves.

Does an API of this sort exist?

Note

Through my attempts to find one, I've only come across these:

http://www.govtrack.us/developers/api

(not sure how to submit an an address or zip code however)

The following resources are available in the API

...Bills and resolutions in the U.S. Congress since 1973 (the 93rd Congress).

...A (bill, person) pair indicating cosponsorship, with join and withdrawn dates.

...Members of Congress and U.S. Presidents since the founding of the nation.

...Terms held in office by Members of Congress and U.S. Presidents. Each term corresponds with an election, meaning each term in the House covers two years (one 'Congress'), as President four years, and in the Senate six years (three 'Congresses').

...Roll call votes in the U.S. Congress since 1789. How people voted is accessed through the Vote_voter API.

...How people voted on roll call votes in the U.S. Congress since 1789. See the Vote API. Filter on the vote field to get the results of a particular vote...

http://www.opencongress.org/api

(seems to be a way to find congress information, but not districts)

This API provides programmers with structured access to all the data on OpenCongress, everything from official bill info to news and blog coverage to user-generated votes on bills and much more...

This API defaults to returning XML. All queries can also return JSON...

https://groups.google.com/forum/?fromgroups=#!topic/opendems-discuss/CeKyi_aANaE

(similar question, no resolution)

I've been looking over Open Dems, and seeing what's exposed at this
  point and what isn't.  I work with Democrats Abroad, and am interested
  in using stuff from the lab for their sites.

I quickly looked over the Precinct API, which does both more and less
  than what I'd need.  An ideal resource would be any way of translating
  addresses into CD at the very least (getting state district data would
  be good as well), since that would make it easier for DA's membership
  to make a difference in races like last month's NY26 race...

Update

I'm looking at the source for the govtrack.us website and the 'doGeoCode' function may be useful.

view-source:http://www.govtrack.us/congress/members

If no one has any suggestions, I will try to go off of what they are doing.


问:
Do people in non-English-speaking countries code in English?
I've heard it said (by coworkers) that everyone "codes in English" regardless of where they're from. I find that difficult to believe, however I wouldn't be surprised if, for most programming languages, the supported character set is relatively narrow.

Have you ever worked in a country where English is not the primary language?

If so, what did their code look like?

答:
I am English and have lived and worked in Germany. I nearly always use English unless I can't think what the English term for something is. Then I use a German word.

I have met one or two who insist on only using English ('because it is better') but then spell things incorrectly which can be very bothersome when it makes its way into the API. There have been some compile-issues when using accents (for example, 'Müller') in source code. These have been forbidden.

Team discussion is exclusively in German. Coding is mixed. Most tend towards German names for variables and methods, etc. but will use English when it suits them. What ticks me off is when the English spelling is wrong.


问:
Has the emerging generation of programmers got the wrong idea about design patterns?
Over the years I've noticed a shift in attitude towards design patterns, particularly amongst the emerging generation of developers.

There seems to be a notion these days that design patterns are silver bullets that instantly cure any problem, a proliferating idea that advancing as a software engineer simply means learning and applying more and more patterns. When confronted with a problem, developers no longer strive to truly understand the issue and design a solution - instead they simply pick a design pattern which seems to be a close fit, and try to brute-force it.

You can see evidence of this by the many, many questions on Stack Overflow that begin with the phrase "what pattern should I use to...".

I fall into a slightly more mature category of developers (5-10 years experience) and I have a very different viewpoint on patterns - simply as a communication tool to enhance clarity. I find this perspective of design patterns being lego bricks (collected like pokemon cards) a little disconcerting.

Will developers lose this attitude as they gain more experience in software engineering? Or could these notions perhaps steer the direction of our craft in years to come?

Did the older generation of developers have any similar concerns about us? (perhaps about OO design or similar...). if so, how did we turn out?

答:
Things are better now because they can ask and we can correct. </p>

<p>There was a time maybe ten years ago where patterns were being discussed in the popular press. The story went that in a few years you wouldn't need programmers, you'd have one architect who would coordinate the work of 50 students (All off-shore) trained in the basic patterns. </p>

Body:
Things are better now because they can ask and we can correct.

There was a time maybe ten years ago where patterns were being discussed in the popular press. The story went that in a few years you wouldn't need programmers, you'd have one architect who would coordinate the work of 50 students (All off-shore) trained in the basic patterns.


问:
What to do when TDD tests reveal new functionality that is needed that also needs tests?
What do you do when you are writing a test and you get to the point where you need to make the test pass and you realize that you need an additional piece of functionality that should be separated into its own function?  That new function needs to be tested as well, but the TDD cycle says to Make a test fail, make it pass then refactor.  If I am on the step where I am trying to make my test pass I'm not supposed to go off and start another failing test to test the new functionality that I need to implement.

For example, I am writing a point class that has a function WillCollideWith(LineSegment):

```<code>public class Point {
    // Point data and constructor ...

    public bool CollidesWithLine(LineSegment lineSegment) {
        Vector PointEndOfMovement = new Vector(Position.X + Velocity.X,
                                               Position.Y + Velocity.Y);
        LineSegment pointPath = new LineSegment(Position, PointEndOfMovement);
        if (lineSegment.Intersects(pointPath)) return true;
        return false;
    }
}
</code>```

I was writing a test for CollidesWithLine when I realized that I would need a LineSegment.Intersects(LineSegment) function.  But, should I just stop what I am doing on my test cycle to go create this new functionality?  That seems to break the "Red, Green, Refactor" principle.

Should I just write the code that detects that lineSegments Intersect inside of the CollidesWithLine function and refactor it after it is working?  That would work in this case since I can access the data from LineSegment, but what about in cases where that kind of data is private?

答: The easiest thing to do in a TDD fashion would be to extract an interface for LineSegment and change your method parameter to take in the interface.  Then you could mock the input line segment and code/test the Intersect method independently.</p>


答: Just comment out your test and recent code (or put into a stash) so you have in fact turned back the clock to the start of the cycle.  Then start with the LineSegment.Intersects(LineSegment) test/code/refactor.  When that's done, uncomment your previous test/code (or pull from stash) and keep with the cycle.

Title: What to do when TDD tests reveal new functionality that is needed that also needs tests?

Body:
What do you do when you are writing a test and you get to the point where you need to make the test pass and you realize that you need an additional piece of functionality that should be separated into its own function?  That new function needs to be tested as well, but the TDD cycle says to Make a test fail, make it pass then refactor.  If I am on the step where I am trying to make my test pass I'm not supposed to go off and start another failing test to test the new functionality that I need to implement.

For example, I am writing a point class that has a function WillCollideWith(LineSegment):

```<code>public class Point {
    // Point data and constructor ...

    public bool CollidesWithLine(LineSegment lineSegment) {
        Vector PointEndOfMovement = new Vector(Position.X + Velocity.X,
                                               Position.Y + Velocity.Y);
        LineSegment pointPath = new LineSegment(Position, PointEndOfMovement);
        if (lineSegment.Intersects(pointPath)) return true;
        return false;
    }
}
</code>```

I was writing a test for CollidesWithLine when I realized that I would need a LineSegment.Intersects(LineSegment) function.  But, should I just stop what I am doing on my test cycle to go create this new functionality?  That seems to break the "Red, Green, Refactor" principle.

Should I just write the code that detects that lineSegments Intersect inside of the CollidesWithLine function and refactor it after it is working?  That would work in this case since I can access the data from LineSegment, but what about in cases where that kind of data is private?


答: I would highly recommend spending some time studying Java before jumping into the fray of Android development, as it adds a whole layor or two of complexity on top of the language. I am fairly new to both Android and Java, but Java in a Nutshell really helped get to grips with the Java part of Android development. This book is really great in explaining the basics(the first few chapters) and differences to C++.</p>

Title: Android: Not able to experiment on own?

Body:
I have just started learning Android App Development a few days ago, with prior knowledge of C/C++, HTML and CSS.

This is the situation I am facing Repeatedly:

I am learning from a Video Tutorial Series, after each video, or each few videos, I say myself: Let's use what I have just learnt in the simple (and also "meaningless") app that I have made so far by watching the tutorials.

I start implementing it, but then after a few minutes, I realize that I cannot do it because I do not know a few other syntax related to the particular thing, (or) I do not know whether these things can be combined with these other things by the use of . (dot).

Whatever I try, I get either an error in eclipse or "Sorry...the app com.example.simple has stopped unexpectedly...." when the app runs.

Then I search StackOverflow, Google and learn that what I want to implement requires learning about a few more classes, syntax and creating a few more java classes.

I am not able to experiment on my own. Is it normal? Is it the HARD-WAY in which one is supposed to learn?

Should I first learn Java and then come back to Android - would that be helpful?


问:
Code maintenance: To add comments in code or to just leave it to the version control?
We have been asked to add comments with start tags, end tags, description, solution etc for each change that we make to the code as part of fixing a bug / implementing a CR.

My concern is, does this provide any added value? As it is, we have all the details in the Version control history, which will help us to track each and every change?

But my leads are insisting on having the comments as a "good" programming practice. One of their argument is when a CR has to be de-scoped/changed, it would be cumbersome if comments are not there.

Considering that the changes would be largely in between code, would it really help to add comments for each and every change we make? Shouldn't we leave it to the version control?

答:
Comments in the code are about what the code is at that moment.  Taking a snapshot at any given time shouldn't refer to old (or worse, future) versions of the code.

Comments in VCS are about how the code has changed.  They should read as a story about development.

Now, every change should include comments?  in most cases, yes.  The only exception I imagine is when the expected behaviour was already documented but wasn't what you got, because of a bug.  Fixing it makes the existing comments more precise, so they don't have to be changed.  The bug itself should be documented in the ticket history and the commit comment, but only in the code if the code looks strange.  In that case, a // make sure <bad thing> doesn't happen should be enough.


答: Your leads are right when they say that comments are a good programming practice, however there are exceptions. Adding a comment for every change that you make is one of them. And you are right by saying that this should belong to the version control system. If you have to keep these comments in a single place, then the VCS is the way to go. Comments in source code tend to grow old and unmaintained. No comments are a lot better than bad comments. What you don't want is having comments in both places (in the code and VCS) that are out of sync. The goal is to keep things DRY by having a single source of truth for changes to the code.</p>

Title: Code maintenance: To add comments in code or to just leave it to the version control?

Body:
We have been asked to add comments with start tags, end tags, description, solution etc for each change that we make to the code as part of fixing a bug / implementing a CR.

My concern is, does this provide any added value? As it is, we have all the details in the Version control history, which will help us to track each and every change?

But my leads are insisting on having the comments as a "good" programming practice. One of their argument is when a CR has to be de-scoped/changed, it would be cumbersome if comments are not there.

Considering that the changes would be largely in between code, would it really help to add comments for each and every change we make? Shouldn't we leave it to the version control?


答:
Use the best tool for the job.  Your version control system should be the best tool for recording when bugfixes and CRs are made: it automatically records the date and who made the change; it never forgets to add a message (if you've configured it to require commit messages); it never annotates the wrong line of code or accidentally deletes a comment.  And if your version control system is already doing a better job than your comments, it's silly to duplicate work by adding comments.

Readability of source code is paramount. A codebase that's cluttered with comments giving the full history of every bugfix and CR made is going to not be very readable at all.

But don't skip comments completely:  Good comments (not slavishly documenting every start / stop / description / solution of every bugfix and CR) enhance the readability of the code.  For example, for a tricky or unclear bit of code that you add to fix a bug, a comment of the form // fix ISSUE#413 telling people where to find more information in your issue tracker is an excellent idea.


问:
Ideal "intermediate" file format to use for structured/styled text?
I have files that I want to make available in an variety of formats:

HTML

PDF

EPUB

Plain Text (maybe)

Most of the files will be sourced in doc, docx, or rtf format, so that needs to be considered.

So I need some kind of format that converts well from docx, doc, and rtf and has plenty of libraries for converting into PDF, EPUB, HTML etc. Ideally libraries in Python, but Java is also okay.

答:
When searching for the intermediate format, there is always a problem with presentational vs. structural markup problem.

Typically, DocBook or LaTeX sources use the clear structural markup with usually few exceptions (misuses) caused by the author.

On the other hand, Word users tend to use mainly the presentational markup (explicitly telling the block of text the font size, font family, weight, ...). Word allows the structural markup, but it is not forced too much.

Plain HTML is clearly structural, but the span and the like element allow to attach a lot of attributes to the block of text in the non-structural manner. You can clearly see the difference between the manually created HTML, technically generated HTML, and the documents converted from Word docs. Therefore, it may be difficult to find a common denominator even for HTML documents. The XML adds even more possibilities that can be misused.

But if you want to have one format that covers everything, then it probably should be XML. However, it may be one with document type designed by you for the purpose. The good thing is that there are tools for verification of your intermediate XML document. This way, you can be later sure that there is a way to the final form.

My guess is that it is almost impossible to convert various sources to the intermediate format with the good quality. It depends a lot on who created the souces. It is likely you will have to write a lot of parser for special subsets of the documents.

Python is probably a good choice. It depends on your knowledge. If you are better in Java or Perl, they can be better. I would prefer Python. (I do not have a good working knowlege of Java, and my Perl knowledge is rusty because I have found Python much better for me.)


问:
One codebase - lots of hosted services (similar to a basecamp style service) - planning structure
We have built a service (PHP Based) for a client, and are now looking to offer it to other clients as a hosted service. For this example, think of it like a hosted forum service, where a client signs up on our site, and is given a subdomain or can use their own domain, and the code picks up the domain, checks it against a 'master' users table, and then loads the content as needed.

I'm trying to work out the best way of handling multiple clients.

At the moment I can only think of two options that would work:

Option 1 - Have 1 set of database tables, but on each table have a column called 'siteid' - this would mean every query has to check the siteid. This would effectively work with just 1 codebase, and 1 database.

Option 2 - Have 1 'master' database with all the core stuff such as the client details and their domain. Then when the systen checks the domain, it pulls the clients database details (username/password/dbname) from a table, and loads a second database. The issue here is security of the mysql server details, however it does have the benefit that they are running their own database instead of sharing one.

Which option would I be better taking here, and why? Ideally I want it to be fairly easy to convert the 'standalone' script to the 'multi-domain' script as we're on a tight deadline.

答:
Option #1 is generally the best option in terms of maintenance.  You make changes once, and its immediately applied to all customers.  I believe the term for this is 'multi tenant'.  The one PHP application I maintain has a couple thousand customer accounts across a number of 'private label' sites all in a single db, and has been running for almost a decade now.

Keep in mind, you dont need to add a 'site id' to every table.  Generally you'd only need to keep track of that in a few tables.  For example, if you have a users table, and an addresses table that links back to it, you dont need the site id in the addresses table since you'd probably have the site id in the users table.

We dont actually work by 'site', but rather, customer account - the same user works across all virtual 'sites'.  But the principle is the same.

There are times when this may not be the most practical - it depends on how much customization is expected.  If customers are expecting drastic changes specific to them, at that point it might be better to keep everything separate.

There's also Option #3, which is simply to have config files specific to an individual site, and have that point to a different database.  This way you remove the need for a shared 'master' db.  If I felt the need to split a system up into multiple db's, this is probably the approach I'd take so as to keep things a bit less complicated by removing the need for a 'master' db.


问:
CSS naming guildlines with elements with multiple classes
Its seems like there are 2 ways someone can handle naming classes for elements that are designed to have multiple classes.  One way would be:

```<code><span class="btn btn-success"></span>
</code>```

This is something that twitter bootstrap uses.  Another possibility I would think would be:

```<code><span class="btn success"></span>
</code>```

It seems like the zurb foundation uses this method.

Now the benefits of the first that I can see is that there less chance of outside css interfering with styling as the class name btn-success would not be as common as the class name success.  The benefit of the second as I can see is that there is less typing and potential better style reuse.

Are there any other benefits/disadvantages of either option and is one of them more popular than the other?

答:
Success can, and is, being used multiple times for multiple applications. You can have a button success but also a label for example. It is just too generic. Next to that it is clear that it can be applied to a btn without explanation. So it is also more clear. Otherwise you would need some smart trick to see what additional classes could be applied, now all classes with a prefix apply to the main class element.

Also this is a quite relevant question about the use of 2 classes instead of one:
https://stackoverflow.com/questions/10501544/why-does-twitter-bootstrap-require-multiple-classes-for-buttons


答:
You are absolutely right.  Tracking changes is the job for your version control system.  Every time you do a commit you should write a commit message explaining what was done, and referencing your bug-tracking system if this is a bug fix.  Putting a comment in the code saying

```<code>// begin fix for bug XXXXX on 10/9/2012
...
// end fix for bug XXXXX
</code>```

every time you fix a bug will quickly render your code unreadable and unmaintainable.  It will also result in duplicating the same information in two places, which will make the mess even worse.

Comments should not be used for bug tracking and they also should not describe what your code is doing. They should explain why you are doing X, or why you are doing X in this particular way.  If you feel the need to write a comment explaining what a block of code is doing, that is a code smell which indicates that you should refactor this block into a function with a descriptive name.

So instead of

```<code>// fixed bug XXXXX on 10/9/2012
</code>```

you might have a comment that says

```<code>// doing X, because otherwise Y will break.
</code>```

or

```<code>// doing X, because doing Y is 10 times slower.
</code>```

Body:
You are absolutely right.  Tracking changes is the job for your version control system.  Every time you do a commit you should write a commit message explaining what was done, and referencing your bug-tracking system if this is a bug fix.  Putting a comment in the code saying

// begin fix for bug XXXXX on 10/9/2012
...
// end fix for bug XXXXX

every time you fix a bug will quickly render your code unreadable and unmaintainable.  It will also result in duplicating the same information in two places, which will make the mess even worse.

Comments should not be used for bug tracking and they also should not describe what your code is doing. They should explain why you are doing X, or why you are doing X in this particular way.  If you feel the need to write a comment explaining what a block of code is doing, that is a code smell which indicates that you should refactor this block into a function with a descriptive name.

So instead of

// fixed bug XXXXX on 10/9/2012

you might have a comment that says

// doing X, because otherwise Y will break.

or

// doing X, because doing Y is 10 times slower.


答:
```<code><span class="btn btn-success"></span>
</code>```

Benefits

The above example takes advantage of namespacing, i.e. success goes with btn, there could also be btn-info, or btn-danger as other examples. This provides for a memorable, and easy to type API.

Title: CSS naming guildlines with elements with multiple classes

Body:
Its seems like there are 2 ways someone can handle naming classes for elements that are designed to have multiple classes.  One way would be:

```<code><span class="btn btn-success"></span>
</code>```

This is something that twitter bootstrap uses.  Another possibility I would think would be:

```<code><span class="btn success"></span>
</code>```

It seems like the zurb foundation uses this method.

Now the benefits of the first that I can see is that there less chance of outside css interfering with styling as the class name btn-success would not be as common as the class name success.  The benefit of the second as I can see is that there is less typing and potential better style reuse.

Are there any other benefits/disadvantages of either option and is one of them more popular than the other?

Body:
<span class="btn btn-success"></span>

Benefits

The above example takes advantage of namespacing, i.e. success goes with btn, there could also be btn-info, or btn-danger as other examples. This provides for a memorable, and easy to type API.


答:
I wouldn't do either. It's not going to be at all clear, from looking at your CSS, what .btn is being applied to. I would assume it was a button (and curse you for not using input[type="button"]) and not a span. Only if I went to look at your HTML would I have a clue what you're doing. Even from your question, I have an urge to ask you what exactly you're trying to achieve.

Choose style names that indicate the type of content within the element.

"success" is a good class name. It tells you that it's an area of content which will indicate success. It implies there will be matching styling for failure. But I'd still want to know it was a span.

```<code>span.success
</code>```

Then if you were to apply an extra style to a button within that span, I'd want to see

```<code>span.success input[type="button"]
</code>```

Body:
I wouldn't do either. It's not going to be at all clear, from looking at your CSS, what .btn is being applied to. I would assume it was a button (and curse you for not using input[type="button"]) and not a span. Only if I went to look at your HTML would I have a clue what you're doing. Even from your question, I have an urge to ask you what exactly you're trying to achieve.

Choose style names that indicate the type of content within the element.

"success" is a good class name. It tells you that it's an area of content which will indicate success. It implies there will be matching styling for failure. But I'd still want to know it was a span.

span.success

Then if you were to apply an extra style to a button within that span, I'd want to see

span.success input[type="button"]


答:
Beside personnal preference there is no real advantange of one solution over the other.

```<code><span class="btn success"></span>
</code>```

If you want to access all of your buttons the selector .btn {/* styles here */} will do the trick, if you want to access all your success elements (message bar, label and buttons the selector .success{/* styles here */} will do it and if you want to specifically access your success button .btn.success {/* styles here */} will get the job done

```<code>.btn {/* styles here */} /* Single class has to be applied to element for those styles to take effect */
.success{/* styles here */} /* Same a previous goes here */
.btn.success {/* styles here */} /* Both classes must be on elements for those styles to take effect*/
</code>```

This method is what oocss (object oriented CSS) is refered to

The other notation is allowing the same thing but in a more verbose way like :

```<code>.btn.btn-success {/* Style here */}
</code>```

or

```<code>.btn-success {/* Style here */} /* Same but without the constrain of using .btn class as well*/
</code>```

So its really down to personnal reference.

  improves readability in the css file while  improves readability in the html file.

see Twitter bootstrap for a full blown css framework using similar technique.

Body:
Beside personnal preference there is no real advantange of one solution over the other.

<span class="btn success"></span>

If you want to access all of your buttons the selector .btn {/* styles here */} will do the trick, if you want to access all your success elements (message bar, label and buttons the selector .success{/* styles here */} will do it and if you want to specifically access your success button .btn.success {/* styles here */} will get the job done

.btn {/* styles here */} /* Single class has to be applied to element for those styles to take effect */
.success{/* styles here */} /* Same a previous goes here */
.btn.success {/* styles here */} /* Both classes must be on elements for those styles to take effect*/

This method is what oocss (object oriented CSS) is refered to

The other notation is allowing the same thing but in a more verbose way like :

.btn.btn-success {/* Style here */}

or

.btn-success {/* Style here */} /* Same but without the constrain of using .btn class as well*/

So its really down to personnal reference.

<span class="btn success"></span>  improves readability in the css file while <span class="btn btn-success"></span> improves readability in the html file.

see Twitter bootstrap for a full blown css framework using similar technique.


答:
In addition to what others have said, consider what happens if a change has ripple effects throughout the system. Say you refactor a part of a core interface in the process of implementing a change request - that kind of change can easily touch a large percentage of the source code files in any non-trivial piece of software with what amounts to trivial changes (class or method name changes). Are you supposed to go through every single file touched by such an operation to manually annotate it with such comments, rather than relying on the VCS doing it all automatically? In one case you're looking at little more than a five minute job with any decent refactoring tool followed by a recompile to make sure nothing broke the build, whereas the other can easily balloon into a day's work. For what specific benefit?

Also consider what happens when you move parts of the code around. One of the database developers I work with is in the camp of largely "each line of SQL should be annotated with the revision in which it was changed, and we're going to do separate revision histories for each file because then it's easier to see who changed what when and why". That works kinda-sorta okay when the change is on the order of changing single lines. It doesn't work quite as well when, like I did recently to fix a serious performance issue, you break out parts of a larger query introducing temporary tables, then change the ordering of some of the queries to better fit the new code flow. Granted, the diff against the previous version was largely meaningless since it said about two thirds of the file had changed, but the check-in comment was also something like "major reorganization to fix performance issues". By the time you looked manually at the two versions, it was pretty clear that large parts really were the same, only moved around. (And it took the stored procedure in question from regularly taking over half a minute to execute, to a few seconds. By that time, it was largely I/O-bound with few places for significant further improvement at least in the short term.)

With very few exceptions, change tracking and issue referencing is the work of the VCS, IMNSHO.


答:
In short, depending on the CSS version answers may vary.

Because, that fact will make difference on suggested approaches.
However, if you do not rely on CSS3 look at this post - How to Develop with CSS

I would recommend to have naming like :

```<code><span class="button result-pending"></span>
</code>```

It has an advantage of clear naming, less confusion in a team development. My rule of thumb is to avoid abbreviations.

Body:
In short, depending on the CSS version answers may vary.

Because, that fact will make difference on suggested approaches.
However, if you do not rely on CSS3 look at this post - How to Develop with CSS

I would recommend to have naming like :
<span class="button result-success"></span>

<span class="button result-pending"></span>

It has an advantage of clear naming, less confusion in a team development. My rule of thumb is to avoid abbreviations.


答:
One type of comment I really appreciate is:

// This implemented for Business Rule 5 of Proposal 2

or whatever the heck you use to gather your requirements.

This has two advantages, one is that it lets you find the reason you implemented a given algorithim without searching and another is that it will help you communicate with non-software engineers that work on/create the requirements docs.

This may not help with smaller teams but if you have analysists that develop your requirements, it can be invaluable.


答:
Version-control-related comments do not belong into the source file. They only add clutter. Since they are likely required to be put in the same place (like a comment block at the top of the file) they will cause comment-only nuisance conflicts when parallel branches are merged.

Any tracking information that can be pulled out of version control should not be duplicated in the body of the code. That goes for silly ideas like the RCS checkout keywords like $Log$ and its ilk.

If the code ever travels outside of the scope of the version control system, that trail of comments about its history loses context and therefore most of its value. To properly understand the description of the change, we need access to the revision, so we can view the diff to the previous version.

Some old files in the Linux kernel have big history comment blocks. Those date back to when there was no version control system, just tarballs and patches.


问:
How can you become a real programming polyglot?
I work as a Java programmer, but C and C++ were always my favourite languages during studies. Unfortunatelly I don't have an opportunity to work with them as often as I would like to. As a result I sometimes get realized that I don't remember something quite important (today example: inherited protected members cannot be accessed in derived class constructors). The other example could be Python and Haskell which I enjoy using but don't use everyday. I got an idea to write my own wiki with easy to forget things (e.g. bash tricks & tips) but I find no sense in writing there everything I can forget about coolest programming languages. I know that the best way would be having a side projects (I want to start working on some C/C++ open source project after graduation), but currently I have to write my graduation thesis and work so I merely don't have time to do this. How do you stay sharp in languages that you don't use everyday?</p>

答:
How do I stay sharp in languages I don't use every day?

For me, the answer is "I don't". I've used perhaps a dozen languages professionally for relatively substantial projects, yet at any one time I only count myself proficient in maybe two, with maybe a third where I can use the language with a little extra effort.

Given an opportunity, I'm certain I could once again become proficient in FORTRAN or PERL or C or AWK or any of several other languages when the need arises. At any given time I only care about what I'm using at that moment.

Don't try to become "a Haskell programmer" or "a java programmer". Instead, focus on being just a really good programmer. Eventually you'll come to realize that languages are just syntax, and the real skill and joy in programming comes not from being proficient in one particular language, but being able to craft something useful in whatever language is appropriate at the time.


问:
What would be a non-contrived reason to have an object with Private Copy Constructor as well as Assignment Operator?
Looking for non-conceptual/non-contrived reasons of when one would need to use an object with both a private copy constructor and a private assignment operator?

As in what problem does this technique/practice solve, that some other technique couldn't solve?

答:
You can look at the standard (which has streams).

The stream objects are non copyable because they hold a non shareable buffer.

If you were to allow copying you would need to define semantics that would allow the transfer of the buffer and still make the source of the transfer usable (what does it mean to use a stream after you have transferred its buffer). Instead they decided it was non copyable.

The stream are non-assignable for the same reason. Assignment is just the other side of the same coin (assignment is just copying (with over-writting))


答:
I wrote a Rand class one time that handles the generation of random numbers. If I passed the a Rand instance into a function by value, then the original Rand object would not update its seed state when the copied value generated numbers. Of course, I could have made the seed state allocated somewhere not in the object itself (such as on the heap). Instead I wanted to pass Rand objects by reference. To avoid accidentally passing them by value, I disabled its copy constructor and assignment operator (by making them private).

Now I also wanted the user to be able to actually copy a Rand object. But this requires a little more work since the copy constructor and assignment operators were private. My solution was to create a member function RandForwarder Rand::clone(), where RandForwarder was a friend class of Rand so it could access those private members. I also gave Rand a public constructor that took a RandForwarder and an assignment operator of RandForwarder so users could do this: Rand r2 = r1.clone(); whille disallowing Rand r2 = r1;

Title: What would be a non-contrived reason to have an object with Private Copy Constructor as well as Assignment Operator?

Body:
Looking for non-conceptual/non-contrived reasons of when one would need to use an object with both a private copy constructor and a private assignment operator?

As in what problem does this technique/practice solve, that some other technique couldn't solve?


答:
On the TDD cycle:

In the "make the test pass" phase, you are supposed to write the simplest implementation that will make the test pass.
To make your test pass, you've decided to create a new collaborator to handle the missing logic because it was maybe too much work to put in your point class to make your test pass.
That's where the problem lies. I suppose the test you were tying to make pass was a too much big step.
So I think the problem lies into your test itself, you should delete/comment that test, and figure out a simpler test that will allow you to take a baby step without introducing the LineSegment.Intersects(LineSegment) part.
One you have that test passing, you can then refactor your code (Here you will apply the SRP principle) by moving this new logic into a LineSegment.Intersects(LineSegment) method. Your tests will still pass because you won't have changed any behaviour but just moved some code around.

On your current design solution

But to me, you have a more profound design issue here is that you are violating the Single Responsibility Principle.
The role of a Point is....to be a point, that's all. There is no smartness in being a point, it's just and x and y value. Points are value types.
This is the same things for Segments, segments are value types composed of two points. They can contain a bit of "smartness" for example to compute their length based on their points position. But that's it.

Now deciding if a point and a segment are colliding, is a whole responsibility on its own. And is certainly too much work for a point or segment to handle on its own. It can't belong to the Point class, because otherwise Points will know about Segments. And it can't belong to Segments because Segments already have the responsibility to take care of the points within the segment and maybe also computing the length of the segment itself.

So this responsibility should be own by another class like for example a "PointSegmentCollisionDetector" which would have a method like:

bool AreInCollision(Point p, Segment s)

And that's something that you would test seperately from Points and Segments.

The nice thing with that design is now you could have different implementation of your collision detector. So it would be easy for example to benchmark your game engine (I assume you are writing a game:p) by switching your collision detection method at runtime. Or to do some visual checking/experiments at runtime between different collision detection strategies.

At the moment, by putting this logic in your point class, you are locking down things and pushing too much responsibility on the Point class.

Hope it makes sense,


问:
Is this a violation of the Liskov Substitution Principle?
Say we have a list of Task entities, and a ProjectTask sub type. Tasks can be closed at any time, except ProjectTasks which cannot be closed once they have a status of Started. The UI should ensure the option to close a started ProjectTask is never available, but some safeguards are present in the domain:

public class Task
{
     public Status Status { get; set; }

     public virtual void Close()
     {
         Status = Status.Closed;
     }
}

public class ProjectTask : Task
{
     public override void Close()
     {
          if (Status == Status.Started)
              throw new Exception("Cannot close a started Project Task");

          base.Close();
     }
}
```

Now when calling Close() on a Task, there is a chance the call will fail if it is a ProjectTask with the started status, when it wouldn't if it was a base Task. But this is the business requirements. It should fail. Can this be regarded as a violation of the Liskov substitution principle?

答:
In addition to being a LSP issue, it seems like it is using exceptions to control program flow (I have to assume that you catch this trivial exception somewhere and do some custom flow rather than let it crash your app).

It seems like this be a good place to implement the State pattern for TaskState and let the state objects manage the valid transitions.


问:
How do you coordinate with co-workers to give a balanced interview?
My company has been conducting a lot of interviews lately for candidates with various experience levels, ranging from interns to senior candidates. We put our candidates through five 45 minute interview sessions where we try to ask a range of questions. One person always asks the same questions that test logic and communication. The rest typically split time between a whiteboard coding question and a discussion of previous projects, technologies the interviewee has worked with, and what he/she is looking for a job.

Generally, we know the range of questions that other people on the loop will ask. Sometimes we switch things up and end up having redundancies. Today, 3 interviewers asked tree-related questions. Other times, we've all honed in on the same project on a resume and have had the interviewee talk about it with everyone.

I think a smooth interview process would help us learn more about the candidate while giving the impression to the candidate that we have our act together as a team. How do you coordinate with others in the interview loop to give a balanced interview?

答:
Discuss the candidates strengths and weakness, and the expectations based on role they are interviewing for.

Rather than focus on themed questions, the interviewers assume roles with different purposes.

If you are doing 5 interviews (hopefully you are doing phone screens so that these face to faces are more productive), try something like this:

A) Have one of the more perceptive / intuitive interviewers go first and do the warm up. General history, interesting work the candidate has done, and have them relate a story or two, and also give the candidate a sense of what the interview cycle will be like. The purpose of this interview is threefold; 1) to settle the candidate's nerves, 2) get all the soft ball HR-ish stuff out of the way, and 3) probe the candidate's answers to try to glean some insight into the candidates head and inform the rest of the interviews. This interview can be between 10 to 30 minutes, and kept light and semi-formal.

B) Have one of the friendlier interviewers give a lighter interview probing the candidates obvious weak area(s). You know / believe the candidate is weak in those areas and you are still interviewing them, so it must not be a deal breaker, and there's no reason to drop the hammer on the candidate. This session doesn't need to be long; 15 minutes is enough; and if you have fewer people you can roll A & B together.

C) Have an objective / fair interviewer give a straight interview focused on the candidates strengths, and give the candidate a chance to show off. Hopefully they don't bone it. Assuming you are interviewing this person because their strengths are what you are looking for, this is the real interview. Otherwise, try to steer it such that they have a chance to show if their strengths can be adapted to what you actually need or not. 30 minutes is enough for this unless the candidate is really accomplished or you want to really put them thru their paces. If the candidate seems good, soften the blow to come a bit with some social engineering; let them know the next guy coming up "can be a bit...uh...[technical|academic|tough]...but don't get discouraged...".

D) Bring in the Heavy; a developer who is at least a half order of magnitude more skilled than the candidate and while not unfriendly per se, robotic and cold works well. Ratchet the formality back up. Keep the focus on pure technology in the abstract / devoid of real world context or what a candidate did that one time at that place they used to work. Make the candidate dance a bit. Hit them with deliberately hard questions. Maybe throw some curveballs. The goal here is not to wash the candidate out, but to see how they deal with pressure. And also, they might surprise you; a candidate who struggles thru some of the softer interviews may really shine when the focus is on pure technology and logic. It can also be useful to have a friendly face in the room, one of the other interviewers, allowing for a good cop bad cop routine. This should be an hour, perhaps more.

E) Wrap it all up with a typical interview close. Do you have any questions for us, don't call us we'll call you, etc. Usually fast; 15 minutes or less is typically enough.

Flavor to taste.

In between the sessions the interviewers who are not in the room can trade quick updates, hone the strategy, and so forth.


问:
What should I aware of , when preparing a document of website for later maintenance use?
The development team has finished a website and my duty is to prepare a document so that other programmers can maintain the website with ease.

I have no experience in this and would like to ask what should be mentioned (document structure) in that report?

So far my idea is only to prepare a ERD diagarm for the database and flow chart for each function. Any other suggestions, eg. what cookies stored?

答:
For a small-scale commercial website, it's a good idea to have:

Database related documentation.

Don't forget the SQL file which creates the database. The documentation should also describe the infrastructure itself (for example how frequent are the backups, etc.)

Technical documentation (not the user manual, but the documentation which describes things like how the architecture of the application is done).

If cost is prohibitive, the technical documentation may be missing if the code is clear enough. If, on the other hand, the code wasn't refactored for months, it's a good idea to write at least a short description of the architecture.

Original works.

It's nice to have JPG and PNG images which are actually used on the website, but when the request consists of modifying an image, it's hardly possible (or at least very expensive) without the original Photoshop file.

The same comes for anything else. As a freelancer, I was asked twice to modify an ASP.NET website with no original source code. Every time, the customer was surprised to learn that it is not possible at a reasonable cost.

Working with minified JavaScript (with no original source) isn't funny neither.

Documentation about the processes, especially the deployment process.

For example, how the JavaScript file was minified? What tool is used to combine CSS files into one? What version of ASP.NET MVC do I need to install on the server?

Legal info (licenses, original source, etc.).

It is usual a nightmare when you want to determine what is covered by which license. Do I have a right to reuse a content? Where do I find the original author? Who wrote a piece of text on a specific page of the website?

Also, what are the particular laws which apply to the website? Are there any legal actions? What about mandatory stuff like the choice of tracking cookies in EU?

Contact info.

Who should I contact if I have an issue with the graphics (for example the original Photoshop file is missing for a part of the website)? Who is legally responsible for the website? etc.

Security-related stuff.

Just today, I've received an e-mail from a customer of mine, asking if I can reset the lost root password of the server, given that the root account was created by the hosting provider, and I never used (and never should use) this account myself.

When nothing is documented, it is not unusual for everyone to use the same account (root) to connect to the server. To avoid such critical situations, documentation should describe the policies related to accounts (who may create them, for whom and in what cases; note that you should never include any password in the documentation), the information about security-critical data, etc.

Disaster recovery plan.

If one day your hosting provider contacts you to tell that all your data was destroyed after your website was hacked or after the data center was flooded, having a disaster recovery plan is sweet. Just ensure that it was tested, and that it is kept constantly up to date.

Many web apps don't have any, so even if they might have some backups, they are usually unable to recover after a major disaster or spend weeks to recover, since nobody knows the precise configuration.

Additional points for having version control (with the history of revisions) and bug tracking system (with all bug reports).

Those are the must have for any commercial website. If you're working on a large project requiring more reliability than just an ordinary website, then Stack Exchange won't help you: there are lots of documents to have, each one being written using specific standards, processes, etc., and the subject is too broad to fit in an answer.

Note that in practice, web apps have no documentation whatsoever. When customers ask me to modify their websites, in practically every case the only things I had was spaghetti code and a short, half-page badly-written description of the project.

The best case I had was a web app for one of the largest French companies: not only I had some sort of requirements (written by a person who never learnt how to write them), but I also had the SQL to create the database structure, and the access to the SVN.


问:
Hallmarks of a Professional PHP Programmer
I'm a 19 year old student who really REALLY enjoys programming, and I'm hoping to glean from your years of experience here. At present, I'm studying PHP every chance I get, and have been for about 3 years, although I've never taken any formal classes. I'd love to some day be a programmer full time, and make a good career of it.

My question to you is this: What do you consider to be the hallmarks or traits of a professional programmer? Mainly in the field of PHP, but other, more generalized qualifications are also more than welcome, as I think PHP is more of  a hobbyist language and may not be the language of choice in the eyes of potential employers. Please correct me if I'm wrong. Above all, I don't want to waste time on something that isn't worth while.

I'm currently feeling pretty confident in my knowledge of PHP as a language, and I know that I could build just about anything I need and have it "work", but I feel sorely lacking in design concepts and code structure. I can even write object oriented code, but in my personal opinion, that isn't worth a hill of beans if it isn't organized well. For this reason, I bought Matt Zandstra's book "PHP Objects, Patterns, and Practice" and have been reading that a little every day.

Anyway, I'm starting to digress a little here, so back to the original question. What advice would you give to an aspiring programmer who wants to make an impact in this field?

Also, on a side note, I've been working on a project with a friend of mine that would give a fairly good idea of where I'm at coding wise. I'm gonna give a link, I don't want anyone to feel as though I'm pushing or spamming here, so don't click it if you don't want to. But if you are interested on giving some feedback there as well, you can see the code on github. I'm known as The Craw there.

https://github.com/PureChat/PureChat--Beta-/tree/

答:
1. High-quality code

It's easy to write code, but much harder to write good, clean code. And by good, I mean readable code which matches a specific style, is commented enough but not too much, has short methods, self-documenting names of variables, etc.

2. Broad knowledge

One can hardly be called a professional developer if he only knows one programming language. Understanding different paradigms (like object oriented, functional or reflective) is a must-have too.

Also, as a web developer, one should know HTTP, JavaScript, SQL, REST and too many things to be listed here. A professional web developer should be able to do an average-scale website alone, with the exception of visual design and graphics. It shouldn't be as good as a website created by a team of highly specialized people, but still should be acceptable.

Knowing your tools is a requirement too. You should be familiar enough with version control, IDEs, etc.

3. Solid experience

You don't get professional after two years of college. Somebody with ten years professional experience will likely have more chances of being called a professional developer.

Of course, there are different sorts of experience. Working in a small company where nobody cares about product quality is not very valuable.

An experience in a large-scale project is nice too. It's pretty easy to build a small website, but much harder to get it right when it comes to a website which should be deployed on an array of servers, rely heavily on caching, etc.

4. Personal motivation

If a person is truly motivated by software development, she should be able to show it. When I interview a person who claims to be passionate about programming and has 15 years experience in software development, but can't answer the simple question: "Talk me about your last personal project related to programming", I know that there is something wrong with this candidate.

Have open source projects with source code available for download. Have a blog. Participate to Stack Exchange. All those things are valuable when presenting yourself as a professional developer.