答:
There are still people in the world who don't use Java generics in "ordinary coding."  I can believe it with C++ templates, but generics?  They aren't even hard to learn/use.  Seriously the best features of Java and C++ are respectively generics and templates.

The best way to convince people of things is to make a compelling argument, be non-threatening, and be right.

So long as you are not doing something like using templates as your programming language, parametric polymorphism (generics/templates) is almost certainly good.

1. Avoids code duplication.

This is obvious, but polymorphic code is general code.  That is why it is called generics.

2. Supports better static checking.

Without parametric polymorphism you end up writing things like public Object clone() or public boolean equals(object b) which are not just abominations, they have types that provide no information about what they do, and invariably end up throwing exceptions all over the place.  The alternative to parametric polymorphism is casts all over the place

3. Non parametric polymorphism OOP code is basically unable to handle "binary methods" in a correct way.

You use these often.

4. It is best practice

In Java, use of generics is considered best practice (see Effective Java by Josh Bloch). Major C++ thinkers like Sutter and Alexandrescu also encourage the use of templates to solve a variety of problems.

5. It fits the OO paradigm.

People often don't notice this, but the combination of sub-typing and generics produces a system MUCH more powerful expressive, and object oriented than any system with just one of them.

Consider Scala's mixins.  These are a nice feature that lets you pull your objects together from component parts.  Generics and templates can simulate some of these benefits.  For example, say one of your objects uses a database.  Good design would have you abstract out the database access into a separate class.  If done right this not only lets you mock your data-store (key to testability), it also means that you can add alternative implementations like that new no-sql database.  Here though, you might have a problem, mattering which implementation you use you will get different capabilities of your business object.

Generics to the rescue!

```<code>   public class Business<S extends Datastore>{
      private S store; ...
   }
</code>```

Now you can start statically differentiating your Business objects based on ability to use database specific features.  You still need some runtime checks and casting, but you can start building MUCH better code.

and

6. Normal code doesn't exist.

There are only three things in the programming universe:

libraries,

configurations, and

bad code.

If you don't think about your code like it is a library you are in serious trouble when the requirements for your project change.  Architecture is (arguably) the art of designing good APIs.

I find this attitude stunning.  After you get used to programming with parametrized types, not using them just makes everything a pain.  And, Java and C++ have a bunch of rough spots which they help remedy.

Body:
There are still people in the world who don't use Java generics in "ordinary coding."  I can believe it with C++ templates, but generics?  They aren't even hard to learn/use.  Seriously the best features of Java and C++ are respectively generics and templates.

The best way to convince people of things is to make a compelling argument, be non-threatening, and be right.

So long as you are not doing something like using templates as your programming language, parametric polymorphism (generics/templates) is almost certainly good.

1. Avoids code duplication.

This is obvious, but polymorphic code is general code.  That is why it is called generics.

2. Supports better static checking.

Without parametric polymorphism you end up writing things like public Object clone() or public boolean equals(object b) which are not just abominations, they have types that provide no information about what they do, and invariably end up throwing exceptions all over the place.  The alternative to parametric polymorphism is casts all over the place

3. Non parametric polymorphism OOP code is basically unable to handle "binary methods" in a correct way.

You use these often.

4. It is best practice

In Java, use of generics is considered best practice (see Effective Java by Josh Bloch). Major C++ thinkers like Sutter and Alexandrescu also encourage the use of templates to solve a variety of problems.

5. It fits the OO paradigm.

People often don't notice this, but the combination of sub-typing and generics produces a system MUCH more powerful expressive, and object oriented than any system with just one of them.

Consider Scala's mixins.  These are a nice feature that lets you pull your objects together from component parts.  Generics and templates can simulate some of these benefits.  For example, say one of your objects uses a database.  Good design would have you abstract out the database access into a separate class.  If done right this not only lets you mock your data-store (key to testability), it also means that you can add alternative implementations like that new no-sql database.  Here though, you might have a problem, mattering which implementation you use you will get different capabilities of your business object.

Generics to the rescue!

   public class Business<S extends Datastore>{
      private S store; ...
   }

Now you can start statically differentiating your Business objects based on ability to use database specific features.  You still need some runtime checks and casting, but you can start building MUCH better code.

and

6. Normal code doesn't exist.

There are only three things in the programming universe:

libraries,

configurations, and

bad code.

If you don't think about your code like it is a library you are in serious trouble when the requirements for your project change.  Architecture is (arguably) the art of designing good APIs.

I find this attitude stunning.  After you get used to programming with parametrized types, not using them just makes everything a pain.  And, Java and C++ have a bunch of rough spots which they help remedy.

ContentLicense: CC BY-SA 4.0


问:
How to spread awareness for generic programming among team members?
I am staying in an environment, where people believe:

Java generics are the feature exclusively used for library writing
and not for the real coding.

C++ is an OO programming language; template is an optional and
avoidable feature

Though, these people rely highly on the libraries written using generic programming (e.g. STL, Java containers). If I write a code using templates or generics, the code reviewer is most likely to reject it and will comment to write it in a "proper / understandable / elegant" way.

Such mentality is applicable from normal programmer to senior most manager. There is no way out, because 90% of the time, these people have their lobbying.

What is the best way (not being cut throat) of explaining them, the practical approach of writing code which constitutes OO and generic programming both at the same time ?

答:
Unless you are the architect/tech lead it will be difficult to mandate that you should use generics/templates. You really should propose the generic/template solution long before the code review, preferrably before you start implementing it.

What you can do, is to demonstrate why you should use a generic in some case. If you can demonstrate the benefits, then your colleagues might agree. The possible reasons why you should use generics/templates should be the following:

It should let you write less code for repetetive tasks

It makes the programmers job easier

It enforces a pattern set by the solution architect

It encapsulates common features, that would force the programmers not to copy-paste code (i.e. avoiding the double maintenance problem)

It reasonably future proofs your code (though this avenue is difficult to reason about)

In a recent Java project I successfully added some generic abstract class because it satisfied some basic things: it made things easier for the others in the team, enforced the pattern that the architect already proposed and had some common code that programmers didn't need to copy and paste. It was a simple pattern that the architect wrote about that reasonably competent people still got wrong (because of the complexity of the actual system in play), but the generics marks which class goes where.

Obviously I can't show off the real example without breaching the non-disclosure agreement. But as an example of what I did would be to do the strategy pattern and enforcing it with generics. So this is the strategy pattern:

And in order for the programmers to enforce this pattern, you can add the generic type on Context that it should use something that has a Strategy type. Code-wise it would look something like this in Java:

```<code>// declare the generic Context class that has a type "S"
// that is an upper bound class of Strategy
public class Context <S extends Strategy> {
    S strategy;

    // Constructor with an initial strategy
    public Context(S initialStrategy) {
        this.strategy = initialStrategy;
    }

    public void doSomething() {
      strategy.execute(); // assumes that Strategy has an execute() method.
    }

    public void setStrategy(S strategy) {
        this.strategy = strategy;
    }
}
</code>```

You can do this pretty much with any pattern as far as I know. Be sure you can test your generic/template design with unit tests to see that it works, in order to have confidence in the code design.

If your colleagues don't like the idea then don't take it personally, it might not have been made as easy of a solution for them to handle as you thought. Which is why you should propose a generic/template solution before you start implementing it. You still have to work together with your colleagues to solve the actual problem in a different fashion.

ContentLicense: CC BY-SA 3.0

Body:
Unless you are the architect/tech lead it will be difficult to mandate that you should use generics/templates. You really should propose the generic/template solution long before the code review, preferrably before you start implementing it.

What you can do, is to demonstrate why you should use a generic in some case. If you can demonstrate the benefits, then your colleagues might agree. The possible reasons why you should use generics/templates should be the following:

It should let you write less code for repetetive tasks

It makes the programmers job easier

It enforces a pattern set by the solution architect

It encapsulates common features, that would force the programmers not to copy-paste code (i.e. avoiding the double maintenance problem)

It reasonably future proofs your code (though this avenue is difficult to reason about)

In a recent Java project I successfully added some generic abstract class because it satisfied some basic things: it made things easier for the others in the team, enforced the pattern that the architect already proposed and had some common code that programmers didn't need to copy and paste. It was a simple pattern that the architect wrote about that reasonably competent people still got wrong (because of the complexity of the actual system in play), but the generics marks which class goes where.

Obviously I can't show off the real example without breaching the non-disclosure agreement. But as an example of what I did would be to do the strategy pattern and enforcing it with generics. So this is the strategy pattern:

And in order for the programmers to enforce this pattern, you can add the generic type on Context that it should use something that has a Strategy type. Code-wise it would look something like this in Java:

