答:
Design patterns are for the programmer, not for the language. Programmers tend to use patterns that help them make sense of the problem at hand. No design pattern is strictly necessary, but it may be of use to help simplify what you're trying to do.

Python, and duck typing specifically, does provide an end around a lot of common patterns and practices, and a lot of the restrictions imposted by some patterns (privacy, immutability, etc) only hold to the extent that the programmer agrees not to break them. But still, they do work as long as the programmer plays along. A door is still a door, even if it's framed by imaginary walls.

Python is considered a "multi-paradigm" language; you can use whatever patterns you want. This is intentional. It provides for complex class hierarchies, for example, even though they're completely unnecessary and a bit artificial. But for some people that particular abstraction is helpful. Not because the problem demands it, but because the programmer does. So there you go.

Title: Are there any design patterns that are unnecessary in dynamic languages like Python?

Body:
I've started reading the design pattern book by the GoF. Some patterns seem very similar with only minor conceptual differences.

Do you think out of the many patterns some are unnecessary in a dynamic language like Python (e.g. because they are substituted by a dynamic feature)?


问:
Are there any design patterns that are unnecessary in dynamic languages like Python?
I've started reading the design pattern book by the GoF. Some patterns seem very similar with only minor conceptual differences.

Do you think out of the many patterns some are unnecessary in a dynamic language like Python (e.g. because they are substituted by a dynamic feature)?

答:
No design patterns are necessary. In any language.

I tend to come across a lot of code written by people who read up on design patterns and then think they should use them all over the place. The result is that the actual code gets buried under tons of interfaces, wrappers and layers and is pretty hard to read. That's a wrong approach to design patterns.

Design patterns exist so that you have a repertoire of useful idioms handy when you come across a problem. But you should never apply any pattern before you identify the problem. Keep It Simple Stupid should always be the superior governing principle.

It also helps to think of design patterns as a concept to think about the problem rather than specific boilerplate code to write. And about much of the boilerplate as workaround to Java lacking free functions and standard function objects that you use in most other languages that have them (like Python, C#, C++ etc).

I might say that I have a visitor pattern, but in any language with first class functions it will be just a function taking a function. Instead of factory class I usually have just a factory function. I might say I have an interface, but then it's just a couple of methods marked with comments, because there wouldn't be any other implementation (of course in python an interface is always just comments, because it's duck-typed). I still speak of the code as using the pattern, because it's a useful way to think about it, but don't actually type in all the stuff until I really need it.

So learn all the patterns as concepts. And forget the specific implementations. The implementation varies, and should vary, in the real world, even just in Java.

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
How to justify code refactoring time?
Have a very large project more than 70k LOC.

The project definitely needs some code refactoring in Core Framework and in other parts as well. There was NO time set in the beginning of the project for refactoring. However with time and more than 40 developers joint and left the project. From my perspective is indispensable.

What would be your key points in arguing and defending a proper software development principle?

答: As I read in one of the other answers, eat this elephant one bite at a time. I'm involved in auditing a large international project, where team members are geographically dispersed. After building the first two versions of the software the team agreed that their approaches, style of coding and building solutions is inconsistent. They agreed to write new parts of the application following the new rules and convention and when (and only then) they have to change some of the old code, they first refactor it to meet the new convention. Everything is working quite well. The refactoring process is almost in its 5th month, some of the code is refactored, some still isn't. New features are brought in time, clients are happy, devs are happy, QA team is also happy. A win-win situation :)</p>

Title: How to justify code refactoring time?


答:
Main point of refactoring is to make things easier in the future.
You cannot show profits of refactoring unless you compare multiple long-term projects few done with and few without constant refactoring. It is generally accepted across developers, that refactoring decreases cost of maintenance and implementation of changes, but those are hard to prove from business standpoint. The key reason to implement refactoring is to reduce Technical Debt.

Also, refactoring should be continuous process and time spend on the refactoring should be included in development task itself. Having special "refactoring task" is not good idea.

Title: How to justify code refactoring time?

Body:
Have a very large project more than 70k LOC.

The project definitely needs some code refactoring in Core Framework and in other parts as well. There was NO time set in the beginning of the project for refactoring. However with time and more than 40 developers joint and left the project. From my perspective is indispensable.

What would be your key points in arguing and defending a proper software development principle?


问:
Should laying out a GUI graphically be considered "cheating?"
I have a friend who has a slightly greater amount of programming experience as me. We were talking about all the different programming technologies we use and Interface Builder came up in conversation.

Being of no programming background except for what I've taught myself, I personally believe that IB and all it's features (IBOutlets, IBActions) help coders of my skill level (and all skill levels, for that matter) complete projects of theirs in less time.

His view of IB is a little enthusiastic. He believes that coders that utilize Interface Builder are "cheating" in the fact that they don't have to lay out interfaces by hand.

Question:

Should using a GUI builder to lay out interface elements be considered "cheating" (since most programming originally required laying interfaces out by hand in code)? Why?

答:
As @Bryan Oakley states, it's just a tool and not a "cheat". It all depends on what exactly you're laying out. If by hand makes it incredibly laborious exercise then you should really look for other alternatives that makes you more productive.

I used to be in the camp of hand coding the interface, but later after a bout of laying out interfaces I took an arrow to the knee and had a different opinion. If I can and it makes me more productive then I'd use a graphic tool to lay out the GUI.

Lately using the MVVM pattern, with the distinction of View and ViewModel, it makes a bit more clear to when you would use graphical tools. Phil Haack discusses this briefly in the Github for Windows episode of Herding Code podcast when asked about the transition from web to application development. It makes more sense to do the ViewModel with coding "by hand", and let the designer build the View graphically (and wire up the ViewModels accordingly).


问:
How should I test my TEST code?

One of the few things that most software developers agree on is that
  you shouldn't rely on code to work correctly unless you test it. If
  you don't test it, it may have hidden bugs that are only going to
  cause you more work down the road.

I understand how to test my normal code, but how should I test my test code to make sure it can effectively find and report errors when they are present? I personally have been stupid enough to write erroneous test cases that would pass when they should not have, thus defeating the purpose of my writing tests in the first place. Fortunately, I found and fixed the errors in time, but according to testing mantra it seems like no test suite would be complete without having its own set of tests to make sure it worked.

It seems to me that the best way to do this would be to make sure the test fails for buggy code.* If I spend 2 minutes alternately adding bugs to the code and making sure it fails, I should have an acceptable degree of confidence that the tests 'work'. This brings me to my second question: What are good ways to introduce bugs to make sure that they are caught by the test cases? Should I just randomly comment out statements, make sure the wrong branch of an if-else gets run by negating its condition, and change the execution order of code with side-effects, etc., until I'm satisfied my tests will catch most common bugs? How do professional developers validate that their tests actually do what they're supposed to do? Do they just assume the tests work, or do they take the time to test them as well? If so how do they test the tests?

I'm not suggesting the people should spend so much time testing their tests and then testing the tests for their tests that they never actually write the real code, but I've done stupid enough things that I feel like I could benefit from a bit of 'meta-testing', and was curious about the best way to go about it. :D

* I could check to see if the test passes when testing 'bug-free' code, but using the code as a spec for the test seem quite backwards...

答:
The standard flow for TDD is:

Write a failing test. (Red)

Make the smallest code change that makes it pass (Green)

Refactor (Keeping it green)

The test for your tests in this case is step 1 - making sure that the test fails before you make any code changes.

Another test that I like is whether you can delete some code and re-implement it a different way, and your tests fail after deletion but work with a different algorithm in place.

As with all things, there is no magic bullet. Forgetting to write a required test is just as easy for a developer to do as forgetting to write the code. At least if you're doing both, you have twice as many opportunities to discover your omission.

Title: How should I test my TEST code?


答:
Imagine that you are in front of a long and huge wall. You need to go to the other side.

Either you refactor the wall in order to build a door, or you go around it.

Estimate the time for both solutions and you get your justification for refactoring.

Don't forget to multiply the time in the second solution by the number of people needing to go to the other side of the wall.

Title: How to justify code refactoring time?


答: By construction, functional code and test code are tested one against the other. One problem remains: the case of common mode bugs, when a bug in functional code is hidden by a bug in test code. TDD is not immune to this effect. This is why testing is usually performed at multiple levels by different people in order to decrease this probability.</p>

Title: How should I test my TEST code?

Body:
One of the few things that most software developers agree on is that
  you shouldn't rely on code to work correctly unless you test it. If
  you don't test it, it may have hidden bugs that are only going to
  cause you more work down the road.

I understand how to test my normal code, but how should I test my test code to make sure it can effectively find and report errors when they are present? I personally have been stupid enough to write erroneous test cases that would pass when they should not have, thus defeating the purpose of my writing tests in the first place. Fortunately, I found and fixed the errors in time, but according to testing mantra it seems like no test suite would be complete without having its own set of tests to make sure it worked.

It seems to me that the best way to do this would be to make sure the test fails for buggy code.* If I spend 2 minutes alternately adding bugs to the code and making sure it fails, I should have an acceptable degree of confidence that the tests 'work'. This brings me to my second question: What are good ways to introduce bugs to make sure that they are caught by the test cases? Should I just randomly comment out statements, make sure the wrong branch of an if-else gets run by negating its condition, and change the execution order of code with side-effects, etc., until I'm satisfied my tests will catch most common bugs? How do professional developers validate that their tests actually do what they're supposed to do? Do they just assume the tests work, or do they take the time to test them as well? If so how do they test the tests?

I'm not suggesting the people should spend so much time testing their tests and then testing the tests for their tests that they never actually write the real code, but I've done stupid enough things that I feel like I could benefit from a bit of 'meta-testing', and was curious about the best way to go about it. :D

* I could check to see if the test passes when testing 'bug-free' code, but using the code as a spec for the test seem quite backwards...


问:
Examples of concurrent iterating scenarios needed
I'm trying to wrap my head around different concurrency solutions to several threads iterating over the same collection but I'm having difficulty coming up with good realistic (but preferably easy to model) scenarios to  code against. I'm looking for realistic scenarios for:

A scenario where several threads can iterate over a collection simultaneously and lock      each item as it comes to it and do some modification, item's can't be visible in a partially updated state

A scenario where different threads try to iterate over a collection but only one at a time should be allowed to

A scenario where several threads might iterate over a collection for reading, but only one thread might iterate for writing

Any other nice concurrency iterating scenarios you might come up with are welcome as well :) thanks!

