答:
On the contrary, creating a potentially shippable product is the very definition of agile, both the lowercase and uppercase varieties.

Working in cycles or iterations but not producing anything shippable at the end of it is essentially what most people in the business call water-scrum-fall. It's a kind of cargo cult, following the motions and rituals of some Agile methodology without actually being, well, agile.

If "agile" does not mean "ability to ship at (almost) any time", then what good is it? If you say that your team is agile, you are communicating to the business that you are able to respond to changes to requirements or to the business environment in general. But if you can't actually ship anything, then how are you "responding" to that change? If you can't ship, then all you are really telling the business is "we won't complain too loudly when you change your mind", which is a lie of omission when they think they're hearing "we can deliver whatever you need, whenever you need it".

I can't find the link anymore, but Microsoft recently did a case study on this. There was a team that converted to some sort of cycle/increment-based Agile methodology and relied on frequent product demos to show progress, but when management said "OK, we're ready, release it" it turned out that the team wasn't actually "done" with any of the work they'd demoed. There were hundreds of critical bugs that had to be fixed, data migration that needed to be performed, validation and security requirements, and so on and so forth. And when all was said and done, it took something like 6 more months to actually get it ready to ship.

My team had a similar experience last year, during which I was the lead and learned my lesson pretty well. Oh, I was obsessive about quality, and so we really were done according to our definition of done. But, as it turned out, a ton of mostly-unpredictable faults happened when we finally hit the staging environment, and it took almost two more months before we were able to go from "done" to "shipped". The business was fairly understanding, considering the size and importance of the product, but it was stressful as hell for those of us essentially getting no "real" work done for two months, and during those two months the business could potentially have been bringing in revenue on a perhaps less complete, less polished, but still shippable product.

The idea of bringing pain forward is at the heart of Continuous Integration. CI says that if integration is hard and expensive, you should do it today, not tomorrow or next week, because the total theoretical amount of effort required to integrate is the same whether you do it as a series of 10-minute interruptions or one 10-day death march. Not only that, but in practice, it actually costs more to integrate later, because individual contributors/teams are able to diverge from each other much more (intentionally or unintentionally) between monthly integrations than they would be between daily integrations, and the higher number of risky or potentially destructive changes means a higher percentage of time spent on just debugging. So, smart teams use CI, and not just in the sense of having a build server but in the sense of forcing everyone to either commit directly to the mainline or integrate with it every day, and deploy to a shared environment every day (or every hour, or whatever).

But CI is a beginning, not an end. CI is for the dev team; it doesn't help the business at all. Just because you got something working in CI doesn't mean it's shippable. And all of the problems with delayed integration that CI aims to solve have technical or business counterparts when production releases are delayed for too long. There's a risk that the dev team has diverged very far from the product requirements, or that the CI infrastructure/environment has diverged very far from production. The only way to minimize that risk is to ship often, which is what "continuous delivery" practices aim to solve, by extending the CI pipeline to include end-to-end test automation, infrastructure automation, and release automation.

You don't have to automate everything; plenty of teams scrape by with manual QA and deployments. But they maybe manage bi-monthly releases, or monthly if they're lucky. That's nowhere near as agile as some companies.

When I hear the word agile, I think of companies like Amazon, Facebook, or Google. It's easy to be agile when your product is only 500 lines of code and you don't have to do much testing, but the real test is when you're managing sprawling products with millions of lines of code and hundreds or thousands of developers. Facebook releases twice a day. Google sometimes releases the same product a few times in the same week. Amazon is on record as releasing something every 11.6 seconds (2011 statistic), although I think Amazon is a bit of a special case because they aren't actually releasing the same thing each time, their architecture is massively service-oriented and distributed.

Simply put, if you can't basically push a button to release shortly after the end of an iteration, then you aren't agile. Being able to respond to changes in or from the business means that you can ship. The business doesn't care that you can start working on something else at the beginning of each iteration, they care if you can deliver what you worked on at the end of it.

N.B. Things like "writing tests" and "polishing the UI design" should happen during the iteration, not at the end of it! Most agile teams have a "definition of done" and those things are very, very high on the list of priorities. I don't even consider that part of shipping, that's fundamental product work that is very dangerous to defer. You're not even close to being agile if those things aren't done at the end of a sprint/iteration/whatever. If you're having trouble completing those things on time, you may need to revisit your team structure - it's a common problem in manufacturing-style teams where developers, designers, testers, and infrastructure are all treated as different teams and separated by literal or metaphorical walls. This is a terrible model but some companies still use it because there's too much bureaucracy or simply too much stubbornness to reorganize.


问:
Does producing potentially shippable product make you less agile?
The cost of developing a feature in Agile is very high because it needs to be ready for shipment.
It includes:

Significant bug fixing

Writing/updating and executing tests

Writing/updating the user manual

Polishing the UI design (placement of controls, color schemes, etc...)

Updating the documents for FDA (in our organization)

When the cost is that high you are less likely to change the feature once you implement it. So does it make your less agile?

答:
If you define "potentially shippable product" as a product that can be taken into production and shipped to the end-user without further work, then there can be situations where producing a potentially shippable product each sprint can create a insurmountable burden.

To use my current situation as an example (in the medical field, so strongly regulated), for an official release, we need about two weeks of manual (regression) testing on a single stable version. This testing can not be automated, because it involves measurements on a human body. In this case, doing a full regression test each sprint is not effective, as it would consume the majority of the sprint.

We are not doing agile, but I am considering to propose it, with the following 'adaptations' from the "textbook implementation":

A "potentially shippable product" means that the product is ready for a (final) formal verification test, where the developers have high confidence that no major issues will be found in either the product or the test cases.

Documentation is kept up-to-date, but not officially signed off for release until the decision falls to actually ship the product. The same goes for all the regulatory paperwork.

When the decision to ship comes, there should be no need to perform any rework on either UI, code or documentation.

ContentLicense: CC BY-SA 3.0


问:
Is there anyone who has used Python/Ruby and PHP for a long time and still prefer PHP?
I am usually fascinated by articles defending PHP and the arguments being used. Quite often authors of these types of articles don't mention what experience they have with other languages. Personally I find it hard to imagine that somebody would know either Python or Ruby, and PHP at a high level and still prefer PHP.

So if anyone fits this description, I would be interested in hearing why you prefer PHP to either of these languages.

答:
I know both Ruby and Python far, far better than I do PHP, and I prefer PHP for the incredibly mundane web programming tasks I occasionally have to do. The server supports it, I can hack together solutions without having any idea why what I'm doing is working, and I can test it easily using a MAMP server with minimal setup. PHP provides quick and dirty solutions to simple problems.*

This is a statement of personal experience, not a value judgement about any language, designer, or developer.

ContentLicense: CC BY-SA 2.5


问:
Passing around impl-specific tokens in generic algorithms in a static/strong type system
I was interested in solving several unrelated problems using generic graph search techniques, so after some fiddling around I came up with the following design: have each problem implement a generic "Problem" interface which has an initial state, and several methods that take in states and moves, and return new states and moves. For example, I can getMoves(state), applyMove(state, move), or check isGoal(state). All of the problem specific details are then in one place, and the generic algorithms can pass around states and moves as generic "tokens" that they don't really care about, using the Problem instance to evaluate their properties. The Problems are also consequently stateless (or what state they have is immutable), which makes their behaviour very easy to reason about.

This was all fine and good in a dynamic/duck type system (JavaScript), but in migrating the idea to a static/strict type system (Java), I've run into some issues.

The most immediate problem was that these "tokens" could really be anything. Arrays, objects, maps, strings, whatever. Javascript didn't care, because the algorithms just passed them around as black-boxes, and the Problems assumed they were being given their own tokens. In Java this is not the case. The first most natural solution is to have all the "tokens" implement some empty State or Move interface. This already has some problems, as if my state is just some data structure, then I need to extend or wrap the structure, but that's basically fine.

The next problem is that the tokens are implementation specific, so every time they're given to the Problem, they need to be cast into what they actually are. Lots of casting strikes me as a red flag, so this seems like a bad (certainly unpleasant) approach.

To avoid all the casting, I briefly considered something involving tons of templates (State<ChessProblem>, Move<ChessProblem>), but that seemed like a headache which might not even fix the problem.

Is there some "proper"/standard way to accomplish this in stricter type systems? Is this just a bad pattern to use in them (or a bad pattern overall)? Any insights would be appreciated. Also, while I am using Java, if other static/strict languages have novel tools for this sort of thing, I'd love to hear about them.

答:
I think you're almost there. Instead of having the States being generic, I would change the definitions of Problems. I assume you are currently thinking of something like this:

interface State {
}

interface Problem {
    public State foo(State s);
}

class ConcreteState implements State {
    ...
}

class ConcreteProblem implements Problem {
    // cannot narrow the argument type due to LSP
    @Override
    public ConcreteState foo(State s) {
        ConcreteState state = (ConcreteState) s;
        ...
        return state;
    }
}
```

<p>We now make the <code>Problem</code> interface generic, and obtain the following:</p>

<pre class="lang-java prettyprint-override"><code>interface State {
}

interface Problem<S extends State> {
    public S foo(S s);
}

class ConcreteState implements State {
    ...
}

class ConcreteProblem implements Problem<ConcreteState> {
    @Override
    public ConcreteState foo(ConcreteState s) {
        ...
    }
}
</code>```

For full benefits, care has to be taken that the State does not leave the Problem, e.g. by storing it externally. This means that the Problem should probably also be used as a State-factory.

Body:
I think you're almost there. Instead of having the States being generic, I would change the definitions of Problems. I assume you are currently thinking of something like this:

interface State {
}