// declare the generic Context class that has a type "S"
// that is an upper bound class of Strategy
public class Context <S extends Strategy> {
    S strategy;

    // Constructor with an initial strategy
    public Context(S initialStrategy) {
        this.strategy = initialStrategy;
    }

    public void doSomething() {
      strategy.execute(); // assumes that Strategy has an execute() method.
    }

    public void setStrategy(S strategy) {
        this.strategy = strategy;
    }
}

You can do this pretty much with any pattern as far as I know. Be sure you can test your generic/template design with unit tests to see that it works, in order to have confidence in the code design.

If your colleagues don't like the idea then don't take it personally, it might not have been made as easy of a solution for them to handle as you thought. Which is why you should propose a generic/template solution before you start implementing it. You still have to work together with your colleagues to solve the actual problem in a different fashion.


问:
Rule of thumb for cost vs. savings for code re-use
Is it a good rule of thumb to always write code for the intent of re-using it somewhere down the road?  Or, depending on the size of the component you are writing, is it better practice to design it for re-use when it makes sense with regards to time spent on it.  What is a good rule of thumb for spending extra time on analysis and design on project components that have "some probability" of being needed later down the road for other things that may or may need this part.

For example, if I have the need for project X to do things A, and B.  A definitely needs to be written for re-use because it just makes sense to do so.  B is very project specific at the moment, and I can hack it all together in a couple days to finish the project on time and give everyone kudos for being a great team, etc.  Or if we say, lets spend a whole friggin' 2 weeks figuring out what project Y/Z might need this thing for and spend a load of extra time on on part B because someday we might need to use it on project Y/Z (where the savings will be realized).

I'd imagine a perfect world situation would be a nicely crafted combination of project specific vs. re-use architected components given the project.  However some code shops might feel it would be a great idea to write everything for the intention of using it at some point down the road.

答:
What is a good rule of thumb for spending extra time on analysis and design on project components that have "some probability" of being needed later down the road for other things that may or may need this part.

For cases like above my preferences are based on an estimate derived at one of my past projects: re-usable code takes 3-4x times more efforts to write (YMMV).

Another thing I noticed is that it's quite hard to properly design code for re-use when all you've got is just one usage example. In other words, when I design "for just in case", without having an example for that, it often turns out that I have to redesign it later when need for real re-use arises.

Given above I tend to avoid designing for re-use until I have a real case for that. In that sense I rather strongly follow YAGNI. On the other hand, when there is at least one case of re-use I try to re/design for that instead of duplicating code - even when my plain calculation of efforts is still in favor of duplication (2x efforts vs 3-4x) - guess this preference have something to do with considerations of further maintenance.

For example, if I have the need for project X to do things A, and B.  A definitely needs to be written for re-use because it just makes sense to do so.  B is very project specific at the moment, and I can hack it all together in a couple days to finish the project on time and give everyone kudos for being a great team, etc.  Or if we say, lets spend a whole friggin' 2 weeks figuring out what project Y/Z might need this thing for and spend a load of extra time on on part B because someday we might need to use it on project Y/Z (where the savings will be realized).

In case like above I'd personally go for quick hacking for B.

The only thing that makes me uncomfortable would be if there are no traces left for this decision (like what is the problem, what options were considered, what was the decision and why). But this is really easy to handle - I do it routinely at decisions like that: just register it in your issue tracker, describe things and let it be there until time allows to take care of that. Or until there's time to prepare that
other project Y/Z - when you can include friggin' 2 weeks in the estimate.

Issue 1234 - throwaway code in thing B -- fix postponed -- efforts estimate 2 weeks


答: After a while of consciously coding in a generic, dependency-inverted style it really does become effortless. With the bonus of automatically reusable code.</p>

Title: Rule of thumb for cost vs. savings for code re-use

Body:
Is it a good rule of thumb to always write code for the intent of re-using it somewhere down the road?  Or, depending on the size of the component you are writing, is it better practice to design it for re-use when it makes sense with regards to time spent on it.  What is a good rule of thumb for spending extra time on analysis and design on project components that have "some probability" of being needed later down the road for other things that may or may need this part.

For example, if I have the need for project X to do things A, and B.  A definitely needs to be written for re-use because it just makes sense to do so.  B is very project specific at the moment, and I can hack it all together in a couple days to finish the project on time and give everyone kudos for being a great team, etc.  Or if we say, lets spend a whole friggin' 2 weeks figuring out what project Y/Z might need this thing for and spend a load of extra time on on part B because someday we might need to use it on project Y/Z (where the savings will be realized).

I'd imagine a perfect world situation would be a nicely crafted combination of project specific vs. re-use architected components given the project.  However some code shops might feel it would be a great idea to write everything for the intention of using it at some point down the road.


问:
How to convert a copy/paste/spaghetti programmer to see the light?
This question was inspired by this one. While that other question was deemed localized, I believe the underlying problem is something that is extremely common in our industry. I know there are some developers, who will read this and think I'm making this stuff up and then they might reply how everyone cares about their work and wants to learn, but just looking at other Programmers SE posts (case in point), I know that's not universally true.

So let's say you have someone on your team (or maybe majority) who's standard operating procedure is to copy/paste and who believes that everything can be solved if only you add enough function calls and variables. This person never heard of TDD, DRY or SOLID and outside of 40 hours at work when they are busy working, they never once read a single methodology/pratices/design book.

In the past I (and others) have asked, how to do you teach OOD. But now I'm thinking that's not the right question. The real question is how do you approach such a person/team and make them curious about better way of doing things? How do you inspire them to learn?  Without that, it seems that all the teaching, meetings, lectures, discussions are useless if they are perfectly happy going back to their desk and doing what they've always done.

I work with a bunch of people like that. They are actually quite bright individuals, but I hate when I hear, "I'm done coding, just need to refactor and split into multiple classes to make DXM happy". They don't refactor for cleaner, readable, maintainable code, but only because otherwise they'll get scolded. I know they are capable of learning, just seems that there's a general lack of motivation.

When I deliver work, it generally has way fewer bugs and the work I owned never became 5000-line monstrosity of a class. Other's would make comments like, "your code is much cleaner and readable than our stuff", so they see the difference.  But at the same time, I feel like they believe they get paid for 40 hours regardless of what they do, so they actually don't mind if they spend 3 full days in QA looking for a bug that shouldn't have been introduced in the first place. Or that they take a week to modify one class because there are so many dependencies they end up touching.  The though, "maybe that class should have been written differently" never seems to pop up.

Can anything be done in these situations? Has anyone succeeded? Or is it best to isolate such mindset to non-critical parts of the project and minimize the damage?

NOTE: When I say "lack of motivation". I don't think it's lack of motivation to work or do a good job because they simply stopped caring.  Most of our team is actually quite the opposite. They definitely care about the product. We have guys that will work nights and weekends. The part I'm trying to get through is with improved habits and skills, they actually wouldn't have to work as much. I guess that "40 hours" thing made this post sound a little too negative.

答:
Good question! I think the answer depends on why people don't want to improve their skills. Possible answers are:

They think they are too busy to learn something new or they think the new way of doing things (like writing all those tests) will take them longer and they don't have time for that. Then the obvious answer would be: give them more time. Learning something or trying something like TDD when you've always done things differently will take more time the first couple of times. If your programmers don't have that time, you can't blame them for not trying.

They have a different perception of their own skills, i.e. they think they're very good programmers producing high-quality code. This is difficult psychological terrain, because shattering that belief can be very demotivating. Maybe some kind of informal competition can help (who produces the fewest defects/feature? the shortest code? the fewest WTF's/minute in a code review?).

There might be an actual motivation problem (i.e. they just want to "do their time and get left alone" until closing time). Luckily, this is too general/not programming-related, because I really don't have an answer for that.

They're beginners and they don't know better. In that case, training, code reviews might help, or a "book club" where a team member has to discuss a new technical book every month.

They've seen silver bullets before, (and were bitterly disappointed) and they think whatever you're trying to sell them is just another new buzzword that sounds good in theory and is little use in practice. In that case, demonstrating the advantages during code reviews and pair programming sessions might work. Try not to be a total know-it-all when you do that.

The best solution really depends on the root problem: For example, formal coding guidelines, metrics and reviews can work for beginners, but people in the "wrong perception of their own skills"-crowd might struggle against them or play the metrics because they see them as counterproductive bureaucratic obstacles to getting their work done.


答:
"I'm done coding, just need to refactor and split into multiple classes to make DXM happy".

That line of thinking right there is a cancer on any team and will kill the motivation of the entire team if not taken care of immediately.  I am referring of course to the fact that by seniority and/or merit you happen to be in a position of technical authority, giving you the power to help influence and bring about good practices into your team.