答:
An example I discovered at a previous workplace:

A piece of code had a collection of frame buffers that were being updated by multiple threads. The threads were:

A thread that received frames from the network, processed them and updated the buffer in question. (Write operation)

A thread that converted frames to pixels for display (Read operation)

Another piece of code that maintained the connection status of the network, and replaced the buffer with the text "Connection Lost". (Write operation)

These frame buffers weren't properly synchronised. I managed to find that the reading thread was iterating the frame buffers and pushing them to native code, when thread 3 came along and caused the entire app to crash.

In this case, reading and writing had to become exclusive (your scenario 2).

ContentLicense: CC BY-SA 2.5


答: One of the great advantages of tools like Interface Builder is that they make it possible to separate the work of design of the UI from the implementation of the program. Someone with minimal coding skill can easily change the layout of the UI, change button and menu captions, translate the UI into a different language, etc.</p>

Title: Should laying out a GUI graphically be considered "cheating?"

Body:
I have a friend who has a slightly greater amount of programming experience as me. We were talking about all the different programming technologies we use and Interface Builder came up in conversation.

Being of no programming background except for what I've taught myself, I personally believe that IB and all it's features (IBOutlets, IBActions) help coders of my skill level (and all skill levels, for that matter) complete projects of theirs in less time.

His view of IB is a little enthusiastic. He believes that coders that utilize Interface Builder are "cheating" in the fact that they don't have to lay out interfaces by hand.

Question:

Should using a GUI builder to lay out interface elements be considered "cheating" (since most programming originally required laying interfaces out by hand in code)? Why?


答:
Design patterns are ways of solving particular problems. If a problem is not met, pattern of resolving it has no use.

People are trying to adapt design patterns everywhere as if it was a best practice to have design patterns in your project. That's other way around. You encounter a problem that can be solved with a factory pattern? Cool. Adapt it. Don't look up your code and try to find the right place to implement a singleton (or factory, or facade, or whatever ...).

Perhaps Python has its own design patterns not available for Java and .NET people (due to nature of these languages)?


问:
One or many RESTful APIs for large company?
I work for a large company which has several non-RESTful APIs. I am tasked with building a web application to interact with these APIs. Each API handles and provides very different business processes and data.

I'd like to build RESTful (a) interface(s) fronting the APIs so as to make them reusable by other future web applications. Then, I'd like JavaScript to interact with the RESTful interface(s).

Should I build one RESTful API (one subdomain) for my entire company

```<code>http://api.mycompany.com
    /business_process_1/resource/
    /business_process_2/resource
    /business_process_3/resource
</code>```

and make it front the very different business processes and data? Or, should I build multiple APIs (multiple subdomains)?

```<code>http://business-process-1.mycompany.com
http://business-process-2.mycompany.com
http://business-process-3.mycompany.com
</code>```

答:
REST is not the URI

The most common implementation of REST consists of the combination of URIs, HATEOAS and HTTP verbs. Therefore I would suggest that focusing on creating a URI structure is a little premature.

Fundamentally, you should design your API so that it is discoverable by a client that understands the content of the payload. For example, ensuring that your payload contains links with rels and microformats means that your clients become less reliant on the URIs and more reliant on what is contained in the payload to drive them.

In this way, you can direct your clients to the most appropriate version of their APIs through links with semantics that they have been programmed to understand, usually through appropriate use of HTTP status codes.

For a general purpose, lightweight, payload format consider Hypertext Application Language (HAL).

And what about my question?

That said, multiple sub-domains with JavaScript leads to cross domain issues which (although mitigated using the document.domain approach) lead to client complexity. From that standpoint alone, you should consider a single starting point and build out from there.


问:
async & await - poll for alternatives
Now that we know what is in store for c#5, there is apparently still an opening for us to influence the choice of the two new keywords for 'Asynchrony' that were announced by Anders Heijsberg yesterday at PDC10.

```<code>async void ArchiveDocuments(List<Url> urls) {
    Task archive = null;
    for(int i = 0; i < urls.Count; ++i) {
        var document = await FetchAsync(urls[i]);
        if (archive != null)
            await archive;
        archive = ArchiveAsync(document);
    }
}
</code>```

Eric Lippert has an explanation of the choice of the current two keywords, and the way in which they have been misunderstood in usability studies. The comments have several other propositions.

Please - one suggestion per answer, duplicates will be nuked.

答:
How about not having a keyword?

I'd like the compiler to realise that, most of the time, when I call an asynchronous method, I want the result of it.

```<code>Document doc = DownloadDocumentAsync();
</code>```

That's it. The reason people are having a hard time thinking up a keyword for this thing is because it's like having a keyword for "do the thing you'd do if things were perfectly normal". That should be the default, not require a keyword.

Update

I originally suggested the compiler should get clever with type inference to figure out what to do. Thinking further about this, I'd keep the existing implementation in the CTP as it is, but make a couple of trivial additions to it, so as to reduce the cases where you'd need to use the await keyword explicitly.

We invent an attribute: [AutoAwait]. This can only be applied to methods. One way to get this applied to your method is to mark it async. But you could also do it by hand, e.g.:

```<code>[AutoAwait]
public Task<Document> DownloadDocumentAsync()
</code>```

Then inside any async method, the compiler will assume you want to await on a call to DownloadDocumentAsync, so you don't need to specify it. Any call to that method will automatically await it.

```<code>Document doc = DownloadDocumentAsync();
</code>```

Now, if you want to "get clever" and obtain the Task<Document>, you use an operator start, which can only appear before a method call:

```<code>Task<Document> task = start DownloadDocumentAsync();
</code>```

Neat, I think. Now a plain method call means what it usually means: wait for the method to complete. And start indicates something different: don't wait.

For code that appears outside of an async method, the only way you're allowed to call an [AutoAwait] method is by prefixing it with start. This forces you to write code that has the same meaning regardless of whether it appears in an async method or not.

Then I start to get greedy! :)

Firstly, I want async to apply to interface methods:

```<code>interface IThing
{
    async int GetCount();
}
</code>```

It basically means that the implementing method must return Task<int> or something compatible with await, and callers to the method will get [AutoAwait] behaviour.

Also when I implement the above method, I want to be able to write:

```<code>async int GetCount()
</code>```

So I don't have to mention Task<int> as the return type.

Also, I want async to apply to delegate types (which, after all, are like interfaces with one method). So:

```<code>public async delegate TResult AsyncFunc<TResult>();
</code>```

An async delegate has - you guessed it - [AutoAwait] behaviour. From an async method you can call it and it will automatically be awaited (unless you choose to just start it). And so if you say:

```<code>AsyncFunc<Document> getDoc = DownloadDocumentAsync;
</code>```

That just works. It's not a method call. No task has been started yet - an async delegate is not a task. It's a factory for making tasks. You can say:

```<code>Document doc = getDoc();
</code>```

And that will start a task and wait for it to finish and give you the result. Or you can say:

```<code>Task<Document> t = start getDoc();
</code>```

So one place in this where the "plumbing" leaks out is that if you want to make a delegate to an async method, you have to know to use an async delegate type. So instead of Func you must say AsyncFunc, and so on. Though one day that kind of thing might be fixed by improved type inference.

Another question is what should happen if you say start on an ordinary (non-async) method. Obviously a compile error would be the safe option. But there are other possibilities.

Title: async & await - poll for alternatives

Body:
How about not having a keyword?

I'd like the compiler to realise that, most of the time, when I call an asynchronous method, I want the result of it.

Document doc = DownloadDocumentAsync();

