问:
What is the best practice for website design and markup now that mobile browsers are common?
Back in 2008, smartphones were a small market and it was commonplace for sites to be designed for a fixed width - say, 900px or 960px - with the page centered if the browser window was larger. Many designers said fluid width was better, but since user screens typically varied between 1024x768 and 1920x1080, fluid width allowed longer line length than is optimal for ease of reading, and so many sites (including Stack Exchange) use fixed width.

Now that mobile devices are common, what is the the best approach to support both desktop and mobile browsers?

Establish a separate mobile site (e.g: mobile.example.com)

Serve a different CSS to mobile devices; if so how? Server-side browser sniffing, or a @media rule?

Use Javascript or something to adapt the website dynamically to the client? Should all websites be expected to be responsive?

Some kind of fluid layout

Something else?

答: I agree with Mihai that you should try to create a separate mobile website instead of using responsive design. It will be fast to upload and more user friendly. I created my all mobile websites using a mobile website creator at http://www.mobilemarketingpub.com and all are working fine. I simply added a re-direct code to main website index page and a jquery file to root directory. Hope it helps!</p>


问:
Is Java much harder to "tweak" for performance compared with C/C++?
Does the "magic" of the JVM hinder the influence a programmer has over micro-optimisations in Java? I recently read in C++ sometimes the ordering of the data members can provide optimizations (granted, in the microsecond environment) and I presumed a programmer's hands are tied when it comes to squeezing performance from Java?

I appreciate a decent algorithm provides greater speed-gains, but once you have the correct algorithm is Java harder to tweak due to the JVM control?

If not, could people give examples of what tricks you can use in Java (besides simple compiler flags).

答:
There's a middle area between micro-optimization, on the one hand, and good choice of algorithm, on the other.

It is the area of constant-factor speedups, and it can yield orders of magnitude.

The way it does so is by lopping off entire fractions of the execution time, like first 30%, then 20% of what's left, then 50% of that, and so on for several iterations, until there's hardly anything left.

You don't see this in little demo-style programs. Where you see it is in big serious programs with lots of class data structures, where the call stack is typically many layers deep.
A good way to find the speedup opportunities is by examining random-time samples of the program's state.

Generally the speedups consist of things like:

minimizing calls to new by pooling and re-using old objects,

recognizing things being done that are sort of in there for generality's sake, rather than actually being necessary,

revising the data structure by using different collection classes that have the same big-O behavior but take advantage of the accessing patterns actually used,

saving data that's been acquired by function calls instead of re-calling the function, (It is a natural and amusing tendency of programmers to assume that functions having shorter names execute faster.)

tolerating a certain amount of inconsistency between redundant data structures, as opposed to trying to keep them entirely consistent with notification events,

etc. etc.

But of course none of these things should be done without first being shown to be problems by taking samples.

ContentLicense: CC BY-SA 3.0


问:
LSP vs OCP / Liskov Substitution VS Open Close
I am trying to understand the SOLID principles of OOP and I've come to the conclusion that LSP and OCP have some similarities (if not to say more).

the open/closed principle states "software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification".

LSP in simple words states that any instance of Foo can be replaced with any instance of Bar which is derived from Foo and the program will work the same very way.

I'm not a pro OOP programmer, but it seems to me that LSP is only possible if Bar, derived from Foo does not change anything in it but only extends it. That means that in particular program LSP is true only when OCP is true and OCP is true only if LSP is true. That means that they are equal.

Correct me if I'm wrong. I really want to understand these ideas.
Great thanks for an answer.

答:
While it's true that OCP and LSP both have to do with modification, the kind of modification OCP talks about isn't the one LSP talks about.

Modifying with regard to OCP is the physical action of a developer writing code in an existing class.

LSP deals with the behavior modification a derived class brings compared to its base class, and the runtime alteration of the program's execution that can be caused by using the subclass instead of the superclass.

So although they might look similar from a distance OCP != LSP. In fact I think they may be the only 2 SOLID principles that can't be understood in terms of each other.


问:
Scale an image with unscalable parts
Brief description of problem: imagine having some vector picture(s) and text annotations on the sides outside of the picture(s).

Now the task is to scale the whole composition while preserving the aspect ratio in order to fit some view-port.  The tricky part is that the text is not scalable only the picture(s).  The distance between text and the image is still relative to the whole image, but the text size is always a constant.

Example: let's assume that our total composition is two times larger than a view-port. Then we can just scale it by 1/2. But because the text parts are a fixed font size, they will become larger than we expect and won't fit in the view-port.

One option I can think of is an iterative process where we repeatedly scale our composition until the delta between it and the view-port satisfies some precision. But this algorithm is quite costly as it involves working with the graphics and the image may be composed of a lot of components which will lead to a lot of matrix computations. What's more, this solution seems to be hard to debug, extend, etc.

Are there any other approaches to solving this scaling problem?

答:
This problem is quite common in the CADD (Computer Aided Drawing and Design) industry where you have dimensions and texts that must scale in a different way than the rest of the drawing.

The industrial-strenght solution used in CAD systems is usually to have some kind of object hierarchy or object tree that represents the whole drawing. Each element of the drawing (included dimensions and texts) is represented in code and in memory by a different object (an instance of a class). Each object knows how to scale itself in the right way. (Of course, we are talking of vector graphics, not raster one)

This is a very heavy solution. It is both heavy to implement (it requires a scene-graph system that represent the drawing and a hierarchy of classes that represents the drawing elements) and to manage (a tree like this is large and heavy to be loaded and managed in memory).

In smaller systems, it is sometime possible to use two different layers. The first layer, on the background, contains the image. The second layer, on the foreground, is transparent and contains the unscalable parts (dimensions, text, etc.). The two layer are moved, rotated and scaled in synchro to each other but are still indipendent. This permits to scale and translate the main image and the dimensions/texts layer in different ways.

This second solution, however, still requires a layerable/stackable view system and quite a lot of code.

Usually, the people who need this kind of capabilities use some kind of geometrical kernel or geometrical library, like opencascade:

http://www.opencascade.org/

Implementing in-house such libraries is very hard and is usually a task reserved to software houses that work in the 2D/3D CADD arena.

Title: Scale an image with unscalable parts


答:
Cut the unscaleable parts, but for each part save its center point and bounding box size.

Scale the remaining image.

Scale the center point but not the size of the cut parts.

If a cut part goes outside the scaled image, move its center point so it lies just inside.