interface Problem {
    public State foo(State s);
}

class ConcreteState implements State {
    ...
}

class ConcreteProblem implements Problem {
    // cannot narrow the argument type due to LSP
    @Override
    public ConcreteState foo(State s) {
        ConcreteState state = (ConcreteState) s;
        ...
        return state;
    }
}

We now make the Problem interface generic, and obtain the following:

interface State {
}

interface Problem<S extends State> {
    public S foo(S s);
}

class ConcreteState implements State {
    ...
}

class ConcreteProblem implements Problem<ConcreteState> {
    @Override
    public ConcreteState foo(ConcreteState s) {
        ...
    }
}

For full benefits, care has to be taken that the State does not leave the Problem, e.g. by storing it externally. This means that the Problem should probably also be used as a State-factory.


问:
Programmer performance
I am a PHP programmer with 1 year of experience. As I am just starting my career, I am learning a lot of things now. I can say I am a little bit of a perfectionist.

When I am assigned a problem I start off by Googling. Then, even when I find a solution, I keep trying for a better one until I find 2-3 options. Then I start learning it and choose the best performing solution.

Even though I am learning a lot, this process gets me labeled as a low performer.

My questions:

As a novice, should I continue to use this learning process and not worry about my performance?

Should I focus more on my performance and less on how the code performs?

答:
You said that although you were "learning a lot, this process gets you labeled a poor performer."

You are measuring your own performance in one way, and your employers are measuring it in another. Determine the difference, and determine whether or not you care. If you feel like being labeled a poor performer doesn't matter to you compared to your learning, then ignore them. If being labeled a poor performer matters to you, convince them that your learning is a more valuable measure of your performance, or improve via the performance measures they're suggesting.

However, consider this:

Maybe you aren't learning as much as you think you are. Can you produce better code now than you could a year ago? Or are you relying on Google to solve the same problems that you did back then?

The way to get better at anything is to practice doing it, and the process you've described is practice Googling code snippets, not practice programming.  Certainly, searching for similarly solved solutions is an aspect of the work of programming, but the core of programming is problem solving by producing code.

Title: Programmer performance


问:
What are the advantages of pass by value?
I always thought pass by value is a legacy from the early languages, because the designers had never seen anything else. But after seeing the brand new languages like Go adapting the same principle confused me.

The only advantage I can think of is you make sure that the value you are passing won't be modified. But every time you need to pass a big structure to a function, you need to pass the pointer (or reference) to prevent copying, if the language permits it.

To prevent modification of parameters, some constness mechanism could be introduced instead of making the whole language pass by value.

I have been coding for years and I rarely needed to pass by value. Almost always, I don't need my value/object to be copied to a function call; and often I don't need it to be modified inside the function*.

What is the motivation behind making modern languages pass by value? Are there any advantages that I am not aware of?

Edit: When I say pass by value, I don't mean primitives. They are easy and cheap to pass by value. My main focus is objects or structs that consists of more than 1 primitive and thus expensive to copy.

*: I have asked around and others reported similar thing with their parameter usage.

答:
Pass-by-reference makes some things more efficient and allows updates to parameters within subroutines, but it is by no means a panacea.

Imagine a parallelized application. When using pass-by-reference, then you need a locking mechanism to keep a sane state. Pass-by-value doesn't have this limitation. I've seen multi-threaded programs which spend more time waiting for mutexes than processing data. Here pass-by-value can be a big efficiency gain.

Imagine a distributed application. This is always pass-by-value, because the remote system needs its own copy of the object. Pass-by-reference must be simulated using proxy objects. It requires extra network overhead to keep the proxy objects in sync. Here pass-by-value save not only processing time, but reduces network bandwidth.


问:
Refreshing website design and architecture
I have a website that is build with asp.net web forms. I would like to refresh design (using css, html5, responsive design) and also change it from web forms to asp.net MVC.

To me this is more of a frontend project. Since there is already existing backend, it is "only" necessary to reuse it in MVC.

Should I first start with design update or MVC? This project if far more easier, than starting a new website from the start, or am I mistaken?

答: Start with the task that adds the most value to the stakeholders (or users). If the site is difficult to maintain, and/or there are large backend changes coming up soon, then work on the backend first. If the users would benefit greatly from a redesign and the backend is not likely to change anytime soon, then start with that first.</p>


答:
MVC, Webforms to me are very different in terms of design patterns. If the site was done well with webforms, then I would think you need to refactor backend logic since there could be a lot of logic done by webform controls like grid. You need to rewrite the logic here and authentication.

Again, it still depends on how good you are expecting the site, you still could use a lot controls in View which is bad, but you can do it, so totally depends on what you want.

Conclusion, if you want to have a good quality website using MVC pattern, you should go to check your Models (business logic) first, then apply the MVC concepts on them; if you just want to complete you task, you can go straight to use existing logic as much as you can in MVC, making changes only if it doesn't work.

Title: Refreshing website design and architecture

Body:
I have a website that is build with asp.net web forms. I would like to refresh design (using css, html5, responsive design) and also change it from web forms to asp.net MVC.

To me this is more of a frontend project. Since there is already existing backend, it is "only" necessary to reuse it in MVC.

Should I first start with design update or MVC? This project if far more easier, than starting a new website from the start, or am I mistaken?


问:
Which statement performs best?
I was faced with this question by my team leader.

Statement 1 (written by me):

```<code>lnkbtn1.visible = lnkbtn2.visible = lnkbtn.visible = false;
</code>```

Statement 2 (written by my team leader):

```<code>lnkbtn1.visible = false;
lnkbtn2.visible = false;
lnkbtn3.visible = false;
</code>```

Which statement is better and why?

答:
What about a more DRY version, where even the code visible =is not repeated over and over again?

```<code> foreach(var btn in new[]{lnkbtn1, lnkbtn2, lnkbtn3})
     btn.visible=false;
</code>```

IMHO that will scale better when the number of buttons increase, or the number of properties of each button which has to be initialized increases.

Title: Which statement performs best?

Body:
What about a more DRY version, where even the code visible =is not repeated over and over again?

 foreach(var btn in new[]{lnkbtn1, lnkbtn2, lnkbtn3})
     btn.visible=false;

IMHO that will scale better when the number of buttons increase, or the number of properties of each button which has to be initialized increases.


问:
How do you deal with time estimates?
If given too little time, quality suffers. If given too much time, developers will find a way to use all alloted time, no matter what. What would be a good way with dealing with estimates? Are they a necessary evil?</p>

答: A completed project is not a set of code.  A completed project is a set of code at a specific point in time.  If your customers/users don't care about when they get the code, then it's probably not very important.</p>

Title: How do you deal with time estimates?


问:
Forked a project, where do my version numbers start?
I have forked a project and have changed lots of it. This fork isn't just a small feature change here and a buried bug fix there, its a pretty substantial change. Only most of the core code is shared.

I forked this project at v2.5.0.  For a while I've started versioning my fork at v3.0 . However I'm not sure if this is the right way, mainly because when that project hits v3.0, things get confusing. But I don't want to start over at v1.0 or v0.1 because that implies infancy, instability, and non-refindness of a project. This isn't true, as most of the core code is very refined and stable.

I'm really lost on what to do, so I ask here: Whats the standard way to deal with this kind of situation? Do most forks start over again, bump up version numbers, or do something else that I'm not aware of.

答:
0.1 may indicate infancy,
but verion 1.0+ means stable.
A increase in major version numbers eg 2.0, 3.0, generally indicated a large feature change.

Eg

Version 1.0 of my application was a tool for running test scripts with setup,

Version 2.0 removed the differentiation between test scripts and environment setup scripts,

Version 3.0 added a GUI for writing scripts as flow charts.
They are recognisably different products, but even Version 1 was a working product, completely stable etc. Versions 2 and 3 came about because it was decided these big changes would be good. If we hadn't have wanted these big changes, and had have just continued doing bug fixes etc. Minor version numbers would have just increased, 1.10,1.20 etc, and that would have been fine.

What I am saying is major version numbers don't indicated maturity, they indicate major feature sets.
Now that was a bit of a tangent from how to version number your product.

What I've seen before, which I quiet liked was
start versioning again from 1.0 (or from 3.0 if you really prefer)
and then in brackets saying which version of the original it last had features pulled from.

Initially:"  MyFork v1.1 (based on OrigProg v3.0)

Some improvenets made to MyFork: MyFork v1.3 (based on OrigProg v3.0)

OrigProg released a major version and MyFork pulled and merged: MyFork v2.1 (based on OrigProg v4.0)