That's it. The reason people are having a hard time thinking up a keyword for this thing is because it's like having a keyword for "do the thing you'd do if things were perfectly normal". That should be the default, not require a keyword.

Update

I originally suggested the compiler should get clever with type inference to figure out what to do. Thinking further about this, I'd keep the existing implementation in the CTP as it is, but make a couple of trivial additions to it, so as to reduce the cases where you'd need to use the await keyword explicitly.

We invent an attribute: [AutoAwait]. This can only be applied to methods. One way to get this applied to your method is to mark it async. But you could also do it by hand, e.g.:

[AutoAwait]
public Task<Document> DownloadDocumentAsync()

Then inside any async method, the compiler will assume you want to await on a call to DownloadDocumentAsync, so you don't need to specify it. Any call to that method will automatically await it.

Document doc = DownloadDocumentAsync();

Now, if you want to "get clever" and obtain the Task<Document>, you use an operator start, which can only appear before a method call:

Task<Document> task = start DownloadDocumentAsync();

Neat, I think. Now a plain method call means what it usually means: wait for the method to complete. And start indicates something different: don't wait.

For code that appears outside of an async method, the only way you're allowed to call an [AutoAwait] method is by prefixing it with start. This forces you to write code that has the same meaning regardless of whether it appears in an async method or not.

Then I start to get greedy! :)

Firstly, I want async to apply to interface methods:

interface IThing
{
    async int GetCount();
}

It basically means that the implementing method must return Task<int> or something compatible with await, and callers to the method will get [AutoAwait] behaviour.

Also when I implement the above method, I want to be able to write:

async int GetCount()

So I don't have to mention Task<int> as the return type.

Also, I want async to apply to delegate types (which, after all, are like interfaces with one method). So:

public async delegate TResult AsyncFunc<TResult>();

An async delegate has - you guessed it - [AutoAwait] behaviour. From an async method you can call it and it will automatically be awaited (unless you choose to just start it). And so if you say:

AsyncFunc<Document> getDoc = DownloadDocumentAsync;

That just works. It's not a method call. No task has been started yet - an async delegate is not a task. It's a factory for making tasks. You can say:

Document doc = getDoc();

And that will start a task and wait for it to finish and give you the result. Or you can say:

Task<Document> t = start getDoc();

So one place in this where the "plumbing" leaks out is that if you want to make a delegate to an async method, you have to know to use an async delegate type. So instead of Func you must say AsyncFunc, and so on. Though one day that kind of thing might be fixed by improved type inference.

Another question is what should happen if you say start on an ordinary (non-async) method. Obviously a compile error would be the safe option. But there are other possibilities.


问:
What pitfalls are inherent in using partial classes?
Over at this question in the comments I mentioned that I heard that partial classes are best avoided if possible.

What if any is the reason for this sentiment? Or If this is an invalid sentiment, how are the perceived detriments overcome?

答:
One of the pitfalls is to think partial classes are somehow related to project modularity. This situation is perfect example.

Partial classes are only good if you have parts on single class created by completly different means. Common use is to have one piece of class generated by some tool (UI designer, model class generator, service generator) and another part added by developer. The tool-generated part can be regenerated at any time. Not so with the part added by developer.


答: Abstract factory pattern is unnecessary in duck-typed language such as Python, as it's practically built into the language.


答:
There is one situation I was confronted with quite a couple of times before.

Although partial classes allow the concept of partial methods they don't allow partial constructors. So if you are using machine generated code it's most probably that there will be a constructor defined already which means you are unable to add custom construction code.

One common work around for this is of course to call other 'constructing methods' directly from the one defined constructor like having

```<code>// example constructor of the partial class
public PartialClass {

    partial void Initialize1();
    partial void Initialize2();
    partial void Initialize3();
    // ...
}
</code>```

but that requires the explicit use of such a pattern which is of course not the case when working with foreign or machine generated code.

Title: What pitfalls are inherent in using partial classes?

Body:
Over at this question in the comments I mentioned that I heard that partial classes are best avoided if possible.

What if any is the reason for this sentiment? Or If this is an invalid sentiment, how are the perceived detriments overcome?

Body:
There is one situation I was confronted with quite a couple of times before.

Although partial classes allow the concept of partial methods they don't allow partial constructors. So if you are using machine generated code it's most probably that there will be a constructor defined already which means you are unable to add custom construction code.

One common work around for this is of course to call other 'constructing methods' directly from the one defined constructor like having

// example constructor of the partial class
public PartialClass {

    partial void Initialize1();
    partial void Initialize2();
    partial void Initialize3();
    // ...
}

but that requires the explicit use of such a pattern which is of course not the case when working with foreign or machine generated code.


问:
What's the most important, useful or enlightening thing you learnt in the last 12 months?
A lot of people in the coding community talk about continuous improvement, deliberate practice and so-on - but when they talk about their current practices it's almost like they 'sprang fully formed from the loins of Zeus' because you don't hear about how their opinions changed over time or what they learnt recently.

Every now and then though I go to a talk, or read a book, or talk to someone and they open up a bit more and I find that I learn a lot from these insights.

So, if you had to pick one thing from the last 12 months that you learnt what would it be?

答:
I learned that getting sold to a new company can indeed improve your job.  My organization was purchased from our old company in May, and things appear to keep getting better.  The new company has spared little/no expense w/our new office, replaced our deprecated development machines with 21st century equipment, exhibited flexibility with managing our projects, and generally made us all feel more than welcome.

