问:
Dealing with co-workers who do not have a consistent coding style?
What do you when you're working with someone who tends to write stylistically bad code? The code I'm talking about is usually technically correct, reasonably structured, and may even be algorithmically elegant, but it just looks ugly. We've got:

Mixture of different naming conventions and titles (underscore_style and camelCase and UpperCamel and CAPS all applied more or less at random to different variables in the same function)

Bizarre and inconsistent spacing, e.g. Functioncall  (arg1 ,arg2,arg3 );

Lots of misspelled words in comments and variable names

We have a good code review system where I work, so we do get to look over and fix the worst stuff. However, it feels really petty to send a code review that consists of 50 lines of "Add a space here. Spell 'itarator' correctly. Change this capitalization. etc."

How would you encourage this person to be more careful and consistent with these kinds of details?

答:
LOL. You would absolutely hate my code. I can't spell to save my life and I don't care.

But I know some people do actually care about those things.

I suggest you fire the person writing that ugly code if they don't change then find somebody that makes things really pretty and hope they can write code that

is usually technically correct,
  reasonably structured, and may even be
  algorithmically elegant

and if they can't then at least you can show the broken pretty code to the customer and sell them on that!

But seriously. Focus on the actually important things first. If you can't find a good, solid reason outside "it hurts my delicate sensibilities" then ignore it for now. If it is actually important then sit down with the person and convince them of that importance. Things like standards that make it easy to tell the difference between class level, method level, shared, constant variables do make a difference. If the coder in question cares at all about his/her profession they will understand and try to do the right thing.


问:
Testing ASP.NET .aspx and .ascx code behind files
I am wondering how to test .aspx.cs and .ascx.cs code behind. Can I use unit testing and if so how? Are there alternatives that will help test the functions in the code behind files? I don't know how to mock the page or control.

I would like to try to apply tdd methodology but I don't know how to unit test the code behind. Do you setup tests for the code behind or move the code to alternate files that are easier to test.

Is moving the code out of the code behind a better practice?

Also, how would you go about unit testing the code behind files?

答:
.aspx files, compared to corresponding .aspx.cs code-behind files) are expected to contain minimum programming code, i.e. large chunks of HTML with here and there the calls to variables, eventually with straightforward loops and conditions.

This means that you will rarely find unit tests for .aspx files, since there are no complicated algorithms or business rules there.

Since .aspx files can still introduce bugs, system testing seems a good choice. The way would be the same as the one you use to test whether your HTML code corresponds to the requirements.

Note: ASP.NET encourages to put too much programming code directly in .aspx files. In Microsoft's demos, you can even find SQL queries there. This is a terrible way to develop websites, and is misleading of what templates are.

For example, in Django templates in Python, things are much clearer, and you don't put your database logic in HTML templates. ASP.NET makes separation of concerns not obvious.

If you find yourself putting business logic or database logic in your HTML templates, or if you notice that many bugs are in your templates, consider introducing layers in your application, and keep only minimum code in templates.

ContentLicense: CC BY-SA 3.0