Made some major changes to MyFork (probably won't be be able to easily merge with OrigProg ever again): MyFork v3.0 (based on OrigProg v4.0)


问:
Looking for a specific type of artificial intelligence
I am looking to create a challenging AI project.

There is an online card game that allows you to build a deck to play with out of randomly presented cards. You have to choose one each time out of a couple of cards. I want to build an AI that picks the cards as I would pick them myself using my knowledge of the game.

My guess is that I would have to create a system that can be trained based on "experience" (taught by training) and adapts its choices based on which previous cards it has already selected.

I am looking for the specific name for this type of AI so I can start finding some resources for it or similar projects if you know any.

答:
I believe the General term that you are looking for is Reinforcement Learning: http://en.wikipedia.org/wiki/Reinforcement_learning. A popular model free form of this is called Q Learning.

A recent example usage of this was to beat that incredibly difficult FlappyBird game: http://sarvagyavaish.github.io/FlappyBirdRL/


问:
Can I get sued over duplicating another program's UI?
If I see something I like in another application, and create something similar from the ground up in a commercial product, could I get sued over it?

Of course it would be styled to look differently, however most of the functionality would be the same since the functionality is what I liked about it. It also would not be the entire system, just a part of one.

I live in the US.

答:
If the User Interface includes graphical assets, such as something done by a professional designer, then yes, you may get sued for copyright infringement.

If you're laying out a treeview and a grid control in a manner similar to Microsoft Outlook, I doubt anyone will care/notice.

However, the manner of laying out data may be protected since that is a work of art.  Take for example the grid used in TV Guide.  Anyone who puts TV shows in that grid format is required to pay a fee, otherwise they need to pay the patent holder.


问:
Is there a practical use from learning Brainfuck?
Brainfuck is an esoteric programming language created in 1993 by Urban Müller.
It was designed to challenge and amuse programmers, and was not made to be suitable for practical use.

But still, it exists and some really cool stuff is written with it.

My question is - will learning/practicing Brainfuck increase the depth of my knowledge of programming? For example: as a high-level programmer (using high-level languages) will it improve understanding of low-level methods and operations? Or is it really just a joke used to spend some time and amuse by showing code that really looks like "code" in a sense that's it's hard to read/understand.

答:
Brainfuck (and number of other esolangs, my favorite is FRACTRAN) take you down to the very basics of computing and the nature of storing state, and looping.

It might be more useful to work on something a bit easier to think of with a less objectionable name such as a Minsky register machine.  If you look at the Wolfram Mathworld article on register machines you will likely see a strong relationship with BrainFuck.

By understanding how programs in these languages work (and many of them are Turing complete) you may get a better idea about the nature of computation and Big O.

The fundamentals of how to write a program in esolangs make the fundamentals of computing a bit more clear... or murky, but through their murkiness shine a light on other aspects of the fundamentals that are forgotten in the higher level languages.


问:
Exceptions catching clutter code and make it hard to read
When I read well written code that checks to make sure all the input is of the correct format and type, and also catches all the things that possibly could go wrong, I find it difficult to understand the core of what the program is doing. It seems protection against the non-normal  case obscures the normal case.

This includes beginning and ending of array special cases, try-catch, using, handling null, 0, "", and all the other strange things.

How can I write code that is clear, but isn't cluttered by non-normal events??

To make this a little more concrete, how can I do this in C#?

答:
There's three specific things I do in my code to deal with this problem:

Early return/break/continue

Although a number of people frown on this as being "like a goto", it helps clear up your code a lot.  When you have a test that detects an exceptional condition, handle the condition and get out of the method you're in, instead of cluttering your method up with a huge if/else.

Break your code into chunks of meaningful normal execution, surrounded by try...catch blocks

When you have a piece of code that could possibly throw an exception, instead of dealing with the exception immediately, put all the code that could meaningfully be associated with the risky code inside the try...catch block.  That way, the block reads as a meaningful chunk of code.  In some ways this is the opposite of the first suggestion, but it's dealing with thrown exceptions instead of boolean conditions.

Move exception throwing code into a separate method, so that exceptions are dealt with in one method and the risky code is run in another

This is just an extreme version of the second recommendation.  If the normal flow of logic is big enough to justify it, move it into a separate method and call that method from inside a try...catch block.  This can also help when you have several layers of error checking, by separating the layers you can make it easier to read the code.

How these suggestions are applied on depends on what the code allows you to do.  I'm also writing from the point of view of a Java programmer; I don't know if there are other mechanisms in C# that would help as well.


问:
Greenspun's Tenth Rule, does every large project include a Lisp interpreter?
Greenspun's tenth rule (actually the only rule) states that:

Any sufficiently complicated C or Fortran program contains an ad hoc, informally-specified, bug-ridden, slow implementation of half of Common Lisp.

My memory is that there are some papers on the topic, perhaps for Borland's Quattro (spreadsheet) project and possibly others.  Google is unhelpful, maybe the right search terms are not coming to mind.  I am looking for papers or articles supporting this claim, if any.

答:
The rule could probably be more accurately (and less amusingly) as "every large software based system will be required to implement dynamic behavior".

This can be done in two ways-

A large complex configuration file with dozens of parameter and hundreds of definitions.

An AD-HOC script language.

"sendmail" is probably the canonical example of type "1". I cannot think of any good examples of type "2" that do not involve embedding a "real" scripting language a la Warcraft/LUA or even Netscape/Javascript.

The problem is for a few parameters its quick and simple to do it with a config file, but, this solution does not really scale. However at no point will it be economical to dump the config file in favour of a script approach when adding one or two options to the config file. So the code that interprets the config file just ends up being a really badly written interpreter.


问:
What's a nice explanation for pointers?
In your own studies (on your own, or for a class) did you have an "ah ha" moment when you finally, really understood pointers? Do you have an explanation you use for beginner programmers that seems particularly effective?

For example, when beginners first encounter pointers in C, they might just add &s and *s until it compiles (as I myself once did). Maybe it was a picture, or a really well motivated example, that made pointers "click" for you or your student. What was it, and what did you try before that didn't seem to work? Were any topics prerequisites (e.g. structs, or arrays)?

In other words, what was necessary to understand the meaning of &s and *, when you could use them with confidence? Learning the syntax and terminology or the use cases isn't enough, at some point the idea needs to be internalized.

Update: I really like the answers so far; please keep them coming. There are a lot of great perspectives here, but I think many are good explanations/slogans for ourselves after we've internalized the concept. I'm looking for the detailed contexts and circumstances when it dawned on you.

For example:

I only somewhat understood pointers
  syntactically in C. I heard two of my
  friends explaining pointers to another
  friend, who asked why a struct was
  passed with a pointer. The first
  friend talked about how it needed to
  be referenced and modified, but it was
  just a short comment from the other
  friend where it hit me: "It's also
  more efficient." Passing 4 bytes
  instead of 16 bytes was the final
  conceptual shift I needed.

答:
My "aha!" moment came in this tutorial:

A Tutorial on Pointers and Arrays in C

To be exact, it came in this chapter: Chapter 3: Pointers and Strings

To be even more precise, it came with this sentence:

The parameter passed to puts() is a
  pointer, that is the value of a
  pointer (since all parameters in C are
  passed by value), and the value of a
  pointer is the address to which it
  points, or, simply, an address.

When I read that, the clouds parted and angels blew trumpet fanfares.

For, you see, every C tutorial or book I'd read prior to that had asserted that C could pass by value or by reference, a nefarious lie.  The truth is that C always passes by value, but sometimes the value passed happens to be an address.  Within the method, a copy is made of that address, just like a copy would be made of an int passed in.  A copy is not made of the value to which the pointer points.  Thus by using the pointer within the method you can access the original value and change it.

I never became a C programmer, but I became a .NET programmer, and objects and object references work the same way; the reference to the object is passed by value (and thus copied), but the object itself isn't copied.  I've worked around many programmers who don't understand this because they never learned pointers.

Title: What's a nice explanation for pointers?


问:
Logging in a distributed system
We have several application servers (and different applications) running on Amazon AWS and our main method of logging is a combination of statsd, carbon/graphite, and an alert system based off of the metrics coming into carbon.  This has been working great for a lot of different situations but I feel we need something else to complement this type of logging.  Something that is not as much for streaming or visualization like graphite, but allows easy lookup by time/date, error type, etc...  What are some techniques that make reviewing your logs quick and effective?
My initial thought is to UDP all logging messages to a central server and insert them into a database (likely MongoDB).  Is this a reasonable approach?</p>

答:
I think you're on the right track. You could centralize logging to a central server and then have logstash consume the logs and store everything in elastic search. Then, you can use Kibana to search / lookup, etc. It's a good complement to statsD+graphite.

http://logstash.net

http://www.elasticsearch.org

http://www.elasticsearch.org/overview/kibana/

Title: Logging in a distributed system


问:
Stopping spiders or unauthorised users from viewing files
I am stumped at this problem.

Users authenticate at my client's website. Then the users see their profile page on my client's website. My client now wants me to provide a URL on their profile page, for his users, to download information from an external website. (This external website is not controlled by my client). That is to say, upon clicking this URL, it links out to an external website and gets a personalized file.

As the information is considered sensitive (not critical), the external website should not allow anyone to download the personalized file.

I'm stumped at figuring out how to allow only one authentication (on my client's website) instead of having the end users authenticating twice (once on my client's website and separately on the external website)

Any ideas?

答:
Pre-signed URLs may be of help. When a user authenticate on one website, the website can query the other website for a pre-signed URL which doesn't need authentication as the main website has already done that.

We are using this feature with amazon.


问:
Microeconomical simulation: coordination/planning between self-interested trading agents
In a typical perfect-information strategy game like Chess, an agent can calculate its best move by searching the state tree for the best possible move, while assuming that the opponent will also make the best possible move (i.e. Mini-max).

I would like to use this approach in a "game" modeling economic activity, where the possible "moves" would be to buy or sell for a given price, and the goal, rather than a specific class of states (e.g. Checkmate), would be to maximize some function F of the agent's state (e.g. F(money, widget) = 10*money + widget).

How to handle buy/sell actions that require coordination between both parties, at the very least agreement upon a price?

The cheap way out would be to set the price beforehand, maybe based upon the current supply -- but the idea of this simulation is to examine how prices emerge when freely determined by "perfectly rational" agents.

A great example of what I do not want is the trading algorithm in SugarScape -- paraphrasing from Growing Artificial Societies p101-102:

when a pair of agents interact to trade, they each compute their internal valuations of the goods, then a bargaining process is conducted and a price is agreed to. If this price makes both agents better off, they complete the transaction

The protocol itself is beautiful, but what it cannot capture (as far as I can tell) is the ability for an agent to pay more than it might otherwise for a good, because it knows that it can sell it for even more at a later date -- what appears to be called "strategic thinking" in this pape at Google Books Multi-Agent-Based Simulation III: 4th International Workshop, MABS 2003... to get realistic behavior like that, it seems one would either (1) have to build an outrageously-complex internal valuation system which could at best only cover situations that were planned for at compile-time, or otherwise (2) have some mechanism to search the state tree... which would require some way of planning future trades.

Note: The chess analogy only works as far as the state-space search goes; the simulation isn't intended to be "zero sum", so a literal mini-max search wouldn't be appropriate -- and ideally, it should work with more than two agents.

答:
Naive answer:

You can't really simulate agents in same way you would play chess. Simply because the "game" depends heavily on external influence than on players themselves. This all comes down to knowledge. If agent knows from some source the price will go up in the future, it might do something in the present to help itself. Actually, in multi-agent simulations theory, the notion of agent's knowledge is extremely important part. Especially if agent doesn't have full knowledge about whole environment and this knowledge cannot be perfectly trusted. So the agent's goal would be to gather and confirm this knowledge and calculate good's future value based on this knowledge. And getting this knowledge is the hard part, because predicting future isn't really what neither humans nor computers are good at.


答: Unless you have direct access to the external site or some kind of agreement with whoever maintains the site this is an unsolvable problem. You need to pass on some kind of token to the external site to let them know it is OK to access whatever sensitive information you are trying to access and this requires some kind of coordination between the two sides. Moreover, whatever protocol you design needs to follow proper security practices. This is not a simple undertaking and is one of the many reasons protocols like OAuth exist.</p>

Title: Stopping spiders or unauthorised users from viewing files

Body:
I am stumped at this problem.

Users authenticate at my client's website. Then the users see their profile page on my client's website. My client now wants me to provide a URL on their profile page, for his users, to download information from an external website. (This external website is not controlled by my client). That is to say, upon clicking this URL, it links out to an external website and gets a personalized file.

As the information is considered sensitive (not critical), the external website should not allow anyone to download the personalized file.

I'm stumped at figuring out how to allow only one authentication (on my client's website) instead of having the end users authenticating twice (once on my client's website and separately on the external website)

Any ideas?


问:
An alternative to an array of functions?
I'm programming an app (php) which requires a very long list of similar yet different functions, which are being called by a set of keys:

```<code>$functions = [
    "do this" => function() {
        // does this
    },
    "do that" => function() {
        // does that
    }
]
etc.
</code>```

I've chosen to place the similar functions in an array because they are not similar enough - getting the same result with one big function which is full of conditional statements isn't gonna work. And I do need to be able to call them only by key, for example:

```<code>$program = ["do this", "do that", "do this"];
foreach ($program as $k => $v) {
    $functions[$v]();
}
</code>```

Thing is this functions-array structure is causing many problems, for example I'm having a hard time calling one array function from within another array function, e.g. this doesn't work:

```<code>"do that" => function() {
    $functions["do this"]();
}
</code>```

nor this:

```<code>"do that" => function() {
    global $functions;
    $functions["do this"]();
}
</code>```

or this:

```<code>"do that" => function($functions) {
    $functions["do this"]();
}

$functions["do that"]($functions);
</code>```

I guess I could have one giant function with a long switch statement:

```<code>function similar_functions($key) {
    switch ($key) {
        case "do this":
            // does this
        break;
        case "do that":
            // does that
        break;
    }
}
</code>```

But that doens't really seem like good practice. Or maybe it is?

So, what are my alternatives? Should I go with the switch structure? Or is there another, better solution?

答:
You could create a class enclosing all your functions and then call them as object's methods</p>

```<code>class SimpleFunctions {

  public function doThis() {
    // Do this
  }

  public function doThat() {
    // Do that
  }

  public function doThisInThat() {
    // Do this in That
    $this->doThis();
  }
}

$funcs = ['doThis', 'doThat', 'doThisInThat'];
$simpleFunctions = new SimpleFunctions();
foreach($funcs as $f) {
  if(!method_exists($simpleFunctions, $f))
    throw new \Exception(sprintf("Method %s not found in %s", $f, get_class($simpleFunctions));

  $simpleFunctions->$f();
}
</code>```

Body:
You could create a class enclosing all your functions and then call them as object's methods

class SimpleFunctions {

  public function doThis() {
    // Do this
  }

  public function doThat() {
    // Do that
  }

  public function doThisInThat() {
    // Do this in That
    $this->doThis();
  }
}

$funcs = ['doThis', 'doThat', 'doThisInThat'];
$simpleFunctions = new SimpleFunctions();
foreach($funcs as $f) {
  if(!method_exists($simpleFunctions, $f))
    throw new \Exception(sprintf("Method %s not found in %s", $f, get_class($simpleFunctions));

  $simpleFunctions->$f();
}


问:
What is the purpose of red zone?
Red zone is a fixed size area in memory beyond the stack pointer that has not been "allocated". Compilers do generate assembly to access that area in simple leaf functions.

But I can't see any real advantages for red zone. Accessing memory beyond stack pointer is really dangerous and can easily lead to data corruption. Why even do this? Saving 2 processor instructions (push ebp; mov ebp esp) won't give real speed up.

答:
The red zone is, purely and simply, an optimization that can save instructions.
It means that it's no longer necessary for the emitted code for every function to subtract from the stack pointer to make local storage like so

```<code>sub XXX, %rsp
</code>```

at the beginning of every function call, even if they are not leaf functions. Often times the code emitted from the compiler can use the temporary space in the red zone below the stack pointer without needing to save it and before calling other functions. This is a useful optimization to have available.

If you no longer have to sub from the stack pointer, the emitted code can use rsp as the base pointer, a job normally reserved for rbp, and the emitted code can use rbp as another general purpose register.

This ultimately means the prologue and epilogue of each function call can save two instructions that would save and restore rbp:

(gnu assembler)

```<code>pushq %rbp       # prologue [ two instructions not necessary ]
movq %rsp,%rbp

.... [code]

movq %rbp,%rsp   # epilogue [ two instructions not necessary ]
popq %rbp
</code>```

Note that in gcc you can pass the -mno-red-zone flag if you don't want it (but the x86-64 ABI requires it). The Linux kernel does not need to be ABI compliant and thus all kernel code is compiled with -mno-red-zone.

Furthermore, accessing memory beyond the stack pointer is not dangerous if that is the expected mode of operation. It's only dangerous and can lead to corruption when it's unplanned, and unexpected. When the emitted code does it, it knows what it is doing.

ContentLicense: CC BY-SA 4.0

Title: What is the purpose of red zone?

Body:
The red zone is, purely and simply, an optimization that can save instructions.
It means that it's no longer necessary for the emitted code for every function to subtract from the stack pointer to make local storage like so

sub XXX, %rsp

at the beginning of every function call, even if they are not leaf functions. Often times the code emitted from the compiler can use the temporary space in the red zone below the stack pointer without needing to save it and before calling other functions. This is a useful optimization to have available.

If you no longer have to sub from the stack pointer, the emitted code can use rsp as the base pointer, a job normally reserved for rbp, and the emitted code can use rbp as another general purpose register.

This ultimately means the prologue and epilogue of each function call can save two instructions that would save and restore rbp:

(gnu assembler)

pushq %rbp       # prologue [ two instructions not necessary ]
movq %rsp,%rbp

.... [code]

movq %rbp,%rsp   # epilogue [ two instructions not necessary ]
popq %rbp

Note that in gcc you can pass the -mno-red-zone flag if you don't want it (but the x86-64 ABI requires it). The Linux kernel does not need to be ABI compliant and thus all kernel code is compiled with -mno-red-zone.

Furthermore, accessing memory beyond the stack pointer is not dangerous if that is the expected mode of operation. It's only dangerous and can lead to corruption when it's unplanned, and unexpected. When the emitted code does it, it knows what it is doing.


问:
Help With Dependency Injection
I am still very confused as to why and when to use Dependency Injection. If anyone could explain maybe using the below example that would be great, any other explanations would be appreciated.

Lets say I am creating a web-app that will save movie reviews written in C# with ASP.NET MVC 5. If I have the following Model code,

```<code>namespace MovieReviewProject.Models
    {
     public class MovieReviews
      {
        [Key]
        public int ReviewID_int{ get; set; }

        /// <summary>
        /// Submitter email address
        /// </summary>
        public string EmailAddress_str{ get; set; }

        /// <summary>
        /// Movie name
        /// </summary>
        public string MoveName_str{ get; set; }

        /// <summary>
        /// The review
        /// </summary>
        public string Review_str { get; set; }

        /// <summary>
        /// The submission date from
        /// </summary>
        public DateTime SubmissionDate_dt { get; set; }

        /// <summary>
        /// The movie rating
        /// </summary>
        public int Rating_int { get; set; }
    }
}
</code>```

how would a class that provides the Controller with the List of all the reviews, adds an average for a movie, and more look like?

I know that DI is mostly used to allow for easier unit testing but other than that what are the perks to it? Is it worth going through old projects and make sure all the providers are using this principal?

答:
For such a requirement, you can use a MovieReviewsRepository class with an interface IMovieReviewsRepository:

```<code> interface IMovieReviewsRepository
 {
      IEnumerable<MovieReview> GetAllReviews(int movieID);
 }
</code>```

In your controller, you can inject an IMovieReviewsRepository object through the constructor:

```<code> class MyReviewController
 {
       public MyReviewController(IMovieReviewsRepository repository)
       {
       }
 }
</code>```

Now you are free to implement the interface by a class MovieReviewsRepository providing the objects from a database, or by a class MovieReviewsRepositoryMock providing, for example, some hardcoded test data without any database access. This will make real unit testing possible. But it will also allow to exchange the source of your "movie review objects" to something completely different like a web service or a file without changing the controller, just by providing different IMovieReviewsRepository implementations

Of course, this approach could be generalized to lots of your model classes by making your repository a generic class, like it is shown here.

Title: Help With Dependency Injection

Body:
For such a requirement, you can use a MovieReviewsRepository class with an interface IMovieReviewsRepository:

 interface IMovieReviewsRepository
 {
      IEnumerable<MovieReview> GetAllReviews(int movieID);
 }

In your controller, you can inject an IMovieReviewsRepository object through the constructor:

 class MyReviewController
 {
       public MyReviewController(IMovieReviewsRepository repository)
       {
       }
 }

Now you are free to implement the interface by a class MovieReviewsRepository providing the objects from a database, or by a class MovieReviewsRepositoryMock providing, for example, some hardcoded test data without any database access. This will make real unit testing possible. But it will also allow to exchange the source of your "movie review objects" to something completely different like a web service or a file without changing the controller, just by providing different IMovieReviewsRepository implementations

Of course, this approach could be generalized to lots of your model classes by making your repository a generic class, like it is shown here.


问:
Minimize touching the already-working code when a radical change is required
I have a code that highly relies on an Array structure like the following:

```<code>$array['customer'][$customer_id]['details'][..];    // it goes to about 10 levels deep
</code>```

However, after almost two years since the initial development, now I have to include another high-level element to that array which will make it something like this:

```<code>$array['company'][$id]['customer'][..];
</code>```

The challenge is that about 12,000 lines of source code are written by four programmers -- I'm the only one still working on the project, AND there is no unit tests, getters and setters, DI, etc. just a bare-bone MVC structure. So, changing the structure of that array will probably require 30% percent of methods to be modified to adapt with the new change, otherwise they just simply won't work as expected.

Is there any general approach for these kinda of headaches? Can I implement a method that could somehow bridge the gap?

I know the question is too vague without seeing the actual source code, however I highly appreciate any recommendations.

Update

Currently I'm thinking of having a method/function which returns the legacy array, however you can actually pass the desired identifier and put it in a loop to get the same effect -- I'm not certain if it will work in all cases, but hopefully will fit in most cases:

```<code>$data = get_legacy_array( $company_id );    // Instead of: $data = $array['customer']...
</code>```

答: It looks like ArrayObject in PHP5 will allow you to create a custom class which can operate as an array, which would allow you to do horrible, horrible things such as [$foo] returning totally different things depending on context. It may not be a good idea, but I don't see why you wouldn't be able to give a smarter data access object the same interface as an array and thus have it be a drop-in replacement. At least if you are accessing based on constant strings then you should be able to change behavior with a minimum of unnecessary astonishment.</p>


问:
Does it make sense to break fluid interface if a bad argument is passed?
If I chain some setters together and one of them does not return $this, then I will get a fatal error. But maybe that is a good thing.</p>

```<code>$object = new object();
$object->set('name','foo')->set('number',12)->set('color'=>'brown');

class object {
  protected $name;
  protected $number;
  protected $color;

  protected $allowed_to_set = array('name','color');

  public function set($property,$value) {
    if(!in_array((string)$property,$this->allowed_to_set)) {
      return false;
    } else {
      $this->$property = $value;
      return $this;
    }
  }
}
</code>```

答:
I'd strongly advice against doing so:

Methods should always return one type. Static typed languages enforce this. Returning different types puts additional burdens on the callee. Before processing the result one has to do tedious type checks.

Your code can trigger fatal php errors: when set('name','foo') returns false, the next call will be false->set('number',12) which will trigger an PHP error. On of course this is not what you intended, right :)

Ignoring the error is as bad. The caller expects a call to have a certain effect. Getting no feedback about something going wrong implies the call succeeded.

In my opinion there are two possible approaches here:

Remove the fluent interface, and always return a boolean.

Throw an exception if the caller is not allowed to set the property. For this you should provide a way to check if the caller is allowed to set the property before. I'd consider it bad practice to try & error if I can do something.

Which one you choose is up to you and your use-case. The first indicates that invalid properties is a valid use-case where you just refuse to set the property. The second indicates an invalid use-case.

Last: don't let your design & architecture be driven by fluent interfaces. They are a nice to have usability of your API and really just a shorthand some like to use.


答:
I think, In your FOREACH loop, you may add

```<code>$method = '_' . <function name><key>;

if (method_exists($this, $method)) {
    $this->$method();
}
else {
    show_error('Could not load Method' . $method);
}
</code>```

Algorithm/Logic: The variable '$method' will store the function name and available key which eventually can work as a method name. IF-condition simply checks the availability of the same method and opens it if method exists otherwise throws an error.

Look of a complete class will be:

```<code>public function your_function()
{
        foreach ($program as $k => $v) {
            //$this->call_function($v); // add 'call_function' in your loop
            $method = '_' . fn.$v; //<function name><key>

            if (method_exists($this, $method)) {
                $this->$method();
            }
            else {
                show_error('Could not load template ' . $method);
            }
        }
}

public function _fnkey()
{
    echo "In Function 1";
}
</code>```

Hope this is useful!

Title: An alternative to an array of functions?

Body:
I'm programming an app (php) which requires a very long list of similar yet different functions, which are being called by a set of keys:

```<code>$functions = [
    "do this" => function() {
        // does this
    },
    "do that" => function() {
        // does that
    }
]
etc.
</code>```

I've chosen to place the similar functions in an array because they are not similar enough - getting the same result with one big function which is full of conditional statements isn't gonna work. And I do need to be able to call them only by key, for example:

```<code>$program = ["do this", "do that", "do this"];
foreach ($program as $k => $v) {
    $functions[$v]();
}
</code>```

Thing is this functions-array structure is causing many problems, for example I'm having a hard time calling one array function from within another array function, e.g. this doesn't work:

```<code>"do that" => function() {
    $functions["do this"]();
}
</code>```

nor this:

```<code>"do that" => function() {
    global $functions;
    $functions["do this"]();
}
</code>```

or this:

```<code>"do that" => function($functions) {
    $functions["do this"]();
}

$functions["do that"]($functions);
</code>```

I guess I could have one giant function with a long switch statement:

```<code>function similar_functions($key) {
    switch ($key) {
        case "do this":
            // does this
        break;
        case "do that":
            // does that
        break;
    }
}
</code>```

But that doens't really seem like good practice. Or maybe it is?

So, what are my alternatives? Should I go with the switch structure? Or is there another, better solution?

Body:
I think, In your FOREACH loop, you may add

$method = '_' . <function name><key>;

if (method_exists($this, $method)) {
    $this->$method();
}
else {
    show_error('Could not load Method' . $method);
}

Algorithm/Logic: The variable '$method' will store the function name and available key which eventually can work as a method name. IF-condition simply checks the availability of the same method and opens it if method exists otherwise throws an error.

Look of a complete class will be:

public function your_function()
{
        foreach ($program as $k => $v) {
            //$this->call_function($v); // add 'call_function' in your loop
            $method = '_' . fn.$v; //<function name><key>

            if (method_exists($this, $method)) {
                $this->$method();
            }
            else {
                show_error('Could not load template ' . $method);
            }
        }
}

public function _fnkey()
{
    echo "In Function 1";
}

Hope this is useful!


答:
Seems like what you need to do comes down to normalizing the data structure, and simply put ['company'][$id] in front of every $array use. You could of course use find & replace (with a tool like AstroGrep), but.. Time for some terminology.

Refactoring.

Refactor first so you can warp your head around it more easily, basically restructuring the problem so its very simple to solve, then just bolt on the new functionality.

Refactoring is changing the internal codebase design to better match (new) demands. Be it performance, stability, or even readability. Adding/changing functionality could be put under the same umbrella but i would not: usually this is the thing one bolts on in a few minutes after the refactoring.

An example..

So when i refactor i do not change any functionality, i just make a place where i can easily bolt on some, at a later time. All functionality is kept identical.

I would have all lookups in that array go through a central place, a function like:

```<code>/**
 * Central customers lookup method, to aid implementing future functionality.
 * @param array $array       The original array.
 * @param Integer $companyid Optional. If given $array['company'][$companyid] must exist.
 * @return array             The $array parameter or a subset thereof.
 */
function GetCompanyCustomers($array, $companyid=null) {
  if ($companyid==null) {
    // Old approach
    return $array;
  } else {
    // Example doublechecks for debugging
    if (!isset($array['company'])) {
      echo 'Error! GetCompanyCustomers() $array["company"] does not exist.';
    }
    if (!isset($array['company'][$companyid])) {
      echo 'Error! GetCompanyCustomers() $array["company"][$companyid] does not exist.';
    }

    // New approach
    return $array['company'][$companyid];
  }
}
</code>```

This facilitates the transition.

First you inject this function (and a setter, perhaps) everywhere and make sure that everything works exactly as before, then you switch to actually using $companyid. Even undoing your changes should be easy, just alter the function again. Consider making matching setter(s).

Further advise:

Its usually not a good idea to have a array that big that contains all data, that is filled again per browser request. It exposes a fundamental bad design. Unless you have to show all that data at once on one page.

Keep in mind to have your data normalized so that parts of the hiearchy are self-describing, self-contained. Use data models to fence off external access, a array may be efficient sometimes but it can bite you especially in an untyped language like PHP. What i did now with the getter could (or should..) be put in a (DataModel representing) class.

Title: Minimize touching the already-working code when a radical change is required

Body:
I have a code that highly relies on an Array structure like the following:

```<code>$array['customer'][$customer_id]['details'][..];    // it goes to about 10 levels deep
</code>```

However, after almost two years since the initial development, now I have to include another high-level element to that array which will make it something like this:

```<code>$array['company'][$id]['customer'][..];
</code>```

The challenge is that about 12,000 lines of source code are written by four programmers -- I'm the only one still working on the project, AND there is no unit tests, getters and setters, DI, etc. just a bare-bone MVC structure. So, changing the structure of that array will probably require 30% percent of methods to be modified to adapt with the new change, otherwise they just simply won't work as expected.

Is there any general approach for these kinda of headaches? Can I implement a method that could somehow bridge the gap?

I know the question is too vague without seeing the actual source code, however I highly appreciate any recommendations.

Update

Currently I'm thinking of having a method/function which returns the legacy array, however you can actually pass the desired identifier and put it in a loop to get the same effect -- I'm not certain if it will work in all cases, but hopefully will fit in most cases:

```<code>$data = get_legacy_array( $company_id );    // Instead of: $data = $array['customer']...
</code>```

Body:
Seems like what you need to do comes down to normalizing the data structure, and simply put ['company'][$id] in front of every $array use. You could of course use find & replace (with a tool like AstroGrep), but.. Time for some terminology.

Refactoring.

Refactor first so you can warp your head around it more easily, basically restructuring the problem so its very simple to solve, then just bolt on the new functionality.

Refactoring is changing the internal codebase design to better match (new) demands. Be it performance, stability, or even readability. Adding/changing functionality could be put under the same umbrella but i would not: usually this is the thing one bolts on in a few minutes after the refactoring.

An example..

So when i refactor i do not change any functionality, i just make a place where i can easily bolt on some, at a later time. All functionality is kept identical.

I would have all lookups in that array go through a central place, a function like:

/**
 * Central customers lookup method, to aid implementing future functionality.
 * @param array $array       The original array.
 * @param Integer $companyid Optional. If given $array['company'][$companyid] must exist.
 * @return array             The $array parameter or a subset thereof.
 */
function GetCompanyCustomers($array, $companyid=null) {
  if ($companyid==null) {
    // Old approach
    return $array;
  } else {
    // Example doublechecks for debugging
    if (!isset($array['company'])) {
      echo 'Error! GetCompanyCustomers() $array["company"] does not exist.';
    }
    if (!isset($array['company'][$companyid])) {
      echo 'Error! GetCompanyCustomers() $array["company"][$companyid] does not exist.';
    }

    // New approach
    return $array['company'][$companyid];
  }
}

This facilitates the transition.

First you inject this function (and a setter, perhaps) everywhere and make sure that everything works exactly as before, then you switch to actually using $companyid. Even undoing your changes should be easy, just alter the function again. Consider making matching setter(s).

Further advise:

Its usually not a good idea to have a array that big that contains all data, that is filled again per browser request. It exposes a fundamental bad design. Unless you have to show all that data at once on one page.

Keep in mind to have your data normalized so that parts of the hiearchy are self-describing, self-contained. Use data models to fence off external access, a array may be efficient sometimes but it can bite you especially in an untyped language like PHP. What i did now with the getter could (or should..) be put in a (DataModel representing) class.


答:
Whilst Doc Browns answer is a perfectly valid approach and will solve your problem, I would strongly suggest that you investigate using an approach that uses Command and Query objects rather than using the repository pattern.

The repository pattern suffers from issues around changes as every time you need a different query you have to add a new method to your repository interface, where as having Command and Query objects as first class citizens in your project means you can just add a new class when you need a new query and you don't have to change any exist code.  It also means that when you want to apply cross cutting concerns (like logging) to your queries/commands then you can do it in a single place and wrap your command/queries in the logging wrapper.

You could implement it along these lines:

You could have a query class like:

```<code>public class GetAllMovieReviewsQuery : IQuery<IEnumerable<MovieReview>>
{
     public GetAllMoveReviewsQuery(int movieId)
     {
          MovieId = movieId;
     }

     public int MovieId{get;private set;}
}
</code>```

This is simple and just collects the parameters it needs through its constructor, and declares the type of the return value of the query.

And then a handler for that query which actually queries the db:

```<code>public class GetAllMovieReviesQueryHandler : IQueryHandler<GetAllMoveReviewsQuery, IEnumerable<MovieReview>>
{
      private DbContext movieDbContext;

      public GetAllMovieReviesQueryHandler(DbContext movieDbContext)
      {
           this.movieDbContext = movieDbContext;
      }

      public IEnumerable<MovieReview> Execute(GetAllMoveReviewsQuery query)
      {
           return dbContext.MovieReviews.Where(x=>x.MovieId == query.MovieId).ToList();
      }
}
</code>```

then in your controller you inject an object which knows how to find the handler for any given query/command (basically a dictionary of the type of a query/command to the handler instance for that query command) and just call this

```<code>  class MyReviewController
  {
       public MyReviewController(IQueryDispatcher dispatcher)
       {
       }

       public IEnumerable<MovieReview> GetReviewsFromMovie(int movieId)
       {
            var query = new GetAllMovieReviewsQuery(movieId);
            return dispatcher.Execute(query);
       }
  }
</code>```

This also has the advantage that you can have different sources for individual queries, by simply replacing the handler which handles that query with one that looks up the answer in a web service or whatever.

To then unit test this you could simply replace the IQueryDispatcher in the controller with a mocked instance which returns the values to test with when given a particular query.

This is an excellent place to start reading and also covers a fair bit about DI, but there are others who also think that the repository pattern has had its day and is more trouble than its worth

Title: Help With Dependency Injection

Body:
I am still very confused as to why and when to use Dependency Injection. If anyone could explain maybe using the below example that would be great, any other explanations would be appreciated.

Lets say I am creating a web-app that will save movie reviews written in C# with ASP.NET MVC 5. If I have the following Model code,

```<code>namespace MovieReviewProject.Models
    {
     public class MovieReviews
      {
        [Key]
        public int ReviewID_int{ get; set; }

        /// <summary>
        /// Submitter email address
        /// </summary>
        public string EmailAddress_str{ get; set; }

        /// <summary>
        /// Movie name
        /// </summary>
        public string MoveName_str{ get; set; }

        /// <summary>
        /// The review
        /// </summary>
        public string Review_str { get; set; }

        /// <summary>
        /// The submission date from
        /// </summary>
        public DateTime SubmissionDate_dt { get; set; }

        /// <summary>
        /// The movie rating
        /// </summary>
        public int Rating_int { get; set; }
    }
}
</code>```

how would a class that provides the Controller with the List of all the reviews, adds an average for a movie, and more look like?

I know that DI is mostly used to allow for easier unit testing but other than that what are the perks to it? Is it worth going through old projects and make sure all the providers are using this principal?

Body:
Whilst Doc Browns answer is a perfectly valid approach and will solve your problem, I would strongly suggest that you investigate using an approach that uses Command and Query objects rather than using the repository pattern.

The repository pattern suffers from issues around changes as every time you need a different query you have to add a new method to your repository interface, where as having Command and Query objects as first class citizens in your project means you can just add a new class when you need a new query and you don't have to change any exist code.  It also means that when you want to apply cross cutting concerns (like logging) to your queries/commands then you can do it in a single place and wrap your command/queries in the logging wrapper.

You could implement it along these lines:

You could have a query class like:

public class GetAllMovieReviewsQuery : IQuery<IEnumerable<MovieReview>>
{
     public GetAllMoveReviewsQuery(int movieId)
     {
          MovieId = movieId;
     }

     public int MovieId{get;private set;}
}

This is simple and just collects the parameters it needs through its constructor, and declares the type of the return value of the query.

And then a handler for that query which actually queries the db:

public class GetAllMovieReviesQueryHandler : IQueryHandler<GetAllMoveReviewsQuery, IEnumerable<MovieReview>>
{
      private DbContext movieDbContext;

      public GetAllMovieReviesQueryHandler(DbContext movieDbContext)
      {
           this.movieDbContext = movieDbContext;
      }

      public IEnumerable<MovieReview> Execute(GetAllMoveReviewsQuery query)
      {
           return dbContext.MovieReviews.Where(x=>x.MovieId == query.MovieId).ToList();
      }
}

then in your controller you inject an object which knows how to find the handler for any given query/command (basically a dictionary of the type of a query/command to the handler instance for that query command) and just call this

  class MyReviewController
  {
       public MyReviewController(IQueryDispatcher dispatcher)
       {
       }

       public IEnumerable<MovieReview> GetReviewsFromMovie(int movieId)
       {
            var query = new GetAllMovieReviewsQuery(movieId);
            return dispatcher.Execute(query);
       }
  }

This also has the advantage that you can have different sources for individual queries, by simply replacing the handler which handles that query with one that looks up the answer in a web service or whatever.

To then unit test this you could simply replace the IQueryDispatcher in the controller with a mocked instance which returns the values to test with when given a particular query.

This is an excellent place to start reading and also covers a fair bit about DI, but there are others who also think that the repository pattern has had its day and is more trouble than its worth


答:
The simple answer: use relative estimates and ship frequently. This is basically the approach used in the Extreme Programming method. The basic steps:

The team creates a list of every useful step forward, generally written from the user's perspective. (E.g., "Customer adds item to cart".)

The product manager sorts the list by priority, inserting release markers. (E.g., "first internal alpha", "first public beta".)

The developers pick out the smallest non-trivial item. They call that 1 point.

The developers estimate everything else in terms of that. Anything too large (e.g., 8 points) gets broken down into smaller pieces.

The developers start in building things one feature at a time, making a working system (that is, something you could release if somebody put a gun to your head) at least once a week.

Each week, the team counts up the points they completed. Next week, they try to take on about the same amount. If they complete all that early, they can opt to do more.

If the product manager wants an estimate for some particular release, they can look at the weekly velocity, count up the points in the release, and do the math.

This may sound too simple, but it has worked very well for me, and plenty of other teams. In particular, because the product manager has full control over the schedule through arranging the upcoming work, schedule pressure is no longer a problem for developers. Business people get to argue with one another about priorities and schedules as much as they want, and I get to keep coding.

Title: How do you deal with time estimates?

Body: If given too little time, quality suffers. If given too much time, developers will find a way to use all alloted time, no matter what. What would be a good way with dealing with estimates? Are they a necessary evil?</p>


问:
Where or when to start to write your own PHP framework?
First of all, I know that reinvent the wheel is, usually, a bad idea, but I want to write a PHP framework to learn OOP in PHP and to understand MVC in my free time.

Said that, I have to do two webs with few and simple database interactions, the basic funcionality of the webs is to show information.

I want to use my own framework in those webs, but I don't know where or when to start. Should I start doing the framework first and then the webs? or should I start doing one web, then the framework and then the other web?

答:
nobody can answer that for you.

As to making a framework, first spend a lot of time thinking and writing about your design goals, what it should do and how it should do it at a conceptual level.

Just starting to type code and hoping you're going to end up with something even remotely coherent is only going to lead to disaster.


答:
Writing a framework for educational purposes is perfectly fine. However, you would be best also doing further research into existing frameworks, in order to learn what functionality they provide and how those frameworks implemented that functionality.

For serious web development, you are likely to be better off using an existing framework, as you will probably want to focus your energy on the development of websites and not frameworks, especially as there are plenty of good frameworks available freely.

Title: Where or when to start to write your own PHP framework?

Body:
First of all, I know that reinvent the wheel is, usually, a bad idea, but I want to write a PHP framework to learn OOP in PHP and to understand MVC in my free time.

Said that, I have to do two webs with few and simple database interactions, the basic funcionality of the webs is to show information.

I want to use my own framework in those webs, but I don't know where or when to start. Should I start doing the framework first and then the webs? or should I start doing one web, then the framework and then the other web?


答:
Why not Both?

Do the webapps, but keep a very strong separation of what code belongs to the the app and what belongs to the framework.


问:
When should I pass value as class variable and when as a method argument?
Is there a general rule of thumb, when we should pass a value as as class variable and when as a method argument? Or is it just a choice of the developer?

For example -- are there any reasons, why following (PHP code):

```<code>class SomeClass
{
    public function __construct()
    {
        $this->id = $_GET['id'];
        $this->showMessage();
    }

    public function showMessage()
    {
        echo 'The ID is '.$this->id;
    }
}
</code>```

is better (or worse?) than this:

```<code>class SomeClass
{
    public function __construct()
    {
        $this->showMessage($_GET['id']);
    }

    public function showMessage($id)
    {
        echo 'The ID is '.$id;
    }
}
</code>```

Note, that I'm only asking about differences between passing value as class variable vs. passing as method argument. Please, don't point out, that I should never operate directly on superglobals in PHP. I know, that this is wrong. I used it here, to simplify the example.

答:
If conceptually the value is part of the object's state, it should be passed as a member field. If it's only part of specific action of the method invocation, it should be passed as a method argument.

For example, let's say objects of SomeClass can be saved to a file. You'll have a save action and you need to pass the file's path.

If you pass the path as a member field, it is now a part of the object state. That means that conceptually, the object is bound to that file. It would make sense then, for example, to load the object from the same file, to block other objects from saving to that file, to overwrite the file without confirmation etc.

If you pass the path as a method argument, it is not part of the object state. The object, after being saved, couldn't care less about the file. In this case, it would make sense to save the object to different files(possible with incremental names), or to ask for confirmation if you save it again to the same file.

The choice, ofcourse, should depend on how the object relates to the value in each individual case.


问:
Why are dark color schemes in editors so popular?
Nowadays, almost everybody is using a dark color scheme in their code editor - dark background with light text. Even most web based editors (e.g on Github) feature dark color schemes.

I honestly don't see the benefits. The human eye is much better at reading dark text on a bright background. Also, black on white color schemes work much better when you're in a brightly lit environment.

I'm currently sitting in an office with the sun shining through the window. I can read the text in my editor (gVim with dark text on white background) just fine, but on the linux console it's much harder. Editing text in console vim is almost impossible for me.

The whole thing seems a bit like a strange hype to me, started by the default settings in certain IDEs/editors. But maybe I'm just weird.. ;)

Anyway, so why is everybody using these?

答:
I firmly believe that it's more good for the eyes. When I sit in front of a monitor for 12 hours constant stream of light(white screen) is really tiring while the dark color is not so intense.

Let me describe more of my setup. At home I use dual screen setup with dark themes and a lamp because I find my sensitive eyes work best when background is lit. Meanwhile at work I am in a bright place all day long so only dark theme is enough.

I have tried different themes and setups because of sensitive eyes and this information may be personal.


答:
I feel it greatly eases the stress on my eyes after long hours of coding. 99% white screen on a bright monitor is asking for a headache.

I also find this very funny, as in web design class in college we were told "NEVER DO THAT" to a webpage ... yet most developers using computers for a long time use it.

Are we designing websites to not be used for long periods of time?

Title: Why are dark color schemes in editors so popular?

Body:
Nowadays, almost everybody is using a dark color scheme in their code editor - dark background with light text. Even most web based editors (e.g on Github) feature dark color schemes.

I honestly don't see the benefits. The human eye is much better at reading dark text on a bright background. Also, black on white color schemes work much better when you're in a brightly lit environment.

I'm currently sitting in an office with the sun shining through the window. I can read the text in my editor (gVim with dark text on white background) just fine, but on the linux console it's much harder. Editing text in console vim is almost impossible for me.

The whole thing seems a bit like a strange hype to me, started by the default settings in certain IDEs/editors. But maybe I'm just weird.. ;)

Anyway, so why is everybody using these?


答: It depends also to developer working attitude. I spent a lot of my time in a room with a bad light condition and, in particular at late time, on dark room so, a white window is really noxious.  </p>


问:
Why is String immutable in Java?
I couldn't understand the reason of it. I always use String class like other developers, but when I modify the value of it, new instance of String created.

What might be the reason of immutability for String class in Java?

I know there are some alternatives like StringBuffer or StringBuilder. It's just curiosity.

答:
1) String Pool