It kinda feels a bit depressing getting sold (a little like a serf having a new feudal lord because he's tied to land which changed hands), but the final result has been much better than I expected.


答:
Aside the designer-generated code, partial classes can still be useful without compromising the code quality.

Examples of correct usage

A few usages I found particularly useful are the following:

SQL queries

I do a lot of stuff where direct, hand-written SQL queries are used instead of ORMs. The most basic architecture is to embed queries directly in code:

```<code>public class Demo
{
    [...]

    public int GetPriceOfProduct(long productId)
    {
        var query = Query(
            "select top 1 [Price] from [Shop].[Products] where [ProductId] = @ProductId",
            this.ConnectionString);

        // Use the query to retrieve the price.
    }

    [...]
}
</code>```

This works well, until you have too many methods and until too many queries start to have more then ten lines. Reviewing only the queries by the DBA is complicated too, since the DBA has to search through all the code. In this case, the queries may be put in a separate class:

```<code>public class Demo
{
    [...]

    public int GetPriceOfProduct(long productId)
    {
        var query = Query(Queries.PriceOfProduct, this.ConnectionString);

        // Use the query to retrieve the price.
    }

    [...]

    private static class Queries
    {
        public const string PriceOfProduct =
            @"select top 1 [Price] from [Shop].[Products] where [ProductId] = @ProductId";
    }
}
</code>```

Once done, the Queries subclass is a good candidate to be put in a separate file.

One way is to make it internal, rename to DemoQueries and create a DemoQueries.cs file. The issue with that is that the code will be longer (specifying ProductOfUserRelationQueries instead of just Queries is actually a bit longer), and that the class will pollute the assembly (including the Intellisense), while you need to access it only in Demo class.

Another way is to make Demo partial, and to have the queries in a separate file, keeping the Queries class inside Demo.

Names in cache

When you cache some elements, it is important to be consistent with names (keys) used in cache. For that and similar to the first example, you can end up with a private class containing a bunch of methods like this:

```<code>public class Demo
{
    [...]

    private static class CacheNames
    {
        public static string PriceOfProduct(long productId)
        {
            return string.Format(@"Price(ProductId<{0}>)", productId);
        }
    }

    [...]
}
</code>```

Trace

The same applies to trace. Sometimes, a code which relies a lot on trace is nearly unreadable since the trace IDs and messages waste too much space. Putting a this.Trace(TraceId.UserRemoved) makes the code much shorter, but you have to define all the TraceIds and their associated event IDs and messages somewhere.

Overloads

This case is rather weird and has to be avoided in most cases, but still, there are valid examples where partial classes help.

I had a project where methods had a huge amount of overloads and other methods which were not doing anything useful rather than calling a different method while changing some parameters. They were required because they were used by the consumers of the library, but it was really annoying to see all them in the source code and being distracted from the real code (note that even an overload can be quite long in terms of LOC: at least three lines for the XMLDoc, but sometimes it was more about twenty lines, then the method itself, with its code contracts and then a tiny little call to the same method with different parameters).

Putting in a separate file all the overloads and methods which weren't doing too much helped concentrating on the core code.

Partial classes are the same as with regions

#regions are bad, and one of the reasons why they are so bad is that they give you an impression that your code is small, when in fact it has thousands of lines and is completely unreadable. The major issue is when somebody uses them inside of a method, to end up with hundreds of lines of code in this method which now does twenty things instead of one.

Partial classes have the same issue: if you rely too much on them, you can have an impression that your class is rather small, while it should have been refactored for months.

They may make the code difficult to navigate

Another flaw with partial classes is that it's not so easy to know where the stuff is. Take Initialize() in Windows Forms. For a person who discovers Windows Forms and partial classes, it's not so easy to understand where this method is: is it a method of the parent Form class, and is a part of .NET Framework? Or maybe it's somewhere in the code for MyForm? Oh, no, it's in a designer-generated code.

Yes, Visual Studio has the F12 - Go to Definition feature, but if you can organize your code into files so the person can tell where a method is, do it.

Body:
Aside the designer-generated code, partial classes can still be useful without compromising the code quality.

Examples of correct usage

A few usages I found particularly useful are the following:

SQL queries

I do a lot of stuff where direct, hand-written SQL queries are used instead of ORMs. The most basic architecture is to embed queries directly in code:

public class Demo
{
    [...]

    public int GetPriceOfProduct(long productId)
    {
        var query = Query(
            "select top 1 [Price] from [Shop].[Products] where [ProductId] = @ProductId",
            this.ConnectionString);

        // Use the query to retrieve the price.
    }

    [...]
}

This works well, until you have too many methods and until too many queries start to have more then ten lines. Reviewing only the queries by the DBA is complicated too, since the DBA has to search through all the code. In this case, the queries may be put in a separate class:

public class Demo
{
    [...]

    public int GetPriceOfProduct(long productId)
    {
        var query = Query(Queries.PriceOfProduct, this.ConnectionString);

        // Use the query to retrieve the price.
    }

    [...]

    private static class Queries
    {
        public const string PriceOfProduct =
            @"select top 1 [Price] from [Shop].[Products] where [ProductId] = @ProductId";
    }
}

Once done, the Queries subclass is a good candidate to be put in a separate file.

One way is to make it internal, rename to DemoQueries and create a DemoQueries.cs file. The issue with that is that the code will be longer (specifying ProductOfUserRelationQueries instead of just Queries is actually a bit longer), and that the class will pollute the assembly (including the Intellisense), while you need to access it only in Demo class.

Another way is to make Demo partial, and to have the queries in a separate file, keeping the Queries class inside Demo.

Names in cache

When you cache some elements, it is important to be consistent with names (keys) used in cache. For that and similar to the first example, you can end up with a private class containing a bunch of methods like this:

public class Demo
{
    [...]

    private static class CacheNames
    {
        public static string PriceOfProduct(long productId)
        {
            return string.Format(@"Price(ProductId<{0}>)", productId);
        }
    }

    [...]
}

Trace

The same applies to trace. Sometimes, a code which relies a lot on trace is nearly unreadable since the trace IDs and messages waste too much space. Putting a this.Trace(TraceId.UserRemoved) makes the code much shorter, but you have to define all the TraceIds and their associated event IDs and messages somewhere.

Overloads

This case is rather weird and has to be avoided in most cases, but still, there are valid examples where partial classes help.

I had a project where methods had a huge amount of overloads and other methods which were not doing anything useful rather than calling a different method while changing some parameters. They were required because they were used by the consumers of the library, but it was really annoying to see all them in the source code and being distracted from the real code (note that even an overload can be quite long in terms of LOC: at least three lines for the XMLDoc, but sometimes it was more about twenty lines, then the method itself, with its code contracts and then a tiny little call to the same method with different parameters).

Putting in a separate file all the overloads and methods which weren't doing too much helped concentrating on the core code.

Partial classes are the same as with regions

#regions are bad, and one of the reasons why they are so bad is that they give you an impression that your code is small, when in fact it has thousands of lines and is completely unreadable. The major issue is when somebody uses them inside of a method, to end up with hundreds of lines of code in this method which now does twenty things instead of one.

Partial classes have the same issue: if you rely too much on them, you can have an impression that your class is rather small, while it should have been refactored for months.

They may make the code difficult to navigate

Another flaw with partial classes is that it's not so easy to know where the stuff is. Take Initialize() in Windows Forms. For a person who discovers Windows Forms and partial classes, it's not so easy to understand where this method is: is it a method of the parent Form class, and is a part of .NET Framework? Or maybe it's somewhere in the code for MyForm? Oh, no, it's in a designer-generated code.

Yes, Visual Studio has the F12 - Go to Definition feature, but if you can organize your code into files so the person can tell where a method is, do it.


问:
What are good practices to perform software based optimization?
On a project that I am working on we encountered some performance problems.

We decided to drop hibernate in favor of plain Jdbc to gain database performance.

By converting our code to Jdbc we achieved the performance that we aimed for but the code quality seems to have deteriorated. And it took us three months to implement the system, which has me wondering if throwing in more hardware would've been less expensive.

What would you do to optimize your application in a manner that limits side affects on architecture and complexity? (Mainly interested in answers from perspective of web applications but other perspective are welcome)

答:
First, why would software based optimization be a bad idea at all?

When you're deploying web services which has their performance dictated more by the underlying technologies than the code itself, then it might be questionable to focus on optimizing your own product code-wise. However, note that as with any kind of optimization, you must profile the perfrormance of the target. If the bottleneck is in used technologies, then either find alternatives or try to find ways to rely less on them with performance-critical tasks.

In general I'd argue that "throwing hardware at it is cheaper" is a very stupid way of thinking. With such attitude, not only are you being lazy and irresponsible, you also lock out people with less hardware resources. Of course this might be a bit different in perspective of web applications which run on dedcated hardware, where such attitude might not be as deceiving as it s with client-deployed software.


答:
So is software based optimization always a bad idea?

No. Neither it's always bad, not always good. However, the optimization you describe — going lower level would not be the preferred way to go about it.

Generally spending numerous hours of development time to shave off few percent of execution time in case of web apps it a waste of money. On the other hand, spending time on making it scalable and eliminating code with suboptimal time complexity might be worth while.

You have to keep in mind, that unless your application is designed to be scalable, you won't be able to easily add more hardware. If parts of the code have ridiculous time complexity, adding hardware won't help deal with growth either.

Another thing is that in many cases, rather than optimizing the code, you should optimize the architecture.

Title: What are good practices to perform software based optimization?

Body:
On a project that I am working on we encountered some performance problems.

We decided to drop hibernate in favor of plain Jdbc to gain database performance.

By converting our code to Jdbc we achieved the performance that we aimed for but the code quality seems to have deteriorated. And it took us three months to implement the system, which has me wondering if throwing in more hardware would've been less expensive.

What would you do to optimize your application in a manner that limits side affects on architecture and complexity? (Mainly interested in answers from perspective of web applications but other perspective are welcome)


答:
Of course it's not always a bad idea. If it were, you could simply use generate-and-test for every computation (or even randomize-and-pray) and depend on faster hardware to do the job cheaper than your programmers could. And in fact, right now the pendulum is swinging towards software optimization, because raw processor speeds are plateau-ing and efficient multi-threaded coding is becoming way more important than it ever was.

That said, it is still often the case that buying a faster machine is ultimately cheaper than uglifying your code by contorting it in the name of performance. It's necessary to be aware of the pressures that will influence the trade-of in one way or another.

The longer your code will have to maintained, the more you suffer from contorted, un-understandable code. (Note that this is not the same as longevity. A sort routine in an OS might be written once, proven correct for all inputs, and then literally never be changed again. In such extreme cases, spending lots of time optimizing and ending up with horrible-looking code makes sense.)

Obviously, you need to know the cost of programmers, the cost of hardware, and at least an idea of how much technical debt you are accumulating, i.e. how much maintenance times will go up with more complicated code. This can vary enormously between individual programmers, so actually knowing your people is surprisingly important.

Never assume. Always measure. Know whether or not the optimization you are pondering will actually improve things, and by how much. If that means you have to write a great deal of code that may need to be taken out again, so be it. Ultimately you still come out ahead because you have more knowledge of your system, and with some care, such experiments can inform your next experiments and actually save you time when a similar question comes up.

As for avoiding technical debt, the important thing is to limit the impact of whatever you change; a data access layer is large, but with proper encapsulation it can have effects only on the data access layer, so at least you know the limit of how much debt you can accumulate all told. Finding a few routines that eat 90% of your time and changing only those is even better (and quite often such routines do exist). A powerful profiler is your friend here.


答:
Optimization is always good - all you have to do is to optimize the correct metric.

Usually, it's worth assuming the cost of optimizations, and the gain - how much does it cost (in programmer salary) to optimize? How much does it increse the revenues?

A few (contrived) examples:

A batch file moving some doc files from the secretary's computer to a local server once a week. It may take 1 hour, nobody cares. Important is to write the script.

A video codec. It will process zillions of pixels through it lifetime, and it will run on embedded devices, with very limited resources. If it's slow, even if it does its job quite well, it will be replaced. So, a team of gurus will write a good part of it in ASM, and will carefully manually reorder instructions to get a few clock cycles out of it.

Some backend Facebook code. If it runs 10% faster, it will shave off 10% of the datacenters energy bill - which runs into zillions $.

A messaging system (Skype, Gmail, etc) it is used by millions. If it's lazy, everybody will complain. You loose market share. It's worth investing man-years to optimize.

A Java accountability app, developed for your company - probably used by a few hundead people. It will be cheaper to buy two more computers than to spend a week optimizing.

In the context of web applications, there are two main reasons to optimize:

When your app/site slows down below user expectations

When your server becomes overloaded, and it's cheaper to optimize than to buy new machines.


问:
How to manage a copyright notice in an open source project?
I'm working on, and adding to, a GitHub-hosted project that includes this LICENCE.md (apparently the MIT licence verbatim):

```<code>Copyright (c) 2012 [Acme Corp]

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
</code>```

I've made changes, improvements etc (say 10% of the code, in ballpark figures) and publish the code to my own GitHub fork.

What should I do with this copyright notice? I'd like to update it (eg, just to add the name of my own organisation), but it says not to. How are these things normally managed? Add a separate copyright file?

答:
I am not a lawyer. The following is assuming US copyright law, and is specific to the MIT license.

The person that wrote the library owns the copyright on the code that he wrote. Only he is allowed to specify the license for that code. Per the license terms you must keep the copy of the LICENCE.md file, verbatim, with the code that he provided you.

You own the copyright to any changes or additions you made to the code. You've created derivative code. Only you are allowed to specify the license for your changed or new code. If you are creating a separate fork of the project, you must select a new, separate, license for your project. You must still keep the old license since it applies to the unmodified code.

If you wish to push your changes back to the original project, you still own the copyright to your changes. You must provide the original author with a license that allows him to redistribute your changes as part of his project, under the license that he chose.

More formal projects would ask you to sign a contributor license agreement or copyright assignment, but if it's an individual he probably wouldn't even realize that he needs one. This is usually done so that he may integrate your code into his codeline without changing any of the existing license terms. Typically a project will include an AUTHORS file listing all of the project contributors, but this is not mandated by the MIT license.


答: What ever changes in the fast evolving software industry, the learning curve is always here. "If there was only a way to learn without taking time to learn."

Title: What's the most important, useful or enlightening thing you learnt in the last 12 months?

Body:
A lot of people in the coding community talk about continuous improvement, deliberate practice and so-on - but when they talk about their current practices it's almost like they 'sprang fully formed from the loins of Zeus' because you don't hear about how their opinions changed over time or what they learnt recently.

Every now and then though I go to a talk, or read a book, or talk to someone and they open up a bit more and I find that I learn a lot from these insights.

So, if you had to pick one thing from the last 12 months that you learnt what would it be?


答:
You should not change the copyright.

You are technically entitled to what remains of a copyright (after being "filtered" through the license) to whatever you added/changed. As long as there is a clear, unambiguous record of your changes (github), you can add a copyright notice under your name in the modifications section if you wish, though this is generally not done.

You could/should add a comment (or to an existing one) indicating who made the changes and when (if they aren't doing this already, don't start it).

```<code>/*
    Copyright (c) 2012 Frob Co.

    Permission is hereby granted, free of charge, to any person obtaining
    a copy of this software and associated documentation files (the "Software"),
    to deal in the Software without restriction, including without limitation
    the rights to use, copy, modify, merge, publish, distribute, sublicense,
    and/or sell copies of the Software, and to permit persons to whom the Software
    is furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in
    all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
    OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
    IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
    CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
    TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
    OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/*
    Changes
    1-1-2012: YOU: Made a frob
*/
</code>```

I believe this is the correct way to paste the MIT license into a file, though I'm not a legal expert (I've never seen it without the "yelling" part of the notice).