问:
Order of parameters in localization code
In localization code (like T('English phrase with %s and %s parameters', param1, param2) the order of parameters in different languages is different. How to handle this?

Our localization engine seems not to support named or numbered parameters, so the parameters need to go in the same order as they are in code.

答:
Pick a different localization engine, or roll your own if there are none for the language you use.

Parameters inversion is quite frequent in internationalization. That's why many format-type functions enable to specify the index of the parameter in the pattern.

For example, in Python, the two following lines print the same thing:

print('Hello, %s!' % ('John'))
print('Hello, {0}!'.format('John')) # Can specify the order
```

<p>In C#, the most used pattern indicates in which order the parameters are taken:</p>

<pre class="lang-cs prettyprint-override"><code>string.Format("Hello, {0}!", "John");
</code>```

Body:
Pick a different localization engine, or roll your own if there are none for the language you use.

Parameters inversion is quite frequent in internationalization. That's why many format-type functions enable to specify the index of the parameter in the pattern.

For example, in Python, the two following lines print the same thing:

print('Hello, %s!' % ('John'))
print('Hello, {0}!'.format('John')) # Can specify the order

In C#, the most used pattern indicates in which order the parameters are taken:

string.Format("Hello, {0}!", "John");


答:
If your localization engine doesn't support named parameters, then there are a few options.

Get a new engine that does support named parameters

Don't let your engine fill in the parameters and feed the translated string to a second "printf" engine, which does support named parameters, to fill in the parameters.

Accept that you will get badly translated output and ensure that your translators know that the parameters may not be swapped during translation.1

1. I have actually worked on a product where this choice was made, due to technical limitations in the printf/display engine.

Title: Order of parameters in localization code

Body:
In localization code (like T('English phrase with %s and %s parameters', param1, param2) the order of parameters in different languages is different. How to handle this?

Our localization engine seems not to support named or numbered parameters, so the parameters need to go in the same order as they are in code.


问:
How does one become a leader in a team of programmers?
What skills, knowledge and talents should a junior programmer aim to obtain in order to be qualified to become a team leader? </p>

答:
Where I work, the title Team Lead is often a completely artificial title applied to developers that don't want to get on the management track and don't want to spend time managing direct reports.

You become a team lead by being the defacto developer on the team to ask when there are technical, business or process issues. And you know you have reached that point when you tell someone on your team No, I don't think you should do it that way and they respect your opinion enough to take your suggestion more often than not. Likewise, you know your manager sees you in that role when you can tell him Have Bob do that rather than Ted, Bob will do a better job and he adjusts the project plan because he knows you know the team better.

ContentLicense: CC BY-SA 2.5


问:
UML Class Diagram: Abstract or Interface?
I am modeling a class diagram and have spotted an opportunity to simplify it slightly. What I want to know is, would this it be better to implement an abstract class or an interface?

The scenario is this, I have the classes:

Artist

Genre

Album

Song

All of which share the methods getName, setName, and getCount (playcount that is). Would it be best to create an abstract 'Music' class with the aforementioned abstract methods, or should I create an interface, since the classes that implement the interface have to include all of the interface's methods (I think, correct me if I'm wrong).

I hope I've given enough detail, please ask questions if I haven't.

Thanks!

答:
You should create an abstract class.

Generally speaking, a song can consist of a Title / Artist / Album / Genre. All of those are just a string of data which can be handled the same way.
By using an abstract class you don't have to write mentioned "getName", "setName" and "getCount" more than once, which sounds pretty neat.

Using an interface would just tell you that the functions should exist in each class, but you'd still have to write them separately. However, if you come up with methods they all have in common, but which work differently for each class, I suppose an interface would make more sense.

What bugs me though is that you want them to be classes. For example, since you would want an album to have it's own "Times played", you'd have to make sure that there's only one instance of that specific album. Each time a new song is added, you'd either have to search through all existing classes with that name and set a pointer or something similar to the already existing one.

Then again, the good part about using an album as an instance of a class, is that it's possible to have several albums with the same "name" without counting them as the same album. Err.. anyways, my mind has drifted away and this is not really related to the question.


问:
ASP.net performance code behind vs app_code
I am wondering about performance of a web site/application when there is code in the code behind files rather than when the code is moved to separate files in the App_Code folder.

My understanding is that the code behind gets compiled and executed every time they are requested by the user. If this is not the case, please let me know. Also, it is my understanding that the code in the App_Code file gets compiled once.

With these understandings, it would seem that moving code the App_Code folder would speed up requests. I understand that there wont be any significant gains until you have lots of files and lots of requests very frequently. However, will this cause any performance value?

Also, by performance I am talking about speed. Specifically speed of client side load. And I know there are other factors that can increase speed on the users end, but I am specifically asking about the above situation.

答:
Your understanding is incorrect.  Both the App_Code and aspx files are compiled just once and then cached.  Individual files are only compiled when used (at least that's the most common case).

There is a performance hit when a page is first hit, as it has to be compiled, if this is a problem web sites may not be for you.

See Understanding ASP.NET Dynamic Compilation:

In order for your Web application to service requests, ASP.NET must first parse and compile the code of your Web application into one or more assemblies. When the code is compiled, it is translated into a language-independent and CPU-independent representation called Microsoft Intermediate Language (MSIL). At run time, MSIL runs in the context of the .NET Framework, which translates MSIL into CPU-specific instructions for the processor on the computer running the application.

ASP.NET dynamic compilation enables you to modify your source code without having to explicitly compile your code before you deploy your Web application. If you modify a source file, ASP.NET automatically recompiles the file and updates all linked resources. The IIS server does not have to be restarted for the changes to take effect unless the <processModel> section has been changed...

By default, ASP.NET Web pages and code files are compiled dynamically when users first request a resource, such as an ASP.NET page (.aspx file), from a Web site. After pages and code files have been compiled the first time, the compiled resources are cached, so that subsequent requests to the same page are extremely efficient...


问:
Differentiating between Factory Method and Abstract Factory
I've been confused for a while about the differences between the patterns Factory Method and Abstract Factory. Been doing a lot of research, still confused.

I have one question:

Is the only difference between the two patterns, is that Factory Method produces one object, and Abstract Factory produces a family of objects? Or are there more differences?

I read a lot on this site and the web about this, only confused me more. I know how to use the patterns, but am having trouble differentiating between the two.

答:
A factory method is essentially just a constructor with another name. This can be useful e.g. to guarantee correct initialization, registration, or to supply default values without having to subclass the product:

```<code>private List<WeakReference<Product>> products = ...;

public Product makeProduct(Param x) {
    Product instance = new Product(x, "default value");
    instance.initialize(42);
    products.add(new WeakReference<>(instance));
    return instance;
}
</code>```

An abstract factory pattern is usually implemented in terms of factory methods, but here the aim is to leave the concrete type unspecified until runtime. So we have a set of products:

```<code>interface Product {}
class ConcreteProduct1 implements Product {}
class ConcreteProduct2 implements Product {}
</code>```

And we have an abstract factory:

```<code>interface Factory {
    public Product makeProduct();
}
</code>```

Such a factory might be used by client code: factory.makeProduct(). Which concrete product is used is delayed to runtime.

```<code>class ConcreteFactory1 implements Factory {
    public Product makeProduct() { return new ConcreteProduct1(); }
}

class ConcreteFactory2 implements Factory {
    public Product makeProduct() { return new ConcreteProduct2(); }
}
</code>```

Typically, an abstract factory will have multiple factory methods for a set of related types, you can think of a factory instance as a “theme”. Abstract factories are also useful for dependency injection.

The factory method pattern is a combination of factory methods with the strategy pattern. Here the idea is that our class needs to create some instance, but will let subclasses override the choice of the instance. In other words, the client and the factory are the same.

```<code>class DomainSpecificStuff {
    public doDomainSpecificStuff() {
        Product p = this.makeProduct();
        p.frobnicate();
    }

    protected makeProduct() {
        return new  ConcreteProduct1();
    }
}

class OtherDomainSpecificStuff {
    @Override
    protected makeProduct() {
        return new ConcreteProduct2();
    }
}
</code>```

So the strategy pattern allows for limited dependency injection through the use of inheritance when used as the FMP.

So what are the useful distinctions between the factory method pattern and abstract factory pattern?

Client: The client of the factory method in the FMP is the factory itself – it's just a spin on the strategy pattern, after all. The client of the AFP is some other class.

Number of Objects: Typically, the FMP will only have a single factory method, whereas the AFP can be used to produce multiple related objects. It is not the case that an AFP must have at least two factory methods, although the creation of related, interdependent objects is where the AFP shines.

Intent: The AFP is a collection of related factory methods which can be passed around in client code. The FMP allows subclasses to swap out a dependency.

Body:
A factory method is essentially just a constructor with another name. This can be useful e.g. to guarantee correct initialization, registration, or to supply default values without having to subclass the product:

private List<WeakReference<Product>> products = ...;

public Product makeProduct(Param x) {
    Product instance = new Product(x, "default value");
    instance.initialize(42);
    products.add(new WeakReference<>(instance));
    return instance;
}

An abstract factory pattern is usually implemented in terms of factory methods, but here the aim is to leave the concrete type unspecified until runtime. So we have a set of products:

interface Product {}
class ConcreteProduct1 implements Product {}
class ConcreteProduct2 implements Product {}

And we have an abstract factory:

interface Factory {
    public Product makeProduct();
}

Such a factory might be used by client code: factory.makeProduct(). Which concrete product is used is delayed to runtime.

class ConcreteFactory1 implements Factory {
    public Product makeProduct() { return new ConcreteProduct1(); }
}

class ConcreteFactory2 implements Factory {
    public Product makeProduct() { return new ConcreteProduct2(); }
}

Typically, an abstract factory will have multiple factory methods for a set of related types, you can think of a factory instance as a “theme”. Abstract factories are also useful for dependency injection.

The factory method pattern is a combination of factory methods with the strategy pattern. Here the idea is that our class needs to create some instance, but will let subclasses override the choice of the instance. In other words, the client and the factory are the same.

class DomainSpecificStuff {
    public doDomainSpecificStuff() {
        Product p = this.makeProduct();
        p.frobnicate();
    }

    protected makeProduct() {
        return new  ConcreteProduct1();
    }
}

class OtherDomainSpecificStuff {
    @Override
    protected makeProduct() {
        return new ConcreteProduct2();
    }
}

So the strategy pattern allows for limited dependency injection through the use of inheritance when used as the FMP.

So what are the useful distinctions between the factory method pattern and abstract factory pattern?

Client: The client of the factory method in the FMP is the factory itself – it's just a spin on the strategy pattern, after all. The client of the AFP is some other class.

Number of Objects: Typically, the FMP will only have a single factory method, whereas the AFP can be used to produce multiple related objects. It is not the case that an AFP must have at least two factory methods, although the creation of related, interdependent objects is where the AFP shines.

Intent: The AFP is a collection of related factory methods which can be passed around in client code. The FMP allows subclasses to swap out a dependency.


问:
Is it really possible to have libraries not depend on other libraries?
I often see the advice that you should try to make each library independent. And yet in reality I can never seem to achieve this. Is this BS advice or is it actually possibly in any realistic way?

Example: I write a 2D Vector library, I then use that to make a 2D collision library. I then build a 2D physics library that uses both the 2D Vector Library and the 2D Collision library. Am I seriously expected to figure out a way to make the physics library not depend on the other 2 libraries? Likely I'll eventually want to be able to serialize/deserialize the physics and collision data which will mean I'll want to make them further depend on some serialization library.

Another example: I have a string library with lots of string functions (think endsWith(str, ending) and startsWith(str, start) or whatever. I then write a templating library that uses my string library.

I rarely seem to be able to write a new library that doesn't use other libraries.

I could write interfaces and then write adaptors for all of those to attempt to decouple one library from another but it's unlikely to be performant and often the models of the different libraries mean that even if I could decouple with an interface trying to use a different library than the one originally decoupled will end up being impossible or massively non-performant.

So, is that original advice BS or is there some way to actually apply the advice in the real world?

答:
I would say that libraries should only depend on the libraries it absolutely needs to get the job done. They shouldn't need to depend on libraries that unrelated parts of the system depend upon.

Sometimes you will see that LibraryA depends on LibraryB and LibraryC. Then if LibraryZ needs to depend on LibraryA, then it also has to depend on LibraryB and C. That's the kind of dependency hell that should be avoided when possible. LibraryZ shouldn't need to know anything about Libraries B & C.

A slightly roundabout real world example....

I'm currently building a system with a number of plugin libraries, and had to answer a similar but slightly different question:

"Is it possible to have plugins that know nothing about any other plugins, but still use information/functionality from other plugin libraries?"

(eg Web Pages have Navigation on them, but to build a Navigation widget - you need to know what Pages are available and the urls of those pages)

After a lot of investigation and prototyping I decided on a messaging bus system. Everything knows about the messages for the system (and a few other core implementation libraries), but they don't know anything about what handles those messages.

While this isn't exactly "libraries don't depends on any other libraries" in this question, it does seriously limit the extent of dependency injection and dll hell, as PluginLibraryZ knows absolutely nothing about PluginLibraryA or any of the libraries that PluginLibraryA depends on (eg library B & C from above). The plugin libraries only know about the messages library, and other libraries that are absolutely necessary to do its own job, and nothing more.

So for your example here, your Physics library would still depend on the 2D vector and 2D Collision libraries - but another part of the system (eg ThrowBall library) that had a need to use the physics library could just raise a message of "WhereDoesBallLand" with all the required parameters (eg weight of the ball, angle and force of throw etc). So your Physics library would do all the calculations to find out where the ball would land, and the ThrowBall library would get an answer to the "Where does the ball land" question. But the ThrowBall library wouldn't depend on the Physics library or the "D vector or Collision libarries.

NOTE: I'm sure that Message Buses aren't the only way of achieving this separation of functionality and dependencies - but it worked for me in my plugin library dependency issue. I even got it down to the frontend website didn't need to know about any of the plugin libraries - just the messages and a couple of core functionality libraries.


问:
Does design by contract imply correct output?
Design by Contract says, in terms of the function talking: "you give me all the right parameters and I'll give you exactly this kind of data" ...in essence.

So, given that, should I use up resources checking the output?  I should check for properties that the function does not guarantee its output possesses, but the properties the function guarantees need not be checked, right?

Here's an example:

```<code>class Transition_Manager {
    string str = generate_non_null_string();
    process_using_a_function_that_can't_handle_null_strings( str );
}
</code>```

答:
The Design-by-Contract methodology makes clear separation of responsibilities:

a client has to fulfill a precondition of a supplier

a supplier has to fulfill its postcondition as soon as the precondition is fulfilled

As a result of this policy

if the precondition is violated, it is a fault of the client (the client is "guilty", it is a bug in the client's code)

if the postcondition is violated, it is a fault in the supplier (the supplier is "guilty", it is a bug in the supplier's code)

That's why it is called "contract" - it is a contract/an agreement between two parties - the client and the supplier - to meet these conditions.

From the client's point of view, it has to fulfil the precondition, but then it can rely on the postcondition that is an obligation of the supplier. There is no need to recheck the output.

In real life it is up to the author(s) of the supplier code how to make sure the output is always correct as soon as the input is correct, be it debugging, testing, verification, code review or something else. In the environments that support DbC natively, it is possible to perform run-time monitoring of preconditions and postconditions during program execution. Contract violation immediately points to the party that is buggy.


问:
Fighting technical debt as the "lowest developer"?
Let's say you work for a company and what you do is develop software for them. You have no idea of the big picture or maybe slight. What you do have are tasks assigned to you via issue tracking system. You're given tasks, you make them work the way the task describes them, you send them back. Like adding 2 integers:

```<code>function add(a,b){return a + b;}
</code>```

But later, as the project goes forward, you notice that as add becomes more complex, you realize that it should have needed some form of architecture, more than just a function that adds parameters and returns a value. However, you didn't know that. In the first place, all they needed was that simple add. You didn't expect add to become so complex.

The project progresses with more features, which you didn't expect to have in the first place. And in the end, you keep piling up hacks and layer upon layer of functions to avoid breaking/rewriting the existing code.

How do you deal with these situations? How do you fight technical debt as "the lowest developer"?

Clarification:

You're the "implementer", the lowest in the hierarchy.

You see the problem, but have no say with the matter.

I'm not quantifying technical debt or looking for tools.

Regarding the third "duplicate"

Refactoring & Rewrite - You are locked to your tasks. You are not paid to do extra.

Architecture Overview - You know the overall system, but no idea of the architecture.

Code Freeze - Not your call. You're not management.

Modularization - No idea of architecture. Modules change as requirements change.

Automated Tests - None exists.

答:
What makes me feeling bad about your scenario is exactly what you wrote in the headline and multiple times in the question text:

You are the lowest developer in the chain

Why is that point so important? Well, first of all, and from a purely technically viewpoint, you are certainly right. You are hired as what you call an "implementor" of things, a worker bee that acts upon commands given.

But even if you are the lowest developer with regard to rank, this still is not quite right. The key here is to realize, that you are only perceiving yourself as being the lowest developer. Have you ever tried to overcome that self-perception and actually take over responsibility for something?

Take! Not wait, until someone makes you responsible.

You see the problem, but have no say with the matter.

I'm not quantifying technical debt or looking for tools.

You are locked to your tasks. You are not paid to do extra.

Not your call. You're not management.

Typically it is quite the opposite: You are paid more and your opinion is respected more, once you show that you are worth the money. It's "do before have", not the other way round.

What I expect from the people within my team is exactly that: A sense of responsibility for the project or product we are trying to build and for all the processes related to that effort. Whenever someone in my team impresses me by taking over responsibility, e.g. proposing improvements or even better start to improve things on their own, these are the people that will get promoted.

To put it the other way: Nobody promotes worker bees, people passively waiting for tasks being assigned to them, lacking even the tiniest blink of initiative "because they are not paid for it", finally whining that they never had a chance.

Of course, all of this again depends on the culture of your company, to what Joel relates to in the "Two Stories" linked by Arthur. If the company managers are really that stupid to block their own people from making progress, then the fluctuation ratio is probably already very high and it may be time to draw conclusions from that. But if that is not the case, the real problem might be within yourself.


问:
Is a PHP array an example of a dynamic data structure?
I did my homework, and it says that dynamic data structures are "data structures that change in size as a program needs it to by allocating and de-allocating memory from the heap".

So I was wondering, are PHP arrays examples of dynamic data structures, or are they limited to binary trees and double-linked lists?

Thanks.

答:
Yes, PHP arrays are dynamic, in the sense that one can create an array, insert new elements, delete elements, etc. without ever worrying about its size. The array grows or shrinks as needed, automatically.

You didn't quite fully "do your homework" though, since most PHP programming books would have told you the above :) By the way, if you need a recommendation, I'd go for O'Reilly's "Programming PHP".

One particularity about PHP arrays is that they are all implemented as associative arrays i.e., ordered collections of key-value pairs (a.k.a. maps, or hash tables). Even a "plain" array of, say, strings, is an associative array where the keys are (automatically generated) indices. For instance, array("a", "b", "c") is actually the same as array(0 => "a", 1 => "b", 2 => "c"). It's a very interesting design...

The last part of your question is rather puzzling, though, i.e. "are PHP arrays examples of dynamic data structures, or are they limited to binary trees and double-linked lists?" Because, binary trees and linked lists are typical examples of dynamic structures as well! (where a node is inserted or removed every time an item is added or deleted from the data structure) So it's like asking if an apple is red or red...

This Wikipedia page compares programming languages and, in particular, tells you which languages support dynamic arrays, or not:

http://en.wikipedia.org/wiki/Comparison_of_programming_languages_(array)


答:
I think conventions such as naming of classes and variables are important and should be followed through, elegant and efficient code too,  but at the risk of having my answer downvoted many times, I have to say that in general the "pretty code" paradigm that is pushed a lot around is in IMHO very overrated.

First off, the developer who wrote it will have to maintain it in the first place, and if he is ever hit by a bus and another programmer cannot figure out how it works because the code is not "pretty", I'd say that the other developer is not very good anyway. And there is a lot of automated formatters/beautifiers out there, so anyone can use those to beautify the code if necessary, w/o wasting time while being "in the flow"/"in the zone".

Please note that I'm not advocating spaghetti/cowboy style coding here, in fact I've seen some very nicely formatted spaghetti code (function bodies spanning 4-5 screens, global variables scattered around different source code files, generally bad picks of names, etc).

Title: Dealing with co-workers who do not have a consistent coding style?

Body:
What do you when you're working with someone who tends to write stylistically bad code? The code I'm talking about is usually technically correct, reasonably structured, and may even be algorithmically elegant, but it just looks ugly. We've got:

Mixture of different naming conventions and titles (underscore_style and camelCase and UpperCamel and CAPS all applied more or less at random to different variables in the same function)

Bizarre and inconsistent spacing, e.g. Functioncall  (arg1 ,arg2,arg3 );

Lots of misspelled words in comments and variable names

We have a good code review system where I work, so we do get to look over and fix the worst stuff. However, it feels really petty to send a code review that consists of 50 lines of "Add a space here. Spell 'itarator' correctly. Change this capitalization. etc."

How would you encourage this person to be more careful and consistent with these kinds of details?


问:
What are the advantages of recursion compared to iteration?
I'm trying to understand when is preferred to use recursion rather than iteration.

Actually I've encountered recursion only in Javascript but never in Python. I imagine that recursion should be used in determinate contexts or languages but I don't understand when I should use it and which advantages it gives me.

I would like to see some examples of advantageous usage of recursion, as opposed to iteration.

答: Recursion is in many cases much simpler and much more easier to understand than iteration. Often you can solve problem that normally would take ~50 lines of code in just 10 lines by using recursion. Of corse every problem that can be solved with recursion can also be solved with iteration and you can get some better performance by that, but in many cases it's much more ugly approach(if you want to rewrite recursive solution). Check Hanoi tower algorithm to check how beautiful can recursive approach be. :)


答:
I often use recursion when I can't achieve immutability via iteration. There is something to be said about trying to avoid immutability all the time- it's not always the correct approach, but sometimes it can be.

Let's take a trivial example that doesn't show the efficacy of recursion to erase mutability:  assume that I want to program Conway's Game of Life, and I have two functions display and evolve (I'm programming this in kotlin for anyone wondering).

```<code>fun evolve(generation: Generation): Generation {
    // Create and return the next generation.
}

fun display(generation: Generation) {
    // Display the current generation.
}
</code>```

Fair enough, and in my main I create a starting generation:

```<code>fun main(args: Array<String>) {
    val generationZero = Generation("xxx",
                                    "ooo",
                                    "xxx")
}
</code>```

where x and o represent dead and live cells respectively.

Now I want to continuously update and display current and future generations:

```<code> fun main(args: Array<String>) {
     val generationZero = Generation("xxx",
                                     "ooo",
                                     "xxx")

     var generationX = generationZero
     while (true) {
         display(generationX)
         generationX = evolve(generationX)
     }
 }
</code>```

This is okay, and in such a trivial example probably not a problem. But for practice's sake I would really like to have no mutability in my code. I refactor my code snippet into this:

```<code>fun runTheGameOfLife(generationX: Generation) {
    display(generationX)

    runTheGameOfLife(evolve(generationX))
}
</code>```

Without a terminating condition this will eventually crash and burn, so you might want to look into that. Otherwise, voilá! You now have sweet, testable code with no mutability.

Please note that I'm not advocating eradicating all mutability- that is silliness of the highest degree, but recursion can simplify and eradicate mutability where it isn't necessary nor safe. It is up to you to determine which places in your code deserve to be mutable.

Title: What are the advantages of recursion compared to iteration?

Body:
I'm trying to understand when is preferred to use recursion rather than iteration.

Actually I've encountered recursion only in Javascript but never in Python. I imagine that recursion should be used in determinate contexts or languages but I don't understand when I should use it and which advantages it gives me.

I would like to see some examples of advantageous usage of recursion, as opposed to iteration.

Body:
I often use recursion when I can't achieve immutability via iteration. There is something to be said about trying to avoid immutability all the time- it's not always the correct approach, but sometimes it can be.

Let's take a trivial example that doesn't show the efficacy of recursion to erase mutability:  assume that I want to program Conway's Game of Life, and I have two functions display and evolve (I'm programming this in kotlin for anyone wondering).

fun evolve(generation: Generation): Generation {
    // Create and return the next generation.
}

fun display(generation: Generation) {
    // Display the current generation.
}

Fair enough, and in my main I create a starting generation:

fun main(args: Array<String>) {
    val generationZero = Generation("xxx",
                                    "ooo",
                                    "xxx")
}

where x and o represent dead and live cells respectively.

Now I want to continuously update and display current and future generations:

 fun main(args: Array<String>) {
     val generationZero = Generation("xxx",
                                     "ooo",
                                     "xxx")

     var generationX = generationZero
     while (true) {
         display(generationX)
         generationX = evolve(generationX)
     }
 }

This is okay, and in such a trivial example probably not a problem. But for practice's sake I would really like to have no mutability in my code. I refactor my code snippet into this:

fun runTheGameOfLife(generationX: Generation) {
    display(generationX)

    runTheGameOfLife(evolve(generationX))
}

Without a terminating condition this will eventually crash and burn, so you might want to look into that. Otherwise, voilá! You now have sweet, testable code with no mutability.

Please note that I'm not advocating eradicating all mutability- that is silliness of the highest degree, but recursion can simplify and eradicate mutability where it isn't necessary nor safe. It is up to you to determine which places in your code deserve to be mutable.


问:
How to document a file format specification
For a project, I need to work with varying types of files from some old games and related software--configuration files, saves, resource archives, and so on. The bulk of these aren't yet documented, nor do tools exist to work with them, so I must reverse-engineer the formats and build my own libraries to handle them.

Although I don't suppose there's great demand for most of it, I intend to publish the results of my efforts. Are there any accepted standards for documenting file formats? Looking around, there are several styles in use: some, like the .ZIP File Format Specification, are very wordy; others, like those on XentaxWiki, are much more terse--I find some of them difficult to read; the one I personally like best is this description of the PlayStation 2 Memory Card File System, which includes both detailed descriptive text and several 'memory maps' with offsets and such--it also most closely matches my use case. It will vary a little for different formats, but it seems there should be some general principles that I should try to follow.

Edit: I seem not to have explained very well what I want to do. Let me construct an example.

I may have some old piece of software which stores its configuration in a 'binary' file--a series of bitfields, integers, strings, and whatnot all glued together and understood by the program, but not human-readable. I decipher this. I wish to document exactly what is the format of this file, in a human-readable way, as a specification for implementing a library to parse and modify this file. Additionally, I'd like this to be easily understood by other people.

There are several ways such a document might be written. The PKZIP example above is very wordy and mostly describes the file format in free text. The PS2 example gives tables of value types, offsets, and sizes, with extensive comments on what they all mean. Many others, like those on XentaxWiki, only list the variable types and sizes, with little or no commentary.

I ask whether there is any standard, akin to a coding style guide, which provides guidance on how to write this kind of documentation. If not, is there any well-known excellent example that I should emulate? If not, can anyone at least summarize some useful advice?

答:
That's odd because a quick search of file formats brought up a Wikipedia article (List of file formats). It also includes several Video Game Data formats.

List of common file formats of data for video games on systems that support filesystems, most commonly PC games.

It also include a large selection of Video Game Storage Media formats.

List of the most common filename extensions used when a game's ROM image or storage medium is copied from an original ROM device to an external memory such as hard disk for back up purposes or for making the game playable with an emulator. In the case of cartridge-based software, if the platform specific extension is not used then filename extensions ".rom" or ".bin" are usually used to clarify that the file contains a copy of a content of a ROM. ROM, disk or tape images usually do not consist of a single file or ROM, rather an entire file or ROM structure contained within a single file on the backup medium.

Are there any accepted standards for documenting file formats?

There is no "official" standard anywhere. Since the file formats are made by a company, the company decides on the format for the documentation.


问:
Are monads a viable (maybe preferable) alternative to inheritance hierarchies?
I'm going to use a language-agnostic description of monads like this, first describing monoids:

A monoid is (roughly) a set of functions that take some type as a parameter and return the same type.

A monad is (roughly) a set of functions that take a wrapper type as a parameter and returns the same wrapper type.

Note those are descriptions, not definitions. Feel free to attack that description!

So in an OO language, a monad permits operation compositions like:

Flier<Duck> m = new Flier<Duck>(duck).takeOff().flyAround().land()

Note that the monad defines and controls the semantics of those operations, rather than the contained class.

Traditionally, in an OO language we'd use a class hierarchy & inheritance to provide those semantics. So we'd have a Bird class with methods takeOff(), flyAround() and land(), and Duck would inherit those.

But then we get into trouble with flightless birds, because penguin.takeOff() fails. We have to resort to Exception throwing and handling.

Also, once we say that Penguin is a Bird, we run into problems with multiple inheritance, for example if we also have a hierarchy of Swimmer.

Essentially we're trying to put classes into categories (with apologies to the Category Theory guys), and define semantics by category rather than in individual classes. But monads seem like a much clearer mechanism for doing that than hierarchies.

So in this case, we'd have a Flier<T> monad like the example above:

Flier<Duck> m = new Flier<Duck>(duck).takeOff().flyAround().land()

...and we would never instantiate a Flier<Penguin>. We could even use static typing to prevent that from happening, maybe with a marker interface. Or runtime capability-checking  to bail out. But really, a programmer should never put a Penguin into Flier, in the same sense they should never divide by zero.

Also, it's more generally applicable. A flier doesn't have to be a Bird. For example Flier<Pterodactyl>, or Flier<Squirrel>, without changing the semantics of those individual types.

Once we classify semantics by composable functions on a container -- instead of with type hierarchies -- it resolves the old problems with classes that "kind of do, kind of don't" fit into a particular hierarchy. It also easily & clearly allows multiple semantics for a class, like Flier<Duck> as well as Swimmer<Duck>. It seems like we've been struggling with a impedance mismatch by classifying behavior with class hierarchies. Monads handle it elegantly.

So my question is, in the same way that we've come to favor composition over inheritance, does it also make sense to favor monads over inheritance?

(BTW I wasn't sure if this should be here or in Comp Sci, but this seems more like a practical modelling problem. But maybe it's better over there.)

答:
The short answer is no, monads are not an alternative to inheritance hierarchies (also known as subtype polymorphism).  You seem to be describing parametric polymorphism, which monads make use of but are not the only thing to do so.

As far as I understand them, monads have essentially nothing to do with inheritance.  I would say that the two things are more-or-less orthogonal: they're intended to address different problems, and so:

They can be used synergistically in at least two senses:

check out the Typeclassopedia, which covers many of Haskell's type classes.  You will notice that there are inheritance-like relationships between them.  For instance, Monad is descended from Applicative which is itself descended from Functor.

data types that are instances of Monads can participate in class hierarchies.  Remember, Monad is more like an interface -- implementing it for a given type tells you some things about the data type, but not everything.

Trying to use one to do the other will be difficult and ugly.

Finally, although this is tangential to your question, you may be interested to learn that monads do have some incredibly powerful ways to compose; read up on monad transformers to find out more.  However, this is still an active area of research because we (and by we, I mean people 100000x smarter than me) haven't figured out great ways to compose monads, and it seems like some monads don't compose arbitrarily.

Now to nit-pick your question (sorry, I intend for this to be helpful, and not to make you feel bad):  I feel there are many questionable premises which I will attempt to cast some light on.

A monad is a set of functions that take a container type as a parameter and returns the same container type.

No, this is Monad in Haskell:  a parameterized type m a with an implementation of return :: a -> m a and (>>=) :: m a -> (a -> m b) -> m b, satisfying the following laws:

```<code>return a >>= k  ==  k a
m >>= return  ==  m
m >>= (\x -> k x >>= h)  ==  (m >>= k) >>= h
</code>```

There are some instances of Monad which are not containers ((->) b), and there are some containers which are not (and can not be made) instances of Monad (Set, because of the type class constraint).  So the "container" intuition is a poor one.  See this for more examples.

So in an OO language, a monad permits operation compositions like:

```<code>  Flier<Duck> m = new Flier<Duck>(duck).takeOff().flyAround().land()
</code>```

No, not at all.  That example does not require a Monad.  All it requires is functions with matching input and output types.  Here's another way to write it which emphasizes that it's just function application:

```<code>Flier<Duck> m = land(flyAround(takeOff(new Flier<Duck>(duck))));
</code>```

I believe this is a pattern known as a "fluent interface" or "method chaining" (but I'm not sure).

Note that the monad defines and controls the semantics of those operations, rather than the contained class.

Data types that are also monads can (and nearly always do!) have operations that are unrelated to monads.  Here's a Haskell example composed of three functions on [] which don't have anything to do with monads: [] "defines and controls the semantics of the operation" and the "contained class" doesn't, but that's not sufficient to make a monad:

```<code>\predicate -> length . filter predicate . reverse
</code>```

You have correctly noted that there are problems with using class hierarchies to model things.  However, your examples don't present any evidence that monads can:

Do a good job at that stuff that inheritance is good at

Do a good job at that stuff that inheritance is bad at

Body:
The short answer is no, monads are not an alternative to inheritance hierarchies (also known as subtype polymorphism).  You seem to be describing parametric polymorphism, which monads make use of but are not the only thing to do so.

As far as I understand them, monads have essentially nothing to do with inheritance.  I would say that the two things are more-or-less orthogonal: they're intended to address different problems, and so:

They can be used synergistically in at least two senses:

check out the Typeclassopedia, which covers many of Haskell's type classes.  You will notice that there are inheritance-like relationships between them.  For instance, Monad is descended from Applicative which is itself descended from Functor.

data types that are instances of Monads can participate in class hierarchies.  Remember, Monad is more like an interface -- implementing it for a given type tells you some things about the data type, but not everything.

Trying to use one to do the other will be difficult and ugly.

Finally, although this is tangential to your question, you may be interested to learn that monads do have some incredibly powerful ways to compose; read up on monad transformers to find out more.  However, this is still an active area of research because we (and by we, I mean people 100000x smarter than me) haven't figured out great ways to compose monads, and it seems like some monads don't compose arbitrarily.

Now to nit-pick your question (sorry, I intend for this to be helpful, and not to make you feel bad):  I feel there are many questionable premises which I will attempt to cast some light on.

A monad is a set of functions that take a container type as a parameter and returns the same container type.

No, this is Monad in Haskell:  a parameterized type m a with an implementation of return :: a -> m a and (>>=) :: m a -> (a -> m b) -> m b, satisfying the following laws:

return a >>= k  ==  k a
m >>= return  ==  m
m >>= (\x -> k x >>= h)  ==  (m >>= k) >>= h

There are some instances of Monad which are not containers ((->) b), and there are some containers which are not (and can not be made) instances of Monad (Set, because of the type class constraint).  So the "container" intuition is a poor one.  See this for more examples.

So in an OO language, a monad permits operation compositions like:

  Flier<Duck> m = new Flier<Duck>(duck).takeOff().flyAround().land()

No, not at all.  That example does not require a Monad.  All it requires is functions with matching input and output types.  Here's another way to write it which emphasizes that it's just function application:

Flier<Duck> m = land(flyAround(takeOff(new Flier<Duck>(duck))));

I believe this is a pattern known as a "fluent interface" or "method chaining" (but I'm not sure).

Note that the monad defines and controls the semantics of those operations, rather than the contained class.

Data types that are also monads can (and nearly always do!) have operations that are unrelated to monads.  Here's a Haskell example composed of three functions on [] which don't have anything to do with monads: [] "defines and controls the semantics of the operation" and the "contained class" doesn't, but that's not sufficient to make a monad:

\predicate -> length . filter predicate . reverse

You have correctly noted that there are problems with using class hierarchies to model things.  However, your examples don't present any evidence that monads can:

Do a good job at that stuff that inheritance is good at

Do a good job at that stuff that inheritance is bad at


问:
Speeds of << >> multiplication and division
You can use << to multiply and >> to divide numbers in python when I time them I find using the binary shift way of doing it is 10x faster than dividing or multiplying the regular way.

Why is using << and >> a lot faster than * and /?

What are the behind the scene processes going on to make * and / so slow?

答:
Lets look at two little C programs that do a bit shift and a divide.

```<code>#include <stdlib.h>

int main(int argc, char* argv[]) {
        int i = atoi(argv[0]);
        int b = i << 2;
}
</code>```

```<code>#include <stdlib.h>

int main(int argc, char* argv[]) {
        int i = atoi(argv[0]);
        int d = i / 4;
}
</code>```

These are then each compiled with gcc -S to see what the actual assembly will be.

With the bit shift version, from the call to atoi to return:

```<code>    callq   _atoi
    movl    $0, %ecx
    movl    %eax, -20(%rbp)
    movl    -20(%rbp), %eax
    shll    $2, %eax
    movl    %eax, -24(%rbp)
    movl    %ecx, %eax
    addq    $32, %rsp
    popq    %rbp
    ret
</code>```

While the divide version:

```<code>    callq   _atoi
    movl    $0, %ecx
    movl    $4, %edx
    movl    %eax, -20(%rbp)
    movl    -20(%rbp), %eax
    movl    %edx, -28(%rbp)         ## 4-byte Spill
    cltd
    movl    -28(%rbp), %r8d         ## 4-byte Reload
    idivl   %r8d
    movl    %eax, -24(%rbp)
    movl    %ecx, %eax
    addq    $32, %rsp
    popq    %rbp
    ret
</code>```

Just by looking at this there are several more instructions in the divide version compared to the bit shift.

The key is what do they do?

In the bit shift version the key instruction is shll    $2, %eax which is a shift left logical - there's the divide, and everything else is just moving values around.

In the divide version, you can see the idivl   %r8d - but just above that is a cltd (convert long to double) and some additional logic around the spill and reload.  This additional work, knowing that we're dealing with a math rather than bits is often necessary to avoid various errors that can occur by doing just bit math.

Lets do some quick multiplication:

```<code>#include <stdlib.h>

int main(int argc, char* argv[]) {
    int i = atoi(argv[0]);
    int b = i >> 2;
}
</code>```

```<code>#include <stdlib.h>

int main(int argc, char* argv[]) {
    int i = atoi(argv[0]);
    int d = i * 4;
}
</code>```

Rather than going through all of this, there is one line different:

```
$ diff mult.s bit.s
24c24
>    shll    $2, %eax
---
<    sarl    $2, %eax
```

Here the compiler was able to identify that the math could be done with a shift, however instead of a logical shift it does a arithmetic shift.  The difference between these would be obvious if we ran these - sarl preserves the sign.  So that -2 * 4 = -8 while the shll does not.

Lets look at this in a quick perl script:

```<code>#!/usr/bin/perl

$foo = 4;
print $foo << 2, "\n";
print $foo * 4, "\n";

$foo = -4;
print $foo << 2, "\n";
print $foo * 4, "\n";
</code>```

Output:

```
16
16
18446744073709551600
-16
```

Um... -4 << 2 is 18446744073709551600 which is not exactly what you are likely expecting when dealing with multiplication and division.  Its right, but its not integer multiplication.

And thus be wary of premature optimization.  Let the compiler optimize for you - it knows what you're really trying to do and will likely do a better job of it, with fewer bugs.

Body:
Lets look at two little C programs that do a bit shift and a divide.

#include <stdlib.h>

int main(int argc, char* argv[]) {
        int i = atoi(argv[0]);
        int b = i << 2;
}

#include <stdlib.h>

int main(int argc, char* argv[]) {
        int i = atoi(argv[0]);
        int d = i / 4;
}

These are then each compiled with gcc -S to see what the actual assembly will be.

With the bit shift version, from the call to atoi to return:

    callq   _atoi
    movl    $0, %ecx
    movl    %eax, -20(%rbp)
    movl    -20(%rbp), %eax
    shll    $2, %eax
    movl    %eax, -24(%rbp)
    movl    %ecx, %eax
    addq    $32, %rsp
    popq    %rbp
    ret

While the divide version:

    callq   _atoi
    movl    $0, %ecx
    movl    $4, %edx
    movl    %eax, -20(%rbp)
    movl    -20(%rbp), %eax
    movl    %edx, -28(%rbp)         ## 4-byte Spill
    cltd
    movl    -28(%rbp), %r8d         ## 4-byte Reload
    idivl   %r8d
    movl    %eax, -24(%rbp)
    movl    %ecx, %eax
    addq    $32, %rsp
    popq    %rbp
    ret

Just by looking at this there are several more instructions in the divide version compared to the bit shift.

The key is what do they do?

In the bit shift version the key instruction is shll    $2, %eax which is a shift left logical - there's the divide, and everything else is just moving values around.

In the divide version, you can see the idivl   %r8d - but just above that is a cltd (convert long to double) and some additional logic around the spill and reload.  This additional work, knowing that we're dealing with a math rather than bits is often necessary to avoid various errors that can occur by doing just bit math.

Lets do some quick multiplication:

#include <stdlib.h>

int main(int argc, char* argv[]) {
    int i = atoi(argv[0]);
    int b = i >> 2;
}

#include <stdlib.h>

int main(int argc, char* argv[]) {
    int i = atoi(argv[0]);
    int d = i * 4;
}

Rather than going through all of this, there is one line different:

$ diff mult.s bit.s
24c24
>    shll    $2, %eax
---
<    sarl    $2, %eax

Here the compiler was able to identify that the math could be done with a shift, however instead of a logical shift it does a arithmetic shift.  The difference between these would be obvious if we ran these - sarl preserves the sign.  So that -2 * 4 = -8 while the shll does not.

Lets look at this in a quick perl script:

#!/usr/bin/perl

$foo = 4;
print $foo << 2, "\n";
print $foo * 4, "\n";

$foo = -4;
print $foo << 2, "\n";
print $foo * 4, "\n";

Output:

16
16
18446744073709551600
-16

Um... -4 << 2 is 18446744073709551600 which is not exactly what you are likely expecting when dealing with multiplication and division.  Its right, but its not integer multiplication.

And thus be wary of premature optimization.  Let the compiler optimize for you - it knows what you're really trying to do and will likely do a better job of it, with fewer bugs.


答:
BINARY_LSHIFT and BINARY_RSHIFT are simpler processes algorithmically than BINARY_MULTIPLY and BINARY_FLOOR_DIVIDE and may take fewer clock-cycles.  That is if you have any binary number and need to bitshift by N, all you have to do is shift the digits over that many spaces and replace with zeros.  Binary multiplication is in general more complicated, though techniques like Dadda multiplier make it quite fast.

Granted, it is possible for an optimizing compiler to recognize cases when you multiply/divide by powers of two and replace with the appropriate left/right shift.  By looking at disassembled byte code python apparently doesn't do this:

```<code>>>> dis.dis(lambda x: x*4)
  1           0 LOAD_FAST                0 (x)
              3 LOAD_CONST               1 (4)
              6 BINARY_MULTIPLY
              7 RETURN_VALUE

>>> dis.dis(lambda x: x<<2)
  1           0 LOAD_FAST                0 (x)
              3 LOAD_CONST               1 (2)
              6 BINARY_LSHIFT
              7 RETURN_VALUE

>>> dis.dis(lambda x: x//2)
  1           0 LOAD_FAST                0 (x)
              3 LOAD_CONST               1 (2)
              6 BINARY_FLOOR_DIVIDE
              7 RETURN_VALUE

>>> dis.dis(lambda x: x>>1)
  1           0 LOAD_FAST                0 (x)
              3 LOAD_CONST               1 (1)
              6 BINARY_RSHIFT
              7 RETURN_VALUE
</code>```

However, on my processor, I find multiplication and left/right shift have similar timing, and floor division (by a power of two) is about 25% slower:

```<code>>>> import timeit

>>> timeit.repeat("z=a + 4", setup="a = 37")
[0.03717184066772461, 0.03291916847229004, 0.03287005424499512]

>>> timeit.repeat("z=a - 4", setup="a = 37")
[0.03534698486328125, 0.03207516670227051, 0.03196907043457031]

>>> timeit.repeat("z=a * 4", setup="a = 37")
[0.04594111442565918, 0.0408930778503418, 0.045324087142944336]

>>> timeit.repeat("z=a // 4", setup="a = 37")
[0.05412912368774414, 0.05091404914855957, 0.04910898208618164]

>>> timeit.repeat("z=a << 2", setup="a = 37")
[0.04751706123352051, 0.04259490966796875, 0.041903018951416016]

>>> timeit.repeat("z=a >> 2", setup="a = 37")
[0.04719185829162598, 0.04201006889343262, 0.042105913162231445]
</code>```

Title: Speeds of << >> multiplication and division

Body:
You can use << to multiply and >> to divide numbers in python when I time them I find using the binary shift way of doing it is 10x faster than dividing or multiplying the regular way.

Why is using << and >> a lot faster than * and /?

What are the behind the scene processes going on to make * and / so slow?

Body:
BINARY_LSHIFT and BINARY_RSHIFT are simpler processes algorithmically than BINARY_MULTIPLY and BINARY_FLOOR_DIVIDE and may take fewer clock-cycles.  That is if you have any binary number and need to bitshift by N, all you have to do is shift the digits over that many spaces and replace with zeros.  Binary multiplication is in general more complicated, though techniques like Dadda multiplier make it quite fast.

Granted, it is possible for an optimizing compiler to recognize cases when you multiply/divide by powers of two and replace with the appropriate left/right shift.  By looking at disassembled byte code python apparently doesn't do this:

>>> dis.dis(lambda x: x*4)
  1           0 LOAD_FAST                0 (x)
              3 LOAD_CONST               1 (4)
              6 BINARY_MULTIPLY
              7 RETURN_VALUE

>>> dis.dis(lambda x: x<<2)
  1           0 LOAD_FAST                0 (x)
              3 LOAD_CONST               1 (2)
              6 BINARY_LSHIFT
              7 RETURN_VALUE

>>> dis.dis(lambda x: x//2)
  1           0 LOAD_FAST                0 (x)
              3 LOAD_CONST               1 (2)
              6 BINARY_FLOOR_DIVIDE
              7 RETURN_VALUE

>>> dis.dis(lambda x: x>>1)
  1           0 LOAD_FAST                0 (x)
              3 LOAD_CONST               1 (1)
              6 BINARY_RSHIFT
              7 RETURN_VALUE

However, on my processor, I find multiplication and left/right shift have similar timing, and floor division (by a power of two) is about 25% slower:

>>> import timeit

>>> timeit.repeat("z=a + 4", setup="a = 37")
[0.03717184066772461, 0.03291916847229004, 0.03287005424499512]

>>> timeit.repeat("z=a - 4", setup="a = 37")
[0.03534698486328125, 0.03207516670227051, 0.03196907043457031]

>>> timeit.repeat("z=a * 4", setup="a = 37")
[0.04594111442565918, 0.0408930778503418, 0.045324087142944336]

>>> timeit.repeat("z=a // 4", setup="a = 37")
[0.05412912368774414, 0.05091404914855957, 0.04910898208618164]

>>> timeit.repeat("z=a << 2", setup="a = 37")
[0.04751706123352051, 0.04259490966796875, 0.041903018951416016]

>>> timeit.repeat("z=a >> 2", setup="a = 37")
[0.04719185829162598, 0.04201006889343262, 0.042105913162231445]


问:
As an lone, Agile (PXP/PSP) developer what is the proper structure for a formal project post-mortem?
Question:

As an lone, Agile (PXP/PSP) developer what is the proper structure for a formal project post-mortem?

Scenario

I'm using a PXP methodology (which is a blend of extreme programming and the personal software process) to work on an undergrad project.  The project revolves around computer vision and architecture.

Although the project has a lot of potential for future improvement, I need to write a project retrospective for this release. I'm used to working with an SRS (requirements specification) and DSD (design specification document) with a structure like :

Introduction

Purpose

Scope

Definitions, acronyms etc.

Description

Product perspective

system interfaces

interfaces

Hardware Interfaces

Software interfaces... constraints etc.

Requirements

Performance, interfaces etc...

Attributes for security, portability etc.

DSD

system overview
-Design consideration

Architecture

detailed system design ... etc.

However, agile project as we know revolve more around stories than functional requirements, and firm designs. A recommended non-agile structure for this final report is :

Introduction :
- Literature review :
- planning : - statement of the methodology used.

Design :

requirements

design aims

Implementation - language choices, coding guidelines etc.

Evaluation - evaluation of how good the algorithms are.

I've not been able to find an example online of a definite project postmortem structue for a PSP project (even the documentation 1 does not mention how it should be structured).

答:
Imposing a strict structure on retrospective document is not very agile itself.

In Agile, you don't find strict rules you have to follow at all costs, such as:

“Unit tests should be written prior to code.”

“The code should have at least 95% code coverage.”

“Each public and protected method should have documentation explaining its usage, each parameter, the return value and, if any, the possibly generated exceptions.”

The reason is that you may find yourself in a case where it's obvious that the rule makes more harm than good for the whole project, thus requiring the team to adapt the rule to their particular case, rather than adapting the process to the rule:

A team may notice that, unlike in other teams, following TDD prevents flexibility they had when they were writing code first, while having only minor impact on the quality.

Another team may find that developers spend weeks trying to go from 94% to 95%, increasing the risk of delivering the software late, while also decreasing code quality, since they spend less time doing code reviews.

A third team may discover that programmers are demoralized documenting boilerplate code, instead of doing real programming. Also, they tend now to make fewer efforts writing self-documenting code with self-documenting names of methods.

This is exactly what retrospective is done for. So why not adapting the retrospective itself?

Note that:

The retrospective would never be the same: if the process evolves, you'll have a different type of problems each time, which will have an impact on the retrospective.

The very first retrospective may be centered around the overall organization of the project: the fresh team just started the project, and not everything is satisfactory enough. They picked Scrum, but some guidelines of Scrum seem not adapted for this team; on the other hand, they would like to use some guidelines from XP. The team is also in two buildings, making communication more difficult that is should to be. The team also notes a hundred more impediments to be solved.

The second retrospective is principally axed on estimates: indeed, the team estimated to be able to do twice what was really done. Two major reasons for this is that (1) the most skillful developer of the team was sick during the second week of the sprint (what should the team do to handle “Hit by a bus” scenario better in the future? Why losing a member of the team had such consequences? Do they have cowboy coders in the team?) and that (2) system administrators were too busy to deploy the project regularly (Won't DevOps help?)

The third retrospective concerns mostly the deceivingly terrible quality of some pieces of code found during code reviews (Are programmers sufficiently trained? Have everyone in the team read Code Complete? Do deadlines encourage sloppy programming?) and the fact that the representative of the customer is never available to answer the questions (Do we need to hire an expert instead? Do we need to be frank with the customer and ask to be more involved in the project?)

As you can notice, imposing a strict structure on a retrospective report wouldn't be obvious, and would only make the report less clear. For example, the most straightforward structure for the second retrospective would be:

Actual estimation process

Description of the actual estimation process,

Specificity of this process compared to what is used by other teams in the company.

The actual issue 1: “Hit by a bus” scenario

The code is not documented enough,

There are no enough communication inside the team during the sprint, so members sometimes ignore what other members do.

The actual issue 2: cowboy coders

The lead developer don't care matching the common rules used by the team,

The lead developer is not a team player and should look for another team.

The actual issue 3: no DevOps

System administrators are too overwhelmed to deliver the product on time,

DevOps can help.

The same structure makes no sense for the first or the third retrospective.

The retrospective itself should adapt itself to needs and constraints of the team.

This means that from team to team and from company to company, you'll find differences in handling retrospective meetings.

A company where the CEO wants a report after each retrospective would organize the retrospective differently from a company where what is said during retrospective is known only by the team.

A team of three developers would have a different retrospective than a team of twelve.

A retrospective of a team of persons who are afraid of being criticized in front of their pairs would have nothing to do with a retrospective done by a team where people welcome constructive criticism and see it as an excellent way to improve.


答: You have to best the previous leader in either a challenge of strength or a game of wit.</p>

Title: How does one become a leader in a team of programmers?

Body: What skills, knowledge and talents should a junior programmer aim to obtain in order to be qualified to become a team leader? </p>


问:
Separating php and html code
What is the industrial practice on how to separate html and php code in a web project? Using echos to generate html is considered bad but what is the standard way to achieve the sought separation? Using template engines like twig?</p>

答:
The general practice is to put HTML in a template.

A template contains minimum programming code: it's mostly HTML, with calls to variables and basic loops and conditional statements. The reason for that is that putting too much programming code in templates would:

Make testing difficult,

Make the reading and changing of the template difficult: the template should be straightforward enough to be able to be modified with minimum risk of introducing bugs.

A template engine, such as Smarty, is then used to transform the template into real content.

Title: Separating php and html code


答:
An example of iteration being more useful than recursion: in a paper by Dijkstra (the relevant part is the first two out of the last three paragraphs), a graph theory problem is discussed.  Somebody had found a recursive solution and published it; and it seemed very impressive and hard to understand.  Dijkstra had been messing around with a mini-language that didn't have recursion, tried to solve the problem, and found that there was a simple solution involving 4 separate stacks that grew and shrank independently.

An example of recursion being more useful than iteration: maze solving.  You can solve a maze recursively by proceeding recursively in each of the directions left/forward/right at each step.  While you could do it iteratively using a stack, that would be uglier, whereas the recursive solution is perfectly clear.

In general, use recursion when it solves the problem more clearly than any obvious alternative.

Many (but not all) languages use a stack to keep track of function calls, so recursion can use up all the space and crash the program -- depending on how many levels deep the recursion goes.  If you use that kind of language, you can make sure that the recursion can never go too deep, or enlarge the stack to be large enough (if the language allows), or use an alternative to recursion.

In functional languages, recursion is often the default, and things that might be expressed as a for loop in other languages are done with recursion instead.  There ways of extracting the basic iteration patterns into other constructions that don't look like either recursion or for loops, such as list comprehensions or the higher-order functions map and reduce (aka fold).  Python has list comprehensions, map, and reduce; Javascript has array comprehensions, map, and reduce.


答:
There are several aproaches, the one hand, using templates from the server side like Smarty, Twig, etc. I don't recommend this approach because you're coupling your presentation code to the technology used in the server (like php, python, ruby, java, ...).

The other approach is to use client side templates/frameworks for the view (like ember, angularjs, backbone, ...). I recommend this approach due to the separation of concerns between view (html,css,js ...) and server code or controllers (php/symphony, python/django, ruby/rails, java/spring ...).

So between your server code and your client code, the uniq glue you've to put is the model object in Json format (or whatever format you need). This way, you can develop code in the view that is reusable by any kind of server code, and thus, you can develop your application logic with different server technologies.

Title: Separating php and html code

Body: What is the industrial practice on how to separate html and php code in a web project? Using echos to generate html is considered bad but what is the standard way to achieve the sought separation? Using template engines like twig?</p>


问:
What's the difference of an object being final and an object being immutable in java?
```<code>final String str = "do not change me";
str = "why not?"; //it will result in compile time error saying that final fields can not be re-assigned once created i.e. the reference cannot be changed

String str1 = "hello world";
    System.out.println(str1.replaceAll("h", "q"));
    str1 = str1.replaceAll("h", "q");
    System.out.println(str1);  //An immutable object on the other hand means that, there is no way for you to change the object or its contents other than changing the reference.
</code>```

Is the above understanding of definition of a final object and immutable object correct?

答:
In Java, objects are not final. Instead: variables, classes, or methods are. A final variable cannot be reassigned, so the variable becomes interchangeable with the value it represents. This is roughly known as “referential transparency”.

An immutable object is an object without changing state. Simplified: If all member fields of an object are final variables, then it's quite likely that the object is immutable as well. If we need an object with changed state, then we have to return a new instance. This is what str.replace(…) does, because Strings are immutable in Java.


问:
How important is it to learn UML for an OO developer?
When studying OOP by myself I often encounter UML class diagrams. I understand them, but don't completely know how to write them.

Meaning, I don't entirely know what each kind of arrow means, and things like that.

1- How important is it to learn the 'language' of UML class diagrams? If it is something worth the time, could you forward me to a good, cohesive yet sufficient source?

2- If/when I do learn to draws UML class diagrams: Are all the little nuances important, or is it that every developer draws UML diagrams a little differently?

答:
There are two ways that UML can be used:

To specify a system or module

To describe a system or module

In the first case, the UML will likely be used to automatically generate code from, so you need to know enough of the details of UML that you get the expected results from your code generation tool.

In the second case, the UML diagrams are only used to support or illustrate a written or verbal explanation. In other words, they are used as a communication tool. In this case it does not matter that much if you get some of the details wrong (especially if you are present to clarify and questions that arise), as long as you get your meaning across.


问:
Agile for the Solo Developer
How would someone implement Agile process concepts as a solo developer?  Agile seems useful for getting applications developed at a faster pace, but it also seems very team oriented...</p>

答:
Further to the answer from klez (all good suggestions), I'd suggest the following:

Keeping a product backlog

A product backlog is basically a list of all items you intend to complete at some stage for this product.

Maintaining a sprint burndown and a product burndown

A sprint burndown starts with a list of all tasks you've decided to complete in this sprint (a subset of your product backlog to be completed over a set period of time - e.g. 2 weeks) along with the estimate of the work required. As you mark things off, you mark them as done; thereby reducing (or burning down) the remaining work for that sprint.

Similarly, a product burndown tracks the remaining work for the whole product backlog

Adopting the concepts of relative estimation and velocity

Relative estimation is an estimation technique that uses the other tasks (or stories) as a guide. For example, if you know task A is easier than task B and about as twice as complex as task C, you'd make sure the "points" for task A were correct relative to those expectations.

The emphasis is not on correctly guessing the amount of work required, but keeping estimates consistent with each other.

Velocity is a measure of how many "points" you get done in a sprint.  If your relative estimation is ensuring consistency, this velocity can be used to estimate which tasks you're likely to get done in the upcoming sprints. Note though that velocity should be constantly revised.

Title: Agile for the Solo Developer

ContentLicense: CC BY-SA 4.0


答:
UML is just a communication tool. Knowing UML would help you to communicate with other persons who know it too, but only in that case.

If you work with peers who use UML daily, then go for it.

UML is a great tool which helps communicating clearly, presenting things in a visual way and reducing verbosity.

It's like using technical terms with people who know them. Instead of saying:

Here, you find the set of classes implement a common class and enable to create instances of that thing, which helps separating the code required to create instances from the business code itself.

I can simply say:

Here, you find the abstract factory and its concrete implementations.

If you're the only one in your team to know what UML is about, learning UML more would only cause communication issues if other developers don't want to learn it: when you will think the diagram you created is clear enough, your colleagues will understand this diagram in their own way, which has nothing to do with yours.

It's like using technical terms in a team of beginner programmers. You tell:

In order to change the aspects of the price, you have to use the Change method overloads, but you can get the actual price by simply using the Price property. Note that tax is a readonly field.

while they don't know the difference between a method and a function nor between a property and a field, and they don't know what is the usage of readonly keyword or what an overload is.

Also note that:

Different persons use different styles: MetaFight already commented on that above. See it like the RFC for e-mail addresses: it's clear and unambiguous, and still, nearly everyone gets it wrong.

UML is difficult, and some parts are tricky enough to be ignored by many people. As an example, here's my answer on Stack Overflow to a question where the actually accepted answer is plainly wrong.

Title: How important is it to learn UML for an OO developer?

Body:
When studying OOP by myself I often encounter UML class diagrams. I understand them, but don't completely know how to write them.

Meaning, I don't entirely know what each kind of arrow means, and things like that.

1- How important is it to learn the 'language' of UML class diagrams? If it is something worth the time, could you forward me to a good, cohesive yet sufficient source?

2- If/when I do learn to draws UML class diagrams: Are all the little nuances important, or is it that every developer draws UML diagrams a little differently?


答:
UML has some nice parts, but it's not good for everything. There are better notations to communicate certain information (e.g. high level software architecture). It can also be very complicated. I found that it's often better to invent notation on-the-fly while drawing a diagram. If I carefully define meanings for my boxes and arrows, diagram is cleaner and more understandable than UML.

As for specifying program structure in UML, IMHO it's a doubtful feature. I know that it can be amusing how well some tools work with class diagrams today, but what's more usable are code generation and refactoring tools in modern IDEs. It's a lot faster to write code of a class than to click it out in UML tool. Secondly, class diagrams that are used to generate code from (or are generated from code) are not usable as a documentation, because they contain too much detail and/or they describe too large parts of a system.

Answering your questions:

I would say that it's good to know UML. Not to use this language in particular, but to compare it to other notations and be able to choose/invent/mix proper form of communication for each situation. The best source is the official specification. Chapters 9 and 10 should be enough for a first grasp of UML.

Nuances are important only if you want to generate code from UML.


问:
Dealing with co-workers who do not have a consistent coding style?
What do you when you're working with someone who tends to write stylistically bad code? The code I'm talking about is usually technically correct, reasonably structured, and may even be algorithmically elegant, but it just looks ugly. We've got:

Mixture of different naming conventions and titles (underscore_style and camelCase and UpperCamel and CAPS all applied more or less at random to different variables in the same function)

Bizarre and inconsistent spacing, e.g. Functioncall  (arg1 ,arg2,arg3 );

Lots of misspelled words in comments and variable names

We have a good code review system where I work, so we do get to look over and fix the worst stuff. However, it feels really petty to send a code review that consists of 50 lines of "Add a space here. Spell 'itarator' correctly. Change this capitalization. etc."

How would you encourage this person to be more careful and consistent with these kinds of details?

答: My solution when dealing with outsourced resources that didn't give a &%$# about formating (or easily preventable bugs for that matter) was to have the build server enforce this. I created a CI server job that ran every night that checked the code out, ran Jalopy and findbugs then checked the code back in. Once the other team learned that not using the standard code conventions would make their job harder, they started to use their IDE to maintain a standard format.</p>


问:
Strategy for storing passwords/credentials in the context of continuous delivery
It is common sense not to store passwords/credentials into SCM.

I would like to know then what would be a good strategy for storing passwords/credentials in the context of continuous delivery.

Where and how do I store credentials?

How do I retrieve and use those credentials/passwords?

答:
I found good ideas here such as:

Encrypting/decrypting data (see nice and detailed post here by John Resig)

Using a separate configuration data repository


问:
Why do projects opt to stay on an older version of the .NET Framework?
Why do projects opt to stay on an older framework version of the .NET Framework?

For example, staying on .NET Framework version 3.5 which was released in 2007 instead of upgrading to the latest 4.5.1 version?

Jon Skeet's Noda Time also targets .NET 3.5. Why?

答:
"Good enough is the enemy of better." -- Jerry Pournelle

Seriously, there has to be a reason for an upgrade besides just "ooh, shiny!".  Among other issues, any time you switch versions of a package your code depends on, you switch out one set of bugs that you're adapted for to another set that you may not be.  In the process of switching, you frequently have to make code changes because of API differences or undocumented changes in behavior. And the list goes on.

There's another question to be asked: "Why do projects opt to upgrade to a newer framework version?"  Ideally, the answers will say something about the value to the project or its constituency of the upgrade.  For example, with a commercial framework, the inability to get professional support for the older version.  More often than not, the answer is "To take advantage of a capability not present in the older version.".


问:
calling an abstract method in abstract class
Suppose i have  an abstract base class Parent which defines an abstract Method A(some parameter) taking a parameter, also it defines an instance Method B which calls method A(parameter) inside its body and passing some parameter.Then we have an concrete child class B which extends the base class and provide its own implementation of Method A using the parameter passes. I have seen many implementation of this practice in frameworks. I want to know how it works and does it provide any benefits.

Here is some code written in Android

```<code>public abstract class ParentActivity extends Activity {
    public abstract void onResume(LoginToken token);

    @Override
        protected void onCreate(Bundle savedInstanceState) {
               super.onCreate(savedInstanceState);
               Some implementation code
        }

    @Override
        public void onResume() {
              super.onResume();
              Some implementation code
              onResume(token);
        }
}

public class ChildActivity extends ParentActivity{
        LoginToken token;
    @Override
        protected void onCreate(Bundle savedInstanceState) {
               super.onCreate(savedInstanceState);
               Some implementation code
        }

    @Override
        public void onResume() {
              Some implementation code
              super.onResume();
        }

    @Override
        public void onResume(LoginToken token) {
             this.token=token;
        }
}
</code>```

答: What you're describing is the Template Method Pattern. The benefit is to describe an overall process (like log in, do something, log out) while the actual steps (or some of them) are implemented by concrete sub-classes.</p>


问:
Generics list without generics
I am using a very primitive Java that doesn't have Generics, and also I can't use reflection.

I want to create a generic list so it would be typed safe (i.e. I only have a list that contains Objects and I want to create a list that contains specific object and not a mix).

On the other hand I also don't want to create a different class for each possible list.

Is there any other way to do that without the use of Generics?

答:
Yes, there is. It will be fully run-time solution (no compile-time type checking), but it's worth it (you will get an early crash on first attempt to insert an object with wrong type).

```<code>public class TypedArrayList extends ArrayList {
    private final Class elementType;

    public TypedList(Class elementType) {
        this.elementType = elementType;
    }

    @Override
    public boolean add(Object element) {
        // preffered version, use it if it's available on your platform
        // if (!elementType.isInstance(element)) {
        if (!elementType.equals(element.getClass())) {
             throw new IllegalArgumentException("Object of type " + element.getClass() + "passed to List of "+ elementType);
        }
        return super.add(element);
    }

    // override other methods
    // that need type checking
}
</code>```

Usage:

```<code>TypedArrayList list = new TypedArrayList(String.class);
list.add("works!");
list.add(new Object()); // throws exception
</code>```

You can do the same for LinkedList and any other list type.

Title: Generics list without generics

Body:
Yes, there is. It will be fully run-time solution (no compile-time type checking), but it's worth it (you will get an early crash on first attempt to insert an object with wrong type).

public class TypedArrayList extends ArrayList {
    private final Class elementType;

    public TypedList(Class elementType) {
        this.elementType = elementType;
    }

    @Override
    public boolean add(Object element) {
        // preffered version, use it if it's available on your platform
        // if (!elementType.isInstance(element)) {
        if (!elementType.equals(element.getClass())) {
             throw new IllegalArgumentException("Object of type " + element.getClass() + "passed to List of "+ elementType);
        }
        return super.add(element);
    }

    // override other methods
    // that need type checking
}

Usage:

TypedArrayList list = new TypedArrayList(String.class);
list.add("works!");
list.add(new Object()); // throws exception

You can do the same for LinkedList and any other list type.


问:
Inheritance vs 'specification' by fields
I'm currently reading 'Head first design patterns' and I already have a few questions on the first chapter of the book.
This chapter introduces the 'prefer composition over inheritance' design principle, by explaining the 'Strategy-Pattern'. My question isn't about the pattern, but rather about a more basic design decision in one of the examples:

There is an abstract Duck class, from which a hand full of other duck classes (like e.g. 'Rubber-' or 'Redhead-Duck') inherit. All of these ducks have a display and quack method.
The display method is what should be differernt in every special duck class (because every duck looks different, as the book says).

```<code>abstract class Duck
{
    public void display();
    public void quack()
    {
        //Quack here
    }
}

class RubberDuck extends Duck
{
    @Override
    public void display()
    {
        //Display a 'Rubber-Duck'
    }
}

class RedheadDuck extends Duck
{
    @Override
    public void display()
    {
        //Display a 'Redhead-Duck'
    }
}
</code>```

But my question is: Wouldn't it make much more sense to have a field inside a (non-abstract) Duck class, which contains the displaying information (a picture or a 3D-model for example) rather than inheriting from an abstract duck class?

```<code>class Duck
{
    private String duckName;
    private Picture duckPicture;

    public Duck(String name, Picture picture)
    {
        this.duckName = name;
        this.duckPicture = picture;
    }

    public void quack()
    {
        //Quack here
    }
    public void display()
    {
        //Show duck here, according to the 'duckPicture' field
    }

    //More methods here, maybe a getter for the 'duckName' field
}
</code>```

What's your opinion on this? Does it make sense to have an abstract duck class and inherit from it or do you prefer the second solution?

答:
If you assume that display operation will only send rasterized image to display device, then you are right - one implementation of display method would suffice.

But, if you have an abstract method for display operation, this method can also do some implementation-specific stuff like:

create the image of a duck using openGL API,

update other fields of a duck (e.g. isDisplayed),

call Display on sub-objects (e.g. DuckWing),

etc.


答:
You have to understand that examples are almost always oversimplified to such an extent that techniques like inheritance look like overkill.

If the real-world code were of a similar complexity as the Duck hierarchy, with each class only differing in which picture/text they show, then you would have a case.

But in reality, the real-world code is much more complex, usually with at least a handful of methods that have radically different implementations across the classes. In that case, it doesn't work anymore to catch the variation in a few fields.

Title: Inheritance vs 'specification' by fields

Body:
I'm currently reading 'Head first design patterns' and I already have a few questions on the first chapter of the book.
This chapter introduces the 'prefer composition over inheritance' design principle, by explaining the 'Strategy-Pattern'. My question isn't about the pattern, but rather about a more basic design decision in one of the examples:

There is an abstract Duck class, from which a hand full of other duck classes (like e.g. 'Rubber-' or 'Redhead-Duck') inherit. All of these ducks have a display and quack method.
The display method is what should be differernt in every special duck class (because every duck looks different, as the book says).

```<code>abstract class Duck
{
    public void display();
    public void quack()
    {
        //Quack here
    }
}

class RubberDuck extends Duck
{
    @Override
    public void display()
    {
        //Display a 'Rubber-Duck'
    }
}

class RedheadDuck extends Duck
{
    @Override
    public void display()
    {
        //Display a 'Redhead-Duck'
    }
}
</code>```

But my question is: Wouldn't it make much more sense to have a field inside a (non-abstract) Duck class, which contains the displaying information (a picture or a 3D-model for example) rather than inheriting from an abstract duck class?

```<code>class Duck
{
    private String duckName;
    private Picture duckPicture;

    public Duck(String name, Picture picture)
    {
        this.duckName = name;
        this.duckPicture = picture;
    }

    public void quack()
    {
        //Quack here
    }
    public void display()
    {
        //Show duck here, according to the 'duckPicture' field
    }

    //More methods here, maybe a getter for the 'duckName' field
}
</code>```

What's your opinion on this? Does it make sense to have an abstract duck class and inherit from it or do you prefer the second solution?


问:
Moving Old Projects To Newer IDE's and Libraries
At work we have a few older projects that are stuck on .NET 1.1 and VS 2003. While these are probably to much work now to move forward I'm wondering if the effort to keep our newer projects up to date will be worth it. Specifically we would be looking at moving about 30 projects from .NET 3.5 to .NET 4.0 and VS2008 to VS2010.

My Questions for the community are:

Do you move your projects along as new tools and libraries become available or just start the newest stuff in the newest versions?

If you do move forward have you found the benefits out weigh the cost of the upgrade?

答:
There are two types of upgrade to consider here:

Upgrading the solution to a different version of studio

re-factoring the solution to run on a newer framework

In the later versions of visual studio you can upgrade the solution to VS10 and still target a previous framework.  I do this frequently as I don't enjoy having every single version of the IDE on my main box.  On most projects this upgrade is done correctly through the wizard that you get if you open an older studio solution in the newer studio.  I do this as soon as everyone has installed and is comfortable with a higher version generally.

Re-factoring to take advantage of the newer framework is more tricky and I would not necessarily do it unless I was undertaking a significant change already as there are often many adjustments that have to be made manually after the change in target.


问:
Managing deployment scripts in the process of continuous delivery
My question concerns deployment scripts in the process of continuous delivery.

Continuous delivery recommends that deployment scripts should be versioned into SCM just as normal code.

What is the best practice to avoid issues such as checking out (e.g. from Git) a script that does not have the right permission or is not executable?

Also, where in the SCM repository should deployment scripts be located?

答:
It must be noted that solutions to this issue are bound to be specific to the underlying technology.

Here is a couple of git and Unix-specific solutions that can serve as a source of inspiration for other SCMs and platforms:

Both rely on the following git command:

```<code>git update-index --chmod=+x $script
</code>```

and git/bash aliases. See full post here: https://stackoverflow.com/a/22710807/536299

Regarding the question of the location in the SCM repository, it could be in a separate SCM repository or in a folder located with the source code.

Body:
It must be noted that solutions to this issue are bound to be specific to the underlying technology.

Here is a couple of git and Unix-specific solutions that can serve as a source of inspiration for other SCMs and platforms:

Both rely on the following git command:

git update-index --chmod=+x $script

and git/bash aliases. See full post here: https://stackoverflow.com/a/22710807/536299

Regarding the question of the location in the SCM repository, it could be in a separate SCM repository or in a folder located with the source code.


答:
For .NET it may depend on the deployment target. .NET 3.5 is supported in even early editions of Windows XP, whereas 4.5 is only supported on Vista and above.

At my workplace we opted to stay on 4.0 because we still have workstations running on Windows XP Pro SP3 (which 4.0 supports). We cannot consider migrating until next year or so just because of that.

Another reason may be a dependency on external code libraries that have been compiled using an older version of the framework and for which no recent version exists.

Title: Why do projects opt to stay on an older version of the .NET Framework?

Body:
Why do projects opt to stay on an older framework version of the .NET Framework?

For example, staying on .NET Framework version 3.5 which was released in 2007 instead of upgrading to the latest 4.5.1 version?

Jon Skeet's Noda Time also targets .NET 3.5. Why?


答:
Recommend an upgrade to a million dollar software project from v3.5 to v4.0 (Not always the same as going from .50 to 1.0), you better have a very good reason. Sorry, but just stating it's 5-10 years old isn't good enough IMHO.

Be prepared to identity the new features and how they will benefit this project. You could argue that if you don't, making an even bigger jump of 3.5 -> 6.0 will be exponentially more expensive because the creator of your programming code won't provide any sort of automated way of doing it as an example.

When you're paying the bills, it's easier to take comfort in "If it isn't broke, don't fix it."