This is all well and good, however if your team was clearly sold on these processes they wouldn't single you out in statements like this to each other that clearly show a lack of respect for the process and a lack of respect in you.  They still see these best practices as a hindrance caused by you and not a process owned by the team that your team will defend of its own merits.

You mention in previous comments that other team members are indeed following these practices and standards well and applying them correctly.  Focus attention first at bolstering support from them, ask them what works, what doesn't work, what they like and what they would like to see changed.  If you do this and take their opinions seriously they will feel very differently about the standards as if they were a community decision instead of a procedure handed down to them from a superior.

You bolster support for best practices and standards by pointing out to the team how they have improved the software development process or quality of software.

Hold a vote on the matters up for discussion and document the results, ideally every decision should be unanimous for the sake of legitimacy but if you are dealing with hard line obstructionists this may be impossible and could just stall out every issue.  Use a majority vote in this situation.  If the majority are against your proposed standards and practices then you have lost the room already, just give it up at that point.

They will own those standards and procedures and will enforce them so that you don't have to.  As a tech lead you shouldn't have to declare edicts and decrees, that is a poor way to be a leader.

Once the team feels as if they own the procedures then members of the team who begin to label you to certain procedures and best practices will be illegitimate to think so.  Your team will help to correct this attitude in others.

Title: How to convert a copy/paste/spaghetti programmer to see the light?

Body:
This question was inspired by this one. While that other question was deemed localized, I believe the underlying problem is something that is extremely common in our industry. I know there are some developers, who will read this and think I'm making this stuff up and then they might reply how everyone cares about their work and wants to learn, but just looking at other Programmers SE posts (case in point), I know that's not universally true.

So let's say you have someone on your team (or maybe majority) who's standard operating procedure is to copy/paste and who believes that everything can be solved if only you add enough function calls and variables. This person never heard of TDD, DRY or SOLID and outside of 40 hours at work when they are busy working, they never once read a single methodology/pratices/design book.

In the past I (and others) have asked, how to do you teach OOD. But now I'm thinking that's not the right question. The real question is how do you approach such a person/team and make them curious about better way of doing things? How do you inspire them to learn?  Without that, it seems that all the teaching, meetings, lectures, discussions are useless if they are perfectly happy going back to their desk and doing what they've always done.

I work with a bunch of people like that. They are actually quite bright individuals, but I hate when I hear, "I'm done coding, just need to refactor and split into multiple classes to make DXM happy". They don't refactor for cleaner, readable, maintainable code, but only because otherwise they'll get scolded. I know they are capable of learning, just seems that there's a general lack of motivation.

When I deliver work, it generally has way fewer bugs and the work I owned never became 5000-line monstrosity of a class. Other's would make comments like, "your code is much cleaner and readable than our stuff", so they see the difference.  But at the same time, I feel like they believe they get paid for 40 hours regardless of what they do, so they actually don't mind if they spend 3 full days in QA looking for a bug that shouldn't have been introduced in the first place. Or that they take a week to modify one class because there are so many dependencies they end up touching.  The though, "maybe that class should have been written differently" never seems to pop up.

Can anything be done in these situations? Has anyone succeeded? Or is it best to isolate such mindset to non-critical parts of the project and minimize the damage?

NOTE: When I say "lack of motivation". I don't think it's lack of motivation to work or do a good job because they simply stopped caring.  Most of our team is actually quite the opposite. They definitely care about the product. We have guys that will work nights and weekends. The part I'm trying to get through is with improved habits and skills, they actually wouldn't have to work as much. I guess that "40 hours" thing made this post sound a little too negative.


问:
What is the Best Style for Functions with Multiple Returns and If/Else Statements?

Possible Duplicate:

  Elegant ways to handle if(if else) else

In a function where there are multiple returns, what is the best style to use?

This style, where there is no 'else' because it is frivolous and you think it is more concise?

```<code>f() {
    if (condition) {
        return value;
    }

    return other_value;
}
</code>```

Or this, if you think that 'else' provides nice syntax sugar to make it more readable?

```<code>f() {
    if (condition) {
        return value;
    } else {
        return other_value;
    }
}
</code>```

Feel free to share whatever other reasons you may have for preferring one over another.

EDIT:

The above samples are hypothetical, if they were this simple, as Yannis Rizos noted below, the ternary operator ( condition ? value : other ) would be acceptable. However I'm also interested in cases like this:

```<code>f() {
    if (condition1) {
        return value;
    } else if (condition2) {
        return value2;
    }
    ...
    else {
        return other_value;
    }
}
</code>```

答: My personal preference is to include the unnecessary else. I find that I can grok the control flow at a glance when it's there, versus having to remember to hunt for returns that branch the flow implicitly. A couple times I've come back to cold code and added something after an "if" and been confused about why it wasn't running, only to realize I hadn't seen the return that bailed the function before getting to my new stuff.


问:
Should I use the language I'm most comfortable in, or the company "standard"
I'm going to be developing an Intranet site for my specific plant, and our company standard for web-development is IIS + ASP.Net + VB.Net + Microsoft SQL Server (note that we have about 10+ plants). The Intranet site will only be used by my plant, and I'm the only one who will support it. I'm much more proficient with a LAMP setup, and I could do development and problem solving much more rapidly with PHP than I could ASP.Net. Even though the company "standard" is ASP.Net/VB.Net, most of what the company does as a whole is to purchase third party software (which is usually Java based), and very, and I do mean very few people in the company even know VB6, let alone ASP.Net/VB.Net.

That being said, is it better to violate the company standard and go with the setup that I can support better, or is it better to go with the setup that the company can support better if I ever were to leave, even though no one currently in the company can support their own standard anyway?

Some additional factors to consider in my personal case:

Again, this is only for my plant, and I'm the only one who will ever be supporting it unless I leave the company, and then my replacement would be supporting it. Not someone else already in the company.

The company does very little development with their standard anyway.

Hardly any of the companies existing software uses their standard.

If I choose the company standard, then I have to use the Express version of Microsoft SQL and a Windows 7 OS. From my readings, the Express version is okay for business use, but the database size is limited.

答:
In this case you need to follow the standard. If the standard doesn't seem to apply, you need to talk to your manager about doing it in a different language.

Of all the standards to follow in development, I personally feel that language choice is the most important. Ignoring the standard language choice in favor of one you are more comfortable with leaves co-workers and/or successors up a creek without a paddle, because they may not have the skills to work on your project. A company's hiring decisions are based on language choice so decisions like these can have a major impact. Introducing yet another platform/language may force the company into a tight spot when they start hiring other people.

Beyond the language you have to consider internal support for the LAMP server. Who is going to administer Apache? How about MySQL? Does the company's software run on a different database? Will the administrators be willing to administer a new platform. Even if you plan on administering these services, the duties could eventually fall on somebody else. If you plan on administering the services, will the network/server admins allow you to do so?

The ramifications of introducing a different platform can be wide and deep. Not following the standard may end up affecting many people besides yourself. Even though you are more proficient in LAMP than ASP.NET, building on that platform could end up costing your company much more in the long run. Key here is communicating with your manager and understanding the effects of the final decision.


答:
It seems to me that this is a management and leadership problem - if its your team then you can work to make improvement (personal and of the code) a core attribute of your team, the question is will that be supported by your management - because you're going to want to do things that will take time (they'll get a net win as you should reduce new technical debt and will be repaying existing technical debt).

So, you assert that you want the team to improve, you get their agreement that this is a good thing (that the team, as a whole, works to improve the quality of its code) and you then start on a programme to make this happen - it sounds so easy... I'm aware its not!

I think there are two parts to this - education and working practices.

Education you can start one lunchtime a week - everyone eats together, you run a 20~30 minute presentation with Q&A. You start with the basics you want - SOLID can occupy the first 2~4 weeks - over time you get the team to speak in rotation and you can work out how to decide who talks on what between you. Allow speakers some prep time within work. Beyond that encourage attendance of local user groups (by making it at least partly social thing if possible)

Working practices... well it depends on what you do now and what tooling you've got, but you might want to look at agreeing coding standards, introducing peer code review (is it solid), unit testing (not necessarily test first), running a continuous integration server and looking at more automated testing (in addition to unit tests). But these have substantially to be introduced with consent/agreement (not the build/CI server!) and you have to want to drive quality forward as a team. There are always things one can improve (Kaizen)

Its also worth looking at Kanban (which is seen by as a driver for change/improvement).