Title: How to manage a copyright notice in an open source project?

Body:
I'm working on, and adding to, a GitHub-hosted project that includes this LICENCE.md (apparently the MIT licence verbatim):

```<code>Copyright (c) 2012 [Acme Corp]

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
</code>```

I've made changes, improvements etc (say 10% of the code, in ballpark figures) and publish the code to my own GitHub fork.

What should I do with this copyright notice? I'd like to update it (eg, just to add the name of my own organisation), but it says not to. How are these things normally managed? Add a separate copyright file?

Body:
You should not change the copyright.

You are technically entitled to what remains of a copyright (after being "filtered" through the license) to whatever you added/changed. As long as there is a clear, unambiguous record of your changes (github), you can add a copyright notice under your name in the modifications section if you wish, though this is generally not done.

You could/should add a comment (or to an existing one) indicating who made the changes and when (if they aren't doing this already, don't start it).

/*
    Copyright (c) 2012 Frob Co.

    Permission is hereby granted, free of charge, to any person obtaining
    a copy of this software and associated documentation files (the "Software"),
    to deal in the Software without restriction, including without limitation
    the rights to use, copy, modify, merge, publish, distribute, sublicense,
    and/or sell copies of the Software, and to permit persons to whom the Software
    is furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in
    all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
    OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
    IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
    CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
    TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
    OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/*
    Changes
    1-1-2012: YOU: Made a frob
*/

I believe this is the correct way to paste the MIT license into a file, though I'm not a legal expert (I've never seen it without the "yelling" part of the notice).


答:
It depends on what is actually causing the performance problems. Performance problems appear in all types of shapes and sizes, and did you actually fix the real bottlenecks?

IMHO a few hours with a query profiler tool and taskmgr/top can solve 90% of the database performance problems. Some additional indexes, restructuring queries or add some caching can make a huge difference.

Even if you add more hardware you might find your application design can't use it. If it is bottlenecked-by-design then more hardware can't help.


