答:
I think the Zen of Python will state why Python is a simple language a lot better than I can:

```<code>Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
</code>```

Edit in response to @Giorgio

As your question states,

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

Python is, to me, what immediately comes to mind. Python's design is in direct response to Perl's methodology, the famous "There's More Than One Way To Do It". While that's great, allowing programmers to very easily write code, it doesn't help with maintenance. Having before managed a (very poorly written, I'll admit) program written in Perl, I appreciate Python forcing both good coding practices and concise language down your throat.

Python also does not force you to follow one particular methodology when writing programs. I can choose to follow strict Object-Oriented programming style, or I can write a simple script to execute sequentially. Not having to initialize a class, then call the main() method like you're forced to do in Java is very nice. (Also, printing to stdout in Python is wonderful, but that's a rather null point).

Finally, the "Batteries Included" methodology of including an expansive standard library with the language is wonderful. Instead of hunting through some external repository for packages, most of what I need is already included in the language. It's also nice having that external repo, but not having to dig through it in order to do a basic operation is really handy.

Title: KISS principle applied to programming language design?

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

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

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

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

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

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

Body:
I think the Zen of Python will state why Python is a simple language a lot better than I can:

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

Edit in response to @Giorgio

As your question states,

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

Python is, to me, what immediately comes to mind. Python's design is in direct response to Perl's methodology, the famous "There's More Than One Way To Do It". While that's great, allowing programmers to very easily write code, it doesn't help with maintenance. Having before managed a (very poorly written, I'll admit) program written in Perl, I appreciate Python forcing both good coding practices and concise language down your throat.

Python also does not force you to follow one particular methodology when writing programs. I can choose to follow strict Object-Oriented programming style, or I can write a simple script to execute sequentially. Not having to initialize a class, then call the main() method like you're forced to do in Java is very nice. (Also, printing to stdout in Python is wonderful, but that's a rather null point).

Finally, the "Batteries Included" methodology of including an expansive standard library with the language is wonderful. Instead of hunting through some external repository for packages, most of what I need is already included in the language. It's also nice having that external repo, but not having to dig through it in order to do a basic operation is really handy.


问:
What is the historical basis of using Javascript in web programming?
I come from a scientific biology background where we also use Python a lot.

Now that I've begun to start with Web development, I've consistently found myself wondering just why it is that JavaScript is the primary client-side language on the Web.

Is JavaScript's predominance a historical accident or something else?  Also, I'm curious if there are any hurdles to integrating Python into client-side scripting?

答:
"Is JavaScript's predominance a historical accident or something else?"

I am personally of the opinion that JS's success is a matter of design as much as many have been and will continue to be loathe to admit it and not just some accident or merely due to the fact that it was the first kid on the playground.

Though named so as to appeal to Java developers and syntaxed like Java's C-based syntax also to appeal to Java developers, Brendan Eich made one of the most badass decisions in the history of the www which was to draw primarily from Scheme for actual language mechanics inspiration, which is something Java developers don't appear to have liked very much at all (which I find highly amusing).

JavaScript uses highly flexible/granular prototypal inheritance for OOP, it has closures, types are 100% dynamic, functions themselves are first-class allowing them to be passed around like any other object or data type and get re-used in different contexts and even get applied to objects on the fly as if they had been declared as actual object members from the start. It is practically screaming to be used for event-driven architectures that need to normalize a ton of proprietary garbage or handle highly non-linear UI problems.

At the end of the dawn of the web it is the only language that has ever been seriously up to the task of normalizing browsers through an actual browser war where Netscape and IE tried to do things differently on purpose, followed by 10+ years of browser truce where IE just did things differently because MS is lazy and self-entrenched into some righteously stupid anti-competitive practices resulting in browser stagnancy, and now a world where the browsers are finally starting to agree on the same general spec in regards to HTML, CSS and the DOM API with IE merely being 2-3 years behind the latest developments rather than 10 owing to Google and Mozilla busting out JIT compilers that made IE's performance numbers look so pathetic MS was finally shamed into properly modernizing their damn browsers. IE9 is the first to actually seriously upgrade the DOM API support to levels that Netscape was supporting back in 2000ish.

JS has had competition in the form of Java Applets and Adobe's ActionScript for Flash. That's about it on the serious contender front. MS tried to push VB but failed miserably because... well... VB. Also, proprietary. There were actually a lot more Flash sites than most people realize. You just couldn't find the silly things with search engines. Applets did their own thing, and it was ugly. Real ugly. JS was the only language that really tackled the problem of working within the context of multiple browsers by people who didn't agree on who was setting the specs they were supposed to be matching up with.

In recent years JS has been exploding into a much wider domain of application. In combination with other web technologies it is geared up to basically knock all other solutions over on the mobile front since it + web technology is really the only realistic choice right now if you really do want to write one app and have it work on everything.

So no, and yes I'm a big fan, but I don't think it clobbered all other contenders on the client-side by accident any more than it becoming explosively popular outside of the browser could be considered an accident now. Before JS, there weren't many Scheme-like languages out there that weren't primarily academic. That's given JS some powerful advantages and the unique needs of the client-side made it possible for those advantages to slowly become crystal clear.

ContentLicense: CC BY-SA 3.0


问:
Is there a purpose for using pull requests on my own repo if I am the only developer?
So I got started with a real project of mine on GitHub and things are going pretty well and ideas are flowing a lot faster than I initially thought. In order to keep things organized, I setup some branches so I can develop different features separately.

Now when I push my branch to GitHub, I have that section where I have two buttons : Pull Request and Compare with the name of the branch I recently pushed to. I understand the purpose of the Compare button but I don't get why I would want to create a pull request on my own repo.

Can someone explain me why I would do that? Is it useful to make pull request on my own repo if I am the only developer?

答: Pull requests would usually be used for either code reviews or contributions from users with their own fork of the project - for a single developer on a project I don't really see a purpose.</p>


答:
For many (perhaps most) individual developers working on their own, creating pull requests is probably not worthwhile. However, I can think of at least one potential reason to do it:

Pull requests can be used to keep track of your project history more easily. A pull request has an issue ID which can be referred to from commit messages and in a change-log, which allows you to easily go back and find the merge point and set of merged commits for a particular change, without having to retain your feature branches indefinitely.

For example, in Pioneer (shameless plug), when we merge a pull request, we add an item to the changelog, with a one-line description of the change and a reference to the pull request ID. Of course, Pioneer has several developers, but the same mechanism could be useful for a developer working on his or her own.

This may be less useful if you decide to stick to a linear commit history (by rebasing your feature branches before merge, so that the merge can always be performed as a fast-forward), and if you are very disciplined about editing and squashing your commits before merging to master, because in that case the individual commit messages can be used as a changelog in themselves.

Title: Is there a purpose for using pull requests on my own repo if I am the only developer?

Body:
So I got started with a real project of mine on GitHub and things are going pretty well and ideas are flowing a lot faster than I initially thought. In order to keep things organized, I setup some branches so I can develop different features separately.

Now when I push my branch to GitHub, I have that section where I have two buttons : Pull Request and Compare with the name of the branch I recently pushed to. I understand the purpose of the Compare button but I don't get why I would want to create a pull request on my own repo.

Can someone explain me why I would do that? Is it useful to make pull request on my own repo if I am the only developer?


问:
How is Agile different from XP?
I read few articles on web to find out how Agile, XP, Scrum, pair programming are different from each other / related to each other and I derived the following line:

Scrum and XP are almost same. XP has shorter period of releases than Scrum

Pair programming is employed in both Agile and XP methodologies

But I was unable to identify how Agile is different from XP.

More than providing a URL, I would be happy to read your experience and thoughts on this.

答: Practically many organisations do not follow a specific methodology 100% like XP or Scrum as they are laid down. Specially if they have just started to follow Agile principles. They may pick and choose certain aspects of any given methodology like Scrum that falls within the Agile bandwagon. Agile is more abstract and it is easier to say that rather than saying we do XP or Scrum.</p>

ContentLicense: CC BY-SA 2.5

Title: How is Agile different from XP?


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

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

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

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

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

答:
LSP in simple words states that any instance of Foo can be replaced with any instance of Bar which is derived from Foo without any loss of program functionality.

This is wrong. LSP states that class Bar shouldn't introduce behavior, that is not expected when code uses Foo, when Bar is derived from Foo. It has nothing to do with loss of functionality. You can remove functionality, but only when code using Foo doesn't depend on this functionality.