One last thought - I'm a vocational programmer, and I'd like my team to be the same  but working more than 40 hours a week is not actually a good thing so one's objective should be to have a team that gets its work done effectively and well within the normal working week and in respect of this the argument for improving working practice is that it is more likely e.g: adding unit tests to demonstrate the failing case when (before) bug-fixing gives you confidence that it is fixed; having a build server gives you confidence in your ability to build your solutions cleanly - if that build also generates deployment packages it means that deployment is dramatically simplified; SOLID code is, by definition, easier to modify; and across the board the less technical debt you incur the less you have to pay back...


问:
Git workflow for multiple teams
We are going to start using Git (not using it yet), and I want to define the workflow.

We have 4 teams at 4 different global locations, developing together the same product. Each team owns a part of the product's code, but sometimes they also have to make changes in the code owned by other teams.

Is there a recommendation for a Git workflow for such an environment?

I have already seen this article, but the approach here is "we create additional branches as seldom as possible", and I believe more in "branch for each user story" approach.

Also, this article presents a nice approach.

I had in mind having a master branch, a permanent branch per each team periodically merging to master, and a per-user-story branches merging to the teams' branches. Does it make sense, or it wouldn't work?

答:
I would say that each team has its own version of the repository, with one global repository where everyone commits to (like in Linux kernel, where the Linus repository IS the kernel and central repository).

Then for maintaining the product code, you could use submodules like @larsmans said, then each team can only work mainly on the part that is most important to them and if they need to work with other part, they can do it to, but they will have to remember to update the submodule, and this is where the problem lies (since it is very easy to get things wrong when using git, thankfully it is also easy to get away from them).

But since your teams are used to this, and are aware that they are changing other team code, it is easier for them to remember to do the submodule update, before changing a foreign module.

OwnerDisplayName: Igor Oks

Title: Git workflow for multiple teams


答:
I fell into programming by accident ~30 years ago. I was motivated to learn basic software engineering principles by being assigned to maintain/support other people's code. In these assignments, I learned how a code reader experiences code - how to empathize with the code reader. I did not want to inflict the pain of my poorly written code on others!

This practice of assigning new programmers to maintain/support other peoples code is not a magic bullet, and it does seem to provide motivation to learn how to produce solid code more often than not.


问:
Work load balance/Task distribution algorithm
I'm looking for an algorithm to either use or as a jump point for load balancing.

Environment:
We have ~7 job types that can be scheduled at any time by our users. Some jobs are fast, others are slow (lot of data processing). We have a single instance of a "job processor" that will discover jobs that have been scheduled and then execute them. The "job processor" will run up to 5 jobs at a time, "threads".

The problem is that one job could consume so many resources that the other 4 jobs don't get processed and even worse, the other scheduled jobs are delayed for long periods of time.

Some jobs can be scheduled as "run immediately" which makes them next in line.

Solution:
Add more instances of the "job processor". We have a big VM server that IT is rolling out 3 VM's to each handle an instance of this "job processor".

By default, it's going to help but I believe that there should be more thought behind it.

My solution:
In addition to making the "job processors" scale horizontally, I think there needs to be a way to determine which jobs an instance will grab based on current load of the instance and also allow for a bias.

I suggest we determine statistics for each job type (avg run time, etc) and give it a score of 1-5 (5 being long running). Each instance will determine what its current load is either based on the total score of the jobs its running currently and then factoring in it's bias. For example, I think we should be able to set an instance to be biased toward small jobs so it avoids larger jobs while another instance is biased toward medium jobs, etc.

I'm looking for advice on how to go about this. Jobs can consume large amounts of time, cpu and/or memory. My goal is to make sure each instance is only pulling down the work it's capable of doing while keeping the scheduled job queue moving along as quickly as possible.

One of the other devs suggested we leave the "job processors" alone to just pull whatever is in the queue next or "round robin". I say that this could lead to a potential issue where a single instance has pulled down too many large jobs and is struggling to get them done while the other instances are idle.

答:
I think your reasoning is sound and that your idea is good and friend's idea is good enough.

Perhaps you should also consider a "Pre-Process" process?

If your jobs are taking so much time that is causing unnecessary wait time in the queue, it may be possible to split a single large job into a series of smaller jobs that are preprocessing data into perhaps staging tables for the parent process.

Bringing the cost of an individual job down so that the disparity in average processing time is much lower would be a considerable alternative to a ranking system.

EDIT: I would also like to note that a ranking system derived from Time per Job can be heavily influenced by environment specific variables, (Eg. A job ranked low because of I/O access on a server with RAID configuration may not have a rank that makes sense on a server with a solid state HDD.)

This can be a pitfall in dermining rank based on the performance of a single environment.


问:
Two HTML elements with same id attribute: How bad is it really?
Just browsing the google maps source code. In their header, they have 2 divs with id="search" one contains the other, and also has jstrack="1" attribute. There is a form separating them like so:

```<code><div id="search" jstrack="1">
    <form action="/maps" id="...rest isn't important">
        ...
        <div id="search">...
</code>```

Since this is google, I'm assuming it's not a mistake.

So how bad can it really be to violate this rule? As long as you are careful in your css and dom selection, why not reuse id's like classes? Does anyone do this on purpose, and if so, why?

答:
Specification says UNIQUE

HTML 4.01 specification says ID must be document-wide unique.

HTML 5 specification says the same thing but in other words. It says that ID attributes must be unique amongst all the IDs in the element's tree, which is basically the document if we read the definition of it.

Avoid duplication

But since HTML renderers are very forgiving when it comes to HTML rendering they tolerate duplicate IDs. This should be avoided if at all possible and strictly avoided when programmatically accessing elements by IDs in JavaScript. I'm not sure what getElementById function should return when several matching elements are found? Should it:

return an error?

return first matching element?

return last matching element?

return a set of matching elements?

return nothing?

But even if browsers work reliably these days, nobody can guarantee this behavior in the future since this is against specification. That's why I recommend you never duplicate IDs within the same document.


问:
How can I make an in-house user group successful?
I would like to launch an in-house user group/forum for the developers in my company, but I'm not sure how to get started.

We have several teams of developers spanning many technologies and levels of experience.  I envision this as an opportunity for all of us to come together and share techniques, best practices, lessons learned, pain points, new technologies, or anything else a dev finds interesting.

This could also be a great way for new hires to integrate, learn how we do things, and share some of the expertise they bring with them.

This is my first attempt at anything like this and I'd like to do it right.

I'm interested in things like:

Driving participation

Keeping things interesting for both 20-year veterans and fresh, green graduates

Avoiding pitfalls known to be toxic to user groups

Has anyone done this successfully?  If so, what can you share about the experience?

答:
I envision this ....

While your vision is interesting, you really need to get every else's vision, first.

This is my first attempt at anything like this and I'd like to do it right.

Get over that notion.  Seriously.  Learning means making some mistakes and then correcting them.  You must get used to the idea that an innovation must include a fair number of failures along the way.

Driving participation

You can lead a horse to water, but you cannot make it drink.

People will participate when they see value.  You don't drive participation.  You create value.

Keeping things interesting for both 20-year veterans and fresh, green graduates

Noble.  Difficult.  You may have to start with one or the other.  Growth can come later.

First, get started with something -- anything -- that seems to work.

Then, when you have some core group that seems to be working, find ways to expand it.

You're selling an experience.  Some people find work rich enough that they don't want anything more.  Some people won't see the value in participating in a developer's group.  Some people won't see the value in an in-house developer's group.

Start small.  Grow incrementally.

Keep management at a distance.  Ideally, not involved at all.

Poll potential members early and often.  Be clear on what they want.


问:
Scrum tool for Product Backlog management
My team and I are very keen on doing Scrum "manual"-style (with paper and scissors). Though, we are struggling to find a tool to manage our backlog.

The main requirements are:

To be able to print the backlog in cards to stick to the whiteboard

To be able to assign backlog items to the releases manually

So far we have not found anything that matches these criteria. Suggestions?

答:
Keep it simple - spreadsheets + mail merge

Wouldn't it be simpler to use Excel spreadsheets and print Word document using Mail-merge and putting in the source of your Excel. Put as many cards on your paper (letter/A4) as required and merge the stories into a printable document.

I've used Excel several times and it works. It's simple, you can also add row colouring based on statuses etc. And when it comes to shareable spreadsheets Google Docs works just as good.


问:
Right license(s) for a freemium offer
I am currently working on a solution written in JavaScript. I plan to release two versions:

For free: the lite one with base options, which is plug and play (it just works when loaded in the page)

For a subscription fee: the full version that has more options and requires support

I am wondering which license(s) would work for me. Here are my thoughts so far, feel free to correct me:

MIT: I am concerned that somebody else might release new features on top of my solution, under a commercial license. It means that I wouldn't be able to add these same features to my own solution in the future.