Java designer knows that String is going to be most used data type in all kind of Java applications and that's why they wanted to optimize from  start. One of key step on that direction was idea of storing String literals in String pool. Goal was to reduce temporary String object by sharing them and in order to share, they must have to be from Immutable class. You can not share a mutable object with two parties which are unknown to each other. Let's take an hypothetical example, where two reference variable is pointing to same String object:

```<code>String s1 = "Java";
String s2 = "Java";
</code>```

Now if s1 changes the object from "Java" to "C++", reference variable also got value s2="C++", which it doesn't even know about it. By making String immutable, this sharing of String literal was possible. In short, key idea of String pool can not be implemented without making String final or Immutable in Java.

2) Security

Java has clear goal in terms of providing a secure environment at every level of service and String is critical in those whole security stuff. String has been widely used as parameter for many Java classes, e.g. for opening network connection, you can pass host and port as String, for reading files in Java you can pass path of files and directory as String and for opening database connection, you can pass database URL as String. If String was not immutable, a user might have granted to access a particular file in system, but after authentication he can change the PATH to something else, this could cause serious security issues. Similarly, while connecting to database or any other machine in network, mutating String value can pose security threats. Mutable strings could also cause security problem in Reflection as well, as the parameters are strings.

3) Use of String in Class Loading Mechanism