But in the end, this is usually hard to achieve, because most of the time, code using Foo depends on all of it's behavior. So removing it violates LSP. But simplifying it like this is only part of LSP.


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

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

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

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

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

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

答:
Here's a big quote from Bruce McKinney's Hardcore Visual Basic, which in turn puts words into the mouths of the designers of BASIC, Kemeny and Kurtz. Emphases mine.

Every computer language has its own feel, its own atmosphere, its own
  spirit. You can’t really define this spirit, but you know what it is
  when you see it. I think of Basic as the antithesis of a statement
  attributed to Albert Einstein:

Make things as simple as possible—but no simpler.

Had that quote been written by the original designers of Basic, John
  Kemeny and Thomas Kurtz, it would have been simplified further:

Make things simpler than possible.

That is the contradiction hardcore Visual Basic programmers live with.
  We want things to be simple, elegant, and intuitive—but they aren’t.
  We want our programs to model reality—but they don’t. We want our
  language to work the way we think, not the way computers or operating
  systems want us to think—but we’re not willing to pay the price.


问:
What exactly does the condition in the MIT license imply?
To quote the license itself:

Copyright (C) [year] [copyright holders]

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

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

I am not exactly sure what the bold part implies.

Lets say that I'm creating some library, and I license it under the MIT license. Someone decides to fork that library and to create a closed-source, commercial version. According to the license, he should be free to do that.

However, what does he additionally need to do under those terms? Credit me as the creator? I guess the "above copyright notice" refers to the "Copyright (C) [..." part, but, wouldn't that list me as the author of his code (although I technically typed out the code)?

And wouldn't including the "permission notice" in what is now his library practically license it under the same conditions that I licensed my own library in?

Or, am I interpreting this incorrectly? Does that refer to my obligations to include the copyright and the permission notice?

答:
The commercial software would need to include the copyright notice for the work it has used. It doesn't mean the entire commercial work is then licensed under the MIT license.

For example, I would expect to see the copyright notice for the commercial software, with the following wording added:

This software includes the Yannbane Awesome Library:
      Copyright (C) 2012 Yannbane

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

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

So by including the license, they are letting people know what terms the "Yannbane Awesome Library" is licensed under - as it is different to the terms of the wider commercial application.


答:
From my understanding:

OCP says: "If you will add new function, create a new class extending an existing one, rather than changing it."

LSP says: "If you create a new class extending an existing class, make sure it's completely interchangeable with its base."

So I think they complement each other but they are not equal.

Title: LSP vs OCP / Liskov Substitution VS Open Close

Body:
I am trying to understand the SOLID principles of OOP and I've come to the conclusion that LSP and OCP have some similarities (if not to say more).

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

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

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

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

ContentLicense: CC BY-SA 4.0


答:
You are confusing the issue. Being agile means that you are following a bunch of values and practices from the agile manifesto. Thats it.

XP and Scrum are development processes that follows those values. Both are "just as agile". The big difference between Scrum and XP is that Scrum does not contain practices specifically for programming, whereas XP has lots of them (TDD, continuous integration, pair programming).

Title: How is Agile different from XP?

Body:
I read few articles on web to find out how Agile, XP, Scrum, pair programming are different from each other / related to each other and I derived the following line:

Scrum and XP are almost same. XP has shorter period of releases than Scrum

Pair programming is employed in both Agile and XP methodologies

But I was unable to identify how Agile is different from XP.

More than providing a URL, I would be happy to read your experience and thoughts on this.


问:
Future of desktop applications on Windows 8
There are a lot of threads discussing existence of WPF/Silverlight/HTML5 on Windows 8, I just need to clarify the picture about desktop applications only, I have following queries to the experts

What are the technologies available for developing desktop applications on Windows 8?

What are the technologies I can use for creating rich multimedia applications. Currently I have an application with DirectX 9 and WPF. If I am to develop something like that for Windows 8 then what options are available to me, and what are the pros and cons of these.

Is it a good idea to continue with the same DirectX 9 code on Windows 8 as well? What is the best option equivalent to DirectX, Is it XNA or is it DirectX 11 or something else?

Performance an extensibility are critical points to me. All suggestions are welcome.

Thanks in Advance.

答:
Your question is wrong. Windows 8 contains 2 separate ecosystems:

Desktop

WinRT / Metro

Desktop is exactly same as it always was. You use same tools, same APIs, same frameworks as Windows 7.

WinRT is brand new and completely different and incompatible. You can share some code here and there, but it is highly questionable if it is even worth it. Especially if lots of your code is in webservices on net.

So if you ask this kind of question, you need to clarify if you are talking about Desktop, WinRT or are you trying to mix both.


问:
Pass structure as an argument in c# method
I want to know if it is possible to pass a Structure as a parameter in c# method and if possible, is it a good practice to do so?

I have a c# method which is taking six arguments, i really hate that. I could create a carrier class for that and pass it as an argument, but i want to know if structure could do the job.

I want to mention here that few arguments to that method are of ref type and few are of value type.

答:
Yes you can (and should) have structures and classes as arguments to methods. This will help encapsulate your data and make it easier if you need to pass more data to your methods. You simply extend the class and recompile.

Obviously, just extending a class is to be avoided if it's a public interface, but if it's just internal to your application then there shouldn't be a problem.


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

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

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

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

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

答:
An OrderItem can not exist without an order or an product. Hence it's weak since it's dependencies control it.

If you for instance remove the order you have no way of knowing where the item should be shipped. Or if you remove the product you don't know what to ship.


答:
Yes, you can do it, but you need to bear a couple of things in mind.

First is that a value type (struct) is stored on the stack (often, not always, see comment-thread), rather than the heap. The stack is limited in size and large objects shouldn't be stored on it. That said, there is a minor performance benefit to storing variables on the stack.

The next is that a value type passed as a method argument will be copied, rather than referenced. This can be a good thing. At least you know that your variable isn't going to be changed by the method. However, the copy is stored on the stack, so be careful. Also, sometimes you want a method to be able to edit the contents of your object.

Finally, you need to know that reference objects within a struct are just pointers to objects on the heap. So if you edit the contents of one of those classes (unless, like a string, they are coded to be immutable), you are going to affect the contents of your own object, even though it is supposedly immutable. This can be very confusing.

As soon as you said that some of the contents are reference objects, I thought "I'd just stick to a class."

As a general rule:

Only use structs to hold other immutable objects.

Only use structs for small collections of data.

Only use structs where changing one item within it will probably change all of the others.

Take an address as a good example:

All contents are strings and thus immutable.

It's only a half-dozen pointers.

While you might remain in the same zipcode, for example, if you move house then you probably change your entire address.

Title: Pass structure as an argument in c# method

Body:
I want to know if it is possible to pass a Structure as a parameter in c# method and if possible, is it a good practice to do so?

I have a c# method which is taking six arguments, i really hate that. I could create a carrier class for that and pass it as an argument, but i want to know if structure could do the job.

I want to mention here that few arguments to that method are of ref type and few are of value type.


问:
Time allocated to code reviews
If you are doing code reviews

How much time do you spend on code reviews, compared to implementation?

How much of the changes undergo code review?

you think it's to much / should be more?

Are there any studies about effectiveness?

[edit] thank you all for the answers, it's hard to pick a "winner" for such a question, there is lots of valuable info in the other replies, too.

答:
Every organisation and code base is different, so it is difficult to get an industry wide value.

If you are really serious then you should start collecting metrics. I.e. Do the code review until is satisfactorily done including rework. Start collecting this in a database (LOC, code complexity, programming language, time etc.). Then also collect metrics on your defect rate during testing. As long as you can reduce this code review should pay by itself. If defect comes back from testing then collect metrics on how much time was spent on fixing defects. Build these data in your organisation, create baselines, and you can predict it quite accurately. The terms to search for further learning is Cost of Quality and Cost of Poor Quality.

The only caveat is that this can start to become bureaucratic and depends on organisation culture.

Title: Time allocated to code reviews