GPL: doesn't seem to work in my case, if I release the lite version under GPL then it means that I also need to release the full version for free.

Dual licensing: I see that some frameworks or libraries offer dual licensing, but I am not sure how it works.

答:
You are the copyright owner, so no matter which license you choose you won't be limited to what you can do with your own software. In that respect, the choice of MIT or GPL is mostly a religious one. You can use either GPL or MIT and still build a commercial product on top of it even if it has features that are identical to what someone else has added.

Be aware, however, if someone else modifies the code, you can't just steal it and incorporate that into your own commercial version. That's not what open source is all about. You can write your own implementation of some cool new feature but you can't steal the code of others.

For me, the choice of license is mostly ideological. The chance of someone actually taking your code, improving it, and somehow stealing your future profits are very, very small. I'm sure there must have been a case of that happening sometime, but it's probably quite rare. If you really are concerned about that you should talk to a lawyer, or reconsider making the code open source. If you don't think it's worth the expense, then probably your software isn't valuable enough for others to want to steal it and profit off of it.

For me, personally, I think you should choose MIT or BSD. Arguably that makes your software the most free because it doesn't restrict how others use the software. I think that is the most altruistic approach, and if you aren't providing your code out of a sense of altruism, why open source it at all? That's just my opinion though, and I respect those that choose GPL even if I don't agree with their choice.

Title: Right license(s) for a freemium offer


答: We use ClearQuest for managing backlogs and features.</p>

Title: Scrum tool for Product Backlog management

Body:
My team and I are very keen on doing Scrum "manual"-style (with paper and scissors). Though, we are struggling to find a tool to manage our backlog.

The main requirements are:

To be able to print the backlog in cards to stick to the whiteboard

To be able to assign backlog items to the releases manually

So far we have not found anything that matches these criteria. Suggestions?


答:
Agree with S.Lott. Keep things small. You can start off by recruiting some of your top developers to give brown bag lunch talks about some of the interesting things that they're doing in house. This type of informal discussions should appeal in several ways - senior developers can share hard-won lessons while the newer developers can find out about interesting projects that are happening within the company.

If there's sufficient interest over time, you can set up a recurring schedule of talks - perhaps weekly or monthly. After your in-house community has built up sufficient interest/momentum, you can engage management to provide support for the group - primarily geared towards attracting interesting outside speakers or helping the developer's group with resources (if necessary).

Title: How can I make an in-house user group successful?

Body:
I would like to launch an in-house user group/forum for the developers in my company, but I'm not sure how to get started.

We have several teams of developers spanning many technologies and levels of experience.  I envision this as an opportunity for all of us to come together and share techniques, best practices, lessons learned, pain points, new technologies, or anything else a dev finds interesting.

This could also be a great way for new hires to integrate, learn how we do things, and share some of the expertise they bring with them.

This is my first attempt at anything like this and I'd like to do it right.

I'm interested in things like:

Driving participation

Keeping things interesting for both 20-year veterans and fresh, green graduates

Avoiding pitfalls known to be toxic to user groups

Has anyone done this successfully?  If so, what can you share about the experience?


问:
Examples of general purpose algorithms that have benefited from running on a GPU?
I am looking for examples of general purpose algorithms (meaning non-graphics related) that have been proven to run an order of magnitude faster on a GPU than on a CPU. I will use these examples to think creatively about other algorithms that I could implement on a GPU.</p>

答:
Mining Bitcoins using a GPU has become very popular.

...peer-to-peer, electronic cash system. Bitcoin creation and transfer is based on an open source cryptographic protocol and is not managed by any central authority. Each bitcoin is subdivided down to eight decimal places, forming 100 million smaller units called satoshis. Bitcoins can be transferred through a computer or smartphone without an intermediate financial institution.

The processing of bitcoin transactions is secured by servers called Bitcoin miners. These servers communicate over an internet-based network and confirm transactions by adding them to a ledger which is updated and archived periodically. In addition to archiving transactions each new ledger update creates some newly-minted bitcoins...

Another application is in financial markets for real-time trading using models such as Black-Scholes.

...A key requirement for utilizing options is calculating their fair value. Finding ways of efficiently solving this pricing problem has been an active field of research for more than thirty years, and it continues to be a focus of modern financial engineering. As more computation has been applied to finance-related problems, finding efficient ways to implement these algorithms on modern architectures has become more important.

This chapter describes how options can be priced efficiently using the GPU. We perform our evaluations using two different pricing models: the Black-Scholes model and lattice models. Both of these approaches map well to the GPU, and both are substantially faster on the GPU than on modern CPUs. Although both also have straightforward mappings to the GPU, implementing lattice models requires additional work because of interdependencies in the calculations...


答:
Add more instances of the "job processor". We have a big VM server that IT is rolling out 3 VM's to each handle an instance of this "job processor".

Correct.

By default, it's going to help but I believe that there should be more thought behind it.

Incorrect.

Any more engineering is an absolute waste of time.

Consider the use cases in detail.

On a single processor Queue, the long-running job gets into the one-and-only processor first.  Other jobs wait.   You don't like this.

On a multiple processor Queues, the long-running job gets into one of the processors, leaving the others free.    Problem solved.

Let's say that you have three long-running jobs that could get started concurrently.  Then, you simply need 4 processors to handle the workload.  Three will get long-running jobs, the fourth will handle the "instant" jobs.

Multiple processors working from a single queue of requests is the standard, widely-adopted, nearly universal solution.  Nothing more is needed.

If you really, really think priorities are important, you use a priority queue instead of a FIFO queue and you manually assign simple priorities.  Don't over-think it.  More thinking is going to simply be a waste of time.

Title: Work load balance/Task distribution algorithm

Body:
I'm looking for an algorithm to either use or as a jump point for load balancing.

Environment:
We have ~7 job types that can be scheduled at any time by our users. Some jobs are fast, others are slow (lot of data processing). We have a single instance of a "job processor" that will discover jobs that have been scheduled and then execute them. The "job processor" will run up to 5 jobs at a time, "threads".

The problem is that one job could consume so many resources that the other 4 jobs don't get processed and even worse, the other scheduled jobs are delayed for long periods of time.

Some jobs can be scheduled as "run immediately" which makes them next in line.

Solution:
Add more instances of the "job processor". We have a big VM server that IT is rolling out 3 VM's to each handle an instance of this "job processor".

By default, it's going to help but I believe that there should be more thought behind it.

My solution:
In addition to making the "job processors" scale horizontally, I think there needs to be a way to determine which jobs an instance will grab based on current load of the instance and also allow for a bias.

I suggest we determine statistics for each job type (avg run time, etc) and give it a score of 1-5 (5 being long running). Each instance will determine what its current load is either based on the total score of the jobs its running currently and then factoring in it's bias. For example, I think we should be able to set an instance to be biased toward small jobs so it avoids larger jobs while another instance is biased toward medium jobs, etc.

I'm looking for advice on how to go about this. Jobs can consume large amounts of time, cpu and/or memory. My goal is to make sure each instance is only pulling down the work it's capable of doing while keeping the scheduled job queue moving along as quickly as possible.

One of the other devs suggested we leave the "job processors" alone to just pull whatever is in the queue next or "round robin". I say that this could lead to a potential issue where a single instance has pulled down too many large jobs and is struggling to get them done while the other instances are idle.


答:
Video and audio transcoding is a great example. It's the conversion from one file format to another. An example is MPEG-2 to H.264.

Note video transcoding is not related to 3D graphics. You cannot encode a video using a vertex and pixel shader.

Title: Examples of general purpose algorithms that have benefited from running on a GPU?

Body: I am looking for examples of general purpose algorithms (meaning non-graphics related) that have been proven to run an order of magnitude faster on a GPU than on a CPU. I will use these examples to think creatively about other algorithms that I could implement on a GPU.</p>


答:
A few things immediately come to mind:

A specialized Bitcoin client was written to use the GPU to perform the cryptographic hashes. The GPU client generally performs more than 10x better than the SMP CPU client on a typical 4-core system. Bitcoin depends on the computation of large numbers of unrelated cryptographic hashes, which can be computed in parallel.

The Folding@Home project offers a GPU client for their molecular dynamics simulations. These computations are performed on the individual bonds between atoms in various environments and conditions. The math is relatively simple, but must be computed billions of times for each bond to simulate mere nanoseconds of activity.

The popular "toy" example used by proponents of GPU computing is the n-body problem.

What these things have in common is that they are embarrassingly parallel. That is, the problem can be decomposed into a small number of discrete computations that are performed many times over a large data set. That is the kind of computation that the GPU is good at.

Complex computations that are dependent on the results of previous computations are not well-suited to the GPU.