Another reason for making String final or Immutable was driven by the fact that it was heavily used in class loading mechanism. As String been not Immutable, an attacker can take advantage of this fact and a request to load standard Java classes e.g. java.io.Reader can be changed to malicious class com.unknown.DataStolenReader. By keeping String final and immutable, we can at least be sure that JVM is loading correct classes.

4) Multithreading Benefits

Since Concurrency and Multi-threading was Java's key offering, it made lot of sense to think about thread-safety of String objects. Since it was expected that String will be used widely, making it Immutable means no external synchronization, means much cleaner code involving sharing of String between multiple threads. This single feature, makes already complicate, confusing and error prone concurrency coding much easier. Because String is immutable and we just share it between threads, it result in more readable code.

5) Optimization and Performance

Now when you make a class Immutable, you know in advance that, this class is not going to change once created. This guarantee open path for many performance optimization e.g. caching. String itself know that, I am not going to change, so String cache its hashcode. It even calculate hashcode lazily and once created, just cache it. In simple world, when you first call hashCode() method of any String object, it calculate hash code and all subsequent call to hashCode() returns already calculated, cached value. This results in good performance gain, given String is heavily used in hash based Maps e.g. Hashtable and HashMap. Caching of hashcode was not possible without making it immutable and final, as it depends upon content of String itself.