Paste the cut parts in their new places (and hope they don't overlap anything else).

Title: Scale an image with unscalable parts

Body:
Brief description of problem: imagine having some vector picture(s) and text annotations on the sides outside of the picture(s).

Now the task is to scale the whole composition while preserving the aspect ratio in order to fit some view-port.  The tricky part is that the text is not scalable only the picture(s).  The distance between text and the image is still relative to the whole image, but the text size is always a constant.

Example: let's assume that our total composition is two times larger than a view-port. Then we can just scale it by 1/2. But because the text parts are a fixed font size, they will become larger than we expect and won't fit in the view-port.

One option I can think of is an iterative process where we repeatedly scale our composition until the delta between it and the view-port satisfies some precision. But this algorithm is quite costly as it involves working with the graphics and the image may be composed of a lot of components which will lead to a lot of matrix computations. What's more, this solution seems to be hard to debug, extend, etc.

Are there any other approaches to solving this scaling problem?


问:
When should we use weak entities when modelling a database?
This is basically a question about what are weak entities? When should we use them? How should they be modeled?

What is the main difference between normal entities and weak entities? Does weak entities correspond to value objects when doing Domain Driven Design?

To help keep the question on topic here is an example taken from Wikipedia that people can use to answer these question:

In this example OrderItem was modeled as a weak entity, but I can't understand why it can't be modeled as a normal entity.

Another question is what if I want to track the order history (i.e. the changes in it status) would that be a normal or weak entity?

答:
Formally a "weak" entity has the following characteristics.

It is existence-dependent on another entity.

i.e., it cannot exist without the entity with which it has a relationship.

It inherits at least part of it's primary key from the entity to which
it is related.

i.e. -> A weak entity's primary key must be a composite key that includes the primary key of the entity on which it is existence-dependent.

I would say that in practice you wouldn't overtly decide to make something a "weak" entity per se; you would instead structure the data to be representative of whatever you are trying to model.

If, after you have done this, you look at a particular entity and it has the characteristics of a "weak" entity, you can document or diagram it accordingly, if for some reason you feel the need to explicitly call this out or for the sake of formality.

If you define your OrderItem to have a uniquely identifying sequential id, and the OrderId is not part of the key, then you are treating OrderItems as first order citizens and don't really have a weak entity.

You could FK other tables to OrderItems individually if you wanted to; it is unnecessary to already have an OrderId to get at OrderItems. On the other hand if you keyed OrderItem with OrderId and a sequenceId (or similar) relevant to the Order, you would have a weak entity and individual line items would only be referenceable using the OrderId and sequenceId. Model usage as intended.

ContentLicense: CC BY-SA 4.0


问:
Creating an in-house single source software development team
Our company wants to create a single department for all software development efforts (rather than having software development managed by each business unit). Business units would then "outsource" their software needs to this department. What would you setup as concerns/expectations that must be cleared before doing this? For example:

Need agreement between units on how much actual time (FTE) is allocated to each unit

Need agreement on scheduling of staff

need agreement on request procedure if extra time is required by one party

etc...

Have you been in a situation like this as a manager of one unit destined to use this? If so, what were problems you experienced? What would you have or did implement? Same if you were the manager of the shared team.

Please assume, for discussion, that the people concerned know that you can't swap devs in and out on a whim. I don't want to know the disadvantages of this approach; I know them. I want to anticipate issues and know how to mitigate the fallout.

答:
The biggest problem I could see is that each business unit will believe that their project is the highest priority, and the others are unimportant.

You will probably already have some formal resource allocation plan.  The key will be managing exceptions.  What happens if a critical bug pops up on an application, and there aren't any developers allocated to that application at the time.  Or if it's a junior developer.

What you don't want is for your developer's phones to be ringing all day with the various business units.  You will need to establish clear lines of communication between the business units and the developers, and a defined process for how work gets done, and enforce discipline on the development team that they don't drop everything and work on a feature just because someone stops by their cube with a problem.  They need to follow the process.


答:
First of all, you need a unified delivery platform. Whether it's a website or a single composite application. It's one thing to manage functionality for multiple business units, it's another thing altogether to manage multiple applications. By having a single platform, the opportunities for code re-use increase. Also it will allow you to align features from multiple business units.

Second, invest in Kanban training if you don't have it yet. You're going to receive a lot of feature requests that vary greatly in complexity, impact, and priority. Attempting to plan projects or Scrum Sprints that address these needs is a logistical nightmare. Instead focus on one thing: priority. Let the business decide the priority of the backlog and feed the pipe. When the team is ready for a new feature, take the next one from the top of the list.  You'd also have to invest in a continuous delivery strategy so that you can deliver new functionality as it's completed rather than having to do large deployments.

Title: Creating an in-house single source software development team

Body:
Our company wants to create a single department for all software development efforts (rather than having software development managed by each business unit). Business units would then "outsource" their software needs to this department. What would you setup as concerns/expectations that must be cleared before doing this? For example:

Need agreement between units on how much actual time (FTE) is allocated to each unit

Need agreement on scheduling of staff

need agreement on request procedure if extra time is required by one party

etc...

Have you been in a situation like this as a manager of one unit destined to use this? If so, what were problems you experienced? What would you have or did implement? Same if you were the manager of the shared team.

Please assume, for discussion, that the people concerned know that you can't swap devs in and out on a whim. I don't want to know the disadvantages of this approach; I know them. I want to anticipate issues and know how to mitigate the fallout.


问:
KISS principle applied to programming language design?
KISS ("keep it simple, stupid" or "keep it simple stupid", see e.g. here) is an important principle in software development, even though it apparently originated in engineering. Citing from the wikipedia article:

The principle is best exemplified by the story of Johnson handing a team of design engineers a handful of tools, with the challenge that the jet aircraft they were designing must be repairable by an average mechanic in the field under combat conditions with only these tools. Hence, the 'stupid' refers to the relationship between the way things break and the sophistication available to fix them.

If I wanted to apply this to the field of software development I would replace "jet aircraft" with "piece of software", "average mechanic" with "average developer" and "under combat conditions" with "under the expected software development / maintenance conditions" (deadlines, time constraints, meetings / interruptions, available tools, and so on).

So it is a commonly accepted idea that one should try to keep a piece of software simple (or simple stupid, in case you omit the comma) so that it easy to work on it later.

But can the KISS principle be applied also to programming language design? Do you know of any programming languages that have been designed specifically with this principle in mind, i.e. to "allow an average programmer under average working conditions to write and maintain as much code as possible with the least cognitive effort"?

If you cite any specific language it would be great if you could add a link to some document in which this intent is clearly expressed by the language designers. In any case, I would be interested to learn about the designers' (documented) intentions rather than your personal opinion about a particular programming language.

答:
Arguably, Tcl was developed along these lines. The entire language can be described in only 12 rules on a single man page. It is remarkably simple and consistent.

The creator of Tcl claimed the following as the original goals:

The language must be extensible: it must be very easy for each
application to add its own features to the basic features of the
language, and the application-specific features should appear
natural, as if they had been designed into the language from the
start.

The language must be very simple and generic, so that it can work
easily with many different applications and so that it doesn't
restrict the features that applications can provide.

Since most of the interesting functionality will come from the
application, the primary purpose of the language is to integrate or
"glue together" the extensions. Thus the language must have good
facilities for integration.

From "History of Tcl" - http://www.tcl.tk/about/history.html


问:
What do you optimize for?
Generally speaking, what type of optimizations do you typically slant yourself towards when designing software?

Are you the type that prefers to optimize your design for

Development time (i.e., quick to write and/or easier to maintain)?

Processing time

Storage (either RAM, DB, Disc, etc) space

Of course this is highly subjective to the type of problems being solved, and the deadlines involved, so I'd like to hear about the reasons that would make you choose one form of optimization over another.

答:
Quality/Testing

Optimise towards quality, as in ensuring there is time in the development schedule for testing, both unit testing and testing after features/phases.

ContentLicense: CC BY-SA 2.5

Title: What do you optimize for?


问:
Storing revisions of a document
This is a follow up question to my original question.  I'm thinking of going with generating diffs and storing those diffs in the database 'History' table.

I'm using diff-match-patch library to generate what is called a 'patch'. On every save, I compare previous and new version and generate this patch. The patch could be used to generate a document at specific point in time.

My dilemma is how to store this data. Should I:

a Insert a new database record for every patch?

b. Store these patches in javascript array and store that array in history table. So there is only one db History record for document with an array of all the patches.

Concerns with:

a. Too many db records generated. Will be slow and CPU intensive to query.

b. Only one record. If record is somehow corrupted/deleted. Entire revision history is gone.

I'm looking for suggestions, concerns with either approach.

答: As you are effectively recreating some of the basic functions of an RCS in your database, you might as well look at how they store the data (whole files, diffs, etc.) and how they produce a complete document if they only store diffs.</p>

Title: Storing revisions of a document


问:
How do bug reports factor in to a sprint?
I've been reading up on Scrum recently. From my understanding, a meeting is held before the sprint starts, to decide what gets moved from the product backlog to the upcoming sprint backlog. Once a feature is completed in the current sprint, it will go into the "Ready to QA" bucket, and it's at this point that I'm getting confused. Do bug reports go back into the product backlog? I assume they can't go back into the sprint backlog as we've already decided what work will be done for this cycle? What happens when QA finds a bug? Where does it go?</p>

答:
In an ideal scrum world, there is no "Ready for QA" bucket (at least not visible outside the team), as a feature is not completed until the QA activities are finished and the bugs fixed. This means that there should be people in the team that can take on the QA activities.

In the real world, you might have a separate QA/test team that works in parallel with the scrum (development) team. In that case, the following approach might work well:

Just before a feature is put in the "Ready for QA" bucket, the (main) developer of that feature and the QA representative who will (likely) take it over sit together and walk through the feature. Any issues found at that time are solved before the feature is put in the "Ready for QA" bucket.
Note that this is not an early part of a sprint demo. It is meant to get the low hanging fruit in the issues solves as soon as possible.

Any issues found after the handover to QA should be placed on the product backlog as stories, to be taken into account in the next planning meeting.

For show-stopper bugs, reserve a fixed amount of time each sprint. If, near the end of the sprint, there is time left in this buffer, it could be filled with issues of lower priority.


问:
How do you balance between "do it right" and "do it ASAP" in your daily work?
I find myself pondering over this question from time to time, again and again. I want to do things the right way: to write clean, understandable and correct code that is easy to maintain. However, what I end up doing is writing patch upon a patch; just because there is no time, clients are waiting, a bug should be fixed overnight, the company is losing money on this problem, a manager is pressing hard etc., etc.

I know perfectly well that in the long term I am wasting more time on these patches, but as this time spans months of work, nobody cares. Also, as one of my managers used to say: "we don't know if there will be a long term if we don't fix it now."

I am sure I am not the only one entrapped in these endless real/ideal choice cycles. So how do you, my fellow programmers, cope with this?

UPDATE:
Thank you all for this interesting discussion.
It is sad that so many people have to choose daily between a quantity and a quality of their code. Still, surprisingly many, people think it is possible to win this battle, so thank you all for this encouragement.

答:
Here's a good plan:

Make your do-it-right plan take exactly same amount of time than do-it-asap.

Optimize your time to do it until your environment is happy; keep the quality

???

Success


问:
Is it justified to use project-wide unique function and variable names to help future refactoring?
Refactoring tools (like ReSharper) often can't be sure whether to rename a given identifier when, for example refactoring a JavaScript function. I guess this is a consequence of JavaScript's dynamic nature.

ReSharper solves this problem by offering to rename reasonable lexical matches too. The developer can opt out of renaming certain functions, if he finds that the lexical match is purely accidental. This means that the developer has to approve every instance that will be affected by the renaming.

For example let's consider we have two Backbone classes which are used completely independently from each other in our application:

```<code>var Header = Backbone.View.extend({
    close: function() {...}
})

var Dialog = Backbone.View.extend({
    close: function() {...}
})
</code>```

If you try to rename Dialog's close method to for example closeAndNotify, then ReSharper will offer to rename all occurences of Header's close method just because they are the same lexically prior to the renaming.

To avoid this problem, please consider this:

```<code>var Header = Backbone.View.extend({
    closeHeader: function() {...}
})

var Dialog = Backbone.View.extend({
    closeDialog: function() {...}
})
</code>```

Now you can rename closeDialog unambiguously - given that you have no other classes having a method with the same name.

Is it worth it to name my functions this way to help future refactoring?

答:
Is it justified to use overly long function or variable names to help future refactoring?

"overly long" implies that the names are too long, but the situation you describe makes me think that part of the problem is that names like close are not long enough, or more properly, specific enough. Long names are helpful not just to automated tools, but to the humans that have to work with them. I'd suggest choosing names that are informative.

It is, of course, possible to go too far. If you insist on every name being unique across the entire project you'll create a headache for yourself just in terms of trying to manage all those names. I'd suggest using names that are sufficiently descriptive that you can easily understand them. You may still have to review changes by hand sometimes, but if the name in question is descriptive you won't have trouble deciding whether or not a change is appropriate.


问:
I failed FizzBuzz, would you hire me?
I'm a developer with a CS degree and have work experience doing development in a number of languages for almost 3  years.

Today I had an interview, overall it went quite well, I prepared for most of the questions and felt ready for anything.  At the end of the interview, they gave me ONE programming question...a problem like FizzBuzz (without the print the number part).  I believe I made too many mistakes and thus have "failed" it.  Is all hope lost for me?

Here is my code:

  void FizzBuzz()
  {
    for(int i = 0; i <= 100; i++)
    {
      bool isThree = i % 3;
      bool isFive = i % 5;

     if (isThree)
     {
         print "Fizz\n";
     }
     else if(isFive)
     {
         print "Buzz\n";
     }
     else
     {
         print "FizzBuzz\n";
     }
  }
 }
```

As you can see I messed up the bools which should have the syntax i % 3 == 0;  If I'm remembering the question right I also put an else instead of an elseif with isThree && isFive.  I was quite stressed, but that's no excuse for missing a simple problem.

So the question is, how important is being able to produce working code on the spot relative to other factors, such as experience and personality? For instance, would the above code be a deal breaker?

答:
The point of FizzBuzz is to show that you actually know how to program, not that you've memorized all the finer syntax rules of the language you've been asked to program in (although that does matter, if they want to know how experienced you are in the language).

If you got this far in the stress of an interview environment, and can show that you understand the errors that you made, I'd say you passed.

Title: I failed FizzBuzz, would you hire me?


答:
I would have to say no, but not for the reason you gave, but that you put the FizzBuzz section last.  With the way your code works, it will never print FizzBuzz when you expect it to.  As Lee commented, it will print it for every value not divisible by 3 or 5.

But the main point is that you learn from it.  I like the fact that you're here asking about how you could have done better.  Make sure you do some code puzzles and research common interview questions.  Also, maybe try timing yourself or do something else that would increase pressure so that you can try to mimic the feeling you're going to get in an interview.  And prep, prep, and do more prepping for the interview if you really want to knock it out of the park.

Title: I failed FizzBuzz, would you hire me?

Body:
I'm a developer with a CS degree and have work experience doing development in a number of languages for almost 3  years.

Today I had an interview, overall it went quite well, I prepared for most of the questions and felt ready for anything.  At the end of the interview, they gave me ONE programming question...a problem like FizzBuzz (without the print the number part).  I believe I made too many mistakes and thus have "failed" it.  Is all hope lost for me?

Here is my code:

  void FizzBuzz()
  {
    for(int i = 0; i <= 100; i++)
    {
      bool isThree = i % 3;
      bool isFive = i % 5;

     if (isThree)
     {
         print "Fizz\n";
     }
     else if(isFive)
     {
         print "Buzz\n";
     }
     else
     {
         print "FizzBuzz\n";
     }
  }
 }
```

As you can see I messed up the bools which should have the syntax i % 3 == 0;  If I'm remembering the question right I also put an else instead of an elseif with isThree && isFive.  I was quite stressed, but that's no excuse for missing a simple problem.

So the question is, how important is being able to produce working code on the spot relative to other factors, such as experience and personality? For instance, would the above code be a deal breaker?


答:
Yes

Most of the people I have interviewed that failed the code exercise portion over minor syntax or slightly off logic ended up being the better hires.

Getting the core idea of the logic straight (which you did) and converting it to something decent and concise from a code point of view (which I think you mostly did) are far more important to me than getting it absolutely perfect.

I buy an IDE for it's syntax checking not hire a dev for it, and you would have realized the other mistakes within moments of your first debug.

You went from the initial requirement to a first attempt fairly directly and without doing anything terrible.  That is more valuable in many environments then perfection in an absence of feedback.  If the employer is that hung up on the details you missed it might be a sign of the environment to come anyway.

If the task was the print numbers variant, missing the detail would look a little bad, but it would not have enough weight to change my decision if I liked you for the position otherwise.

[Edit]
As Alex pointed out there is the reaction and composure aspect as well.  Personally I try to get that out of the way before getting to the practical exercises by trying to corner the interviewee on something a little outside their experience but some may choose to combine the two.  Every once and a while I have run into someone who only has textbook knowledge and they sail right through the theoretical and background issues but seriously get hung up on where to start with the practical exercise.  Some cannot even figure out where to begin.

These individuals are EXACTLY what I want weeded out with this exercise.

So unless you took 20 minutes in making the interviewer clarify the requirement I imagine your solution was more or less your first attempt with possibly a couple of corrections as you went.  If you got what you put above in under 5 min you showed you can think enough for my standards.

Title: I failed FizzBuzz, would you hire me?


问:
What should be stored in UserContext?
From my general understanding I believe UserContext for a web application is supposed to hold user authentication and authorization (user roles) information.

As part of user roles, there are definitions on who can access what data and accordingly the corresponding reference data is loaded into the UserContext as well.

Is this a good practice to load and use reference data from UserContext? Does this have any impact with the number of sessions vs size of data it is holding inside JVM?

I am thinking we use UserContext only for authentication and authorization but load the reference data from cache on demand and use it if required.

答:
This is always a trade off of how much space you're taking up in the session.  How big is your reference data?  Generally speaking, unless it's small I'd use the caching approach you described.

DOn't forget that user sessions can be shared across clusters etc as well, so generally speaking keeping them small is a good thing.

Title: What should be stored in UserContext?


问:
How to handle sorting of complex objects?
How would one sort a list of objects that have more than one sortable element?

Suppose you have a simple object Car and car is a defined as such:

```<code>class Car {
    public String make;
    public String model;
    public int year;
    public String color;
    // ... No methods, just a structure / container
}
</code>```

I designed a simple framework that would allow for multiple SortOptions to be provided to a Sorter that would then sort the list.

```<code>interface ISorter<T> {
    List<T> sort(List<T> items);
    void addSortOption(ISortOption<T> option);
    ISortOption<T>[] getSortOptions();
    void setSortOption(ISortOption<T> option);
}

interface ISortOption<T> {
    String getLabel();
    int compare(T t1, T t2);
}
</code>```

Example use

```<code>class SimpleStringSorter extends MergeSorter<String> {
    {
        addSorter(new AlphaSorter());
    }

    private static final class AlphaSorter implements ISortOption<String> {
        // ... implementation of alpha compare and get label
    }
}
</code>```

The issue with this solution is that it is not easily expandable. If car was to ever receive a new field, say, currentOwner. I would need to add the field, then track down the sorter class file, implement a new sort option class then recompile the application for redistribution.

Is there an easier more expandable/practical way to sort data like this?

答:
Implement java.lang.Comparable and use collections like java.util.TreeSet that rely on "natural ordering."  Implementing the compareTo() method in the Comparable interface is a lot like implementing an equals() method - that link contains an example of both.  It is critical to implement equals() and hashcode() if you implement compareTo() and all three must be compatible with each other!

```<code>private int compareNullHelper(Object a, Object b) {
    // sorts nulls first
    if (a == null) {
        if (b != null) { return -1; }
    } else if (b == null) { return 1; }
    return a.compareTo(b);
}

/** Sorts by make, model, year, color. */
@Override
public int compareTo(Car that) {
    // ensures consistency with equals()
    if (this.equals(that)) { return 0; }

    int ret = compareNullHelper(this.make, that.make);
    if (ret != 0) { return ret; }

    ret = compareNullHelper(this.model, that.model);
    if (ret != 0) { return ret; }

    ret = this.year - that.year;
    if (ret != 0) { return ret; }

    ret = compareNullHelper(this.color, that.color);
    if (ret != 0) { return ret; }

    // If you can't tell, return -1 which means that they are in the right
    // order but unequal - ensures consistency with equals()
    return -1;
}
</code>```

Now you can write:

```<code>Set<Car> orderedCars = new TreeSet<Car>();
orderedCars.addAll(myCars);
</code>```

If you need to sort according to different criteria, make additional Comparator classes (that's another Java API interface) for each sort order.  If you make Car implement Comparable and the compareTo() method of your Car class goes by make, model, year, color, you might want to make a ByColorComparator implements Comparator that compares by color, year, make, model.  Then say:

```<code>Set<Car> carsByColor = new TreeSet<Car>(new ByColorComparator());
orderedCars.addAll(myCars);
</code>```

The built-in sorting in Java collections is insanely fast.  For years Java collections have been one of the best things about the platform.

One thing to note is that this technique will work with Hibernate or JPA (if you have an open database session) to automatically grab related objects from the database that may be needed for sorting.

Body:
Implement java.lang.Comparable and use collections like java.util.TreeSet that rely on "natural ordering."  Implementing the compareTo() method in the Comparable interface is a lot like implementing an equals() method - that link contains an example of both.  It is critical to implement equals() and hashcode() if you implement compareTo() and all three must be compatible with each other!

private int compareNullHelper(Object a, Object b) {
    // sorts nulls first
    if (a == null) {
        if (b != null) { return -1; }
    } else if (b == null) { return 1; }
    return a.compareTo(b);
}

/** Sorts by make, model, year, color. */
@Override
public int compareTo(Car that) {
    // ensures consistency with equals()
    if (this.equals(that)) { return 0; }

    int ret = compareNullHelper(this.make, that.make);
    if (ret != 0) { return ret; }

    ret = compareNullHelper(this.model, that.model);
    if (ret != 0) { return ret; }

    ret = this.year - that.year;
    if (ret != 0) { return ret; }

    ret = compareNullHelper(this.color, that.color);
    if (ret != 0) { return ret; }

    // If you can't tell, return -1 which means that they are in the right
    // order but unequal - ensures consistency with equals()
    return -1;
}

Now you can write:

Set<Car> orderedCars = new TreeSet<Car>();
orderedCars.addAll(myCars);

If you need to sort according to different criteria, make additional Comparator classes (that's another Java API interface) for each sort order.  If you make Car implement Comparable and the compareTo() method of your Car class goes by make, model, year, color, you might want to make a ByColorComparator implements Comparator that compares by color, year, make, model.  Then say:

Set<Car> carsByColor = new TreeSet<Car>(new ByColorComparator());
orderedCars.addAll(myCars);

The built-in sorting in Java collections is insanely fast.  For years Java collections have been one of the best things about the platform.

One thing to note is that this technique will work with Hibernate or JPA (if you have an open database session) to automatically grab related objects from the database that may be needed for sorting.


答:
Actually you can use a comparator which has a method compare(a,b) which you can implement.

Then you can pass it in for the compare step (this is supported in nearly all standard libraries of most languages).

For example in java you can call

```<code>Collections.sort(fooList, new Comparator<Car>(){
    public int compare(Car a,Car b){
        return a.getModel().compareTo(b.getModel());
        // or compare what you want return -1, 0 or 1
        // for less than, equal and greater than resp.
    }
});
</code>```

To sort your lists according to a custom comparator

In java 8 there is a lambda syntax to create the Comparator in a single line.

This means there will be only one sorting algorithm to maintain and a bunch of comparators which can remain in the same class as what it is comparing, (or near the place where the comparing is taking place).

This also allows for a "tiered" sort, you can implement something like:

```<code>public static Comparator<T> createTieredComparator(final Comparator<? super T> comp1, final Comparator<? super T> comp2){
    return new Comparator<T>(){
        public int compare(T a,T b){
            int res = comp1.compare(a,b);
            if(res!=0)
                return res;
            else
                return comp2.compare(a,b);
        }
    };
}
</code>```

This will prefer the comparison made by comp1 and only return the result of comp2 when they would be considered equal according to comp1.

Title: How to handle sorting of complex objects?

Body:
How would one sort a list of objects that have more than one sortable element?

Suppose you have a simple object Car and car is a defined as such:

```<code>class Car {
    public String make;
    public String model;
    public int year;
    public String color;
    // ... No methods, just a structure / container
}
</code>```

I designed a simple framework that would allow for multiple SortOptions to be provided to a Sorter that would then sort the list.

```<code>interface ISorter<T> {
    List<T> sort(List<T> items);
    void addSortOption(ISortOption<T> option);
    ISortOption<T>[] getSortOptions();
    void setSortOption(ISortOption<T> option);
}

interface ISortOption<T> {
    String getLabel();
    int compare(T t1, T t2);
}
</code>```

Example use

```<code>class SimpleStringSorter extends MergeSorter<String> {
    {
        addSorter(new AlphaSorter());
    }

    private static final class AlphaSorter implements ISortOption<String> {
        // ... implementation of alpha compare and get label
    }
}
</code>```

The issue with this solution is that it is not easily expandable. If car was to ever receive a new field, say, currentOwner. I would need to add the field, then track down the sorter class file, implement a new sort option class then recompile the application for redistribution.

Is there an easier more expandable/practical way to sort data like this?

Body:
Actually you can use a comparator which has a method compare(a,b) which you can implement.

Then you can pass it in for the compare step (this is supported in nearly all standard libraries of most languages).

For example in java you can call

Collections.sort(fooList, new Comparator<Car>(){
    public int compare(Car a,Car b){
        return a.getModel().compareTo(b.getModel());
        // or compare what you want return -1, 0 or 1
        // for less than, equal and greater than resp.
    }
});

To sort your lists according to a custom comparator

In java 8 there is a lambda syntax to create the Comparator in a single line.

This means there will be only one sorting algorithm to maintain and a bunch of comparators which can remain in the same class as what it is comparing, (or near the place where the comparing is taking place).

This also allows for a "tiered" sort, you can implement something like:

public static Comparator<T> createTieredComparator(final Comparator<? super T> comp1, final Comparator<? super T> comp2){
    return new Comparator<T>(){
        public int compare(T a,T b){
            int res = comp1.compare(a,b);
            if(res!=0)
                return res;
            else
                return comp2.compare(a,b);
        }
    };
}

This will prefer the comparison made by comp1 and only return the result of comp2 when they would be considered equal according to comp1.


答:
We have a kind of one-stop shop that supports a lot of different applications that belong to different parts of the business (and ultimately to clients).

First thing is to organize for success. Get everyone in the group on the same source control for instance. Next even though you all report to the same person rather than diffeernt business groups, there is nothing stopping you internally from designating programmers by product line or internal client.

We do move people around some in an emergency or when a new big project comes along, but generally they work on the same applications for the same clients. Each internal group of people may support multiple internal clients though. This at least gives the best chance that someone familar with the application is looking at it. It also means the C# programmers will be working with the C# programs and the Access programmers won't be expected to suddenly take on a project way out of their skill set.

If you are bringing together groups with wildly different expertise, then you need to build a matrix of who is qualified to work on what. (This will help in resource planning). You may need to find the time to set up some cross training, so that developers who use languages that don't have many projects can expand their skills to be more valuable to the group.

You may also need to look at making sure you have created a path for developers to move up in the organization. One of the few benefits to the change you are about to make is that more devlopers in one place means more chances to move up to senior developer and technical lead.

Given that you previously had many programmers in different parts of the organization, likely you have wildly different types of expertise, coding standards, processes. Some teams might be agile and some might be using Waterfall. If you want this to be effective in the long run, you need to work on moving to more standarized ways of doing business. Start with source control, then move to processes (If you can get everyone on agile, it might help some of your resourcing issues as once someone is on a sprint  he or she woudl stay on the sprint.) In some teams you might have support devs and new development devs and others might expect a person to do both new development and support. Standardize on one method. Determine if possible a stardard set of tools you will all use or that will be used on all new projects. Set coding standards that will be used for all new projects  (It may be too much to expect to change all the existing code done using a wild variety of standards.)

Next you need to set up how you are going to handle resourcing. There has to be a weekly or monthly resourcing meeting and all new projects will go into it and resources will be assigned. Resources can be reassigned between meetings but only within the resources available to a particular group (so if accounting has 3 resources assigned this month, they can move them from project A to project B when it suddenly becomes a hot topic, but they can't steal resources from the Sales team until the next resource meeting). If you are doing agile, the resource planning meeting should be one week before the start of a sprint and all sprints should be on the same schedule and duration (everyone has two week sprints and the sprints all start on the same day, for instance). Do not forget to allow time for production support in resource planning.

Get a standard process set up for how you will estimate the hours needed for each project. Do not forget to add time for QA, fixing bugs, deployment issues, development of technical specs, communication (you can spend a lot of time in a project on meetings and emails). In your resourcing, never plan any person for more than 75% of the time (you have to allow time in the schedule for leave,holidays, required company meetings, unavoidable delay, setting up computers when they havea new one etc. ) In my experience assuming 100% of the time for project work is one of the biggest reasons for deadlines to be missed, no one is ever at 100% of the time on direct work forever.

Make the individual departments you are supporting responsible to create requirements documents. If unfamilar people will at times be working on their projects, you need formal requirements documents. No Requirement document, no project. Period. Also, you will have to have a formal project management system set up. No one will work on anything until the internal client has set up a project to charge the time against. No more "oh by the ways", everything will have to be formally requested and worked into the resource plan. No more last minute requests either (except actual production bugs of course), let them know that all resources will be planned X amount of time in advance. Bugs should be reported in a formal system as well, there are many bug trackers out there.

In implementing the change, now might be a good time to get things you haven't been able to get before, like better equipment for everyone or some tools you would like but haven't had the budget to purchase (ask for suggestions from the folks in the trenches). Make sure everyone at least has two monitors!! And a good chair. Getting better euipment might help people in accepting the new system as at least there will be something in it for them!

I'm sure there is more, but that is all that comes to mind right this second. At least it will get you started on the planning process of how to implement.


答:
First off, if managers of various non-technical departments are used to having someone with a coding background directly reporting to them, to whom they can hand off technical projects, and now all those technical people are in a department reporting to someone else, the managers are going to do whatever they can to get around the new "normal" processes and get to their former techie. They aren't going to like this new arrangement one bit; they'll perceive slower responses to their requests for new work, more hoops to jump through, and extra costs that used to be fixed at the techie's salary (if techie time is "budgeted" among the rest of the departments).

You (in the shoes of the new manager of this new tech department) are going to have to nip this in the bud. First, you're going to need to restrict access to the tech team, physically if necessary. This starts with the tech team themselves; they must understand that they now work for a new boss, who is going to evaluate performance based on what he told each techie to do, not what their old boss is trying to get done via an end run around the process. There will be a transition period as there is with any reorg; techies will have to "break up" with their old bosses ("I know, you were great, but we have to stop seeing each other like this"). People who remain stubbornly loyal to their old bosses may have to be let go; if they won't do what you want, they're useless to you regardless of their capabilities.

If the tech team is trying, but the old bosses are still wiggling their way past whatever gateway you set up, then make that gateway physical; have maintenance install a keycard door leading to the developer offices, and only you and the devs have access. When their old bosses come to you angry about this, stand your ground; they work for you now, not them.

As for scheduling the techies' time on projects for other departments, that's a business decision that is dependent on the number and scope of these projects. Usually, if the old scenario was a bunch of individual devs doing whatever the department needed, that usually means a lot of little stuff. Prioritize it and hand it to the devs best qualified to work on it. When it's done, it's done, and arrange delivery to the department that requested it.

Now, that strategy may seem to make you redundant; if all the techies are still doing the same work they would have done under their old bosses, then what's changed? What's changed is that now you can see the big picture based on what's coming in, and guide development efforts along the way. You don't have to have the techs do exactly what the department heads ask for, if you see a way to do it better. Look for opportunities to improve processes, and to consolidate piecemeal solutions into something more purpose-built. Obviously, coordinate with the various departments, but as the head of this new development department, you're basically now in the de facto position of business analyst; if you see a better way to do what's being asked for, by all means pipe up.

What's also changed is that all these individual devs are now organized under a team structure, and what would have taken one dev weeks can take the team days. These "big projects" for business process automation and engineering are going to take a team effort; that's why they didn't get done before, because there wasn't a team to do it (and there wasn't someone with the willingness and/or authority to coordinate across the multiple departments on a single solution).


答:
At my last job, sprints were scheduled based on the "ideal hours" concept; of an 8-hour developer-day, 5 hours were head-down TDDing new features that never existed before. The other three were doing everything else; e-mails, meetings, compiling/committing/updating code, refactoring work, and yes, bug fixes.

We considered a job that was done but had bugs to still count towards team velocity; however, bugs were technical debt that had to be paid off when it accrued, and therefore obviously to be avoided. We never had a real problem with people doing sloppy work; nobody wanted to have to backtrack.

Every now and again, we'd also have bug-fixing sprints. We had the dubious good fortune to have a client that couldn't deliver requirements at the pace we could consume them, so to let the backlog build up a bit, we often scheduled two weeks where the object was to "kill as many defects and pay off as much technical debt as you can". Technically, velocity for such a sprint is zero, but this is work that needs to be done and which makes the client happy, so it's worthwhile.

Title: How do bug reports factor in to a sprint?

Body: I've been reading up on Scrum recently. From my understanding, a meeting is held before the sprint starts, to decide what gets moved from the product backlog to the upcoming sprint backlog. Once a feature is completed in the current sprint, it will go into the "Ready to QA" bucket, and it's at this point that I'm getting confused. Do bug reports go back into the product backlog? I assume they can't go back into the sprint backlog as we've already decided what work will be done for this cycle? What happens when QA finds a bug? Where does it go?</p>


答:
If the time spent on defect is fairly consistent from one spring to another, then you don't really need to manage it - your team velocity is going to reflect that.

Otherwise, if defects fixing can be planned (i.e. you can postpone fixing them for the duration of a sprint), then do so.

Otherwise, Scrum doesn't have a good answer - defects are going to be an unplanned sprint content change in the middle of a sprint, which means you'll need to renegociate your commitments.


问:
How can I give my client "full access" to their PHP application's MySQL database?
I am building a PHP application for a client and I'm seriously considering WordPress or a simple framework that will allow me to quickly build out features like forums, etc.

However, the client is adamant about having "full access" to the database and the ability to "mine the data."  Unfortunately, I'm almost certain they will be disappointed when they realize they won't be able to easily glean meaningful insight by looking at serialized fields in wp_usermeta, etc.

One thought I had was to replicate a variation on the live database where I flatten out all of those ambiguous and/or serialized fields into something that is then parsable by a mere mortal using a tool as simple as phpMyAdmin.

Unfortunately, the client is not going to settle for a simple backend dashboard where I create the custom reports for them even though I know that would be the easiest and most sane approach.

答:
I would ask about reporting requirements - if it really is a concern that the app data be in a specific format, you may need to pursue a slightly different path (e.g. A custom Plug In, etc.). See what requirements they have in that regard.

Other than that, you could just let them have DB access.


答:
Determine what your client's requirements and grasp of technical concepts. Additionally determine what the timeframe and what they are willing to spend. This information might possibly lead you to a few decisions:

Use an out of the box approach like WordPress or some other CMS(-esque) system that is fairly easy to develop for. The caveat to this is you have precious little you can do about the data model used. Perhaps writing some documentation would help alleviate the pain. This approach will be fast, cheap, but a bit harder on the "data mining" side of things.

Develop a custom system on some framework like Symfony. This gives you the maximum control of what and how your data will be stored. This allows you to be more flexible and allows you to give your client exactly what (s)he needs. Of course this approach is going to be more time consuming and costly. Of course rolling your own can also be more fun than working with something like WordPress.

Of course one thing to always consider when dealing with a client with odd demands is how much is this client worth. Some people can be poisonous with odd and ill-informed requests that turn into more hassle than is worth dealing with.

Title: How can I give my client "full access" to their PHP application's MySQL database?

Body:
I am building a PHP application for a client and I'm seriously considering WordPress or a simple framework that will allow me to quickly build out features like forums, etc.

However, the client is adamant about having "full access" to the database and the ability to "mine the data."  Unfortunately, I'm almost certain they will be disappointed when they realize they won't be able to easily glean meaningful insight by looking at serialized fields in wp_usermeta, etc.

One thought I had was to replicate a variation on the live database where I flatten out all of those ambiguous and/or serialized fields into something that is then parsable by a mere mortal using a tool as simple as phpMyAdmin.

Unfortunately, the client is not going to settle for a simple backend dashboard where I create the custom reports for them even though I know that would be the easiest and most sane approach.


答:
In my experience there are some customers which can't see reason.  I don't know if your customer fits into this group or not based on the information at hand.  I'm guessing its possible given the overtones of your question.  That being said the rest of my answer will focus on how to deal with this group of customers.

I have had a couple of occasions where I fought the good fight and tried to reason with customers who had unrealistic expectations such as this.  In the end I of course "lost" since the customer is always right.  Once they got what they wanted however, they inevitably saw at that point (whether they wanted to admit it or not) that I had been right and that I wasn't just being controlling but that my recommendations really had been in their best interest.

I think you hit upon a good point whether you meant it or not when you quoted "full access" in your question.  I think the answer here is to make them think they have full access or at least as much access as you can possibly give.  Depending on how technically savvy they are you can get away with this at varying degrees.  There's nothing wrong with giving them read access.  Unless they have technical capability/training, they're going to get in there and quickly see that you were "right."  If you give them read-only access but tell them they have "full access" and they come back and say no you didn't, you can always play dumb and "double check" the permissions.  I don't think they would know they didn't have full access unless they tried to write to the database which they really shouldn't be doing anyways as they'd be risking bringing WordPress to its knees.

In short my answer is to "give them what they want"... or other words make them think they're getting what they want.


答:
Gather Requirements before even thinking of * how*
As has been stated - gather requirements. It may be that they mean just what they ask; SQL dumps. (Which I'd build in anyway for back up purposes)

Then consider how to achieve these requirements. It may be as simple as a Wordpress plugin, I'm not too aware about the technicalities of the Wordpress API, but this should be possible.

It may even be possible to knock up a seperate app for this kind of functionality. CodeIgniter has a pretty extensive database class - I rigged up a CMS w/ blog and database statistics in around a day. Plus it takes a lot of extra concerns out of your hands; using its extensive list of helper functions.

It may be useful to develop some helper classes yourself for this purpose. They may complement your existing toolkit and be useful in the future.

I understand the time benefits of using an off the shelf solution such as Wordpress, but this may be negated if you're building something like a forum in to it. I can't help but think that is going to bite you in the long term..


答:
Make it work then make it perfect

I may draw some slack for this - but if time is of the essence, then your main priority should be to get it working, simple as that. Comment extensively about the shortcomings in your code and make a note of what you've done in any project/time management software you're using.

Hopefully this will give you more time to return to these issues and make them perfect.

Obviously there is no absolute correct answer to this, but it's an answer I try and stick to. You may not find it suited to your current work style though. Which leads me on to the alternative...

Just find a method that works for you; and then stick with it. Everyone has their own way of dealing with projects and there's no "one size fits all" approach. Find an approach, and make it yours.

Title: How do you balance between "do it right" and "do it ASAP" in your daily work?

Body:
I find myself pondering over this question from time to time, again and again. I want to do things the right way: to write clean, understandable and correct code that is easy to maintain. However, what I end up doing is writing patch upon a patch; just because there is no time, clients are waiting, a bug should be fixed overnight, the company is losing money on this problem, a manager is pressing hard etc., etc.

I know perfectly well that in the long term I am wasting more time on these patches, but as this time spans months of work, nobody cares. Also, as one of my managers used to say: "we don't know if there will be a long term if we don't fix it now."

I am sure I am not the only one entrapped in these endless real/ideal choice cycles. So how do you, my fellow programmers, cope with this?

UPDATE:
Thank you all for this interesting discussion.
It is sad that so many people have to choose daily between a quantity and a quality of their code. Still, surprisingly many, people think it is possible to win this battle, so thank you all for this encouragement.


问:
In Subversion, how should I set up a new major version of my application?
I'm about to start work on a new version (version 4) of my commercial application. I use Subversion.

Based on your experiences, mistakes, and successes, how would you recommend I set up the new version in Subversion?

Here's some info: I intend to keep releasing critical updates in version 3 for some time after version 4 is released. However all development of new features will be solely in version 4.

In case it is relevant: I'm a solo developer on this product, and that is likely to remain the case.

EDIT: I'm aware of SVN's tags and branches. I guess what I need is an optimal strategy for using tags and branches in my situation.

答:
What you want to do is create Branches. It is as it sounds a branch in your source tree, typically a copy of your source when you release it. You would commit into this branch for the critical updates, and build the update from this branch.

What you are commiting into right now would be the trunk and you would code version 4 in there. If any major changes are commited to version 3, and you would like to have it in version 4, you would do a merge from the branch (v3) to the trunk(v4) to bring the changes over to the trunk.

You can also look at tags, which are like branches but link to a single version, typically the last revision of a version (or the first).


答:
It depends.

You can keep version 4 in the trunk and continue developing on V4. Version 3 would be a branch, that you'd update as needed. The benefit of this approach is if a critical issue was discovered in V3 that is also in V4, you could do a simple merge on the file(s) across the branches.

The other option is to create and entirely new repository for V4. This will give you a fresh start. The downside is the change history is reset and you will not be able to merge files via Subversion. You'll have to use a program such as Beyond Compare to merge in changes.

Personally I would stick with the first approach. Create a V3 branch and maintain the code and the updates in this branch. The new V4 code can be developed in the trunk.

Title: In Subversion, how should I set up a new major version of my application?

Body:
I'm about to start work on a new version (version 4) of my commercial application. I use Subversion.

Based on your experiences, mistakes, and successes, how would you recommend I set up the new version in Subversion?

Here's some info: I intend to keep releasing critical updates in version 3 for some time after version 4 is released. However all development of new features will be solely in version 4.

In case it is relevant: I'm a solo developer on this product, and that is likely to remain the case.

EDIT: I'm aware of SVN's tags and branches. I guess what I need is an optimal strategy for using tags and branches in my situation.


问:
What should every programmer know about programming?
Please, stay on technical issues, avoid behavior, cultural, career or political issues.

答: My first vote would be for Naming Conventions. </p>


答:
I found an excellent guide to this situation:</p>

```<code>If you want to be able to both develop a newer version (in trunk) and
fix bugs on an older version, what you want is a branch for the older
version. You can fix your bug in the older version's branch, then
make a new tag of that.
Example:
/repo/
        project/
                trunk/
                branches/
                tags/
You've developed your software in trunk and are now ready to call it
version 1.0. You make a branch and a tag:
svn cp $REPO/project/trunk $REPO/project/branches/1.x
svn cp $REPO/project/branches/1.x $REPO/project/tags/1.0
/repo/
        project/
                trunk/
                branches/
                        1.x/
                tags/
                        1.0/
Now you continue to develop in trunk, adding new features, and this
will eventually become version 2.0. But while you're doing this, you
find a bug in 1.0 and need to fix it quick. So you check out branches/
1.x, make the change, test it, and commit it. Then you tag that as 1.1:
svn cp $REPO/project/branches/1.x $REPO/project/tags/1.1
/repo/
        project/
                trunk/
                branches/
                        1.x/
                tags/
                        1.0/
                        1.1/
If the bug also exists in trunk, then you need to port your bugfix to
trunk. "svn merge" can help you there.
cd trunk-wc
svn merge -c$R $REPO/project/branches/1.x .
where $R is the revision in which you fixed the bug on the 1.x
branch. Now you test the fix in trunk and then commit it. Now the bug
is fixed in trunk too.
</code>```

Body:
I found an excellent guide to this situation:

If you want to be able to both develop a newer version (in trunk) and
fix bugs on an older version, what you want is a branch for the older
version. You can fix your bug in the older version's branch, then
make a new tag of that.
Example:
/repo/
        project/
                trunk/
                branches/
                tags/
You've developed your software in trunk and are now ready to call it
version 1.0. You make a branch and a tag:
svn cp $REPO/project/trunk $REPO/project/branches/1.x
svn cp $REPO/project/branches/1.x $REPO/project/tags/1.0
/repo/
        project/
                trunk/
                branches/
                        1.x/
                tags/
                        1.0/
Now you continue to develop in trunk, adding new features, and this
will eventually become version 2.0. But while you're doing this, you
find a bug in 1.0 and need to fix it quick. So you check out branches/
1.x, make the change, test it, and commit it. Then you tag that as 1.1:
svn cp $REPO/project/branches/1.x $REPO/project/tags/1.1
/repo/
        project/
                trunk/
                branches/
                        1.x/
                tags/
                        1.0/
                        1.1/
If the bug also exists in trunk, then you need to port your bugfix to
trunk. "svn merge" can help you there.
cd trunk-wc
svn merge -c$R $REPO/project/branches/1.x .
where $R is the revision in which you fixed the bug on the 1.x
branch. Now you test the fix in trunk and then commit it. Now the bug
is fixed in trunk too.


问:
How to manage product backlog/user stories
We're about to start a new project using Agile (using TFS), and I have a couple of "good practice" questions regarding the product backlog:-

When we first start adding users stories, is it a good idea to put them in (say) a "Backlog" iteration, or just leave their iteration blank? Obviously when the time comes to start work on a US it would be moved into the appropriate iteration backlog.

When breaking an epic down into smaller USs, would I simply close the original epic, as it's no longer required? Or should I create the new USs as children of the epic? (it's then someone's responsibility to close the epic once all child USs have been completed).

Lastly, should the product backlog list all USs regardless of status, or only those that have not been started (i.e in my proposed "Backlog" iteration)?

I realise these questions aren't life-or-death, but it would be nice to know how other people manage their product backlogs so we can organise things properly from the start.

答:
I am not familiar with TFS (is that a software tool?) but I can give you some answers based on Schwarber.

1. Story Containers

There are only two containers of stories that you should ever be thinking about, the product backlog and the sprint backlog.  Software tools for tracking scrum may allow you to keep around old sprint backlogs for historical analysis and that is ok, but you must close out an old sprint backlog (i.e. make sure everything in it is finished or moved out) before doing any work on the next sprint backlog.

Sometimes there is a tendency to create the next sprint's backlog in a software tool while still in the current sprint.  Do not do this.  If that future sprint backlog is there, people will try to put stories into it.  This disrupts the proper planning process, raises tensions, and confuses scheduling issues.

If you fail to keep proper boundaries between your sprints then you are, in essence, running multiple, similtanious sprints.  You are multi-tasking.  At the very least the overhead of task switching will slow you down; research indicates that a full context switch in humans, from puzzle A to puzzle B, takes 15 minutes.  My experience suggests this drag can be 50% or more of your productivity.

2. Epics

Keep your epics around.  Someone asked for this feature, they will probably come back and want to know the status of the epic.  That person, department, or customer will be thinking of the 'story' they submitted, now promoted to epic.  They won't be thinking about the smaller stories involved and may not even recognize that story Foo is related to their request.  The epic is a convenient handle for communication between development and the customer.

Since the epics don't actually get worked on themselves, just the associated stories, the epics move directly from your product backlog to your finished pile.

3. Where do the stories go?

A story should only be in one container at a time.  It should start out in the product backlog, move to a sprint backlog, and then be finished.  If someone comes looking for their story in the product backlog and doesn't find it, that must mean it is in process or finished.

4. Final thoughts about managing a deep product backlog

Force-ranked order becomes pretty meaningless when you have hundreds of items in your product backlog.  Sure, the how you arrange items 20-70 might be fairly meaningful, but who really cares if #300 is before or after #301?

One possible solution to this is to have multiple sub-component backlogs that feed into a main product backlog.  For example, you might have UI, DB, Backend, API, Infrastructure, and Technical Debt as your sub-components.  Each component backlog might be delegated to a different person for management.  A periodic meeting would have to decide what stories to move onto the main product backlog.  In order to maintain a proper balance of stories in your product backlog, it is best to decide a priori a guideline (not rule) for the proportions of stories that get promoted to the main backlog.  One API story for every two UI stories?  How many stories can you take from Technical Debt in comparison to the number of Backend stories you need to take?

This system adds considerable complexity and requires lots of extra coordination.  It should only be undertaken when the the product backlog grows so large that the Product Owner can't think about all of the stories at once.


问:
how to change the sequence used in planning poker
Is it possible to change the used sequence in Planning Poker, for some stories, it is thought that when the stories gets larger it contains more uncertainty but stories have nearly exact time estimations and these estimations don't drop into two bounds defined by Fibonacci series.</p>

答:
Fibonacci is only a guideline.  It is a graduated way to do rough estimates and to avoid arguing.  It would be a shame to spend any significant time discussing (or arguing) if a story is actually 15 or 16 points.  That is only a 6% difference.  Likewise, if my team spends more than a minute or two discussing whether a story is a 3 or a 5, I will mark down 4 in the software.

Also, it is unlikely that your ability to accurately estimate spans more than an order of magnitude.  If you are assigning a 1 to some stories, a 13 is really on the verge of being too large.  I used to have a rule with my team that any story larger than 13 had to be broken up, but they eventually started doing that to the 13s also.  We almost never have anything larger than an 8.

If your estimation meeting is long or contentious, you are getting too far into the details.  Story points are fast and rough estimates, don't try to make them exact.  My rule of thumb is that is should take 15 minutes per developer to estimate a two week sprint.  An hour for a team of four.  Don't spend more time on it than that.

OwnerDisplayName: yesildal


问:
Looking for best practice for version numbering of dependent software components
We are trying to decide on a good way to do version numbering for software components, which are depending on each other.

Let's be more specific:

Software component A is a firmware running on an embedded device and component B is its respective driver for a normal PC (Linux/Windows machine). They are communicating with each other using a custom protocol. Since, our product is also targeted at developers, we will offer stable and unstable (experimental) versions of both components (the firmware is closed-source, while the driver is open-source). Our biggest difficulty is how to handle API changes in the communication protocol.

While we were implementing a compatibility check in the driver - it checks if the firmware version is compatible to the driver's version - we started to discuss multiple ways of version numbering.

We came up with one solution, but we also felt like reinventing the wheel. That is why I'd like to get some feedback from the programmer/software developer community, since we think this is a common problem.

So here is our solution:

We plan to follow the widely used major.minor.patch version numbering and to use even/odd minor numbers for the stable/unstable versions. If we introduce changes in the API, we will increase the minor number.

This convention will lead to the following example situation:

Current stable branch is 1.2.1 and unstable is 1.3.7. Now, a new patch for unstable changes the API, what will cause the new unstable version number to become 1.5.0. Once, the unstable branch is considered stable, let's say in 1.5.3, we will release it as 1.4.0.

I would be happy about an answer to any of the related questions below:

Can you suggest a best practice for handling the issues described above?

Do you think our "custom" convention is good?

What changes would you apply to the described convention?

答:
IMHO version numbers are like product names; important in that they're visible but unimportant in that they're decoration rather than content.

Still the version number, like a product name, carries meaning. And the most important thing you can do is avoid confusion. So here are some common expectations with respect to version numbers. To the extent that these exceptions are not met, the user will probably be confused:

Version numbers are monotonically increasing

This is probably the most obvious expectation, and at the same time the least likely to actually be true. At-a-glance, the user expects that version 2.3.5 comes after version 2.2.17, and has the same or better technology. But of course 2.3.x is a development branch, and 2.2.x is stable, and 2.3.5 actually was release back in 2004 and the 2.2 branch is still actively being worked on and 2.2.17 was released just last April and contains... well, you get the idea. You might as well just call version 2.2 "Potato" for all the meaning that the number carries. Welcome to version "Potato-17"!!

Similar Versions are Upgradeable/Compatible

If I have version 3.7 on my computer, and 3.8 comes out with all new shiny frozbots, I expect that with some upgrade or patch or whatever, my 3.7 can become 3.8 with no interruption. But if I'm on 3.7 and you release 5.2, I'm not so optimistic. Of course, I'd rather be pleasantly surprised rather than disappointed.

The first digit is significant

I wouldn't even bother to mention this if Java wasn't so prominently confusing on the matter. Unless someone told you, you would not expect that "Java 7" was actually version 1.7. And the first time you heard this, you response was almost certainly: "What? .. Why?"

Clearly the purist will say that the major version number will only change if the platform change is not backwards-compatible. But do you actually intend to drop backwards compatibility ever? Often major version revs are a marketing decision not a technical one; the Java absurdity comes from both camps having it their way at the same time, to almost comical effect.

Finally

As I just mentioned, version numbers are often as much about marketing as they are about technology. And that's OK, since that's kind of what version numbers are for: the inform you at a glance as to what's new about the software. Big number change means big functionality change. Small number change means almost no functionality change. That's what people expect. Whether it's true or not determines whether or not your version numbers carry the same meaning that your users think they do.

-- EDIT --

I forgot to mention this, but Caleb pointed it out nicely: Don't use version numbers to indicate anything important (e.g. stable/unstable) without making it otherwise explicit elsewhere. Yes, you know that the odd minor version number indicates development, but that makes one of us. Debian's "unstable" release moniker is a good example; or you could also use a totally separate product name; "Frozbot 1.2" for your product name, and "Devbot 1.3" for your development version.


问:
What is the mathematical model of a Python's class?
I understand that the classical model from the lambda-papers is not valid for Python.

And the closures are not the mathematical model of the implementation of the Python system.

So which model is it?

答:
The main difference between Python and models from classical papers on the lambda calculus is that Python is a multi-paradigm language. Most papers which consider the lambda calculus consider a pure functional language, without the complexities involved by adding other paradigms (like OOP or logical programming).

From the question and your comments, I take it that you are interested in the foundations of such multi-paradigm languages. In that case, I can highly suggest Concepts, Techniques, and Models of Computer Programming by Peter van Roy and Seif Haridi. The book is mainly about the Mozart/Oz language, which in itself is a rather academic language. However, the book very clearly demonstrates how to start off with a very small core language and build object-orientation, functional, and logic programming on top of it (and all within the same core language).

As for the actual mathematical model, most programming languages have only an informal or semi-formal specification. Seldom do you find one that has a proper theory like the lambda calculus as its foundation. There are a lot of different mathematical models that have been invented and are more or less applicable. What's interesting is that there is a general distinction into the different approaches to how programming semantics are modeled: semantics can be described denotationally, operationally, or algebraically. If you want to go even deeper, then reading up a little about the Unifying Theories of Programming is a start, albeit a tough one with a steep learning curve.


答:
What you are asking about is the branch (and merge) strategy to use. So take the post of karthik t and take that as a recipe.

For some background, read the following resources:

SVN Red Book for the repository layout (single vs. multi project repositories)

Branch Patterns in your context, you will use a release branch per major version

Software Configuration Management Patterns the base theory that is used in Subversion (and all other CM systems). See there the patterns, especially the release line there.


问:
Why do iterators in Python raise an exception?
Here's the syntax for iterators in Java (somewhat similar syntax in C#):

Iterator it = sequence.iterator();

while (it.hasNext()) {
    System.out.println(it.next());
}
```

<p>Which makes sense. Here's the equivalent syntax in Python:</p>

```it = iter(sequence)
while True:
    try:
        value = it.next()
    except StopIteration:
        break
    print(value)
```

I thought Exceptions were supposed to be used only in, well, exceptional circumstances.

Why does Python use exceptions to stop iteration?

答:
The reason why python uses an Exception to stop an iteration is documented in PEP 234:

It has been questioned whether an exception to signal the end of
      the iteration isn't too expensive.  Several alternatives for the
      StopIteration exception have been proposed: a special value End
      to signal the end, a function end() to test whether the iterator
      is finished, even reusing the IndexError exception.

A special value has the problem that if a sequence ever
  contains that special value, a loop over that sequence will
  end prematurely without any warning.  If the experience with
  null-terminated C strings hasn't taught us the problems this
  can cause, imagine the trouble a Python introspection tool
  would have iterating over a list of all built-in names,
  assuming that the special End value was a built-in name!

Calling an end() function would require two calls per
  iteration.  Two calls is much more expensive than one call
  plus a test for an exception.  Especially the time-critical
  for loop can test very cheaply for an exception.

Reusing IndexError can cause confusion because it can be a
  genuine error, which would be masked by ending the loop
  prematurely.

Note: the idiomatic python way to loop over a sequence is like this:

```<code>for value in sequence:
    print (value)
</code>```

Body:
The reason why python uses an Exception to stop an iteration is documented in PEP 234:

It has been questioned whether an exception to signal the end of
      the iteration isn't too expensive.  Several alternatives for the
      StopIteration exception have been proposed: a special value End
      to signal the end, a function end() to test whether the iterator
      is finished, even reusing the IndexError exception.

A special value has the problem that if a sequence ever
  contains that special value, a loop over that sequence will
  end prematurely without any warning.  If the experience with
  null-terminated C strings hasn't taught us the problems this
  can cause, imagine the trouble a Python introspection tool
  would have iterating over a list of all built-in names,
  assuming that the special End value was a built-in name!

Calling an end() function would require two calls per
  iteration.  Two calls is much more expensive than one call
  plus a test for an exception.  Especially the time-critical
  for loop can test very cheaply for an exception.

Reusing IndexError can cause confusion because it can be a
  genuine error, which would be masked by ending the loop
  prematurely.

Note: the idiomatic python way to loop over a sequence is like this:

for value in sequence:
    print (value)


问:
Is there a design pattern for chained observers?
Several times, I've found myself in a situation where I want to add functionality to an existing Observer-Observable relationship.

For example, let's say I have an Observable class called PriceFeed, instances of which are created by a variety of PriceSources.  Observers on this are notified whenever the underlying PriceSource updates the PriceFeed with a new price.

Now I want to add a feature that allows a (temporary) override to be set on the PriceFeed.  The PriceSource should still update prices on the PriceFeed, but for as long as the override is set, whenever a consumer asks PriceFeed for it's current value, it should get the override.

The way I did this was to introduce a new OverrideablePriceFeed that is itself both an Observer and an Observable, and that decorates the actual PriceFeed.  It's implementation of .getPrice() is straight from Chain of Responsibility, but how about the handling of Observable events?  When an override is set or cleared, it should issue it's own event to Observers, as well as forwarding events from the underlying PriceFeed.

I think of this as some kind of a chained observer, and was curious if there's a more definitive description of a similar pattern.

答:
That's called Reactive Programming.

Look at Rx.

Rx is all about this.

It treats observables as enumerables and then what you are doing becomes as simple as calling map on the first sequence of events.

```<code> events.map(new function(each) { return override != null ? override : each }
</code>```

Rx is available for many languages, you'll find a video with an introduction of RxJS for Javascript here, http://youtu.be/FqBq4uoiG0M

Body:
That's called Reactive Programming.

Look at Rx.

Rx is all about this.

It treats observables as enumerables and then what you are doing becomes as simple as calling map on the first sequence of events.

 events.map(new function(each) { return override != null ? override : each }

Rx is available for many languages, you'll find a video with an introduction of RxJS for Javascript here, http://youtu.be/FqBq4uoiG0M


问:
Internationalization of non-english application
I know there are lots of posts for internationalization, but this is something I didn't found while searching.

I have a PHP Web application, which is pretty big right now. It's developed actively for 4 years and wasn't built with internationalization in mind. Text is everywhere - in plain HTML, in PHP variables, in echo's, in the DB...

Now I'm familiar with the concept of gettext and this is what i plan to use for the internationalization project of the application. However the app is not written in English and  here is my question:

Should I first translate everything to English while wrapping every string in gettext() function, or I can use my native language as a base?

P.S. also any quick suggestions (links maybe) on making my life easier with the whole i18n project will be greatly appreciated!

答:
Not a very good source, Ill see if i can find a better one. Until then, this is from Gnome dev center

Currently, gettext does not support non-ASCII characters (i.e. any characters with a code above 127) in source code.


答:
As I live and work in Germany, our websites use translations all the time. We use Ruby on Rails, but from what I read gettext() seems to work similar to  RoRs translation system. It won't matter if you have the translation already. Just create the file with your local texts and find some nice system to sort this file (mostly following your sites structure.)

We normally do something like this:

```<code>main.news: News
main.download: Download

portal.order.name: Name
portal.order.street: Street
portal.order.city: City
</code>```

So this would be the first two are texts on the main page and the others are labels for the order form in the portal section. You the would get them with gettext("main.new"). Do not just make one long list or you will never find stuff again. Allow for some stuff to appear several times (like we have addresses in several forms). You could make tags for them like address.street, address.city, but don't try to avoid repetitions 100%.

It may help to have the translations in Excel sheets or similar, from where you generate the text files. This may make handling easier. We don't do this normally, a good editor is ok too.

Then comes the database, which is more complex. There are several ways to do this. Basically have separate tables for the translations like Product with ProductTranslations or just repeat fields like title_en, title_de etc.

The table approach is better if you have many languages. The fields are simpler and searching with SQL is easier. But we use Apache Solr for the textsearch, having one core per language which works pretty well, so the database is mainly for storage.

Depending on your language be prepared to encoding problems. If any possible avoid having to copy data over different systems. Worst is Windows to Linux. If necessary use the most direct way possible. We once exported MS-SQL server data to CSV and the read back into Linux/Mysql. Constant source of pain. Worked far better when we skipped the CSV part and read data directly through ODBC.

Title: Internationalization of non-english application

Body:
I know there are lots of posts for internationalization, but this is something I didn't found while searching.

I have a PHP Web application, which is pretty big right now. It's developed actively for 4 years and wasn't built with internationalization in mind. Text is everywhere - in plain HTML, in PHP variables, in echo's, in the DB...

Now I'm familiar with the concept of gettext and this is what i plan to use for the internationalization project of the application. However the app is not written in English and  here is my question:

Should I first translate everything to English while wrapping every string in gettext() function, or I can use my native language as a base?

P.S. also any quick suggestions (links maybe) on making my life easier with the whole i18n project will be greatly appreciated!

Body:
As I live and work in Germany, our websites use translations all the time. We use Ruby on Rails, but from what I read gettext() seems to work similar to  RoRs translation system. It won't matter if you have the translation already. Just create the file with your local texts and find some nice system to sort this file (mostly following your sites structure.)

We normally do something like this:

main.news: News
main.download: Download

portal.order.name: Name
portal.order.street: Street
portal.order.city: City

So this would be the first two are texts on the main page and the others are labels for the order form in the portal section. You the would get them with gettext("main.new"). Do not just make one long list or you will never find stuff again. Allow for some stuff to appear several times (like we have addresses in several forms). You could make tags for them like address.street, address.city, but don't try to avoid repetitions 100%.

It may help to have the translations in Excel sheets or similar, from where you generate the text files. This may make handling easier. We don't do this normally, a good editor is ok too.

Then comes the database, which is more complex. There are several ways to do this. Basically have separate tables for the translations like Product with ProductTranslations or just repeat fields like title_en, title_de etc.

The table approach is better if you have many languages. The fields are simpler and searching with SQL is easier. But we use Apache Solr for the textsearch, having one core per language which works pretty well, so the database is mainly for storage.

Depending on your language be prepared to encoding problems. If any possible avoid having to copy data over different systems. Worst is Windows to Linux. If necessary use the most direct way possible. We once exported MS-SQL server data to CSV and the read back into Linux/Mysql. Constant source of pain. Worked far better when we skipped the CSV part and read data directly through ODBC.


答:
It is just my very humble opinion but I think you really should use english as the default language of your application (as for every other conceivable application).

There are at least three reasons for this:

Most if not all of the existing tools recognize and handle just english (or at least just english-like languages). I'm italian and I know very well what does it mean to handle non-ASCII (accented) characters in code and in UIs.

Nowadays it is almost impossible to develop an application without any code exchange with foreign people. Just think to SO itself. You stomp against a problem, look for help on SO and publish a snippet of your code here. The people that could help you will have a hard job trying to understand your native language variable names and comments.

Most important, on the web almost everybody understand english. Maybe just a little percentage of people can actually speak it and understand the spoken language but almost everybody can read it and understand the written language. English is arguably the best choice as a default (or "safe fail" or "fall-back") language.

Despite this, there isn't any compelling reason to translate evrything into english as your first move. Just translate it while you move to the new version.

Moreover: do not try to translate everything. There are elements of code and of UI that will never get exposed, not even to other (foreign) programmers.

Just try to translate these elements:

Messages that shows up in the UI (notification and the like) and in the console (error messages and the like)

UI texts (of course...). That means any text in HTML and Javascript.

If possible, public class names, public variable names, public methods names and comments in code. These elements will likely be read and used by other programmers and in this moment you cannot know what will be their mother language.

If you use some cusom build script (Ant/Maven/Rake/Whatever), some custom versioning script (GIT, SVN, etc.) or some custom code-generation tool, translate them as well. They are part of your toolbox/toolchain and it is important that other (maybe foreign) programmer can understand and use them.

I know that translating source code is a huge and terrible effort. I do not mean you have to do it all at once and just now. Just translate the code while you refactor and just when you stomp on it. It is better to have a mixed english/native-language source tree than a native-language only (because every decent programmer in your area will have to understand english in any case. This means that you cannot do any damage translating your stuff into english).

Leave in you language the elements that do not show up in UI and in code and/or that are too painful to translate. For example:

DB tables and columns names. Create an external "glossary" file for them.

Private ("inner") classes, private variable and private method names. Most likely, these elements will never show up elsewhere and you can safely ignore them.

Keep in mind that most IDEs can help you a lot in this task. Also, you can easily write some custom PHP (or Python/Perl/Ruby) script to help yourself finding and changing the text strings.


问:
Should I use a parser generator or should I roll my own custom lexer and parser code?
What specific advantages and disadvantages of each way to working on a programming language grammar?

Why/When should I roll my own? Why/When should I use a generator?

答:
Option 3: Neither (Roll your own parser generator)

Just because there's a reason not to use ANTLR, bison, Coco/R, Grammatica, JavaCC, Lemon, Parboiled, SableCC, Quex, etc - that doesn't mean you should instantly roll your own parser+lexer.

Identify why all these tools are not good enough - why don't they let you achieve your goal?

Unless you're certain that the oddities in the grammar you're dealing with are unique, you shouldn't just create a single custom parser+lexer for it. Instead, create a tool that will create what you want, but can also be used to fulfil future needs, then release it as Free Software to prevent other people having the same problem as you.


问:
Fitting an established site into a CI framework
I manage a rather large, feature full nightmare of a site which has no end of feature creep settings/options/etc.

Up to now its been coded in a procedural/functional way and would like to move to an OO,MVC setup. I'm quite new to it all but have done alot of research and feel that CodeIgniter is a code choice of framework to use to help quicken the transfer. Before looking at a framework, I started constructing a list of objects to create classes out of:

photos

users

forum topics

forums

blogs

blog posts

comments

The trouble I have now, is I do understand where these generic/universal objects fall into the CI MVC setup. What is the best way to organise this kind of stuff? These classes can generally be used on multiple models/views/controllers.

答:
"These classes can generally used on multiple models/views/controllers". From a MVC perspective there is no problem of a model being used in several controllers and views.

So you are left with the model, but as far as I see, there should simply be one model class for each of those objects, since they relate to one database table each. Then they may interact with each other, which partially may be handled by the controller or by the models themselves (depending a bit on use case, preferably by the models).