答:
You asked "how bad". So to flesh out @RobertKoritnik's (entirely accurate) answer a bit...

That code is incorrect. Incorrect doesn't come in shades of grey. This code violates the standard and is therefore incorrect. It would fail validation checking, and it should.

That said, no browser currently on the market would complain about it, or have any problem with it at all. Browsers would be within their rights to complain about it, but none of the current versions of any of them currently do. Which doesn't mean future versions might not treat this code badly.

Your behavior trying to use that ID as a selector, either in css or javascript, is unguessable and probably varies from browser to browser. I suppose a study could be done to see how each browser reacts to that. I think in the best case, it would treat it just like "class=", and select the list of them. (That might confuse JavaScript libraries, though--if I were the author of jQuery, I might have optimized my selector code so that if you come to me with a selector starting with "#", I expect a single object, and getting a list might bork me completely.)

It also might select the first one, or possibly the last one, or select none of them, or crash the browser entirely. No way to tell without trying it.

"How bad" then depends entirely on how strictly a particular browser implements the HTML spec, and what it does when confronted with a violation of that spec.

EDIT: I JUST happened to come across this today. I'm pulling in various components from search forms on various types of entities to produce a great big all-in-one reporting utility for this site, I'm loading up the remote pages' search forms in hidden divs and slotting them into my report generator when the appropriate entity type is selected as the source for the report. So there's a hidden version of the form, and a version displayed in the report generator. The JavaScript that came with, in all cases, refers to elements by ID, of which there are now TWO on the page--the hidden one, and the displayed one.

What jQuery seems to be doing is selecting me the FIRST one, which in all cases is exactly the one I DON'T want.

I'm working around this by writing selectors to specify the region of the page I want to get my field in (ie: $('#containerDiv #specificElement') ). But there's one answer to your question--jQuery on Chrome definitely behaves a particular way when confronted with this spec violation.

Title: Two HTML elements with same id attribute: How bad is it really?

Body:
Just browsing the google maps source code. In their header, they have 2 divs with id="search" one contains the other, and also has jstrack="1" attribute. There is a form separating them like so:

```<code><div id="search" jstrack="1">
    <form action="/maps" id="...rest isn't important">
        ...
        <div id="search">...
</code>```

Since this is google, I'm assuming it's not a mistake.

So how bad can it really be to violate this rule? As long as you are careful in your css and dom selection, why not reuse id's like classes? Does anyone do this on purpose, and if so, why?


问:
What's the best way to design a data and php model for a multi-account system?
I'm doing some high-level sketching of a system that will require users to register, when they do they get an account and can invite others to that account.

To be clear, an account would be similar to a private workspace, and the users will belong to that account and cannot exist outside of that account. The users will be identified by a unique username (likely their email) and this will give them access to the account on a one (account) to many (emails / users) basis.

Each record generated in that account is visible only to those users who belong to that account.

Is there a good pattern for modeling this type of system?

Being extremely new to programming, I'm imagining a field in each table that references the account #, but this makes virtually every entity a one to many.

Is there a better way?

答:
n users - 1 account (1 user can belong to just one account, n users can belong to 1 account, where n is 0..infinity):

```<code> accounts (
   account_id   primary key
 )

 users (
   user_id      primary key,
   account_id   not null references accounts(account_id)
 )
</code>```

n users - m accounts; which is probably what you need (a user can belong to m accounts, an account might have n users)

```<code> accounts (
   account_id   primary key
 )

 users (
   user_id      primary key
 )

 user_accounts (
   user_id      not null references accounts(user_id)
   account_id   not null references accounts(account_id)
   unique(user_id, account_id)
 )
</code>```

in order to ensure that no information is leaked, several approaches exist. Some databases and frameworks might allow you to specify this requirement "declaratively", which will give you maximum security (or security as good as the implementation- which in many cases will be better than you can achieve- as the people developing the database/framework will probably have more resources).

Unfortunately, complete and pure RDBMS solutions are not implemented in widely available systems, and even if they existed, I'm guessing they would be tied to the RDBMS role system; that is, you could grant select privileges over certain rows to certain database roles, but that might certainly not be applicable to your problem (i.e. you'd have to create roles per user in your app and execute queries as the appropriate user; as far as I know this is not practical in any platform I know of).

If you are using an ORM to access your database, you might have better luck. I know Hibernate implements something where you can check conditions before executing any operation ( http://docs.jboss.org/hibernate/core/3.3/reference/en/html/events.html#objectstate-decl-security ) or filter data, and I believe Yii's ORM allows for something similar.

If those are not available, or not suitable for your particular case, you will have to work further up your stack. A traditional solution is to mandate all data access to go through a layer which enforces security- actually this is one of the best reasons to implement a DAO/Service layer separation; DAOs contain "raw" data access and the service layer checks privileges. If you avoid accessing the DAO outside the Services, you have all your security logic in a predictable place (i.e. the same class/classes) and thus it is easier to check.

Another common solution is to access your database through stored procedures which enforce security. This often has the drawback that stored procedures are considered less nice to write (i.e. PL/SQL is unfriendlier than Java), although that's debatable. On the other hand, if you have several applications accessing the database, and esp. if they use different languages, you won't have to duplicate all the access check stuff everywhere.

Also, this might be an appropriate problem for aspect oriented programming.

Finally, please note that all of the above only give security "outwards" (i.e. ensure that the application can not act insecurely due to user action). If attackers can tamper "inside" the application, it's game over- this means you should adhere to standard safe coding (i.e. avoid buffer overruns, XSS, etc.).

Body:
n users - 1 account (1 user can belong to just one account, n users can belong to 1 account, where n is 0..infinity):

 accounts (
   account_id   primary key
 )

 users (
   user_id      primary key,
   account_id   not null references accounts(account_id)
 )

n users - m accounts; which is probably what you need (a user can belong to m accounts, an account might have n users)

 accounts (
   account_id   primary key
 )

 users (
   user_id      primary key
 )

 user_accounts (
   user_id      not null references accounts(user_id)
   account_id   not null references accounts(account_id)
   unique(user_id, account_id)
 )

in order to ensure that no information is leaked, several approaches exist. Some databases and frameworks might allow you to specify this requirement "declaratively", which will give you maximum security (or security as good as the implementation- which in many cases will be better than you can achieve- as the people developing the database/framework will probably have more resources).

Unfortunately, complete and pure RDBMS solutions are not implemented in widely available systems, and even if they existed, I'm guessing they would be tied to the RDBMS role system; that is, you could grant select privileges over certain rows to certain database roles, but that might certainly not be applicable to your problem (i.e. you'd have to create roles per user in your app and execute queries as the appropriate user; as far as I know this is not practical in any platform I know of).