问:
What's the difference between using RDFS/OWL versus XML?
I was wondering what advantages the ontology languages of RDFS/OWL has over using a tagging/markup system (such as http://www.schema.org/) for managing and creating metadata?</p>

答: Your question makes little sense as is. RDFS is a very basic schema language to express RDF constraints. OWL is more advanced schema to express a complicated ontology. They have absolutely nothing in common with XML except that they can be expressed in XML.


问:
Controllers and re-factoring for maintainability / sensibility
I have read many posts similar to this on the site: however I still am questioning what is best in my situation (also the answers are contradicting from question to question).

I have a website (web-application) with a controller per section of domain logic (i.e. ProductsController, NewsController, ContactsController, etc..) and one very large very ugly admin controller which contains the logic for the Add/Edit/View/Delete functions for each section... now as you can imagine this controller is getting very out of control (whereas each function is not overly large, having dozens of functions in one controller does not sit well with me...).

From what I've read the general consensus is to just lump the admin functions in the 'sections' controller; however some also suggest you create a new controller for each admin section as well. so I would then have ProductsController and AdminProductsController - to me this seems a little overkill, however I have no real clue about this: any tips or readings would be appreciated - or if there is a 'industry best practise' that would be nice to know as well.

答:
Why do we refactor? So that it's easier to maintain later.

What is easier to maintain?

Each admin matters in the "sections" controller, polluting your probably-already-big-controllers.

Each admin matters in a new controller for each section.

How you answer this question tells you what you should do.

And as @SomeKittens suggests, it does sound like you want to separate the admin part in its own folder.


答:
Disclaimer:My experience with MVC stems solely from Joomla!

I think separating Admin/public is exactly what you want to do.  Personally, I wouldn't keep the Controllers in the same file, but rather keep all the admin components in their own subdirectory.  This reduces visual complexity and keeps it simple.

Title: Controllers and re-factoring for maintainability / sensibility

Body:
I have read many posts similar to this on the site: however I still am questioning what is best in my situation (also the answers are contradicting from question to question).

I have a website (web-application) with a controller per section of domain logic (i.e. ProductsController, NewsController, ContactsController, etc..) and one very large very ugly admin controller which contains the logic for the Add/Edit/View/Delete functions for each section... now as you can imagine this controller is getting very out of control (whereas each function is not overly large, having dozens of functions in one controller does not sit well with me...).

From what I've read the general consensus is to just lump the admin functions in the 'sections' controller; however some also suggest you create a new controller for each admin section as well. so I would then have ProductsController and AdminProductsController - to me this seems a little overkill, however I have no real clue about this: any tips or readings would be appreciated - or if there is a 'industry best practise' that would be nice to know as well.


答:
When working with MVC-inspired patterns for the Web, it is recommended to have 1:1 relationship between Controllers and Views. This should split you code-base in much better manageable chunks.

Also, as a side effect, you might encounter situation where you are repeating same exact code with only different structures from model layer. Like for example listing latest documents and latest users. The code-flow in both controller-view pairs is the same, only difference is the source of data.

To further separate the administration from public parts, you can put relevant parts in different namespaces, which then are mapped to subdirectories with same name by the class loader.


答:
This is how i lay my controllers out. Each controller is responsible for a specific group of my site.

Controllers folder

```<code>application/controllers/
  admin/
    utilities.php
    accounts.php
    invoices.php
  profile/ - any user based controllers, same as above maybe?
  auth.php - all login, password resets etc.
</code>```

Views Folder

```<code>application/views
  utilities/
    partials/
      _form.php
    add.php
    edit.php
    index.php
    view.php
  accounts/
  invoices/
</code>```

Body:
This is how i lay my controllers out. Each controller is responsible for a specific group of my site.

Controllers folder

application/controllers/
  admin/
    utilities.php
    accounts.php
    invoices.php
  profile/ - any user based controllers, same as above maybe?
  auth.php - all login, password resets etc.

Views Folder

application/views
  utilities/
    partials/
      _form.php
    add.php
    edit.php
    index.php
    view.php
  accounts/
  invoices/


问:
Business trying to make technical decisions
We've often run across scenarios where the business will promise a client a new feature.  The business will promise that the feature be implemented in a specific way.  These technical details promised by the business are usually poor.  Unfortunately, client is now set and want this feature to be implemented in the way described by the business.

In the end, the business just wants this feature to be completed without regard to quality and maintainability.  Is there a good way to push back?  How can we explain to the business that providing technical details before the requirements have been gathered is a bad idea?

答:
From the developer's perspective, this is one of two flavors of fail, when it comes to spec-writing. The other thing that can happen is when sales makes big promises, and then turns to IT to specify the project and deliver a write-up that can be turned into a quote.

Problem is, often that's the bulk of the work. Quite likely the actual code is just implementing the details of the approach laid out in a well-designed spec.

At the same time, sales finds it difficult to bill for preliminaries like specs development. We're not quite in bed yet with the client, and it's weird to hit them up for money to figure out how much money to hit them up for.

This is why most "first time" projects with new clients end up being loss leaders. If you're LUCKY, you use that first project to train the client on how to be a client, and you can start earning your butt back on the second project, or the maintenance agreement on the first one.


问:
What simple techniques do you use to improve performance?
I'm talking about the way we write simple routines in order to improve performance without making your code harder to read... for instance, this is the typical for we learned:

```<code>for(int i = 0; i < collection.length(); i++ ){
   // stuff here
}
</code>```

But, I usually do this when a foreach is not applicable:

```<code>for(int i = 0, j = collection.length(); i < j; i++ ){
   // stuff here
}
</code>```

I think this is a better approach since it will call the length method once only... my girlfriend says it's cryptic though. Is there any other simple trick you use on your own developments?

答:
Take advantage of short-circuiting:

if(someVar || SomeMethod())

takes just as long to code, and is just as readable as:

if(someMethod() || someVar)

yet it's going to evaluate more quickly over time.


问:
SVN command line client: checkout refused when LDAP password changed “svn: OPTIONS of” (repo) “authorization failed” (but works in TortoiseSVN)
When using the command line/terminal svn client, a colleague is getting "svn: OPTIONS of " [repo] "...authorization failed" error message when they attempt to checkout the repo to be their local working copy.

They used to be able to do this but have recently had to change their password (periodic routine security policy). And it stopped working. NOTE: The svn check command does ask for a password everytime (which they supply - i.e. their new one.)

BUT strangely they have no problem with Tortoise SVN, it works on that. They supply their usual login and new password and it works.

Our setup is a virtualised CentOS Linux machine with several Linux user accounts where development takes place and the SVN central repo is on a separate server, authentication is using our LDAP login (i.e. the same corporate login used to login to our Windows machines). We login as Linux users to our development server from our Windows machines, using standard terminal SSH tools, e.g. PuTTY or MobaXTerm or CygWin.

When I change my password I don't get the same problem, I am able to checkout.

I have seen many questions about this error message from searching various forums on google but none have provided me with a solution as yet.

One of the solutions I found suggests to clear or remove a local cache containing authentication, in a .subversion folder, we tried this but still the same problem. Also tried checking out to another folder.

So it seems we have clean out any trace of cached passwords but yet it still rejects.

Could there be another place on our CentOS Linux machine that caches the login
What is meant by OPTIONS (could it be a setting somewhere on our development machine or on the SVN repo server?)
Could it be a HTTP Proxy cache of my colleague's credentials stored somewhere - so we need to clear that when a password is changed?

(Mistakenly posted on superuser.com (which is about users), so closed it there and moved it here)

答: I bet Tortoise SVN is reading different configuration options than the CLI SVN.  SVN can read its configuration from many different sources.  I would try playing with settings like store-auth-creds in the per-user INI file or registry.


问:
Is it best practice to have a file only of "includes/requires"?
I have 5-10 files on one server that all catch XMLRPC-PHP requests.  There's about 20 lines of require_once in each one that are all the same.  It'd make life simpler for me to create a separate file that only has the requires and require that in my XMLRPC files.  Is this best practice, or does it open up issues that I don't know about?

答:
I've done that before and it did save some effort, but got it fiddly as I didn't always need every single file and sometimes needed a few more. If you always need those and only those, then I think it's a good plan.

However, there are alternatives if you have control of the file hierarchy and are not using third party libraries e.g. using php's __autoload() function to have the files automatically included when you try to instantiate the class. I'd tend to prefer this if at all possible as it needs a lot less maintenance.


问:
Reasons NOT to use JSF
I am new to StackExchange, but I figured you would be able to help me.

We're crating a new Java Enterprise application, replacing an legacy JSP solution. Due to many many changes, the UI and parts of the business logic will completely be rethought and reimplemented.

Our first thought was JSF, as it is the standard in Java EE. At first I had a good impression. But now I am trying to implement a functional prototype, and have some really serious concerns about using it.

First of all, it creates the worst, most cluttered invalid pseudo-HTML/CSS/JS mix I've ever seen. It violates every single rule I learned in web-development. Furthermore it throws together, what never should be so tightly coupled: Layout, Design, Logic and Communication with the server. I don't see how I would be able to extend this output comfortably, whether styling with CSS, adding UI candy (like configurable hot-keys, drag-and-drop widgets) or whatever.

Secondly, it is way too complicated. Its complexity is outstanding. If you ask me, it's a poor abstraction of basic web technologies, crippled and useless in the end. What benefits do I have? None, if you think about. Hundreds of components? I see ten-thousands of HTML/CSS snippets, ten-thousands of JavaScript snippets and thousands of jQuery plug-ins in addition. It solves really many problems - we wouldn't have if we wouldn't use JSF. Or the front-controller pattern at all.

And Lastly, I think we will have to start over in, say 2 years. I don't see how I can implement all of our first GUI mock-up (Besides; we have no JSF Expert in our team). Maybe we could hack it together somehow. And then there will be more. I'm sure we could hack our hack. But at some point, we'll be stuck. Due to everything above the service tier is in control of JSF. And we will have to start over.

My suggestion would be to implement a REST api, using JAX-RS. Then create a HTML5/Javascript client with client side MVC. (or some flavor of MVC..) By the way; we will need the REST api anyway, as we are developing a partial Android front-end, too.

I doubt, that JSF is the best solution nowadays. As the Internet is evolving, I really don't see why we should use this 'rake'.

Now, what are pros/cons? How can I emphasize my point to not use JSF? What are strong points to use JSF over my suggestion?

答:
We had a legacy JSP/Struts 1.0 application. We skipped Struts 2, JSF and everything else that has happened since Struts 1 and jumped in to Spring 3.0. It has support (and an active community) for our wish list - Eclipse IDE, MVC and REST.  Plus we ditched our vintage homegrown Javascript/ajax for jquery.

YMMV but Spring has been a smooth migration for us.

Title: Reasons NOT to use JSF


答:
JSF is adequate stateful web framework for Java that is a standard which means its supported out of the box by many major vendors (including FOSS ones).  It has strong 3rd party library support (PrimeFaces, IceFaces etc).  However, it does fundamentally 'break the web' due to its stateful nature (and a bunch of other things).  See Matt Raible's comparison of JVM based web frameworks, JSF usually comes close to last.

Edit - with JSF 2.2 - you can begin to argue that it doesn't break the web as much as it once did.  In fact it's HTML5 integration is not all terrible :-).

Title: Reasons NOT to use JSF

Body:
I am new to StackExchange, but I figured you would be able to help me.

We're crating a new Java Enterprise application, replacing an legacy JSP solution. Due to many many changes, the UI and parts of the business logic will completely be rethought and reimplemented.

Our first thought was JSF, as it is the standard in Java EE. At first I had a good impression. But now I am trying to implement a functional prototype, and have some really serious concerns about using it.

First of all, it creates the worst, most cluttered invalid pseudo-HTML/CSS/JS mix I've ever seen. It violates every single rule I learned in web-development. Furthermore it throws together, what never should be so tightly coupled: Layout, Design, Logic and Communication with the server. I don't see how I would be able to extend this output comfortably, whether styling with CSS, adding UI candy (like configurable hot-keys, drag-and-drop widgets) or whatever.

Secondly, it is way too complicated. Its complexity is outstanding. If you ask me, it's a poor abstraction of basic web technologies, crippled and useless in the end. What benefits do I have? None, if you think about. Hundreds of components? I see ten-thousands of HTML/CSS snippets, ten-thousands of JavaScript snippets and thousands of jQuery plug-ins in addition. It solves really many problems - we wouldn't have if we wouldn't use JSF. Or the front-controller pattern at all.