Title: Why is String immutable in Java?

Body:
1) String Pool

Java designer knows that String is going to be most used data type in all kind of Java applications and that's why they wanted to optimize from  start. One of key step on that direction was idea of storing String literals in String pool. Goal was to reduce temporary String object by sharing them and in order to share, they must have to be from Immutable class. You can not share a mutable object with two parties which are unknown to each other. Let's take an hypothetical example, where two reference variable is pointing to same String object:

String s1 = "Java";
String s2 = "Java";

Now if s1 changes the object from "Java" to "C++", reference variable also got value s2="C++", which it doesn't even know about it. By making String immutable, this sharing of String literal was possible. In short, key idea of String pool can not be implemented without making String final or Immutable in Java.

2) Security

Java has clear goal in terms of providing a secure environment at every level of service and String is critical in those whole security stuff. String has been widely used as parameter for many Java classes, e.g. for opening network connection, you can pass host and port as String, for reading files in Java you can pass path of files and directory as String and for opening database connection, you can pass database URL as String. If String was not immutable, a user might have granted to access a particular file in system, but after authentication he can change the PATH to something else, this could cause serious security issues. Similarly, while connecting to database or any other machine in network, mutating String value can pose security threats. Mutable strings could also cause security problem in Reflection as well, as the parameters are strings.