If you are using an ORM to access your database, you might have better luck. I know Hibernate implements something where you can check conditions before executing any operation ( http://docs.jboss.org/hibernate/core/3.3/reference/en/html/events.html#objectstate-decl-security ) or filter data, and I believe Yii's ORM allows for something similar.

If those are not available, or not suitable for your particular case, you will have to work further up your stack. A traditional solution is to mandate all data access to go through a layer which enforces security- actually this is one of the best reasons to implement a DAO/Service layer separation; DAOs contain "raw" data access and the service layer checks privileges. If you avoid accessing the DAO outside the Services, you have all your security logic in a predictable place (i.e. the same class/classes) and thus it is easier to check.

Another common solution is to access your database through stored procedures which enforce security. This often has the drawback that stored procedures are considered less nice to write (i.e. PL/SQL is unfriendlier than Java), although that's debatable. On the other hand, if you have several applications accessing the database, and esp. if they use different languages, you won't have to duplicate all the access check stuff everywhere.

Also, this might be an appropriate problem for aspect oriented programming.

Finally, please note that all of the above only give security "outwards" (i.e. ensure that the application can not act insecurely due to user action). If attackers can tamper "inside" the application, it's game over- this means you should adhere to standard safe coding (i.e. avoid buffer overruns, XSS, etc.).


问:
Package name best practice when porting a library
What is the suggested way (specifically in the open-source world) for the package name when porting a library.

Say I am porting someone else's library where they have used a reverse domain name stucture for there package name, so there library package name was some thing like com.therename.thelib. What should I do if I decide to port it to a new language? Should I keep the domain name intact, even though they didn't have a hand in it? Or should I change it to something like com.myname.thelib?

答:
If this is Java, always use reverse-domain with a domain you control. Suppose you keep the name and someone else ports the library, and people create libraries, some depending on your port and some depending on the other port, you could have namespace issues.

That's unlikely to happen, but why risk it?

If you want to maintain the name, contact the domain owners.


问:
What is (was) an update channel?
I was checking out what version of Firefox I'm using and it was telling me that I'm on the 'release update channel'.  So I googles "Update Channel" and I finds this seemingly antiquated MSDN article which has a confusing bit of ASP.NET pre-processed into the article to give you the sense that you both should not use this technology and should never have used this technology.

Microsoft Active Channel technology is obsolete as of Windows Internet Explorer 7 and should not be used. Users want an easy and convenient way to download and install new versions of software. Software Update Channels are specialized channels that you can use to notify users of software updates and also deliver and install the updates on their computers. Users who have downloaded your software and subscribed to your Software Update Channel are notified when new versions of your software become available. When notified of an update, users can click a gleaming icon representing your channel, which returns them to your download site so they can obtain the new version. Users can also choose to have software updates delivered and installed on their computers automatically.

Active Channel technology is obsolete as of Internet Explorer 7 and should not be used. This article introduces you to the terminology, benefits, and implementation of Software Update Channels. After reading this article, you will understand how easy it is for users to discover and interact with this technology, and you will know how to create your own Software Update Channels. Links to relevant overviews, references, and tutorials are provided at the end of the article.

So, I ask you.  Is this still some sort of metaphor for getting software easily to your clients.  If I store the info for my programs updates in a database, is there existing non-obsolete Microsofty technology that could take a generated XML file and tell people using my software that there are updates available and you should probably download them?

答: It means you are on the stable releases channel, you won't get any beta update.</p>

Title: What is (was) an update channel?


问:
How do you manage extensibility in your multi-tenant systems?
I've got a few big web based multi-tenant products now, and very soon I can see that there will be a lot of customizations that are tenant specific.

An extra field here or there, maybe an extra page or some extra logic in the middle of a workflow - that sort of thing.

Some of these customizations can be rolled into the core product, and that's great. Some of them are highly specific and would get in everyone else's way.

I have a few ideas in mind for managing this, but none of them seem to scale well. The obvious solution is to introduce a ton of client-level settings, allowing various 'features' to be enabled on per-client basis. The downside with that, of course, is massive complexity and clutter. You could introduce a truly huge number of settings, and over time various types of logic (presentation, business) could get way out of hand. Then there's the problem of client-specific fields, which begs for something cleaner than just adding a bunch of nullable fields to the existing tables.

So what are people doing to manage this? Force.com seems to be the master of extensibility; obviously they've created a platform from the ground up that is super extensible. You can add on to almost anything with their web-based UI. FogBugz did something similiar where they created a robust plugin model that, come to think of it, might have actually been inspired by Force. I know they spent a lot of time and money on it and if I'm not mistaken the intention was to actually use it internally for future product development.

Sounds like the kind of thing I could be tempted to build but probably shouldn't. :)

Is a massive investment in pluggable architecture the only way to go? How are you managing these problems, and what kind of results are you seeing?

EDIT: It does look as though FogBugz handled the problem by building a fairly robust platform and then using that to put together their screens. To extend it you create a DLL containing classes that implement interfaces like ISearchScreenGridColumn, and that becomes a module. I'm sure it was tremendously expensive to build considering that they have a large of devs and they worked on it for months, plus their surface area is perhaps 5% of the size of my application.

Right now I am seriously wondering if Force.com is the right way to handle this. And I am a hard core ASP.Net guy, so this is a strange position to find myself in.

答:
1) Running someone else's code on boxes you own is a quite tough problem. Either you can trust them or you can defer responsibility reasonably, you will have to sandbox their code very heavily and have a higher-than-average dedication to security. As your plugin system allows more functionality, the difficulty of making it secure grows. Things like denial of service (plugins consume too much resources), information leakage (plugins can access other tenants' data), etc. can be very real and troublesome, I wouldn't take part into this unless I could get people very acquainted with these problems or very capable people with lots of time to get it right.