And Lastly, I think we will have to start over in, say 2 years. I don't see how I can implement all of our first GUI mock-up (Besides; we have no JSF Expert in our team). Maybe we could hack it together somehow. And then there will be more. I'm sure we could hack our hack. But at some point, we'll be stuck. Due to everything above the service tier is in control of JSF. And we will have to start over.

My suggestion would be to implement a REST api, using JAX-RS. Then create a HTML5/Javascript client with client side MVC. (or some flavor of MVC..) By the way; we will need the REST api anyway, as we are developing a partial Android front-end, too.

I doubt, that JSF is the best solution nowadays. As the Internet is evolving, I really don't see why we should use this 'rake'.

Now, what are pros/cons? How can I emphasize my point to not use JSF? What are strong points to use JSF over my suggestion?


答:
Now, what are pros/cons? How can I emphasize my point to not use JSF? What are strong points to use JSF over my suggestion?

You already seem to have made upt your mind about the cons, and I have to a gree with some of them (it does not separate layout and logic enough, and the resulting HTML is often atrocious), but disagree on others (if you use Facelets, which I would very much recommend, then the output should definitely be valid).

So here's some pros:

There are some very powerful component libraries like PrimceFaces or RichFaces that offer a lot of functionality out of the box. These can save you a lot of work if they cover your requirements (not so much if you have non-negotiable requirements not covered by them).

Composite Components offer a very clean way to modularize your pages

JSF integrates very well with the rest of Java EE

AJAX via component re-rendering is really easy and convenient

But certainly none of these advantages are so big that you should use JSF over some other framework that your team already has experience with.

Title: Reasons NOT to use JSF


问:
Good reasons for destroying mutexes with waiting threads
I'd like to see some valid examples of needing to let a thread enter a locked, non-re entrant mutex, then destroying the mutex (which supposedly terminates the thread).

I can't think of any good reason to do this. I can't remember precisely what we were arguing about earlier today, but my colleague insists such techniques are needed for "point-of-no-return" problems (again, forgive me, but I forgot the example he gave me).

答: I think you are using your mutex as a semaphore to signal that the threads all need to shutdown. This could be useful if any one (or subset) of the threads is capable of detecting conditions that require all the other threads to stop. This would also require all the threads to routinely access this mutex & a parent thread wait for them all to terminate before terminating itself or restarting the threads.


答:
I learned that the purpose of software testing is to find bugs. It is not to verify that the system is correct.

There are important psychological factors at play: If your goal is to show that the program is "correct," you will gravitate toward tests you know will pass. But if your goal is to find bugs, you will gravitate toward tests that will really push your system to the limits.

There is even an important change to the language you use. If a test finds a bug, you call it successful. If the test doesn't [that is, the program passes], you call it unsuccessful. I caught myself going along the lines of "verification" thinking, and it makes a big difference.

This psychological effect is discussed more in The Art of Software Testing, a classic book that I highly recommend. The author, Myers, also recommends that whoever is testing a program shouldn't be the author, nor even in the same management chain. You can do this if you are coding on your own, so it takes discipline.


答:
You've got some options, jump to the end for the summary.

So let's break this one down...

Copyright (c) 2012 [Acme Corp]

This is the Copyright notice and it belongs to Acme Corp.  It was claimed in 2012, which is relevant because Copyright does eventually expire.

If the claim was actually given to "Acme Corp", ie. it was boilerplate cut & pasted from the MIT example, then you could almost claim that there is NO copyright on this work.  Acme Corp is a fictitious organization, and failing to update the boilerplate puts the claim on dubious grounds.

But let's be good citizens, and grant the copyright to the actual claimants.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

This next section, the Permission notice, is stating that you can do just about anything you want with the code, including modifying the licensing agreement!  The catch is that you can't change the license on the existing code - you can change only what you modify.

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

This part simply means you have to persist the notices that are above.

So, what can you do?

You can and should lay copyright claim to the code you wrote and / or modified.

To do so with the same MIT license:  Just add your copyright notice after the 2012 Acme Corp copyright notice in the files you modified.

You can license your modifications under a different license, if you so choose.

To use a different license:  Add your copyright and license notice after the entire 2012 Acme Corp block (copyright, permission / license, exclusion of warranty) in the files you modified.

In the simplified case of your question, here's what you need to do:

Emphasis added to highlight the differences.

```
<strong>Original work</strong> Copyright (c) 2012 [Acme Corp]
<strong>Modified work Copyright 2012 Steve Bennett</strong>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
```

Body:
You've got some options, jump to the end for the summary.

So let's break this one down...

Copyright (c) 2012 [Acme Corp]

This is the Copyright notice and it belongs to Acme Corp.  It was claimed in 2012, which is relevant because Copyright does eventually expire.

If the claim was actually given to "Acme Corp", ie. it was boilerplate cut & pasted from the MIT example, then you could almost claim that there is NO copyright on this work.  Acme Corp is a fictitious organization, and failing to update the boilerplate puts the claim on dubious grounds.

But let's be good citizens, and grant the copyright to the actual claimants.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

This next section, the Permission notice, is stating that you can do just about anything you want with the code, including modifying the licensing agreement!  The catch is that you can't change the license on the existing code - you can change only what you modify.

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

This part simply means you have to persist the notices that are above.

So, what can you do?

You can and should lay copyright claim to the code you wrote and / or modified.

To do so with the same MIT license:  Just add your copyright notice after the 2012 Acme Corp copyright notice in the files you modified.

You can license your modifications under a different license, if you so choose.

To use a different license:  Add your copyright and license notice after the entire 2012 Acme Corp block (copyright, permission / license, exclusion of warranty) in the files you modified.

In the simplified case of your question, here's what you need to do:

Emphasis added to highlight the differences.

Original work Copyright (c) 2012 [Acme Corp]
Modified work Copyright 2012 Steve Bennett

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.


答: I suppose you could make an argument that a mutex that protects a resource should be destroyed and any waiting threads killed if something happens to the resource (e.g. threads waiting to write to a device which goes off-line).  Or possibly in a hard-real-time environment where any tasks which haven't completed during their quantum have to be force-exited.  Kind of a stretch, though, I don't see this being a general-purpose solution.

Title: Good reasons for destroying mutexes with waiting threads

Body:
I'd like to see some valid examples of needing to let a thread enter a locked, non-re entrant mutex, then destroying the mutex (which supposedly terminates the thread).

I can't think of any good reason to do this. I can't remember precisely what we were arguing about earlier today, but my colleague insists such techniques are needed for "point-of-no-return" problems (again, forgive me, but I forgot the example he gave me).


问:
Pair Programming and ISO 27001
I’ve been working in an eXtreme programming team and doing pair programming for over 7 years in a windows environment. When we first started doing it someone would log in with their windows credentials and therefore all access to domain resources, and more specifically version control, would be accountable to that windows user. Eventually we have evolved to have windows pairing accounts for specific pairing stations (e.g pairA, pairB, PairC etc…). All the devs know the passwords to these accounts. Accountability for commits (check-ins) is achieved by putting the programmers initials in the comment during the commit.

Up until now this has worked fine for us, but my company is currently going through a ISO 27001 audit and this was flagged up by the auditor as a risk. I have a number of possible solutions such as creating a pairing account for every pair combination, but I really would like to know whether anyone else has encountered this problem and how they solved it?

What solution was acceptable by the auditors?

答:
I would keep the accounts as they are, typically only one person is driving, and even if the other person uses the machine (unofficially) the person logged in should still be aware of what is happening on their machine.

Checkins would still need comments to show who the pair was however.

Title: Pair Programming and ISO 27001


答:
So far, I've handled this by adding contributors to the list of copyright holders, and leaving the licence text unchanged.

Essentially, this means that you are publishing the additional changes under the same licence as the others did before, and that the derived work should be licenced under these terms as a whole. This also means that the original authors may no longer re-licence it, as they are no longer the sole copyright holders (they can re-licence their original work without your additions, obviously).

As a non-lawyer, my interpretation of the last sentence is that you are not allowed to remove copyright notices, but you can add your own.


问:
Should laying out a GUI graphically be considered "cheating?"
I have a friend who has a slightly greater amount of programming experience as me. We were talking about all the different programming technologies we use and Interface Builder came up in conversation.

Being of no programming background except for what I've taught myself, I personally believe that IB and all it's features (IBOutlets, IBActions) help coders of my skill level (and all skill levels, for that matter) complete projects of theirs in less time.

His view of IB is a little enthusiastic. He believes that coders that utilize Interface Builder are "cheating" in the fact that they don't have to lay out interfaces by hand.

Question:

Should using a GUI builder to lay out interface elements be considered "cheating" (since most programming originally required laying interfaces out by hand in code)? Why?

答:
It's certainly not cheating, although I would have a little less respect for a developer who couldn't lay out a GUI without one.  IMO, using one is no different from using a system-provided datatype -- why implement your own linked list or hash map if you can use one out of the system library?

FWIW I had to implement a UI in Java Swing a couple of months ago.  I'd never used it, so I wrote it all by hand so I could get a better understanding of how it worked.  Now that I know the basic API, I'll never write one by hand again if I can help it!