3) Use of String in Class Loading Mechanism

Another reason for making String final or Immutable was driven by the fact that it was heavily used in class loading mechanism. As String been not Immutable, an attacker can take advantage of this fact and a request to load standard Java classes e.g. java.io.Reader can be changed to malicious class com.unknown.DataStolenReader. By keeping String final and immutable, we can at least be sure that JVM is loading correct classes.

4) Multithreading Benefits

Since Concurrency and Multi-threading was Java's key offering, it made lot of sense to think about thread-safety of String objects. Since it was expected that String will be used widely, making it Immutable means no external synchronization, means much cleaner code involving sharing of String between multiple threads. This single feature, makes already complicate, confusing and error prone concurrency coding much easier. Because String is immutable and we just share it between threads, it result in more readable code.

5) Optimization and Performance

Now when you make a class Immutable, you know in advance that, this class is not going to change once created. This guarantee open path for many performance optimization e.g. caching. String itself know that, I am not going to change, so String cache its hashcode. It even calculate hashcode lazily and once created, just cache it. In simple world, when you first call hashCode() method of any String object, it calculate hash code and all subsequent call to hashCode() returns already calculated, cached value. This results in good performance gain, given String is heavily used in hash based Maps e.g. Hashtable and HashMap. Caching of hashcode was not possible without making it immutable and final, as it depends upon content of String itself.