2) Yes, modularity and customizability are tough. Things such as the Strategy pattern can help (a fancy name for function pointers; in Java it's typically implemented by declaring an Interface which users of the class can implement to customize the behaviour of your code), but you'll want very isolated and decoupled code for this to work.

3) Data-wise, this might be one of the examples of schemaless storage being useful. If you have a relational data model, having tables with lots of columns for different customers is problematic (yes, you end up with lots of nullable columns, which is bad; one reason is that it's hard or impossible to set the correct constraints [i.e. constraints which do not allow invalid combinations of nulls to appear]). Adding customer-specific tables (i.e. users and foo_users, with users holding the fields valid for all customers and foo_users having the Foo specific fileds) is better; you can have correct constraints easily, but your RDBMS might not handle it gracefully (due to join explosion, limits on number of tables, etc.) and will probably look ugly in your code.

You might end up implementing a key-value store in your RDBMS, which makes your data model less relational-ish and will cause discomfort (i.e. relational databases work best with relational-ish models). I'm not sure whether a NoSQL solution will fit the problem overall, but the schemaless-ness of most implementations might be an advantage.

OwnerDisplayName: Brian MacKay


答:
I faced a similar problem, and I'll tell you how I went about resolving it.

Firstly, there is a "core" library, or engine.  This basically runs the show, much as you have already got figured out.  It handles things common to every system, from rendering forms dynamical, user and account management, roles, you name it, it does it.

Every part of the system is contained within a module.  A module has dependencies (other modules that it depends on).  For example, the "core" system has Security (users, groups, roles, password policies), Locale, (translations, countries, cultures), File Repository, Email, etc, etc.  Each module defines itself using an xml file.  The xml file basically specifies the schemas, tables, calculation classes, screen definitions etceteras.  These are read in when the application starts if the file date has changed.

Customer-specific modules have their own xml files and own DLL.  It all plus in and functions accordingly and transparently with the rest of the system.  Right down to replacing existing MVC views with custom ones, with custom code and custom view models.

If a customer wishes to extend existing functionality, the xml/system provides a method where I can "derive" one module from another.  The new module has all the existing functionality, but with the customer's specific requirements in a new DLL and with an extended XML file that can make the modifications.  The Caveat is, they can't actually remove existing fields in this system ,but we can extend it and provide entirely new objects and functionality.

Title: How do you manage extensibility in your multi-tenant systems?

Body:
I've got a few big web based multi-tenant products now, and very soon I can see that there will be a lot of customizations that are tenant specific.

An extra field here or there, maybe an extra page or some extra logic in the middle of a workflow - that sort of thing.

Some of these customizations can be rolled into the core product, and that's great. Some of them are highly specific and would get in everyone else's way.

I have a few ideas in mind for managing this, but none of them seem to scale well. The obvious solution is to introduce a ton of client-level settings, allowing various 'features' to be enabled on per-client basis. The downside with that, of course, is massive complexity and clutter. You could introduce a truly huge number of settings, and over time various types of logic (presentation, business) could get way out of hand. Then there's the problem of client-specific fields, which begs for something cleaner than just adding a bunch of nullable fields to the existing tables.

So what are people doing to manage this? Force.com seems to be the master of extensibility; obviously they've created a platform from the ground up that is super extensible. You can add on to almost anything with their web-based UI. FogBugz did something similiar where they created a robust plugin model that, come to think of it, might have actually been inspired by Force. I know they spent a lot of time and money on it and if I'm not mistaken the intention was to actually use it internally for future product development.

Sounds like the kind of thing I could be tempted to build but probably shouldn't. :)

Is a massive investment in pluggable architecture the only way to go? How are you managing these problems, and what kind of results are you seeing?

EDIT: It does look as though FogBugz handled the problem by building a fairly robust platform and then using that to put together their screens. To extend it you create a DLL containing classes that implement interfaces like ISearchScreenGridColumn, and that becomes a module. I'm sure it was tremendously expensive to build considering that they have a large of devs and they worked on it for months, plus their surface area is perhaps 5% of the size of my application.

Right now I am seriously wondering if Force.com is the right way to handle this. And I am a hard core ASP.Net guy, so this is a strange position to find myself in.

OwnerDisplayName: Moo-Juice


答:
Part of what you are looking for is a "priority queue". At previous employers, we did a very primitive version of this, but my heuristic was to only allow some processors to handle short running jobs (short jobs could take minutes), while others were handling longer running jobs (the quarterly report could take almost 2 days to process). This guaranteed that short jobs always had processing time available. I also used a scoreboard that listed jobs ready to be run, and the first processor able to handle the task would pick it up and run it single threaded (they were cheap computers that hadn't been depreciated and so could not be discarded). Many folks use the opposite: a scheduler that tells processors which work unit to do next. My advice would be to have each instance running a single task - this drastically simplifies the scheduling.

Scheduling of arbitrary jobs of arbitrary lengths is a hard problem in distributed processing. Almost every decision is going to involve simulating lots of runs. Which is one of the quirks of queuing theory, which this stuff is going to be based on.

One of the other devs suggested we leave the "job processors" alone to just pull whatever is in the queue next or "round robin". I say that this could lead to a potential issue where a single instance has pulled down too many large jobs and is struggling to get them done while the other instances are idle.

This needs simulation to answer. My earlier scheme used something very similar. If you have stats on previous job runs, you can model it in Excel. I've picked up this book from another post recommending it and am looking to learn some techniques to better be able to answer problems like what you're describing. Actual numbers trump everything, so gather data and do simulations based on them.


答:
Problems that require a lot of math that can be done in concurrently. Where I used to work we wanted to play with GPU's to add/subtract/multiply 2 matrixes to work out genetic corrleation. The first time I heard of GPU's was that they were being used by a finacial software house to do some of their modelling (monte carlo and so forth). The would be usefull in code breaking.

GPU's probably wont help much with your more regular programming problems where a couple of CPU cores are enough because most regular programs only need to run a few concurrent process. (migh be different with memory/disk that is very much faster than we currently have)


问:
Software to organize and maintain project documentation, specification?
I'm looking for software to organize and maintain projects internal documentation, specification, requirements, etc. Currently we store all documentation as lots of MS Word DOC files in a source control repository, which gives us version control, and that's nice. But you can't search this information, create links between them, categorize, collaborate.

Requirements, preferences:

Zero install on client side (WEB based).

Document version control.

Document annotations.

Document linking.

Full search (all documentation).

MS Word (*.doc) import\export.

WYSIWYG text editor.

Systems I have discovered and tried so far:

MediaWiki

XWiki

Confluence

答:
How about something like Sphinx?

You write your documentation in reStructuredText (the syntax is similar to Markdown, which Stack Overflow uses) into plain text files (=easy to version control) and Sphinx spits out HTML pages.

The two most prominent Sphinx users (that I know of) are the Python language and TortoiseHG (see the links for the Sphinx generated documentation).

EDIT:

I just read that you are talking about project-internal documentation, not end-user documentation.

In my opinion, something like Sphinx is the best way for internal documentation as well (provided that you can get your analysts to write reStructuredText) because:

You can easily version control the documents (and diffs of text files take much, much less space than binary files like .doc or .pdf).

If a developer wants a nice readable .doc or .pdf file, he can create it with Sphinx from the sources.

If Sphinx is too complicated, there is even an easier way: you can write your documentation in Markdown and use Pandoc to create (for example) .rtf, .doc or .pdf files (it can do a lot more).

I found Pandoc easier to get started than Sphinx, but Pandoc can't create nice menu hierarchies like Sphinx (like in the Python and TortoiseHG documentation I linked above).

No matter which of the tools you use, if you have an internal web server and a build server, you can set it up so that the build server generates HTML output and copies this on the web server each time someone pushes something to the documentation. So your analysts don't even have to think about the final output, they just need to commit and push their changes.


答:
I would suggest using a UML and ERD tool, in addition to your documents. Also, you could store these documents on ZOHO at ZOHO-Docs, which is not free, but it is extremely cheap and allows document search facilities.

Whatever the tool you end up using, you need to organize the document contents carefully to be able to use text search and get meaningful results. Document content organization together with clever and standard file naming could help greatly.

Title: Software to organize and maintain project documentation, specification?

Body:
I'm looking for software to organize and maintain projects internal documentation, specification, requirements, etc. Currently we store all documentation as lots of MS Word DOC files in a source control repository, which gives us version control, and that's nice. But you can't search this information, create links between them, categorize, collaborate.

Requirements, preferences:

Zero install on client side (WEB based).

Document version control.

Document annotations.

Document linking.

Full search (all documentation).

MS Word (*.doc) import\export.

WYSIWYG text editor.

Systems I have discovered and tried so far:

MediaWiki

XWiki

Confluence


答:
You can do a great many things - but that doesn't mean that you should.

As a programmer (generally speaking) we build our lives on being precise and following the rules - here is a rule that is simple to follow, that is fairly fundamental to what we do - we like (depend upon) unique identifiers within a given scope...

Breaking the rule is something we can do because the browser are way too accommodating - but really we'd all be better off if browsers were strict about needing well formed and valid HTML, the small amount of pain it would have caused would have long since been repaid!

So, is it really that bad? As a programmer how can you even ask? Its a crime against civilisation (-:

Addendum:

You write that browsers are too accommodating like it's bad thing

I do, because it is - we're not talking about complicated rules, we're talking substantially about making things well formed and otherwise applying rules which can be tested mechanically and which in turn make it easier for the result to be processed mechanically. If the browsers had been strict then the tools would very rapidly have adapted to support that - it wasn't so they didn't, some to the extent they exploit that failing instead. Just think on this - email would have been a much nicer medium if MS and Netscape had not screwed it up by allowing unrestricted HTML when a far less complex "email markup language" with explicit support for quoted text would have given us a far better tool... but that ship sailed and similarly we can't close the stable door on what browsers allow (we should, HTML5 should have) but we can't


问:
Agile product planning alternatives to aid goal-oriented feature quality
What do I mean by high-level plan? The kind of plan that outlines product's functionality that needs to be developed but not going into too many details that are done afterwards. This kind of plan helps deciding functionality development order (priority) or even eliminating non-necessary ones. A great high level plan isn't just a set of functional requirements, but rather a product vision with obvious goal in mind.

In Agile terms these kind of functionality documentation is the Backlog. We're used to its content - user stories - as defined by Mike Cohn that go:

As a role I want functionality so that benefit.

But as we know from experience this may lead to:

unusable stories

Like: As a visitor I want to login so that I'm allowed to do stuff.

But how would one improve this user story? What other benefits can we describe that are more relevant than ...do stuff?

flat list of unmanageable seemingly unrelated stories

Hard to see which ones are related or not (they shouldn't be but I don't think we can totally avoid this), or even which ones provide means for achieving the same high-level goal.

too many unrelated goals/benefits

Goals just because we need to write them but without actual business value benefit - the high level business goal in mind.

The problem

As I have experienced there are more ways to write bad/unusable user stories than writing really good ones. And it's easy to get to the wrong tracks even if you're careful. And how can one write better user stories when they are working on their own product, so they don't have means to learn from other fellow team members, and they have to provide user stories now. Not after 6 months of learning.

That's why I would like to know about alternatives to planning a project on the high level that ensures better feature description and relevancy. I've heard of Effect mapping that seems very good in keeping goal focus and filtering relevant from irrelevant but I don't have any experience with it. I can imagine that setting a goal can be crucial. So if you set it wrong, everything else is wrong as well. Or better said irrelevant.

The main question is: Can we follow some easy to understand and narrow guideline that will lead us to a great high-level plan. A guideline that allows less errors and better leads to valuable plan/results. I can see myself writing user stories afterwards that describe features to implement. The problem with user stories is that it's easy to get lost in them. If you don't have lots of experience with user stories that may hinder your product because they distract you from the actual goal. All you can see are product features described in user stories. Something else above that would allow us to create better stories and also easily filter out those that are extremely relevant.

What are other more reliable approaches that simple user stories planning that are used in agile planning?

Focus of this question

I have been writing user stories on several projects in the past and know exactly how hard and vague this task is. I've also seen that writing these is even harder when you're writing them for your own project/product. You can easily over-design your product or incorrectly prioritise/evaluate features.

So I would like to write feature set for my coming product in a way they are actually relevant and prioritise them accordingly to reach my goal as reliably as possible.

So feature relevancy and quality along with goal-oriented prioritisation. And I'm talking about measurable quantitative goals like

20% month over month income increase or

  5% sale conversion rate of user visits

and not something vague like increase users or increase sales.

We can see that writing relevant features that support these goals is much harder.

答:
As a visitor I want to login so that I'm logged in -- Bad example. Better example: As a visitor I want to login so that I'm allowed to _______.

flat list of unmanageable stories -- Arrange them hierarchically, by functional areas. As a logged-in user, I want ____ so that ____  or, as an Accounting user, I want ____ so that ____

too many value-less goals -- Stop writing those.

Can we follow some easy to understand and narrow guideline -- Does this User Story lead to meaningful and testable requirements?


答: Another possibility might be to use LaTeX or some other text formater (perhaps texinfo or even lout) for documentation. Parts of it can be machine generated. There are some tools for HTML conversion, like HeVeA to convert LaTeX to HTML. You can also use doxygen to generate documentation from structured comments inside your source code. And the hand written parts of the documentation can (and should) be managed as source code (e.g. w.r.t. version control and build).</p>