答: Basically any set of identical code in multiple places should be consolidated.  As long as you're sure the exact same set of includes are required in each place I would put them together in one file.  The performance difference (if any) is negligible and maintainability is more important.</p>

Title: Is it best practice to have a file only of "includes/requires"?

Body: I have 5-10 files on one server that all catch XMLRPC-PHP requests.  There's about 20 lines of require_once in each one that are all the same.  It'd make life simpler for me to create a separate file that only has the requires and require that in my XMLRPC files.  Is this best practice, or does it open up issues that I don't know about?


问:
How could one make a reasonably efficient, pointer-sized mutex?
I have my own ideas about how a pointer-sized mutex could be made: The integer is used as a set of flags, counter, index, and a spinlock that guards an entry in a table of pre-allocated kernel objects given to mutexes only when threads are contending, and released afterward (only need at most N table entries for N threads).

Watching MS' SRWLOCK structure change leads me to believe they conditionally store the tail of an xor list (or a table index?) in the pointer when contested. The first 4 bits are flags of some kind.

To clarify

I was wondering if there were any other ideas about making a user mode mutex that is the size of a pointer and only requires the allocation of a kernel object if it is contested. My idea involves spinlocking, so I am hoping there exists something that does not.

答: Is the mutex supposed to be reentrant?  If so, you'll need a few bits to hold a recursion count.  Also a thread/process ID.  You might also want to keep a pointer or some kind of reference to a queue to hold IDs of threads waiting on the mutex, depends on whether you want threads to queue up or simply let them acquire the mutex based on their scheduling order.  Your pointers are 64 bits, right? ;)</p>


答:
I would assume the auditors would prefer that developers log in as themselves and not as some "pair" which has a shared password.  The risk should be obvious--a developer adds some malicious code as "PairA" and puts someone else's initials in the comment (or doesn't comment it at all).  How do you trace back to the malicious developer?

I'd recommend that whoever is driving first (in a session) log in with his own ID, and the pair continue to put both of their initials in the comments--that way, the code remains traceable back to an actual developer.

Title: Pair Programming and ISO 27001

Body:
I’ve been working in an eXtreme programming team and doing pair programming for over 7 years in a windows environment. When we first started doing it someone would log in with their windows credentials and therefore all access to domain resources, and more specifically version control, would be accountable to that windows user. Eventually we have evolved to have windows pairing accounts for specific pairing stations (e.g pairA, pairB, PairC etc…). All the devs know the passwords to these accounts. Accountability for commits (check-ins) is achieved by putting the programmers initials in the comment during the commit.

Up until now this has worked fine for us, but my company is currently going through a ISO 27001 audit and this was flagged up by the auditor as a risk. I have a number of possible solutions such as creating a pairing account for every pair combination, but I really would like to know whether anyone else has encountered this problem and how they solved it?

What solution was acceptable by the auditors?


答: Instead of creating separate accounts so that work is not locked to a possibly absent user, use your version control system.  When a pair starts working, create a task branch.  Commit code to the task branch whenever the tests pass.  When the task is complete, merge back and close the task branch.</p>

Title: Pair Programming and ISO 27001


答:
Up until now this has worked fine for us, but my company is currently
  going through a ISO 27001 audit

ISO 27001 or not, your current system only works because you're a small company where there's a high degree of communication and mutual trust. That sort of thing doesn't scale up very well, so you'd probably have to consider other options at some point in the future anyway.

Creating a separate account for every possible pair seems even less practical: you'd need 90 accounts for a group of 10 developers, and each of those 10 developers would have to know 9 different login/password combinations.

The only practical solution is to use individual accounts, as others have suggested, and track the identity of the second person in the pair some other way (comment in your version control commit, field in the issue tracking system, etc.).

Title: Pair Programming and ISO 27001


问:
What parts of your coding standard contribute to quality code?
In response to This Question, I ask:   What are the best parts of your coding standard?

What are the best practices that help with code quality, reliability, maintainability, readability, etc.

Please include the language, the item from the standard, and the reason it improves your code.

答:
Any Language:

Adequate and consistent use of whitespace, both vertical and horizontal, vastly improves the ability of the code to be rapidly skimmed as well as read at a normal pace. I'm not going to argue about tabs versus spaces, as long as their usage is consistent, but proper indentation and judicious use of blank lines and spaces around operators are all absolutely necessary.

Related: keeping line lengths to a reasonable limit such as 80 columns has demonstrable benefits: no weird wrapping on consoles, no need to scroll, and the ability to view multiple files side by side on a wide monitor, not to mention that it tends to help encourage refactoring of deeply-nested code and run-on expressions.


问:
Open Source Project: Company to register copyright
I'm releasing an open source project. I want to make it as inclusive as possible for any community that might embrace it. Specifically, I don't want the code copyrighted in my name when an entire community might work on it; that approach seems self-centred and alienating. My immediate thought to avoid this issue is to assign the copyright to a company rather than myself. How do I do this? Do I have to register a corporation? Can I just give the name of a group and call that a company? What legal hurdles are there? I honestly have no idea when it comes to this sort of thing.

(I'm in Canada and want to use the GPL, if that helps.)

答:
Not a lawyer, not legal advice.

There are 3 types of companies: Sole Proprietorship, Partnership, and Corporation.  In my understanding, only a corporation is a separate legal entity, so that must be what you're talking about here.

As someone who has incorporated a company in Canada before, trust me, this is a big pain in the butt.  There are hundreds of dollars of expenses, plus you have to keep up paperwork every year, not to mention a corporate tax return.  Doing it yourself is time consuming, and if you want to hire it out, it costs a lot more than a personal tax return.  Just to create something to register a copyright to?  I suggest not doing that.

Whether or not you want the code copyrighted under your name is irrelevant.  As soon as you write something, the copyright belongs to you, unless you're working "for hire".  You then have the right to license it any way you want.  All of open source is based around this principle.

Personally I'd be happier if the copyright of an open source project belonged to the original author rather than some corporation, because what's stopping someone from selling the company?  It could just be gobbled up.

I say, don't worry about registering or assigning copyright, just release the thing under the GPL and be done with it.


问:
How do you track third-party software licenses?
How do you track licenses for third-party libraries that you use in your software? How did you vet the licenses? Sometimes licenses change or libraries switch licenses--how do you stay up to date?

At the moment I've got an Excel spreadsheet with worksheets for third-party software, licenses, and the projects we use them on (organized like a relational database). It seems to work OK, but I think it will go out-of-date pretty quickly.

答:
This is a great opportunity for cooperation between Engineering and Legal. All third-party software should be cleared by Legal prior to coding (or risk coding it out later... or worse); and while you're at it, let Legal track the licenses and how they're used! </p>

<p>Spreadsheets and databases work with small volumes, but they are not scalabe solutions. Many companies do a periodic code scan to audit third-party license use in their products, but this is much riskier and more expensive than tracking the info from the start. See this relevant white paper: http://www.ententesoftware.com/documents/PlanningVsScanning.pdf. </p>

Body:
This is a great opportunity for cooperation between Engineering and Legal. All third-party software should be cleared by Legal prior to coding (or risk coding it out later... or worse); and while you're at it, let Legal track the licenses and how they're used!

Spreadsheets and databases work with small volumes, but they are not scalabe solutions. Many companies do a periodic code scan to audit third-party license use in their products, but this is much riskier and more expensive than tracking the info from the start. See this relevant white paper: http://www.ententesoftware.com/documents/PlanningVsScanning.pdf.


问:
Add a second developer to the team
In my company, I'm the only developer, but we plan on expanding the team by hiring a second programmer. I know there are a lot of implications to that (especially around source control). I've Googled a lot, but haven't found a good tutorial/article on how to grow the team from one to many developers.

Do you have any resources that we could make use of?

答:
I went into the same question like a year ago. My partner and I run a small consultant company and most of the code was written by myself (he is on the sales team). At some point, the number of projects increased and we noticed it was not only the code we have to care about; there are a lot of things you need to handle (documents, workflows, continous integration, testing, source control, etc) and the best choice you make here, the less headache will be on the near future.

I knew Jira from another job as being a very productive bug tracking system. It is scrum based, but even if scrum is not your thing, it is a great tool to work with. You keep track of every bug, task, new feature and such from one centralized web application and, it can be used either licensed or on a monthly payment basis. Big companies trust Jira for their development, so, why shouldn't small ones do? Taking into account the cost of Jira on demand is now less than an average development cost. For me, this was a no-brainer.

Jira comes with lots of plugins, some are cheap, some are not, some are given at no cost at all. One of those plugings we are using is Fisheye, which is a source control repository compatible with SVN. As of now, we store on Fisheye 7 projects with many thousands of line code. Never had an issue with the Atlassian guys, and their support (jira based of course) totally rocks.

Sharepoint is a great tool as well, but it is not focused for development. It is a CMS, easy to use, but for different porpouses.

Give Jira a try, there are free trials, I'm sure it will fit your needs. Cheers.

Title: Add a second developer to the team