问:
Why is heap size fixed on JVMs?
Can anyone explain to me why JVMs (I didn't check too many, but I've never seen one that didn't do it that way) need to run on a fixed heap size? I know it's easier to implement on a simple contiguous heap, but the Sun JVM is now over a decade old, so I'd expect them to have had time to improve this.

Needing to define the maximum memory size of your program at startup time seems such a 1960s thing to do, and then there are the bad interactions with OS virtual memory management (GC retrieving swapped out data, inability to determine how much memory the Java process is really using from the OS side, huge amounts of VM space wasted (I know, you don't care on your fancy 48bit machines...)). I also guess that the various sad attempts to build small operating systems inside the JVM (EE application servers, OSGi) are at least partially to blame on this circumstance, because running multiple Java processes on a system invariably leads to wasted resources because you have to give each of them the memory it might have to use at peak.

Surprisingly, Google didn't yield the storms of outrage over this that I would expect, but they may just have been buried under the millions of people finding out about fixed heap size and just accepting it for a fact.

答:
You are wrong. The heap size of JVMs is not fixed, only bounded:

-Xmx sets the maximum heap memory size

-Xms sets the minimum heap memory size

Setting an upper limit is necessary for several reasons. First, it tells the garbage collector when to spring into action. Second, it prevents the JVM from clogging the whole machine by consuming too much memory. The minimum heap size is probably useful to reserve the ammount of memory the program needs at least, to prevent it running out of memory (because other processes consume too much).

Title: Why is heap size fixed on JVMs?


问:
Practical Usage Of Structures in c#

Possible Duplicate:

  When do you use a struct instead of a class?

While working in OOPs, we always battle around structures and classes.

But in real world, we always sticks to classes. I just want to know what is the practical usage of structures in C# and where are they beneficial over the classes.

Or they are just a topic for theory.

答:
Structures are great for representing value types. Things like dates, ranges, numbers; stuff where equality depends on the value of the object rather than the instance of the object. They're good for messages and certain other components in a concurrent program, since the copy semantics make some aspects of that sort of design very clean.

But that's rather in their definition. In practice, they're used more often as a map to some data on disk, or from some other external source since structs can be made to have rules about how they are laid out and packed in memory. So then instead of reading up a byte array and doing the parsing yourself, you can marshal up the structure all at once, letting the runtime do the error-prone stuff.

Title: Practical Usage Of Structures in c#


答:
Gosh, there are some weird misconceptions on what OCP and LSP and some are due to mismatch of some terminologies and confusing examples. Both principles are only the "same thing" if you implement them the same way. Patterns usually follow the principles in one way or another with few exceptions.

The differences will be explained further down but first let us take a dive into the principles themselves:

Open-Closed Principle (OCP)

According to Uncle Bob:

You should be able to extend a classes behavior, without modifying it.

Note that the word extend in this case doesn't necessarily mean that you should subclass the actual class that needs the new behavior. See how I mentioned at first mismatch of terminology? The keyword extend only means subclassing in Java, but the principles are older than Java.

The original came from Bertrand Meyer in 1988:

Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.

Here it is much clearer that the principle is applied to software entities. A bad example would be override the software entity as you're modifying the code completely instead of providing some point of extension. The behavior of the software entity itself should be extensible and a good example of this is implementation of the Strategy-pattern (because it is the easiest to show of the GoF-patterns bunch IMHO):

// Context is closed for modifications. Meaning you are
// not supposed to change the code here.
public class Context {

    // Context is however open for extension through
    // this private field
    private IBehavior behavior;

    // The context calls the behavior in this public
    // method. If you want to change this you need
    // to implement it in the IBehavior object
    public void doStuff() {
        if (this.behavior != null)
            this.behavior.doStuff();
    }

    // You can dynamically set a new behavior at will
    public void setBehavior(IBehavior behavior) {
        this.behavior = behavior;
    }
}

// The extension point looks like this and can be
// subclassed/implemented
public interface IBehavior {
    public void doStuff();
}
```

<p>In the example above the <code>Context</code> is <em>locked</em> for further modifications. Most programmers would probably want to subclass the class in order to extend it but here we don't because it assumes it's behavior can be <em>changed</em> through anything that implements the <code>IBehavior</code> interface. </p>

<p>I.e. the context class is <em>closed for modification but open for extension</em>. It actually follows another basic principle because we're putting the behavior with object composition instead of inheritance:</p>

<blockquote>
  <p>"Favor 'object composition' over 'class inheritance'." (Gang of Four 1995:20)</p>
</blockquote>

<p>I'll let the reader read up on that principle as it is outside the scope of this question. To continue with the example, say we have the following implementations of the IBehavior interface:</p>

<pre class="lang-java prettyprint-override"><code>public class HelloWorldBehavior implements IBehavior {
    public void doStuff() {
        System.println("Hello world!");
    }
}

public class GoodByeBehavior implements IBehavior {
    public void doStuff() {
        System.out.println("Good bye cruel world!");
    }
}
</code>```

Using this pattern we can modify the behavior of the context at runtime, through the setBehavior method as extension point.

// in your main method
Context c = new Context();

c.setBehavior(new HelloWorldBehavior());
c.doStuff();
// prints out "Hello world!"

c.setBehavior(new GoodByeBehavior());
c.doStuff();
// prints out "Good bye cruel world!"
```

<p>So whenever you want to extend the "closed" context class, do it by subclassing it's "open" collaborating dependency. This is clearly not the same thing as subclassing the context itself yet it is OCP. LSP makes no mention about this either.</p>

<h2>Extending with Mixins Instead of Inheritance</h2>

<p>There are other ways to do OCP other than subclassing. One way is to keep your classes open for extension through the use of <em>mixins</em>. This is useful e.g. in languages that are prototype-based rather than class-based. The idea is to amend a dynamic object with more methods or attributes as needed, in other words objects that blends or "mixes in" with other objects.</p>

<p>Here is a javascript example of a mixin that renders a simple HTML template for anchors:</p>

<pre class="lang-js prettyprint-override"><code>// The mixin, provides a template for anchor HTML elements, i.e. <a>
var LinkMixin = {
    render: function() {
        return ''
            + this.content
            + ';
    }
}

// Constructor for a youtube link
var YoutubeLink = function(content, youtubeId) {
    this.content = content;
    this.setLink(this.youtubeId);
};
// Methods are added to the prototype
YoutubeLink.prototype = {
    setLink: function(youtubeid) {
        this.link = 'http://www.youtube.com/watch?v=' + youtubeid;
    }
};
// Extend YoutubeLink prototype with the LinkMixin using
// underscore/lodash extend
_.extend(YoutubeLink.protoype, LinkMixin);

// When used:
var ytLink = new YoutubeLink("Cool Movie!", "idOaZpX8lnA");

console.log(ytLink.render());
// will output:
// Cool Movie!
</code>```

The idea is to extend the objects dynamically and the advantage of this is that objects may share methods even if they are in completely different domains. In the above case you can easily create other kinds of html anchors by extending your specific implementation with the LinkMixin.

In terms of OCP, the "mixins" are extensions. In the example above the YoutubeLink is our software entity that is closed for modification, but open for extensions through the use of mixins. The object hierarchy is flattened out which makes it impossible to check for types. However this is not really a bad thing, and I'll explain in further down that checking for types is generally a bad idea and breaks the idea with polymorphism.

Note that it is possible to do multiple inheritance with this method as most extend implementations can mix-in multiple objects:

_.extend(MyClass, Mixin1, Mixin2 /* [, ...] */);
```

<p>The only thing you need to keep in mind is to not collide the names, i.e. mixins happen to define the same name of some attributes or methods as they will be overridden. In my humble experience this is a non-issue and if it does happen it is an indication of flawed design.</p>

<h1>Liskov's Substitution Principle (LSP)</h1>

<p>Uncle Bob defines it simply by:</p>

<blockquote>
  <p>Derived classes must be substitutable for their base classes.</p>
</blockquote>

<p>This principle is old, in fact Uncle Bob's definition doesn't differentiate the principles as that makes LSP still closely related to OCP by the fact that, in the above Strategy example, the same supertype is used (<code>IBehavior</code>). So lets look at it's original definition by Barbara Liskov and see if we can find out something else about this principle that looks like a mathematical theorem:</p>

<blockquote>
  <p>What is wanted here is something like the following substitution property: If
  for each object <code>o1</code> of type <code>S</code> there is an object <code>o2</code> of type <code>T</code> such that for all programs <code>P</code> defined in terms of <code>T</code>, the behavior of <code>P</code> is unchanged when <code>o1</code> is substituted for <code>o2</code> then <code>S</code> is a subtype of <code>T</code>.</p>
</blockquote>

<p>Lets shrug on this for a while, notice as it doesn't mention classes at all. In JavaScript you can actually follow LSP even though it is not explicitly class-based. If your program has a list of at least a couple of JavaScript objects that:</p>

<ul>
<li>needs to be computed the same way,</li>
<li>have the same behavior, and</li>
<li>are otherwise in some way completely different</li>
</ul>

<p>...then the objects are regarded as having the same "type" and it doesn't really matter for the program. <strong>This is essentially polymorphism.</strong> In generic sense; you shouldn't need to know the actual subtype if you're using it's interface. OCP does not say anything explicit about this. It also actually pinpoints a design mistake most novice programmers do:</p>

<p><strong>Whenever you're feeling the urge to check the subtype of an object, you're most likely doing it WRONG.</strong></p>

<p>Okay, so it might not be wrong all the time but if you have the urge to do some <em>type checking</em> with <code>instanceof</code> or enums, you might be doing the program a bit more convoluted for yourself than it needs to be. But this is not always the case; quick and dirty hacks to get things working is an okay concession to make in my mind if the solution is small enough, and if you practice merciless refactoring, it may get improved once changes demand it. </p>

<p>There are ways around this "design mistake", depending on the actual problem:</p>

<ul>
<li>The super class is not calling the prerequisites, forcing the caller to do so instead.</li>
<li>The super class is missing a generic method that the caller needs.</li>
</ul>

<p>Both of these are common code design "mistakes". There are a couple of different refactorings you can do, such as pull-up method, or refactor to a pattern such the Visitor pattern.</p>

<p>I actually like the Visitor pattern a lot as it can take care of large if-statement spaghetti and it is simpler to implement than what you'd think on existing code. Say we have the following context:</p>

<pre class="lang-java prettyprint-override"><code>public class Context {

    public void doStuff(string query) {

        // outcome no. 1
        if (query.Equals("Hello")) {
            System.out.println("Hello world!");
        }

        // outcome no. 2
        else if (query.Equals("Bye")) {
            System.out.println("Good bye cruel world!");
        }

        // a change request may require another outcome...

    }

}

// usage:
Context c = new Context();

c.doStuff("Hello");
// prints "Hello world"

c.doStuff("Bye");
// prints "Bye"
</code>```

The outcomes of the if-statement can be translated into their own visitors as each is depending on some decision and some code to run. We can extract these like this:

public interface IVisitor {
    public bool canDo(string query);
    public void doStuff();
}

// outcome 1
public class HelloVisitor implements IVisitor {
    public bool canDo(string query) {
        return query.Equals("Hello");
    }
    public void doStuff() {
         System.out.println("Hello World");
    }
}

// outcome 2
public class ByeVisitor implements IVisitor {
    public bool canDo(string query) {
        return query.Equals("Bye");
    }
    public void doStuff() {
        System.out.println("Good bye cruel world");
    }
}
```

<p>At this point, if the programmer did not know about the Visitor pattern, he'd instead implement the Context class to check if it is of some certain type. Because the Visitor classes have a boolean <code>canDo</code> method, the implementor can use that method call to determine if it is the right object to do the job. The context class can use all visitors (and add new ones) like this:</p>

<pre class="lang-java prettyprint-override"><code>public class Context {
    private ArrayList<IVisitor> visitors = new ArrayList<IVisitor>();

    public Context() {
        visitors.add(new HelloVisitor());
        visitors.add(new ByeVisitor());
    }

    // instead of if-statements, go through all visitors
    // and use the canDo method to determine if the
    // visitor object is the right one to "visit"
    public void doStuff(string query) {
        for(IVisitor visitor : visitors) {
            if (visitor.canDo(query)) {
                visitor.doStuff();
                break;
                // or return... it depends if you have logic
                // after this foreach loop
            }
        }
    }

    // dynamically adds new visitors
    public void addVisitor(IVisitor visitor) {
        if (visitor != null)
            visitors.add(visitor);
    }
}
</code>```

Both patterns follow OCP and LSP, however they are both pinpointing different things about them. So how does code look like if it violates one of the principles?

Violating one principle but following the other

There are ways to break one of the principles but still have the other be followed. The examples below seem contrived, for good reason, but I've actually seen these popping up in production code (and even worser):

Follows OCP but not LSP

Lets say we have the given code:

public interface IPerson {}

public class Boss implements IPerson {
    public void doBossStuff() { ... }
}

public class Peon implements IPerson {
    public void doPeonStuff() { ... }
}

public class Context {
    public Collection<IPerson> getPersons() { ... }
}
```

<p>This piece of code follows the open-closed principle. If we're calling the context's <code>GetPersons</code> method, we'll get a bunch of persons all with their own implementations. That means that IPerson is closed for modification, but open for extension. However things take a dark turn when we have to use it:</p>

<pre class="lang-java prettyprint-override"><code>// in some routine that needs to do stuff with
// a collection of IPerson:
Collection<IPerson> persons = context.getPersons();
for (IPerson person : persons) {
    // now we have to check the type... :-P
    if (person instanceof Boss) {
        ((Boss) person).doBossStuff();
    }
    else if (person instanceof Peon) {
        ((Peon) person).doPeonStuff();
    }
}
</code>```

You have to do type checking and type conversion! Remember how I mentioned above how type checking is a bad thing? Oh no! But fear not, as also mentioned above either do some pull-up refactoring or implement a Visitor pattern. In this case we can simply do a pull up refactoring after adding a general method:

public class Boss implements IPerson {
    // we're adding this general method
    public void doStuff() {
        // that does the call instead
        this.doBossStuff();
    }
    public void doBossStuff() { ... }
}

public interface IPerson {
    // pulled up method from Boss
    public void doStuff();
}

// do the same for Peon
```

<p>The benefit now is that you don't need to know the exact type anymore, following LSP:</p>

<pre class="lang-java prettyprint-override"><code>// in some routine that needs to do stuff with
// a collection of IPerson:
Collection<IPerson> persons = context.getPersons();
for (IPerson person : persons) {
    // yay, no type checking!
    person.doStuff();
}
</code>```

Follows LSP but not OCP

Lets look at some code that follows LSP but not OCP, it is kind of contrived but bear with me on this one it's very subtle mistake:

public class LiskovBase {
    public void doStuff() {
        System.out.println("My name is Liskov");
    }
}

public class LiskovSub extends LiskovBase {
    public void doStuff() {
        System.out.println("I'm a sub Liskov!");
    }
}

public class Context {
    private LiskovBase base;

    // the good stuff
    public void doLiskovyStuff() {
        base.doStuff();
    }

    public void setBase(LiskovBase base) { this.base = base }
}
```

<p>The code does LSP because the context can use LiskovBase without knowing the actual type. You'd think this code follows OCP as well but look closely, is the class really <em>closed</em>? What if the <code>doStuff</code> method did more than just print out a line?</p>

<p>The answer if it follows OCP is simply: <strong>NO</strong>, it isn't because in this object design we're required to override the code completely with something else. This opens up the cut-and-paste can of worms as you have to copy code over from the base class to get things working. The <code>doStuff</code> method sure is open for extension, but it wasn't completely closed for modification.</p>

<p>We can apply the Template method pattern on this. The template method pattern is so common in frameworks that you might have been using it without knowing it (e.g. java swing components, c# forms and components, etc.). Here is that one way to close the <code>doStuff</code> method for modification and making sure it stays closed by marking it with java's <code>final</code> keyword. That keyword prevents anyone from subclassing the class further (in C# you can use <code>sealed</code> to do the same thing).</p>

<pre class="lang-java prettyprint-override"><code>public class LiskovBase {
    // this is now a template method
    // the code that was duplicated
    public final void doStuff() {
        System.out.println(getStuffString());
    }

    // extension point, the code that "varies"
    // in LiskovBase and it's subclasses
    // called by the template method above
    // we expect it to be virtual and overridden
    public string getStuffString() {
        return "My name is Liskov";
    }
}

public class LiskovSub extends LiskovBase {
    // the extension overridden
    // the actual code that varied
    public string getStuffString() {
        return "I'm sub Liskov!";
    }
}
</code>```

This example follows OCP and seems silly, which it is, but imagine this scaled up with more code to handle. I keep seeing code deployed in production where subclasses completely override everything and the overridden code is mostly cut-n-pasted between implementations. It works, but as with all code duplication is also a set-up for maintenance nightmares.

Conclusion

I hope this all clears out some questions regarding OCP and LSP and the differences/similarities between them. It is easy to dismiss them as the same but the examples above should show that they aren't.

Do note that, gathering from above sample code:

OCP is about locking the working code down but still keep it open somehow with some kind of extension points.

This is to avoid code duplication by encapsulating the code that changes as with the example of Template Method pattern. It also allows for failing fast as breaking changes are painful (i.e. change one place, break it everywhere else). For the sake of maintenance the concept of encapsulating change is a good thing, because changes always happen.

LSP is about letting the user handle different objects that implement a supertype without checking what the actual type they are. This is inherently what polymorphism is about.

This principle provides an alternative to do type-checking and type-conversion, that can get out of hand as the number of types grow, and can be achieved through pull-up refactoring or applying patterns such as Visitor.

Body:
Gosh, there are some weird misconceptions on what OCP and LSP and some are due to mismatch of some terminologies and confusing examples. Both principles are only the "same thing" if you implement them the same way. Patterns usually follow the principles in one way or another with few exceptions.

The differences will be explained further down but first let us take a dive into the principles themselves:

Open-Closed Principle (OCP)

According to Uncle Bob:

You should be able to extend a classes behavior, without modifying it.

Note that the word extend in this case doesn't necessarily mean that you should subclass the actual class that needs the new behavior. See how I mentioned at first mismatch of terminology? The keyword extend only means subclassing in Java, but the principles are older than Java.

The original came from Bertrand Meyer in 1988:

Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.

Here it is much clearer that the principle is applied to software entities. A bad example would be override the software entity as you're modifying the code completely instead of providing some point of extension. The behavior of the software entity itself should be extensible and a good example of this is implementation of the Strategy-pattern (because it is the easiest to show of the GoF-patterns bunch IMHO):

// Context is closed for modifications. Meaning you are
// not supposed to change the code here.
public class Context {

    // Context is however open for extension through
    // this private field
    private IBehavior behavior;

    // The context calls the behavior in this public
    // method. If you want to change this you need
    // to implement it in the IBehavior object
    public void doStuff() {
        if (this.behavior != null)
            this.behavior.doStuff();
    }

    // You can dynamically set a new behavior at will
    public void setBehavior(IBehavior behavior) {
        this.behavior = behavior;
    }
}

// The extension point looks like this and can be
// subclassed/implemented
public interface IBehavior {
    public void doStuff();
}

In the example above the Context is locked for further modifications. Most programmers would probably want to subclass the class in order to extend it but here we don't because it assumes it's behavior can be changed through anything that implements the IBehavior interface.

I.e. the context class is closed for modification but open for extension. It actually follows another basic principle because we're putting the behavior with object composition instead of inheritance:

"Favor 'object composition' over 'class inheritance'." (Gang of Four 1995:20)

I'll let the reader read up on that principle as it is outside the scope of this question. To continue with the example, say we have the following implementations of the IBehavior interface:

public class HelloWorldBehavior implements IBehavior {
    public void doStuff() {
        System.println("Hello world!");
    }
}

public class GoodByeBehavior implements IBehavior {
    public void doStuff() {
        System.out.println("Good bye cruel world!");
    }
}

Using this pattern we can modify the behavior of the context at runtime, through the setBehavior method as extension point.

// in your main method
Context c = new Context();

c.setBehavior(new HelloWorldBehavior());
c.doStuff();
// prints out "Hello world!"

c.setBehavior(new GoodByeBehavior());
c.doStuff();
// prints out "Good bye cruel world!"

So whenever you want to extend the "closed" context class, do it by subclassing it's "open" collaborating dependency. This is clearly not the same thing as subclassing the context itself yet it is OCP. LSP makes no mention about this either.

Extending with Mixins Instead of Inheritance

There are other ways to do OCP other than subclassing. One way is to keep your classes open for extension through the use of mixins. This is useful e.g. in languages that are prototype-based rather than class-based. The idea is to amend a dynamic object with more methods or attributes as needed, in other words objects that blends or "mixes in" with other objects.

Here is a javascript example of a mixin that renders a simple HTML template for anchors:

// The mixin, provides a template for anchor HTML elements, i.e. <a>
var LinkMixin = {
    render: function() {
        return '<a href="' + this.link +'">'
            + this.content
            + '</a>;
    }
}

// Constructor for a youtube link
var YoutubeLink = function(content, youtubeId) {
    this.content = content;
    this.setLink(this.youtubeId);
};
// Methods are added to the prototype
YoutubeLink.prototype = {
    setLink: function(youtubeid) {
        this.link = 'http://www.youtube.com/watch?v=' + youtubeid;
    }
};
// Extend YoutubeLink prototype with the LinkMixin using
// underscore/lodash extend
_.extend(YoutubeLink.protoype, LinkMixin);

// When used:
var ytLink = new YoutubeLink("Cool Movie!", "idOaZpX8lnA");

console.log(ytLink.render());
// will output:
// <a href="http://www.youtube.com/watch?=vidOaZpX8lnA">Cool Movie!</a>

The idea is to extend the objects dynamically and the advantage of this is that objects may share methods even if they are in completely different domains. In the above case you can easily create other kinds of html anchors by extending your specific implementation with the LinkMixin.

In terms of OCP, the "mixins" are extensions. In the example above the YoutubeLink is our software entity that is closed for modification, but open for extensions through the use of mixins. The object hierarchy is flattened out which makes it impossible to check for types. However this is not really a bad thing, and I'll explain in further down that checking for types is generally a bad idea and breaks the idea with polymorphism.

Note that it is possible to do multiple inheritance with this method as most extend implementations can mix-in multiple objects:

_.extend(MyClass, Mixin1, Mixin2 /* [, ...] */);

The only thing you need to keep in mind is to not collide the names, i.e. mixins happen to define the same name of some attributes or methods as they will be overridden. In my humble experience this is a non-issue and if it does happen it is an indication of flawed design.

Liskov's Substitution Principle (LSP)

Uncle Bob defines it simply by:

Derived classes must be substitutable for their base classes.

This principle is old, in fact Uncle Bob's definition doesn't differentiate the principles as that makes LSP still closely related to OCP by the fact that, in the above Strategy example, the same supertype is used (IBehavior). So lets look at it's original definition by Barbara Liskov and see if we can find out something else about this principle that looks like a mathematical theorem:

What is wanted here is something like the following substitution property: If
  for each object o1 of type S there is an object o2 of type T such that for all programs P defined in terms of T, the behavior of P is unchanged when o1 is substituted for o2 then S is a subtype of T.

Lets shrug on this for a while, notice as it doesn't mention classes at all. In JavaScript you can actually follow LSP even though it is not explicitly class-based. If your program has a list of at least a couple of JavaScript objects that:

needs to be computed the same way,

have the same behavior, and

are otherwise in some way completely different

...then the objects are regarded as having the same "type" and it doesn't really matter for the program. This is essentially polymorphism. In generic sense; you shouldn't need to know the actual subtype if you're using it's interface. OCP does not say anything explicit about this. It also actually pinpoints a design mistake most novice programmers do:

Whenever you're feeling the urge to check the subtype of an object, you're most likely doing it WRONG.

Okay, so it might not be wrong all the time but if you have the urge to do some type checking with instanceof or enums, you might be doing the program a bit more convoluted for yourself than it needs to be. But this is not always the case; quick and dirty hacks to get things working is an okay concession to make in my mind if the solution is small enough, and if you practice merciless refactoring, it may get improved once changes demand it.

There are ways around this "design mistake", depending on the actual problem:

The super class is not calling the prerequisites, forcing the caller to do so instead.

The super class is missing a generic method that the caller needs.

Both of these are common code design "mistakes". There are a couple of different refactorings you can do, such as pull-up method, or refactor to a pattern such the Visitor pattern.

I actually like the Visitor pattern a lot as it can take care of large if-statement spaghetti and it is simpler to implement than what you'd think on existing code. Say we have the following context:

public class Context {

    public void doStuff(string query) {

        // outcome no. 1
        if (query.Equals("Hello")) {
            System.out.println("Hello world!");
        }

        // outcome no. 2
        else if (query.Equals("Bye")) {
            System.out.println("Good bye cruel world!");
        }

        // a change request may require another outcome...

    }

}

// usage:
Context c = new Context();

c.doStuff("Hello");
// prints "Hello world"

c.doStuff("Bye");
// prints "Bye"

The outcomes of the if-statement can be translated into their own visitors as each is depending on some decision and some code to run. We can extract these like this:

public interface IVisitor {
    public bool canDo(string query);
    public void doStuff();
}

// outcome 1
public class HelloVisitor implements IVisitor {
    public bool canDo(string query) {
        return query.Equals("Hello");
    }
    public void doStuff() {
         System.out.println("Hello World");
    }
}

// outcome 2
public class ByeVisitor implements IVisitor {
    public bool canDo(string query) {
        return query.Equals("Bye");
    }
    public void doStuff() {
        System.out.println("Good bye cruel world");
    }
}

At this point, if the programmer did not know about the Visitor pattern, he'd instead implement the Context class to check if it is of some certain type. Because the Visitor classes have a boolean canDo method, the implementor can use that method call to determine if it is the right object to do the job. The context class can use all visitors (and add new ones) like this:

public class Context {
    private ArrayList<IVisitor> visitors = new ArrayList<IVisitor>();

    public Context() {
        visitors.add(new HelloVisitor());
        visitors.add(new ByeVisitor());
    }

    // instead of if-statements, go through all visitors
    // and use the canDo method to determine if the
    // visitor object is the right one to "visit"
    public void doStuff(string query) {
        for(IVisitor visitor : visitors) {
            if (visitor.canDo(query)) {
                visitor.doStuff();
                break;
                // or return... it depends if you have logic
                // after this foreach loop
            }
        }
    }

    // dynamically adds new visitors
    public void addVisitor(IVisitor visitor) {
        if (visitor != null)
            visitors.add(visitor);
    }
}

Both patterns follow OCP and LSP, however they are both pinpointing different things about them. So how does code look like if it violates one of the principles?

Violating one principle but following the other

There are ways to break one of the principles but still have the other be followed. The examples below seem contrived, for good reason, but I've actually seen these popping up in production code (and even worser):

Follows OCP but not LSP

Lets say we have the given code:

public interface IPerson {}

public class Boss implements IPerson {
    public void doBossStuff() { ... }
}

public class Peon implements IPerson {
    public void doPeonStuff() { ... }
}

public class Context {
    public Collection<IPerson> getPersons() { ... }
}

This piece of code follows the open-closed principle. If we're calling the context's GetPersons method, we'll get a bunch of persons all with their own implementations. That means that IPerson is closed for modification, but open for extension. However things take a dark turn when we have to use it:

// in some routine that needs to do stuff with
// a collection of IPerson:
Collection<IPerson> persons = context.getPersons();
for (IPerson person : persons) {
    // now we have to check the type... :-P
    if (person instanceof Boss) {
        ((Boss) person).doBossStuff();
    }
    else if (person instanceof Peon) {
        ((Peon) person).doPeonStuff();
    }
}

You have to do type checking and type conversion! Remember how I mentioned above how type checking is a bad thing? Oh no! But fear not, as also mentioned above either do some pull-up refactoring or implement a Visitor pattern. In this case we can simply do a pull up refactoring after adding a general method:

public class Boss implements IPerson {
    // we're adding this general method
    public void doStuff() {
        // that does the call instead
        this.doBossStuff();
    }
    public void doBossStuff() { ... }
}

public interface IPerson {
    // pulled up method from Boss
    public void doStuff();
}

// do the same for Peon

The benefit now is that you don't need to know the exact type anymore, following LSP:

// in some routine that needs to do stuff with
// a collection of IPerson:
Collection<IPerson> persons = context.getPersons();
for (IPerson person : persons) {
    // yay, no type checking!
    person.doStuff();
}

Follows LSP but not OCP

Lets look at some code that follows LSP but not OCP, it is kind of contrived but bear with me on this one it's very subtle mistake:

public class LiskovBase {
    public void doStuff() {
        System.out.println("My name is Liskov");
    }
}

public class LiskovSub extends LiskovBase {
    public void doStuff() {
        System.out.println("I'm a sub Liskov!");
    }
}

public class Context {
    private LiskovBase base;

    // the good stuff
    public void doLiskovyStuff() {
        base.doStuff();
    }

    public void setBase(LiskovBase base) { this.base = base }
}

The code does LSP because the context can use LiskovBase without knowing the actual type. You'd think this code follows OCP as well but look closely, is the class really closed? What if the doStuff method did more than just print out a line?

The answer if it follows OCP is simply: NO, it isn't because in this object design we're required to override the code completely with something else. This opens up the cut-and-paste can of worms as you have to copy code over from the base class to get things working. The doStuff method sure is open for extension, but it wasn't completely closed for modification.

We can apply the Template method pattern on this. The template method pattern is so common in frameworks that you might have been using it without knowing it (e.g. java swing components, c# forms and components, etc.). Here is that one way to close the doStuff method for modification and making sure it stays closed by marking it with java's final keyword. That keyword prevents anyone from subclassing the class further (in C# you can use sealed to do the same thing).

public class LiskovBase {
    // this is now a template method
    // the code that was duplicated
    public final void doStuff() {
        System.out.println(getStuffString());
    }

    // extension point, the code that "varies"
    // in LiskovBase and it's subclasses
    // called by the template method above
    // we expect it to be virtual and overridden
    public string getStuffString() {
        return "My name is Liskov";
    }
}

public class LiskovSub extends LiskovBase {
    // the extension overridden
    // the actual code that varied
    public string getStuffString() {
        return "I'm sub Liskov!";
    }
}

This example follows OCP and seems silly, which it is, but imagine this scaled up with more code to handle. I keep seeing code deployed in production where subclasses completely override everything and the overridden code is mostly cut-n-pasted between implementations. It works, but as with all code duplication is also a set-up for maintenance nightmares.

Conclusion

I hope this all clears out some questions regarding OCP and LSP and the differences/similarities between them. It is easy to dismiss them as the same but the examples above should show that they aren't.

Do note that, gathering from above sample code:

OCP is about locking the working code down but still keep it open somehow with some kind of extension points.

This is to avoid code duplication by encapsulating the code that changes as with the example of Template Method pattern. It also allows for failing fast as breaking changes are painful (i.e. change one place, break it everywhere else). For the sake of maintenance the concept of encapsulating change is a good thing, because changes always happen.

LSP is about letting the user handle different objects that implement a supertype without checking what the actual type they are. This is inherently what polymorphism is about.

This principle provides an alternative to do type-checking and type-conversion, that can get out of hand as the number of types grow, and can be achieved through pull-up refactoring or applying patterns such as Visitor.


答:
As says user281377, you only specify an upper limit of how much memory your process can consume. Of course, the application itself will only grab the space it needs.

Whether there should exist a default upper limit or not is another question, with both pro and contra.

Title: Why is heap size fixed on JVMs?

Body:
Can anyone explain to me why JVMs (I didn't check too many, but I've never seen one that didn't do it that way) need to run on a fixed heap size? I know it's easier to implement on a simple contiguous heap, but the Sun JVM is now over a decade old, so I'd expect them to have had time to improve this.

Needing to define the maximum memory size of your program at startup time seems such a 1960s thing to do, and then there are the bad interactions with OS virtual memory management (GC retrieving swapped out data, inability to determine how much memory the Java process is really using from the OS side, huge amounts of VM space wasted (I know, you don't care on your fancy 48bit machines...)). I also guess that the various sad attempts to build small operating systems inside the JVM (EE application servers, OSGi) are at least partially to blame on this circumstance, because running multiple Java processes on a system invariably leads to wasted resources because you have to give each of them the memory it might have to use at peak.

Surprisingly, Google didn't yield the storms of outrage over this that I would expect, but they may just have been buried under the millions of people finding out about fixed heap size and just accepting it for a fact.


答:
In C#, structs are value types, while classes are reference types.

So you use a struct whenever a value type is called for, and a class if a reference type is more handy.

That's about all there is to it.

Title: Practical Usage Of Structures in c#

Body:
Possible Duplicate:

  When do you use a struct instead of a class?

While working in OOPs, we always battle around structures and classes.

But in real world, we always sticks to classes. I just want to know what is the practical usage of structures in C# and where are they beneficial over the classes.

Or they are just a topic for theory.


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

It is a good thing you clarified what you mean by "simple", because in my mind a simple programming language is one with minimal syntax and few features (Scheme, Forth, ML), which does not directly translate to your definition. I think you are really looking for languages design with RAD (rapid application development) in mind, and there are quite a few of them. See this StackOverflow thread, for instance: https://stackoverflow.com/questions/66227/what-is-the-best-multi-platform-rad-language


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

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

答: "Should I use this tried-and-tested 'wheel' or reinvent it?" </p>


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

答:
The way I see it there are two main solutions to this:

Don't allocate 100% of your time to the current sprint. Allow 10-15% of your time for bug fixing and other support activities that will come up during the sprint. Then if a blocking bug comes up you have the time to fix it in the current sprint.

If a non blocking bug comes up you can either fix it at the end of the current sprint if you have the time left over or it goes into the "pot" for the next sprint.

Have a "bug fixing" sprint every so often. Probably just before the next major release. You can use this to "mop up" as many bugs as you can/want to fix for the next release.

Neither of these solutions is probably true to "pure" Scrum, but they work in the real world.

During a "regular" sprint you can still include tasks to fix specific bugs, treating them as you would a piece of new functionality.


答:
My own rule of thumb, it may be wrong:

I'd say a struct is the strong, static typing equivalent of a tuple. Use it when every possible combination of values in the struct is valid and equally reasonable.

On the contrary, classes have a limited set of valid states and have more complex setters and getters, that may need to do validation, too.

Title: Practical Usage Of Structures in c#


答:
In C# you are forced to allocate objects on the heap and reference them with a pointer. Structs allow you to put "objects" on the stack. Allocating a value on the stack rather than a pointer affects checks for equality, garbage collection, and the speed of allocation.

C# mixes in a heap vs stack decision. In C++ you can do the opposite of C# if you like and put a class on the stack and struct on the heap. With C++ it comes down to design choices about polymorphism rather than the memory allocation decision that C# forces on you.

Title: Practical Usage Of Structures in c#


答:
This is something that causes a lot of confusion. I prefer considering these principles somewhat philosophically, because there are many different examples for them, and sometimes concrete examples don't really capture their whole essence.

What OCP tries to fix

Say we need to add functionality to a given program. The easiest way to go about it, especially for people who were trained to think procedurally, is to add an if clause wherever needed, or something of the like.

The problems with that are

It changes the flow of existing, working code.

It forces a new conditional branching on every case. For example, say you have a list of books, and some of them are on sale, and you want to iterate over all of them and print their price, such that if they're on sale, the printed price will include the string "(ON SALE)".

You can do this by adding an additional field to all books named "is_on_sale", and then you can check that field when printing any book's price, or alternatively, you can instantiate on-sale books from the database using a different type, which prints "(ON SALE)" in the price string (not a perfect design but it delivers the point home).

The problem with the first, procedural solution, is an extra field for each book, and extra redundant complexity in many cases. The second solution only forces logic where it is actually required.

Now consider the fact that there could be plenty of cases where different data and logic is required, and you'll see why keeping OCP in mind while designing your classes, or reacting to changes in requirements, is a good idea.

By now you should get the main idea: Try to put yourself into a situation where new code can be implemented as polymorphic extensions, not procedural modifications.

But never be afraid to analyze the context, and see if the drawbacks happen to outweigh the benefits, because even a principle such as OCP can make a 20-class mess out of a 20-line program, if not treated carefully.

What LSP tries to fix

We all love code reuse. A disease that follows is that many programs don't understand it completely, to the point where they're blindly factoring common lines of code only to create unreadable complexities and redundant tight-coupling between modules that, other than a few lines of code, have nothing in common as far as the conceptual work-to-be-done goes.

The biggest example of this is interface reuse. You've probably witnessed it yourself; a class implements an interface, not because its a logical implementation of it (or an extension in case of concrete base classes), but because the methods it happens to declare at that point have the right signatures as far as it's concerned.

But then you encounter a problem. If classes implement interfaces only by considering the signatures of the methods they declare, then you find yourself able to pass instances of classes from one conceptual functionality into places which demand completely different functionality, that only happen to depend upon similar signatures.

That isn't that horrible, but it causes a lot of confusion, and we have the technology to prevent ourselves from making mistakes like these. What we need to do is to treat interfaces as API + Protocol. The API is apparent in declarations, and the protocol is apparent in existing uses of the interface. If we have 2 conceptual protocols which share the same API, they should be represented as 2 different interfaces. Otherwise we get caught up in DRY dogmatism and, ironically, only create harder to maintain code.

Now you should be able to understand the definition perfectly. LSP says: Don't inherit from a base class and implement functionality in those sub-classes that, other places, which depend on the base class, won't get along with.


答:
I imagine the answer has something to do with Java's heritage.  It was originally designed as a language to be used for embedded systems, where obviously resources are constrained and you don't want processes to simply gobble up whatever's available.  It also helps with system administration, as it makes it easier to provision resources on a server if you can set resource limits.  I see that the latest JVMs seem to use multiple non-continuous heaps, although of course it all appears as a single heap to your code.

(FWIW, you had to specify a program's memory requirements under Apple's pre-Darwin MacOS versions [up to System 7 anyway, which was the last one I used], which was well into the 80s.)

Title: Why is heap size fixed on JVMs?


问:
How do I prove or disprove "God objects" are wrong?
Problem Summary:

Long story short, I inherited a code base and a development team I am not allowed to replace and the use of God Objects is a big issue.  Going forward, I want to have us re-factor things but I am getting push-back from the teams who want to do everything with God Objects "because its easier" and this means I would not be allowed to re-factor.  I pushed back citing my years of development experience, that I'm the new boss who was hired to know these things, etc,  and so did the third party offshore companies account sales rep, and this is now at the executive level and my meeting is tomorrow and I want to go in with a lot of technical ammunition to advocate best practices because I feel it will be cheaper in the long run (And I personally feel that is what the third party is worried about) for the company.

My issue is from a technical level, I know its good long term but I'm having trouble with the ultra short term and 6 months term, and while its something I "know" I can't prove it with references and cited resources outside of one person (Robert C. Martin, aka Uncle Bob), as that is what I am being asked to do as I have been told having data from one person and only one person (Robert C Martin) is not good enough of an argument.

Question:

What are some resources I can cite directly (Title, year published, page number, quote) by well known experts in the field that explicitly say this use of "God" Objects/Classes/Systems is bad (or good, since we are looking for the most technically valid solution)?

Research I have already done:

I have a number of books here and I have searched their indexes for the use of the words "god object" and "god class". I found that oddly its almost never used and the copy of the GoF book I have for example, never uses it (At least according to the index in front of me) but I have found it in the two books below, but I want more I can use.

I checked the Wikipedia page for "God Object" and its currently a stub with little reference links so although I personally agree with that it says, it doesn't have much I can use in an environment where personal experience is not considered valid.  The book cited is also considered too old to be valid by the people I am debating these technical points with as the argument they are making is that "it was once thought to be bad but nobody could prove it, and now modern software says "god" objects are good to use".  I personally believe that this statement is incorrect, but I want to prove the truth, whatever it is.

In Robert C Martin's "Agile Principles, Patterns, and Practices in C#" (ISBN: 0-13-185725-8, hardcover) where on page 266 it states "Everybody knows that god classes are a bad idea.  We don't want to concentrate all the intelligence of a system into a single object or a single function.  One of the goals of OOD is the partitioning and distribution of behavior into many classes and many function." -- And then goes on to say sometimes its better to use God Classes anyway sometimes (Citing micro-controllers as an example).

In Robert C Martin's "Clean Code: A Handbook of Agile Software Craftsmanship" page 136 (And only this page) talks about the "God class" and calls it out as a prime example of a violation of the "classes should be small" rule he uses to promote the Single Responsibility Principle" starting on on page 138.

The problem I have is all my references and citations come from the same person (Robert C. Martin), and am from the same single person/source.  I am being told that because he is just one view, my desire to not use "God Classes" is invalid and not accepted as a standard best practice in the software industry.  Is this true?  Am I doing things wrong from a technical perspective by trying to keep to the teaching of Uncle Bob?

God Objects and Object Oriented Programming and Design:

The more I think of this the more I think this is more something you learn when you study OOP and it's never explicitly called out; Its implicit to good design is my thinking (Feel free to correct me, please, as I want to learn), the problem is I "know" this, but but not everybody does, so in this case its not considered a valid argument because I am effectively calling it out as universal truth when in fact most people are statistically ignorant of it since statistically most people are not programmers.

Conclusion:

I am at a loss on what to search for to get the best additional results to cite, since they are making a technical claim and I want to know the truth and be able to prove it with citations like a real engineer/scientist, even if I am biased against god objects due to my personal experience with code that used them.  Any assistance or citations would be deeply appreciated.

答:
You may want to see guru of the week #84. It's all about god objects (monoliths) and how they are bad.

Extract:

(Major) It isolates potentially independent functionality inside a
  class [...] (Minor) It can discourage extending the class with new
  functionality [...]

OwnerDisplayName: honestduane


答:
Based on how you're describing your workflow from a story, with a product backlog, a sprint backlog, and other buckets (I'm assuming they look something like "in progress/in development", "ready for QA", "finished"), it sounds like you're adding some elements of Kanban to Scrum - a not uncommon combination sometimes called Scrumban. The notion of Kanban adds limits to the size of each bucket to prevent your developers from having too many stories in progress or your testers from testing too much. It's similar to velocity for moving items from your product backlog into your sprint backlog, but within a sprint.

I would approach the problem by having your tasks be the user stories, with your user stories moving from the product backlog to the sprint backlog to the in progress bucket to the ready for QA bucket to the finished bucket. After the developer finishes the story (based on your definition of finished), he would move it into the "ready for QA" bucket where the next person would pull it out and work on it. If there are any problems with it, a defect would be entered in your tracking system and the user story would be moved into the finished bucket since it's been implemented and tested. If there are no problems with it, it moves right into the finished bucket.

When the defect comes from within your sprint, there's no problem with putting it back into the sprint backlog (or perhaps some kind of "in progress" bucket). A story with known defects is usually considered to be unfinished. If it's determined that there's insufficient time to finish the story or the defects are attributed to not understanding the story, an option might be to descope it from the sprint entirely until you can better understand the need - in this case, I'd recommend not including the defective implementation in your released product.

If, due to your defect, the story doesn't get finished in your sprint, this will come out in your velocity calculations for future sprints. Unfinished stories (defective stories) don't get you any story points, so you'll plan for smaller sprints. Fewer complex stories will lead to more time in testing and will encourage you to spent more effort finding defects early - preventing defects is not only cheaper, but takes less time than the sum of the time spent to identify that a problem exists, find the problem in the design or implementation, fix the problem, and retest to ensure the problem has been solved without any other negative impacts on the system. Since the timebox is key, the ability to prevent defects leads to more productive sprints in the future.

Regardless of what you do, you should involve the Product Owner (who is hopefully a customer/user representative) when it comes to deciding how to prioritize defects. Some defects might be acceptable to be put into a release if there are workarounds or they are rare, meaning the defect would show up as a story in a future sprint. Other defects might be urgent and "showstoppers" - these must be addressed immediately and a product can't be used if they exist.

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

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


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

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

Need agreement on scheduling of staff

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

etc...

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

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

答:
A few things that you might want to consider:

Making sure that there is one person (you!) as a 'gatekeeper' for projects and priorities.

The hardest part of the shared unit is defining priority - that's something that you'll want to openly talk about not with the open group, but with management.  Not every task is equal, and not every task is of equal priority to the organization.  (i.e. if there is an issue of setting up an online sales portal versus a reporting system for HR - the sales portal would likely come first.)

Buy some quality fire-treated clothing.  The seat might get hot from time to time.  :-)


答:
Programmers are not coffee mugs!

Coffee mugs, furniture, laptops, and sometimes even labor can be shared between departments, units or team. And I bet, coffee mugs wont crib or fail. It's just that sharing programmers, while good and possible is not that straight forward.

There is nothing wrong with regards to sharing. The trouble is not really about two different departments who are trying to share. The issues are usually with the programmers who face constant change.

Here is what you might want to consider:

The time slices and thrashing. -
Just dividing number of hours (or even worse minutes) of time slices for the person to shift around the jobs makes the programmers exponentially unproductive as the overall slices go smaller. Specifically I would prefer to work on at least a week long switch, sometimes at least a few days at a time -but definitely it will limit

The familiarity and dependency.

The familiarity of domain and problem and dependency on others is what make or breaks many software projects than the ingenious skills of programmers. You may give freedom to the programmer when will he work on the (do coding and testing) of second project- but when you need to meet other team members, attend meetings that does brain storming and decision making about requirements, project management, customer interaction - all this cann't be really done in isolation and you might just get contesting between the meetings.

Scope & responsibility
What is very important really is how do you want to borrow the programmer - do you just expect some guidance or consultation? or is he/she expected to write some independent code; or he/she going to participate in interactive process be it requirements, design or integration? Who is going to maintain

Last but most important -
It may not always the case, but different teams have different ways of approaching to solutions, different types of coding; some team's customers put high significance on timeline where as some will expect absolutely bug free software. Working on different project makes you adapt to some of this factor. However, when you are constantly switching between to different types of projects it takes a toll!

Having said that, it is always visible sometimes that optimizing projects by exchanging resources is important and quite often. But ultimately it boils down to the capacity and capability of the individuals who are shared.

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

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

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

Need agreement on scheduling of staff

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

etc...

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

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


问:
Strategy to find bottleneck in a network
Our enterprise is having some problem when the number of incoming request goes beyond a certain amount.

To make things simpler, we have N websites that uses, amongst other, a local web service. This service is hosted by IIS, and it's a .NET 4.0 (C#) application executed in a farm. It's REST-oriented, built around OpenRasta.

As already mentioned, by stress testing it with JMeter, we've found that beyond a certain amount of request the service's performance drop.

Anyway, this service is, amongst other, a client itself of other 3 distinct web services and also a client for a DB server, so it's not very clear what really is the culprit of this abrupt decay. In turn, these 3 other web services are installed in our farm too, and client of other DB servers (and services, possibly, that are out of my team control).

What strategy do you suggest to try to locate where the bottleneck(s) are? Do you have any high-level suggestions?

答:
In performance diagnostics and tuning there are no easy answers. Every component is suspect and be careful what assumptions you make. In my experience 95% of the problem were our assumptions.

From your description my wild guess is you have a pool problem. Check the connection and worker pools for your databases and web services. Check their size and more importantly if db connections are not being closed. Pool size might be a better question over on serverfault

Some easy steps are checking network links, cables and port speeds. The basic Windows task manager can tell you a lot about a server and the cpu + memory use of each process (you need to set the options to show the extra statistics)

Story: we too used Jmeter and found a mysterious performance problem. The test servers were only 50% utilized but transactions were stuck at a specific rate. 2 days later we discovered the NIC in Jmeter box was running at 100Mb and not gigabit.


答:
Time allocation, scheduling, procedures, etc. is just administrative work. It's a necessary evil. What is more important is the intent.

Usually, the productivity of developers is proportional to their expertise (of a particular project and technology). The more they stay focused on a project, the better they know it, the more efficient they become.

By pooling/sharing them among several, you loose this productivity. But there may be a reason to do so: transfer of knowledge. You sacrifice your own productivity to teach/help/assist others for them to become more familiar with a technology, hence more productive. This can have very good results as learning is a time consuming activity, and a mentor is very useful, especially for sparsely documented projects or technologies.

However, if they think like "the deadline is next week, let's add N developers to it!" they are doomed. Indeed, developers are not interchangeable pieces. Even worse, adding developers at the end of a project may hinder it more than help, delaying it even further.


问:
Is there tool agnostic terminology for source control activities?
My team is entering into some discussions on source control (process and possibly tools) and we would like a tool agnostic terminology for the various activities. The environment does have multiple (old) VCS's, and multiple desired (new) VCS's. Is there a standard definition of activities, or at least some commonly accepted set?

Example activities (in CVS terminology):

Branch

Check out

Update

Merge

答:
Just (learn and) use Git's terminology. Git is the current gold standard of vcs. If a feature doesn't exist in Git, use the word from whatever system it exists in.

edit for pedantry:
There is of course a subset of terminology that has the same meaning in several tools. I think defining that subset is subjective and somewhat meaningless, it's much better to learn about Git and use Git's terminology. So the answer to your question is yes and no.


问:
How can I track programming productivity on a daily basis?
How can I track that I'm developing software more or less productive than the previous days? </p>

答: Measure the time it takes from you sit down at your computer in the morning until you do any non-work-related activity, such as 9gag, facebook, reddit, etc. Your productivity that day is proportional to that number.</p>