问:
Migrating old Asp.net 1.1 project to mvc 3 or 4
we have to migrate a very old project that are having more than 500 web forms and 400 tables and it is hugely depends on stored procedures, the current specification is:

Asp.Net : .NET version 1.1

language: VB

uses 2 Tier architecture (UI and business(includes DataAccess also))

xml is used to pass the data between UI and Biz layer

For data access sql queries and stored procedures are used that fetch data as dataset.

Finance related domain.

a lot of javascript for validation

Planned specification:

Asp.net 4.0 with c#

MVC 3 or 4

Now my questions are

Is it possible to implement mvc only for UI layer, if possible then how to use current business layer? Also we don't have class and properties because it uses xml to pass data, also we have to use same legacy database.

We don't want to use Entity framework, because of performance, legacy database(not properly designed), uses more than 700 stored procedure.

how to create model i.e Domain level or project level because my solution contains 14 projects?

Is it possible to implement Repository pattern in separate layer?

答:
Yes, absolutely. Your MVC controllers can interface with whatever business layer you already have in place. In fact, this might be a good way to begin your transition.

This isn't worded as a question, but if you are asking "do I have to use EF", then the answer is no, of course you don't.

Your domain model classes do not need to be in your MVC project, they can live separately in existing projects and be referenced by your MVC project.

This is nothing to do with the MVC "layer". You can create your repositories in a separate layer as you would for any other project and have the MVC project use them. Some people may wrap access to repo's in a service layer. Others are moving away from repo's when using tools like Entity Framework and NHibernate as they can be considered repo's themselves, but that is a topic for another thread/question.


答:
I think its mostly a personal preference, very few people do extensive studies on their editor colorscheme.

Over the last decades I found people justifying it with one or more of the following reasons (among which some were used for black on white too)

They come from DOS or similar times, and it was like that always.

When they started coding, there was a sense of "coolness" to use  dark background.

They often code in late hours, with the room rather dark. It reduces the contrast a little bit, and the eyes feel better.

They say it feels like that it reduces strain on the eyes for their experience.

It was the default for their editor (e.g. vim) or terminal, and they just got used to it.

They feel like their eyes are more sensitive to colors, presumably due to not being used so much (e.g. rhodopsin etc. being available in larger quantities).

It allows them to use much lighter pastel colors in their colorschemes that would be much harder to read on white background.

Semitransparent windows (or fake transparency with a background image) are claimed to look nicer with dark background.

That said, my personal reason is that I feel my eyes less strained in dark environments, and I also like the color scheme more. I have also set photoshop to dark menu base and find that working in as few light as possible makes my perception of colors there better. And of course it makes me feel sometimes a bit like in the good old 80s, especially when I set my terminal color to that nice glowing green on black...


答:
I honestly don't see the benefits. The human eye is much better at reading dark text on a bright background. Also, black on white color schemes work much better when you're in a brightly lit environment.

While the human eye is better at reading dark text on light background, that configuration is also more stressful on the eye. When you are looking into a monitor for hours every day, this causes stress for the eyes (especially in poorly-lit conditions).

In my case, I adapt the theme on the rest of my environment:

at home in the evening, I keep my room light off, use dark backgrounds and reduce my monitor's contrast in the evening.

at work, I use dark backgrounds in the morning (relaxing on the eyes), and light backgrounds after lunch (on sunny days, I can see the sun through the window, looking over my monitor).


问:
When should I pass setting-like value as class' variable and when as an assoc. array?
Following my other question, is there a general rule of thumb, when we should pass a setting-like value, that controls class' behavior (for example displayed texts) as as class' constant or variable, one-by-one, and when it is better to "pack" them to one associative array? Or is it just a choice of the developer?

For example -- is this approach better (PHP code):

```<code>class SomeClass
{
    public $errorIncorrectProtocol = 'Please, don't use GET protocol in this context!';
    public $errorMissingId = 'The ID can't be empty or equal zero...';
}
</code>```

than this one:

```<code>class SomeClass
{
    public $errorMessages = array
    (
        'IncorrectProtocol'=>'Please, don't use GET protocol in this context!',
        'MissingId'=>'The ID can't be empty or equal zero...'
    );
}
</code>```

and if yes -- then, why?

答:
A good practice here (in PHP at least) is to use a combination of constants and arrays. To follow your error messages example:

```<code>class SomeClass {
    const ERR_INCORRECT_PROTOCOL = "incorrectProtocol";
    const ERR_MISSING_ID = "missingId";

    public $errorMessages = array(
        self::ERR_INCORRECT_PROTOCOL => "Please, don't use GET protocol in this context!",
        self::ERR_MISSING_ID => "The ID can't be empty or equal zero..."
    );
}
</code>```

Error messages can then easily be retrieved:

```<code>$someObj = new SomeClass();
$someObj->errorMessages[SomeClass::ERR_INCORRECT_PROTOCOL];
</code>```

Generally speaking, I don't think having individual variables in this context provides any benefits over using a constants and arrays. Instead, it simply clutters the internals of your class, or worse (if they're publicly exposed) clutters your API and possibly confuses developers (what's this errorMissingId? Is it some error object? A string? Is it safe to change? Do I need it?)

Body:
A good practice here (in PHP at least) is to use a combination of constants and arrays. To follow your error messages example:

class SomeClass {
    const ERR_INCORRECT_PROTOCOL = "incorrectProtocol";
    const ERR_MISSING_ID = "missingId";

    public $errorMessages = array(
        self::ERR_INCORRECT_PROTOCOL => "Please, don't use GET protocol in this context!",
        self::ERR_MISSING_ID => "The ID can't be empty or equal zero..."
    );
}

Error messages can then easily be retrieved:

$someObj = new SomeClass();
$someObj->errorMessages[SomeClass::ERR_INCORRECT_PROTOCOL];

Generally speaking, I don't think having individual variables in this context provides any benefits over using a constants and arrays. Instead, it simply clutters the internals of your class, or worse (if they're publicly exposed) clutters your API and possibly confuses developers (what's this errorMissingId? Is it some error object? A string? Is it safe to change? Do I need it?)


答:
Typically a framework is released by a team experienced in building a type of application to give other less experienced developers a head start.  If you are less experienced, then building a framework is probably not the best place to start.

For instance, A team that builds web applications might release their codebase as a framework (krakenjs, rails, django, etc..).  A team that designs web sites might release their sass/less base as a framework (bootstrap, foundation).  Building a framework without first building real applications is just putting the cart before the horse IMO.

"David Heinemeier Hansson extracted Ruby on Rails from his work on
Basecamp, a project management tool by 37signals (now a web
application company)." - http://en.wikipedia.org/wiki/Ruby_on_rails#History

"Django grew organically from real-world applications written by a Web development team in > Lawrence, Kansas, USA" - http://www.djangobook.com/en/2.0/chapter01.html#django-s-history

It would be more beneficial to build real applications, possibly using existing frameworks, then if you are successful, release the base of those projects as a new framework, or an extension to an existing one.

In contrast to frameworks, OOP is a more general programming approach that is used across many application types.  You could have an OOP business module, an OOP GUI, etc...

For some references, see a list of books here: http://www.island-data.com/bookreviews/oobooks.html  Then try to model small applications, for example if you are into animals, you could start with the classic Animal/Dog/Cat (http://www.inf.ed.ac.uk/teaching/courses/inf1/op/Lectures/pub/07-poly.handout-2x2.pdf), building your way to the PetStore.  Choose whatever type of application keeps your interest and start building.

Just keep in mind that the web application, and your application, are probably separate concerns, and sometimes frameworks will actually sacrifice OOP design to get a web application up quickly, so be careful commingling the two.