答: It turns out you only need one instruction to build a machine capable of Turing-computation. This class of machines that have only one instruction and are Turing-complete is called One Instruction Set Computers or also somewhat jokingly Ultimate RISC.


问:
Giving team members more decision-making power led to very long arguments, blocking progress since there is no one with the final say
Currently we use Scrum with the exception that our Scrum Masters sometimes act as project managers rather than facilitators of the Scrum process. About half of the time team members pull tasks on their own, but half of the time the Scrum Master assigns the tasks to team members.

I would like us to fully adopt self-organizing teams. However when we tried giving team members more decision-making power, it led to very long arguments between team members, and since there would be no one with the final say, these arguments would block progress.

Do you think there is a way to minimize arguments with self-organizing Scrum teams?

答:
This is a very large question, much larger than just scrum.  It reaches to the core of team play.  The idea of giving more control to the individuals is to make them more efficient by removing red tape.  However, there is a tradeoff.  With red tape in the way, everyone is marching towards the same goal inefficiently.  Take the red tape away, and everyone marches efficiently, but towards their own goal.  If you have instilled a good sense of the overall project's goal in all of the individuals, this works great.  If the individuals disagree on the final direction, then bickering begins.

I recommend two techniques beyond the obvious "unify your team goals a bit more": one is to give remove the red tape slowly.  Give the team time to react to the changes, and see if they can re-align themselves.  Sudden changes in development rules are much harder to get used to than the gradual ones.  The second is to attack the problem from a higher vantage point.  See if you can have a meta-control on the problem such as, "if I see bickering, the red tape comes back until we all calm down."

The last bit of advice I have is to never approach two team-members that are butting heads directly.  By definition, they are in butting heads mode, and they won't mind butting heads with you as you try to fix things.  Always seek to move them out of opposition, rather than trying to manually squelsh the opposition directly by making a decision for them.

ContentLicense: CC BY-SA 3.0


问:
Why do expressions print variable value using System.out.print?
Why does java print the value of the variable that is assigned it in the code below? I want understand what is happening here.

My thought is that the expression inside println() method is evaluated first. For the first example, 5 is assigned to int x. At that point, does x become available for the println() method to print its value?

This code confuses me. I wouldn't have thought expression like x=5 could return a value. Thank you.

Examples:

```<code>int x;
System.out.println(x=5); //prints 5

boolean isValid;
System.out.println(isValid = true); //prints true

String fruit;
System.out.println(fruit="Orange"); //prints orange
</code>```

答:
The parameter of of a method can be an expression.

```<code>System.out.println(x - y)
</code>```

This works because x - y is an expression.

In most C like languages, the assignment operator is also part of an expression.  For example in C# Why do assignment statements return a value? Eric Lippert points out the difference between a statement an an expression.  An expression returns something.  +, -, ! and so on - those operators return things.  The = operator is no different in this respect, it returns something too.

That an assignment operator returns a value is idiomatic in C like languages.  And while the original thoughts of why that was the case in C are lost, x = y is just as much of an expression as x - y is.

It turns out that x = 42 returns the value of 42 also.  This is useful for side effects like x = y = z = 42 which is actually x = (y = (z = 42))).  And here, z = 42 returns 42, which is then used in y = 42 and so forth.

You will also see the return value used in things such as:

```<code>while ((line = in.readLine()) != null) {
    processLine(++lineNo, line);
}
</code>```

where the assignment to line is done and checked to see if it is not null.

This is perfectly idiomatic code for most languages that trace a linage back to C.

Further reading: Java Language Specification, section 15.26: Assignment Operators

Body:
The parameter of of a method can be an expression.

System.out.println(x - y)

This works because x - y is an expression.

In most C like languages, the assignment operator is also part of an expression.  For example in C# Why do assignment statements return a value? Eric Lippert points out the difference between a statement an an expression.  An expression returns something.  +, -, ! and so on - those operators return things.  The = operator is no different in this respect, it returns something too.

That an assignment operator returns a value is idiomatic in C like languages.  And while the original thoughts of why that was the case in C are lost, x = y is just as much of an expression as x - y is.

It turns out that x = 42 returns the value of 42 also.  This is useful for side effects like x = y = z = 42 which is actually x = (y = (z = 42))).  And here, z = 42 returns 42, which is then used in y = 42 and so forth.

You will also see the return value used in things such as:

while ((line = in.readLine()) != null) {
    processLine(++lineNo, line);
}

where the assignment to line is done and checked to see if it is not null.

This is perfectly idiomatic code for most languages that trace a linage back to C.

Further reading: Java Language Specification, section 15.26: Assignment Operators


问:
Sprint Planning Meetings - determine if a work item is "planned"?
We've been working with Scrum for a while now, generally successfully. However of late, as the pressure has started to mount up we've encountered several situations where items came through planning meetings but when it actually came time to code, it became apparent they were woefully under-specified.

This is an annoying and awkward waste of time. So I'm wondering, is there anything we can do to make sure that a work item is properly understood and planned before it's included in a sprint?

We don't use TDD, but my experiences with it suggest that it's a good way of ensuring a programmer understands a task before beginning work. So I did consider trying to work out some automated testing as a possible approach to this. But not all work items are amenable to automated tests, and it's likely to be difficult/boring for non-programmers in the meeting.

As an aside, out of curiosity, is when one has decided on acceptance criteria, should they go on a work item, or a user story, or both?

答:
One of the scrum ceremonies is grooming, you can make use of that meeting during each sprint to groom about future PBIs that your team is going to pick. In the meeting the whole team (Software Engineer, Quality Engineer, functional designer and SM) gather around together with Product owner and mostly it is FD and PO job to explain and describe the user stories and team can elaborate about how it is technically possible to implement and be tested (And make sure you document those outcome if it is possible for future reference). And in case you need to break the PBI or there are some notes you can decide in the grooming.

Also in planning you can also remind each other just briefly about the PBIs implementation blue print and testing scope.

I am not sure about the technology that you use but for example in tfs you can define PBIs and tasks and put all of those detail and outcomes of meeting into PBI so when programmer picks the it, he or she knows about background of PBI and all the requirement.


问:
Why doesn't monad take `(M a -> M b)`?
All apologies -- I'm still very much on the outside of Haskell looking in.

Why does the bind for a monad have this signature:

M a -> (a -> M b) -> M b

and not

M a -> (M a -> M b) -> M b

i.e. a function that takes M a instead of just a

a is available to the function in both, but the context that M provides is not available to the function in the 1st. Just the lifted value itself.

(If that's a silly question, just downvote me a lot & I'll delete it... like I say, still very much on the outside looking in)

答: Just a hint: a -> M b is more general than M a -> M b, since you can do a -> M a any time with return.

Title: Why doesn't monad take `(M a -> M b)`?


答:
First I strongly disagree with the opionion stated in other answers that the SM should make a final decision. The scrum masters task is

to get impediments out of the way, often by presenting them to the team, which otherwise might just ignore them.

to help the team to become a good (scrum)team.

Taking a decision out of their hand is exactly the wrong thing to do.

Instead I'd aproach the problem the following way:

observe: What is the actual problem? Possibilities might be

a conflict within the team, that manifests in constant opposition

not enough information thus, no proper basis for a decision

fear of being made responsible for a decision on thinks is wrong or at least not optimal

present: make the team aware of the problem. Make the consequences of the behaviour obvious. The PO might want to present the damage this inability to decide makes. It also should be clarified that the PO demonstrates trust in the team and the team should act worthy of that trust.

let the team solve the problem: In a moderated discussion (typical a retrospective) the team should come up with proposals for solutions and decide on one.

Actual solution might be:

democratic voting with a way to break ties, for example by giving experienced developers a tenth of a vote more.

decide on a team member that makes a certain kind of decision (probably after listening to the arguments of the others)

timebox decisions

properly prepare decisions by having clear phases: e.g. collecting of information, discussion, decision

decision by consent, i.e. one doesn't look for a solution everybody (or the majority agrees to but, a solution which everybody can live with)

Title: Giving team members more decision-making power led to very long arguments, blocking progress since there is no one with the final say

Body:
Currently we use Scrum with the exception that our Scrum Masters sometimes act as project managers rather than facilitators of the Scrum process. About half of the time team members pull tasks on their own, but half of the time the Scrum Master assigns the tasks to team members.

I would like us to fully adopt self-organizing teams. However when we tried giving team members more decision-making power, it led to very long arguments between team members, and since there would be no one with the final say, these arguments would block progress.

Do you think there is a way to minimize arguments with self-organizing Scrum teams?


问:
Able to read Code but struggling majorly to write it
I had my first programming exam recently...and well I pretty much flopped it. Did not do great at all. I have only myself to blame as outside of college time, I pretty much did nothing.

Now I have another coming up near summer time and I'm not allowing this to happen again. For a couple of weeks now I've been reading, reading and reading some more. I keep going over the older things I missed and the newer things we're doing. So, obviously I can notice a huge difference in my understanding of the language. However, that's about it. I can read the code and I now have an idea of what's going on in the code... but when it comes to me writing the code myself I'm just clueless. It's like I never know what approach to take and can never really fully comprehend the questions.

I have done a fair amount of reading (been doing around 5-6 hours for the past month or so) each day... But when opening my IDE I always feel doomed it's really demotivating. Especially because I have knowledge of nodes, lists, arraylists, interfaces ect ect but besides from reading them on a page that's about it. I can point out exactly everything that's going on in a program so annotating a presample code I find fine... but writing my own code is another story..

答:
This question already has some really good answers, but there are a few thoughts I havent't seen yet.

Learning a programming language is much like learning a 'real' language: It's always much easier to read than to write, be it a single sentence, a scientific paper, or a book. When reading, much can be figured out just from the context, understanding the text or code as you read it. When you see a word you don't know, maybe you know another word with the same stem; when you see a method, the name of the method gives you a good idea of what it does. When writing, you have to remember not only the syntax, but also the actual words to use. And its the same for programming.

As others have said, you can't learn to write programs just from reading programs.

Start small. Look for a Java tutorial, and do all the units, one after another. And when you are confident enough, pick a small project to test your skills, maybe some simple game you know well that does not require too much GUI interaction. When you've decided, don't just open your Eclipse and stare at the 'blank page'. Create a storyboard. You don't have to draw elaborate UML diagrams, just think about how certain aspects of the program could be solved -- how the story or your argument unfolds, so to speak.  And when writing the code, start with a rough draft. I usually write lots of comments, describing what the program should do, in what order, and then start filling in the actual program code.


问:
Why is an A element often used instead of a BUTTON for web design?
Is there any particular reason why people use the A tag to mimic a BUTTON in HTML and JavaScript?</p>

答:
One of the reasons is that you can't href a button, which also means that the browser won't show at the bottom the target link on mouse hover.

Another reason is that button requires to be embedded in a form, as well as, at least in XHTML 1.1, in a div. This means lots of markup for a simple button.

Unless the button leads to an action which changes state (which logically requires a POST), why would anyone use a button instead of a link?

IF you have a set of actions, some being symbolized by buttons (for example "Save changes" and "Revert to previous state"), and some other being logically simple links (for example "Display details" which leads to a different page which shows a detailed view of a modified item), UX-wise, it would be more intuitive for the user to have an uniform view, i.e. having three items which look like buttons, instead of two buttons and a link. This doesn't mean that you should bend your markup to adjust it to the presentation.


问:
Package software separately from content that is CC BY-NC-SA 3.0 license
I have content that is CC BY-NC-SA 3.0 (see http://creativecommons.org/licenses/by-nc-sa/3.0/), can software that uses it still be produced commercially and just let the user download the content separately?

In other words, if I have commercial software that uses the content with CC license, can the software still be distributed as commercial and just not be distributed with that content... OR, would that still violate that CC license and the software therefore can't be commercially sold?

If someone knows the answer or can point me to a place to find out the answer, I would really appreciate it.

Thanks!

答:
The NC-clause Creative Commons licenses are often criticized for not defining well what "non-commercial" means exactly, so it doesn't provide much legal certainty for the licensor or licensee.

The full legal text of the CC-BY-NC-SA 3.0 (which is the one which "counts". What you linked to is just the "human-readable" synopsis) reads:

c.You may not exercise any of the rights granted to You in Section 3
  above in any manner that is primarily intended for or directed toward
  commercial advantage or private monetary compensation.

(The rights granted in section 3 are the rights to distribute or publicly perform the work)

The Creative Commons FAQ says:

Whether a use is commercial will depend on the specifics of the situation and the intentions of the user. [...]
  There will always be uses that are challenging to categorize as
  commercial or noncommercial. CC cannot advise you on what is and is
  not commercial use. If you are unsure, you should either contact the
  rights holder for clarification, or search for works that permit
  commercial uses.

Emphasis is mine and my recommendation what you should do. Licenses are a communication tool used by creators to communicate how they wish their work to get used. When a communication tool fails, you should try to communicate in a different way.

So try to find the creator(s) of the NC content and ask them if what you want to do is commercial activity in their opinion or not.

Some aspects which might be interesting to them are:

Is the NC content required by your application or is it just an optional supplement?

Will you use the NC content to promote your application?

Does the user actively choose to download the NC content or does the application download it automaticaly?

Do you allow people who didn't buy your software to obtain the NC content for free?

Is the user aware which parts of the content are CC-BY-NC-SA? (more important for the BY and the SA than the NC)


答:
Like others are saying, you just need to practice writing code. In order for that to be fulfilling, you need to challenge yourself with solving some kind of problem, whether it's printing predefined messages, making a simple interactive calculator or solving some specific task.

If you're short on inspiration, Project Euler has a plethora of math/programming exercises of increasing difficulty. They give you clear and challenging goals to accomplish, and should help you get more comfortable designing programs.

Title: Able to read Code but struggling majorly to write it

Body:
I had my first programming exam recently...and well I pretty much flopped it. Did not do great at all. I have only myself to blame as outside of college time, I pretty much did nothing.

Now I have another coming up near summer time and I'm not allowing this to happen again. For a couple of weeks now I've been reading, reading and reading some more. I keep going over the older things I missed and the newer things we're doing. So, obviously I can notice a huge difference in my understanding of the language. However, that's about it. I can read the code and I now have an idea of what's going on in the code... but when it comes to me writing the code myself I'm just clueless. It's like I never know what approach to take and can never really fully comprehend the questions.

I have done a fair amount of reading (been doing around 5-6 hours for the past month or so) each day... But when opening my IDE I always feel doomed it's really demotivating. Especially because I have knowledge of nodes, lists, arraylists, interfaces ect ect but besides from reading them on a page that's about it. I can point out exactly everything that's going on in a program so annotating a presample code I find fine... but writing my own code is another story..


问:
How do I explain to my boss what a 'Virtual Machine' means?
Most probably my boss didn't write a single word on a keyboard in his entire life.

He saw computers and he has a cell phone. He is a smart man.

How can I explain to him what a 'virtual machine' is?
(VM as in VMWare + virtual Box, not the VM as in Java, LLVM, .NET)

One of the reasons for asking this is that I want to tell him that having a Linux VM to connect to internet with a Windows host is safer than connecting directly to Windows.

答:
Well, that depends on why you want to explain it, and in how much details.

A good first attempt could be

A program to simulate a computer inside a computer. It is useful for
  testing programs that need a separate computer, without actually
  having a second computer.

Then, you can refine your explanation depending on his questions.


问:
Speed difference between VM-based and compiled code
Not so long ago I was told by a senior academic that, these days, VM-based code could run nearly as fast as compiled code, but my own experience is that compiled code runs several orders of time faster.

This is based on code attempting to do the same thing (processing a very large XML file) - in the case of the VM-based code (Groovy) I guess my code would complete in about two years (correct) whereas the C/C++ based alternative took about three hours.

The algorithms were not quite the same - but that was because using C/C++ allowed me to manipulate the memory at a byte level using pointers. The Groovy code was easier to write as the language was much more expressive, but the price paid was slow execution.

I don't claim to be the world's greatest coder so I would willingly accept that my code could have been improved: but what is the general view?

答:
Performance of C, C++ and Java are comparable. Java is sometimes even faster though usually it is a little bit slower.

However dynamically typed languages (which Groovy is) are slower, because they have to look up member and methods all over all the time while statically typed languages can do it in advance and just use appropriate offsets.

Of course if you are making it further slower by using different algorithm that involves more copying, you are no longer comparing the speed of the languages. But some algorithms can only be used in some languages, which counts to their advantage. That is mainly the case of anything that relies on C/C++'s weak typing where you can take a piece of memory and tell the compiler to treat it as any type you want. No dynamic language can do that and most managed languages (like Java) can't do that either.

Note, that this applies independently of whether the dynamic language is run on a VM or compiled to native code. Most dynamic languages are run on VMs, but there are compiled ones too and they are all slower then statically typed ones.


问:
Why does Mono for Android cost money if the mono project is opensource and therefore everything based on it must be opensource?
Why does Mono for Android cost money if the mono project is opensource and therefore everything based on it must be opensource?</p>

答: Mono is LICENSED to OTHERS as Open Source.  That does not imply that the owners of the copyright have the same restrictions -- they can do whatever they like, including all forms of closed-source use, even if that seems to go against their founding principles.  To prevent that, you would AT LEAST need the company's official, registered aims to clearly state that all products would be open source, and probably for CEOs / other executives to be employed on a contract stating that they would always only create open source products.  Even then, the definition of "product" could undo that safeguard.</p>


问:
Why is Encapsulation considered a primary principle in OOP?
I am currently trying to understand more deeply the 4 principles of OOP: Abstraction, Encapsulation, Inheritance, and Polymorphism.

After studying the four principles, I don't fully understand why Encapsulation is considered one of the four primary principles of OOP.

Encapsulation is extremely common and useful in OOP, but it seems to me as more of a technique or strategy to use as part of Abstraction.

A good definition for Abstraction:

'Abstraction is the concept of moving the focus from the details and concrete implementation of things, to the types (i.e. classes), the operations available (i.e. methods), etc, thus making the programming simpler, more general, and more abstract.'

Encapsulation, on the other hand, is this:

'Hiding the internal implementation details of a class from the outside software world, and prividing an interface for other software entities to communicate and manipulate that class.`

If so, it seems to me that Encapsulation is mostly a technique to make things more abstract in the software system. Thus, it acts more of a strategy that implements the concept of Abstraction, rather than a primary principle by itself. It could be considered a 'principle' and not only a technique, but it still would be a part of the more general Abstraction principle, and not a major principle by itself.

Does anybody agree? If I'm wrong, please explain why.

答:
You need both a level of abstraction and the principle of encapsulation in order to think about objects as the primary units in the system.

Before OO the primary unit was functions that manipulated data. This was itself an abstraction above machine code which was operations acting on data. The principle of abstraction in the context of OO basically says stop thinking about functions and start thinking about units of collected behavior like we have in the real world (which leads to objects).

Encapsulation says that these units of collected behavior must be solely responsible for their own behavior and must stop other units of behavior from interfering with that (which again leads to objects).

So you really need both abstraction and encapsulation to get to objects, given that objects are distinct units of behavior that take responsibility for their own behavior.

It is possible to imagine a system where you have distinct units of common behavior but that these proto-objects have no restriction on other proto-objects going in and messing around the behavior. In fact that describes most badly designed OO software, full of getters and setters and exposed private methods.

Without encapsulation you don't have "objects" as people like Kay imagined, so abstraction to units of behavior is not enough.


答:
You won't get anywhere by just reading code; you need to be writing code. Just write code. Don't worry if the code you write is crap; everyone has written crap code. Some people make a living out of it. Nobody starts off writing good code and I'm of the opinion that while learning, it's almost necessary to write bad code because only then does the difference between good and bad code become truly apparent.

It's hard to appreciate the difference between good and bad code when reading two blocks of code that do the same thing, but when you've written a script and you get someone knowledgeable to review it and provide feedback the difference often becomes much more apparent because you can directly apply it to what you know.

Programming is not something you can learn by rote memorisation; it's not like your times tables or dates in history. Programming is a practical skill that requires constant practice to stay sharp. Learning programming without writing code is like learning to swim by reading a book.


答:
Actually, Google published a paper around two years ago about this topic which describes what you have noticed here. C++ programs allow typically more optimizations than programs written in languages like Java/Scala/Go (or in your case Groovy), which gives more opportunities to make them faster - but for the price of increased programming effort.

Said that, a speed factor of >5000 is to my experience very unusual. A factor between 2 to 20 is what I have noticed in the past (depending on the problem and the "other language" to be compared with C++). Such a factor indicates that there is a good chance of optimizing your Groovy program by at least one or two orders of magnitude without changing the language. www.stackoverflow.com would be the place to discuss certain optimization issues (provided you are willing to post some core parts of your code there).

Title: Speed difference between VM-based and compiled code

Body:
Not so long ago I was told by a senior academic that, these days, VM-based code could run nearly as fast as compiled code, but my own experience is that compiled code runs several orders of time faster.

This is based on code attempting to do the same thing (processing a very large XML file) - in the case of the VM-based code (Groovy) I guess my code would complete in about two years (correct) whereas the C/C++ based alternative took about three hours.

The algorithms were not quite the same - but that was because using C/C++ allowed me to manipulate the memory at a byte level using pointers. The Groovy code was easier to write as the language was much more expressive, but the price paid was slow execution.

I don't claim to be the world's greatest coder so I would willingly accept that my code could have been improved: but what is the general view?


答:
A Quick Foreword

Learn By Doing: Knowledge vs Know-How

There's a huge difference knowledge and know-how. It's a common mistake for new learners to think that because they can "understand" a program as they read it, they actually understand the reasoning for the program being written the way it is.

And the only way to get to that second part is to practice. Sit down, open a text editor, a command line, and get down to it.

Programming in the Small

It's likely (and expected) that at this stage your ability to comprehend how several complex software components interact with one another is limited. And it's actually a good thing, as it forces you to start from the basics. Don't jump the gun and move at the right pace: start with small exercises for small tasks.

To be honest I've never been convinced that starting to learn programming with Java is the way to go (I used to teach programming for a living in university, and still do occasionally private tuition). It is in itself too complex to get you started, and most Java books will appear quite daunting. Nevertheless, it surely can be done (at least for some areas of that global knowledge we expect from programmerS), as long as you restrict yourself to learning step by step.

Books

As you're set on Java, and if you need a decent Java book, I'd recommend:

Thinking in Java. It's OK, though now slightly outdated.

The Java Tutorial. It's not exactly the best learner's companion, but a great reference to keep at hand, as it covers all the basics and provides examples. The Learning the Java Language Trail should probably be on your reading list, though I'd think it can be daunting for complete beginners as it introduces concepts that may be hard to grasp at first.

Effective Java. It's not a great book for learning, but also an awesome reference you should have at hand for later. Not to read in one sitting, but in bite-sized chunks.

I'm only mentioning this as I don't know what you use in class. There's a tons of other books. Some are good. Some will cripple students for years.

Your Study Process

The Basic Workflow

From now on, I'd advise you to follow this 2-step process for all the exercises and code samples you've seen in class:

read and study

read the exercises

make sure you understood them

code

close the book

sit down in front of a computer with that code editor and command line

attempt to rewrite the program by yourself

In case of Failure

If you fail and feel like you need to take a peek at the book, your failure is likely to be either:

(most likely) that you didn't actually understand the solution,

(less likely) that you've forgotten how a particular bit of the solution looks like: syntax, API use, ...

The first cause is likely to be what you face the most often. The second one is anecdotal. Both are addressed by recurrent practice.

Every time you fail at implementing one of these early examples, look at the book again, then close it again. Don't code while looking at the book. I'd even advise that you delete your entire solution and start over. The repetition is an annoying but important part of the learning process.

Do not take this lightly. Every time you feel the urge to tell yourself "yeah, ok, I know this" or "I'm 90% there, it's almost as good as done" and want to skip to another section, fight that urge back and start over. It's very difficult to have the honesty to admit to yourself that you didn't fully understand a concept.

Side note: I consider it a great disservice that most school programs now attempt to "kickstart" programming courses by dumbing things down too much and providing tooling that's too advanced for students: the goal is not to make your life miserable or for you too learn by heart things that later in your career will be automated by your tools and that you'll sometimes even barely remember. It's to teach you all the bits that float around.

In Case of Success: Go Beyond!

If you succeed at implementing your exercise, don't necessarily jump directly to the next one. Try to see what you can do to improve that one. Can you change the output that was requested? Add a small feature? An option? Try to, as you are now in that fun zone where you're passed the main difficulty, and these self-imposed tiny requirements are more likely to keep your spirits up a bit.

Don't go too far though: you don't go from printing the alphabet and reversing it to suddenly making it appear on a diagonal on the screen with a gradient of colors. Take small steps. Learning is a long and iterative process, and you need to approach problems with increasing levels of difficulty (for instance, see how I usually think of explaining recursion).

It's Just Learning - A Comparison

Your problem is actually not related to programming at all. It's the same problem thousands of people encounter when they try to learn maths.

If you give them a problem, they don't see how to work their way to the solution. However, if you write down the solution for them, most will understand it and think "darn, that was so simple!". Yet you'll give them a similar problem with different measures and hypotheses and they'll fail to solve it: they didn't understand the logic behind it, and they need practice to be able to do it themselves.

Note that this is a common problem with maths, but in my opinion you see it in tons of other fields where there's some logic required: learning solfege, language grammar, physics, etc... And it's not down to a "natural" ability to understand these things: it just comes down to practice (be it in that area, or in others that lead the individual to grasp concepts in this field more easily).

There's no reason you can't learn to write code. You just jave to keep trying until you reach that "ah AH!" / Eureka moment. Then move on to the next, harder, problem.

These may help as well (later):

Learn programming backwards, or "so I failed the FizzBuzz test. Now what?"

https://softwareengineering.stackexchange.com/questions/151229/im-having-trouble-learning/151242#151242


答:
virtual machine. a self-contained operating environment that behaves as if it is a separate computer, with no access to the host operating system: When an application runs in a virtual machine, there is little chance that it will damage files or applications in the host system.

Also  a platform-independent execution environment that itself runs as a normal application inside a host operating system and enables a program written for the virtual machine to execute the same way on any platform:

Title: How do I explain to my boss what a 'Virtual Machine' means?

Body:
Most probably my boss didn't write a single word on a keyboard in his entire life.

He saw computers and he has a cell phone. He is a smart man.

How can I explain to him what a 'virtual machine' is?
(VM as in VMWare + virtual Box, not the VM as in Java, LLVM, .NET)

One of the reasons for asking this is that I want to tell him that having a Linux VM to connect to internet with a Windows host is safer than connecting directly to Windows.


问:
See remote repository differences with a graphical tool
My GIT repo is stored on a remote Linux server that I'm accessing from my Windows PC through Netbeans.

Once my changes are done I would like to review them quickly before committing.

The server has no graphical components so I can't launch "gitk" from there.
I'm not very comfortable with a text diff on the server with "git diff" command. It is not readable enough for me.

msysgit is installed on my Windows PC. I would like to launch a kind of remote "gitk" command from my PC but couldn't find a way to do it. Didn't find anything on the web related to this.

Any other "graphical" way to do this would be convenient.

Any idea how to do this?

Thanks in advance

EDIT

To clarify my workflow (since my question seems to lack clarity):

I work on my code with Netbeans IDE on a local copy of my remote working repository. This copy has no versioning. The synchronization is done through SFTP. Meaning, at project creation Netbeans makes a SFTP GET of the entire repo localy. Then, when I save my changes (on local copy) Netbeans automatically makes a SFTP PUT to the remote repo through SFTP to keep in sync.

The working repository on the web server (Linux based) has git versioning. Hence keeping track of the same changes that I made on the Windows copy.

For simplicity reasons (I'm working alone on this project so far) I don't want to clone the working repo or create a different branch than master. Hence I'm working on this unique repository and directly with the master branch.

Once a development is done and tested (my changes are not yet staged for commit) I want to have a last look at them before committing. To achieve this I would like to use a graphical tool. I have msysgit installed on the windows PC but I didn't find a way to load a remote repository to my local gitk through SSH (I don't think it is possible).

Finaly:
I'm looking for a way to do this with gitk or any other tool. I didn't find one so far. git-cola for instance doesn't propose anything but loading local repos.

I found a solution proposed here: https://stackoverflow.com/questions/6810820/git-gui-when-on-a-remote-server

But I'm wondering if a simpler solution exists.

EDIT2

The idea of this question was not to start a debate on which tool is better for my concern. It was: how to do it the best way WHATEVER the tool is.

Anyway, here is the workflow I'm finally using for those interested:

The working repo is on the Linux server.

Netbeans (or whatever the tool is) is editing a local copy of this remote working repo on windows. The "download from" and "upload to" the remote repo are made through a ssh connection. So remote repo and local repo are always synchronized.
The simplest way to look at what was done since last commit on the repo is to make the windows local repo a git working repo and launch gitk from there.

Only inconvenience is not to forget to commit the local repo when I commit the remote one to get same diffs between last commit and current.

Hopefully it will help other persons with same concern.

答:
It sounds like you're not understanding a key feature to Git. Git is a distributed version control system. This differs from a centralized revision control system because a repository's entire history can exist in many places at once.

When you make a commit using git, this commit is on your computer only. When you make a new branch, this branch exists on your computer only. You can do this many times making hundreds of commits on different branches and the only place they will exist is on your computer. That is, until you push those commits + branches or someone else fetches them.

This brings in the  concept of remotes. Remotes are simply other locations of the same repository. You could have a remote on your server, on GitHub or even another location on the same computer. With the right setup you can push commits to remotes and you can fetch commits from the remotes.

Using one of the Gui's listed here you can get a good view of a repository's history. The gui will show you where different branches are located both on your local repository and on any remotes that your local repo knows about. In order to get new information about remote repositories you need to do a fetch.

It is safe to assume that if a given branch is at commit X then any of X's parent commits are also applied to that branch.


问:
What exactly is procedural programming? How exactly is it different from OOP? Is it the same as functional programming?
I am programming in Java in a very object-oriented (OO) style. OOP comes very intuitively to me, but I have very little knowledge about other kinds of programming.

What exactly is procedural programming? How exactly is it different from OOP? Is it the same thing as functional programming?

I used to think that all programming that isn't OO is procedural. But I'm starting to think this isn't true.

答:
Procedural Programming is definitely not functional programming.

Procedural programming is when you have a model of the computer as a machine in your head, and you're thinking about how it's modifying data in memory.  So first you set A to the value 3, then you add 1 and store that in memory location A again (overwriting the previous value).

Functional programming would be saying A is 3, and B is A + 1, and then letting the computer figure out how to calculate B.  Once you've defined A it should be immutable (non-changing).  Functional also allows you to do things like pass a function around as a first-class value (a function can take a function as an argument).

Object-oriented programming often combines both, and is kind of orthogonal to both.  You can use functional programming and return an immutable object, and that object can have a method that returns some calculated value, and even do it lazily - that's functional object oriented programming.  You can also have an object that represents a "repository" (abstract version of a database), and you can "save" stuff in the repository and "get" stuff back out, and let that object handle all the details of how that's done.  That's basically object oriented procedural programming.


答:
Procedural Programming is an approach to programming that is one of the basic of building blocks for many other language designs (functional not being one).

Most languages fall into the set of "Procedural Programming" and it is probably the most natural design approach for most people (if you think in terms of OO, then I'd say you're in a minority).

BASIC is procedural.

As others have said, it is a mechanism for structuring programs in a sequential manner.

First I do x

Second I do y

Thirdly I do Z

It requires a mechanism for defining "procedures" - blocks of named code similar to OO methods, that can accept zero to many parameters, and optionally return a value (which would then generally be called a function - probably leading to your confusion with functional languages)

The paradigm does not dictate what the things you do will be, or the manner of the things being passed around.

It simply describes that the program will be structured as a series of procedures (or functions) that operate in a sequential manner.  The data is then defined independently of the procedures.

This differs from object-oriented programming, which structures the program around collections of data and methods (not functions) that act on that data.

One way to think about it is in terms of data scope.

In a procedural language scoping is fairly simple.  A variable may be in the scope of a given procedure (declared locally), up to the level of the top thing calling stuff (declared globally), with nested scopes between.

In an object-oriented language you add a new scoping context, being that of the object currently in use, which is orthogonal to the above.

Another way to think of procedural, as compares to object-oriented is to consider an object-oriented language where all methods must be declared as static.  The result is a procedural language where classes can be used to group procedures together.

Title: What exactly is procedural programming? How exactly is it different from OOP? Is it the same as functional programming?

Body:
I am programming in Java in a very object-oriented (OO) style. OOP comes very intuitively to me, but I have very little knowledge about other kinds of programming.

What exactly is procedural programming? How exactly is it different from OOP? Is it the same thing as functional programming?

I used to think that all programming that isn't OO is procedural. But I'm starting to think this isn't true.


答:
Wikipedia has good explanations for these terms. Regardless, here's the summary:

Imperative programming models computation as a sequence of statements that alter mutable state.

Procedural programming is imperative programming that breaks down the code into subroutines.

Structured programming is a more disciplined approach to procedural programming that forbids arbitrary jumps (e.g. goto) and global state changes.

Declarative programming is the opposite of imperative programming - it specifies what to calculate rather than how (e.g. SQL, regexes).

Functional programming models computation as expressions that (may) yield values. Functions are values and can be passed to or returned from other functions. Mutation is discouraged; all variables are immutable by default. As a result, it's more declarative than imperative, since it emphasizes what is being computed rather than the sequence of state changes needed to achieve it.

Purely functional programming disallows mutation altogether (though contrary to popular belief still has mechanisms for achieving side effects).

Total functional programming additionally forbids exceptions and infinite looping. (A total function in mathematics is a function that returns a value for all of its inputs.)

Object-oriented programming emphasizes the use of objects/interfaces to achieve abstraction and modularity.

Their relationships are a bit complicated because OOP is a pretty loaded term. You can use objects in both functional languages and procedural languages, but the languages that advertise themselves as OO are procedural. To further confound the issue:

Most people don't know the difference between an object and an abstract data type

Mainstream OOP languages make no mention of ADTs, provide very poor support for them, and tout objects as The One True Way.

No one says Abstract Data Type-Oriented Programming (because it'd be a silly thing to do; you need both ADTs and objects.)

This causes people to think OOP is the only way to achieve abstraction, and that functional programming and OOP are somehow opposites or mutually exclusive. A lot of people also think all functional languages are pure and disallow mutation.

Additionally, people generally toss around imperative/procedural interchangeably, sometimes contrasting it with OOP (implying abstraction-less code, generally C) and sometimes contrasting it to functional programming. The term structured programming has mostly fallen out of use as far as I can tell (likely because at this point most people take for granted that goto and globals are considered harmful.)


答:
Just thought I'd chime in on this topic because it really hits close to home.

You just need to start coding. Don't get me wrong, reading is great but what really gives you that working coding knowledge is actually building something. I learnt more from a single summer placement than I did the previous year reading about it.

I should also add that you should't just start coding blindly. Make a project for yourself. You need some sort of direction to put yourself in so you know what you want to make. You'll be surprised to see how much you'll learn quickly. If you just open up an IDE and start making simple hello world examples, that demotivating feeling will creep up on you quickly. Find something with a little depth and before you know it you'll be expanding on it.


问:
lots of images and ajax, or better solution?
I have a control where the user can select a value for the x and y axis from 2 dropdowns, and then there is a 4 by 4 grid (an image) which will show what their selections correspond to (updating dynamically).

So, if the grid is:

```<code>a b c d
e f g h
i j k l
m n o p
</code>```

If the user picks 2 for row (column is null for now), e f g h should highlight (using an outline). If they then pick 3 for column, only g should highlight. And so on for every combination.

I know I can figure this out by making 25 separate images (one for each square + 4 rows + 4 cols + both null) and then load in the right image using ajax, but my question is if there is a better way or some sort of dynamic solution where I can draw over the image, or overlay another image in an intelligent fashion?

答:
The way I ended up deciding to go was to use a full image and css to turn it into sprites, put the sprites in a table, and use table borders and JavaScript for highlighting.

ETA: The reason I went this way (thanks @gnat) was threefold:

Less bandwidth- pulling 1 image down is much more efficient than potentially pulling 25 (and having to use ajax every time an option changes). Not to mention I don't have to create and store said images.

Backwards compatibility. Every browser can render a table with borders, but only the newer generation of browsers (html5 compliant) can use things like the canvas object, for example, if I were going to draw over the image.

Simplicity. It's easy to manipulate borders around rows, columns, or an individual cell of a table using javascript.


问:
What should I do when I've already waited too long between commits?
I was naughty... Too much "cowboy coding," not enough committing. Now, here I am with an enormous commit. Yes, I should have been committing all along, but it's too late now.

What is better?

Do one very large commit listing all the things I changed

Try to break it into smaller commits that likely won't compile, as files have multiple fixes, changes, additional method names, etc.

Try to do partial reversions of files just for appropriate commits, then put the new changes back.

Note: as of right now I am the only programmer working on this project; the only person who will look at any of these commit comments is me, at least until we hire more programmers.

By the way: I am using SVN and Subclipse. I did create a new branch before doing any of these changes.

More information: I asked a separate question related to how I got into this situation in the first place: How to prepare for rewriting an application's glue

答:
I think whatever you do, try to avoid checking in code that you know won't compile.

If you think your third option is feasible, that might be a good way to do it, as long as you can ensure that your sequence of commits won't create an uncompilable system. Otherwise, just do the one big commit. It's ugly, but it's simple, quick, and gets it done. Going forward, commit more often.


答:
Although the only reasonable answer is to never break the trunk, some times it is not possible. For example, svn can break commit if you commit too much (maybe an option, or a feature, I am not sure). In such special cases, just check in in pieces. Since you are a single programmer it is not going to disturb anyone.

Therefore, I would go for option 1. If not possible, then option 2.

Option 3 requires much effort, and it simply isn't worth it.

Title: What should I do when I've already waited too long between commits?

Body:
I was naughty... Too much "cowboy coding," not enough committing. Now, here I am with an enormous commit. Yes, I should have been committing all along, but it's too late now.

What is better?

Do one very large commit listing all the things I changed

Try to break it into smaller commits that likely won't compile, as files have multiple fixes, changes, additional method names, etc.

Try to do partial reversions of files just for appropriate commits, then put the new changes back.

Note: as of right now I am the only programmer working on this project; the only person who will look at any of these commit comments is me, at least until we hire more programmers.

By the way: I am using SVN and Subclipse. I did create a new branch before doing any of these changes.

More information: I asked a separate question related to how I got into this situation in the first place: How to prepare for rewriting an application's glue


答:
When making an assignment, the value assigned is considered the "result" or "return value" of the expression.  It's subtle and maybe not clear because your example is something that is rarely done.

For example:

```<code>int i = 5;
int j = (i = 6);
</code>```

At this point in the code, both i and j are equal to 6.  We assigned i to the value 6 and then captured the return value of the expression, which is the value which was transferred, which is 6.

Personally, I would avoid this because it can be very confusing and easy to introduce bugs.  Especially in a System.out.println or any call that is expected to not change the state.  It violates the principle of least astonishment.

Ever wonder why programming classes teach you to always use a double-equals (==) in an if statement?  Ever noticed that with a single equal sign, it may still work?  This is why.  The process of evaluating a condition is changing the condition, creating a truism or falsism.  The number of software defects caused by if (x = y).....

Many programmers (I have not picked up the habit yet, but probably ought to) prefer to write if statements with the constant on the left side like if (5 == x) instead of if (x == 5) so that if they accidentally use a single equal sign, the compiler won't allow it.

To take this to your code example, you are right, the expression is "returning" a value.

```<code>String fruit;
System.out.println(fruit="Orange"); //prints orange
</code>```

When the JVM runs this code, one instruction at a time, it sees 3 instructions in this order:

```<code>String fruit;
String someInternalStackVariableYouDontSee = (fruit = "Orange");
System.out.println(someInternalStackVariableYouDontSee );
</code>```

Title: Why do expressions print variable value using System.out.print?

Body:
Why does java print the value of the variable that is assigned it in the code below? I want understand what is happening here.

My thought is that the expression inside println() method is evaluated first. For the first example, 5 is assigned to int x. At that point, does x become available for the println() method to print its value?

This code confuses me. I wouldn't have thought expression like x=5 could return a value. Thank you.

Examples:

```<code>int x;
System.out.println(x=5); //prints 5

boolean isValid;
System.out.println(isValid = true); //prints true

String fruit;
System.out.println(fruit="Orange"); //prints orange
</code>```

Body:
When making an assignment, the value assigned is considered the "result" or "return value" of the expression.  It's subtle and maybe not clear because your example is something that is rarely done.

For example:

int i = 5;
int j = (i = 6);

At this point in the code, both i and j are equal to 6.  We assigned i to the value 6 and then captured the return value of the expression, which is the value which was transferred, which is 6.

Personally, I would avoid this because it can be very confusing and easy to introduce bugs.  Especially in a System.out.println or any call that is expected to not change the state.  It violates the principle of least astonishment.

Ever wonder why programming classes teach you to always use a double-equals (==) in an if statement?  Ever noticed that with a single equal sign, it may still work?  This is why.  The process of evaluating a condition is changing the condition, creating a truism or falsism.  The number of software defects caused by if (x = y).....

Many programmers (I have not picked up the habit yet, but probably ought to) prefer to write if statements with the constant on the left side like if (5 == x) instead of if (x == 5) so that if they accidentally use a single equal sign, the compiler won't allow it.

To take this to your code example, you are right, the expression is "returning" a value.

String fruit;
System.out.println(fruit="Orange"); //prints orange

When the JVM runs this code, one instruction at a time, it sees 3 instructions in this order:

String fruit;
String someInternalStackVariableYouDontSee = (fruit = "Orange");
System.out.println(someInternalStackVariableYouDontSee );


答:
The problem is not in long delays between commits but in the fact that you keep the code in uncompilable state too long time. First of all what is your definition of 'long'? For some people 5 minutes for transitional state is too much but some can polish their code for days without even try to run compiler.

In fact it doesn't matter - what matters is that you lost control of your code, your code became unmanageable. This is normal, it just means that you have technological debt and it's time to think about refactoring. So you are frustrated? You code doesn't not compile, you even don't have unit tests? How can you think about refactoring in this case? No worries. Finish your "cowboy coding" and start cleaning it. Ideally try to write some tests. You don't have time for that? Ok, start from small improvements.

Some changes doesn't require tests. Change the name of variable for more suitable, move repeating code into separate function, etc... You will get better idea of your code. After that you can do bigger changes. Again, try to write tests if possible. Make your code manageable.

After that you will see that next change doesn't take you "too long" (whatever it means).


问:
How to explain OOP to a matlab programmer?
I have a lot of friends who come from electrical / physical / mechanical engineering background, and are curious about what is "OOP" all about. They all know Matlab quite well, so they do have basic programming background; but they have a very hard time grasping a complex type system which can benefit from the concepts OOP introduces.

Can anyone propose a way I can try to explain it to them? I'm just not familiar with Matlab myself, so I'm having troubles finding parallels. I think using simple examples like shapes or animals is a bit too abstract for those engineers. So far I've tried using a Matrix interface vs array-based / sparse / whatever implementations, but that didn't work so well, probably because different matrix types are already well-supported in Matlab.

答:
They all know Matlab quite well

Then it is quite simple : let them try simulink. Simulink models are in OOP spirit. If they understand how to create a simulink model, and if they know how simulink works, then they already know what OO is about.


问:
How to really understand programming?
I have started to learn to program. I am interested in it and dont mind how long it takes to learn. But I am using books to start out and I find that there are some things I get and some things I have no idea.

I can understand the code when I see an example but I feel completely lost if I were to go out and do something on my own. I have barely any experience: maybe 20 or so hours, which I understand is absolutely nothing.

When does everything come together?

What are some best ways to learn that anyone else has found?

Are there any good projects people have done that have been a great learning experience?

答:
The absolute best way to learn how to program is to write code.

There's no way around it, especially as - and you said so yourself - it's the goal in itself.

Reading is For Background and Research

Books, blogs, podcasts and the likes will get you started and give you general background and knowledge at first, and then help you study more complex algorithms or learn about software engineering techniques and best practices.

Get Started

If you want to learn to code, you need to code. Pick a language, find something you want to start working on, and get down to it. Or find a list of small exercices and do them.

Possible Book Suggestions

Several approaches. In any case, it's vital that you actually do what the books tell you to do and don't just simply read them.

For the Practical Mind

If you're the practical kind, these would be good introductory books to coding. That is, if you're curious enough to then go beyond what the books teach you:

Learn X the Hard Way Series, by Zed Shaw

Learn Python the Hard Way (the original)

Learn Ruby the Hard Way

Learn C the Hard Way

Why's Poignant Guide to Ruby, by why the lucky stiff (aka Johnathan Gillette)

Learn You a Haskell for Great Good, by Miran Lipovaca

Some will say they are light on the details and overlook very important concepts, but the point is to get you going and to enjoy programming quick. So if you're easily distracted and want to see quick results, maybe these are for you.

For the Academic in You

If you're the studious and academic kind, these are good bibles, if you get past the fact you can also use them to kill someone:

Structure and Interpretations of Computer Programs, by Hal Abelson, Jerry Sussman and Julie Sussman

Concepts, Techniques and Models of Computer Programming, by Peter Van Roy and Seif Haridi

Some consider them not a good fit to get started, because they are detached from the reality of software engineering in professional settings (mostly because of the languages and tooling used, but also because of the purity generally sought in the answers).

They are extremely good books though.

For the Life-Long Learner

Or at least for the one who goes beyond just learning the basics and wants to dive into the more arcane areas of the craft, both in terms of algorithmics or in terms of software engineering practices:

The Pragmatic Programmer, by Andrew Hunt and David Thomas

The Art of Computer Programming (can also be a decent armor plate, or provide lots of energy in winter), by Donald Knuth

Software Engineering, by Ian Somerville

Refactoring: Improving the Design of Existing Code, by Fowler, Beck, Brant, Opdyke, Roberts

Working Effectively with Legacy Code, by Michael Feathers

Clean Code, by Robert C. Martin

Code Complete *, by Steve McConnell

Suggested Helpful P.SE Threads

Able to read Code but struggling majorly to write it (actually posted just a few hours before your question)

How can I  really master a programming language?

https://softwareengineering.stackexchange.com/questions/151229/im-having-trouble-learning/151242#151242

Learn programming backwards, or "so I failed the FizzBuzz test. Now what?"

* For some reason unknown to me, I dislike this book very much. Blasphemy, I know, right? Too heavy, hard to navigate (subjective), repeats itself too much and could easily be half-the size. Maybe because I read it too late in my career, I don't know.

Title: How to really understand programming?


问:
WHere do I put my update class and handle request / response from HTTP web request?
I don't know how to organize my code.  Right now I just dumped everything in MainPage for testing.  But what is the proper way to handle getting data from REST web service in Windows Phone 8?  I have multiple pages that need to utilize the data that is returned.</p>

```<code>    /// <summary>
/// State information for our BeginGetResponse async call
/// </summary>
public class UpdateState
{
    public HttpWebRequest AsyncRequest { get; set; }
    public HttpWebResponse AsyncResponse { get; set; }
}

public partial class MainPage : PhoneApplicationPage
{
    // Constructor
    public MainPage()
    {
        InitializeComponent();

        // Sample code to localize the ApplicationBar
        //BuildLocalizedApplicationBar();
    }

    private async void test()
    {

        var handler = new HttpClientHandler();
        if (handler.SupportsAutomaticDecompression)
        {
            handler.AutomaticDecompression = DecompressionMethods.GZip |
                                             DecompressionMethods.Deflate;
        }

        // form the URI
        UriBuilder fullUri = new UriBuilder("http://test/GetData?");
        fullUri.Query = "format=xml&param=test&dateFrom=20071225&dateTo=20080101";

        var httpClient = new HttpClient(handler);
        var str = await httpClient.GetStringAsync(fullUri.Uri);
        string test = "";
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {

        test();

        // form the URI
        UriBuilder fullUri = new UriBuilder("http://test/GetData?");
        fullUri.Query = "format=xml&param=test&dateFrom=20140124&dateTo=201425 ";

        // initialize a new WebRequest
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(fullUri.Uri);

        // set up the state object for the async request
        UpdateState state = new UpdateState();
        state.AsyncRequest = request;

        // start the asynchronous request
        request.BeginGetResponse(new AsyncCallback(HandleResponse),
            state);
    }

    /// <summary>
    /// Handle the information returned from the async request
    /// </summary>
    /// <param name="asyncResult"></param>
    private void HandleResponse(IAsyncResult asyncResult)
    {
        // get the state information
        UpdateState forecastState = (UpdateState)asyncResult.AsyncState;
        HttpWebRequest forecastRequest = (HttpWebRequest)forecastState.AsyncRequest;

        // end the async request
        forecastState.AsyncResponse = (HttpWebResponse)forecastRequest.EndGetResponse(asyncResult);

        Stream streamResult;

        string newCredit = "";
        string newCityName = "";
        int newHeight = 0;

        string XMLresult = string.Empty;

        try
        {

            // get the stream containing the response from the async call
            string type = forecastState.AsyncResponse.ContentType;
            streamResult = forecastState.AsyncResponse.GetResponseStream();

            XMLresult = getXMLData(streamResult);

            // load the XML
            XElement xmlData = XElement.Parse(XMLresult);

            string t = "";

        }
        catch (FormatException)
        {
            // there was some kind of error processing the response from the web
            // additional error handling would normally be added here
            return;
        }

    }
</code>```

答:
Take a look at the Single Responsibility Principle.  The idea is you would create separate classes for each chunk of code that does only one thing.  These should all be in their own CS file by the way.

In your example, I would split out the Http Request and XML parsing into their own classes.  The Xml Parsing code should return a Model class which represents the data structure you are expecting back.  Once you get to that point, go back and review all your code.  Ask yourself do each one of these files only do a single thing?  If not, refactor your more to split out more classes.


问:
My architecture has a problem with views that required information from different objects. How can I solve this?
I am building an architecture like this:
These are my SW layers

```<code> ______________
|              |
|    Views     |
|______________|

 ______________
|              |
|Business Logic|
|______________|

 ______________
|              |
|  Repository  |
|______________|
</code>```

My views are going to generate my HTML to be sent to the user
Business logic is where all the business logics are
Repository is a layer to access the DB

My idea is that the repository uses entities (that are basically the representation of the tables, in order to perform DB queries.

The layers communicate between themselves using Business Objects, that are objects that represent the real-world-object itself. They can contain business rules and methods.

The views build/use DTOs, they are basically objects that have the information required to be shown on the screen. They expect also this kind of object on actions and, before calling the business logic, they create BO.

First question: what is your overall feeling about this architecture?

I've used similar architecture for some projects and I always got this problem:
If my view has this list to show :

```<code>Student1, age, course, Date Enrolled, Already paid?
</code>```

It has information from different BO.
How do you think one should build the structure?

These were the alternatives I could think of:

The view layer could call the methods to get the student, then the course it studies, then the payment information. This would cause a lot of DB accesses and my view would have the knowledge about how to act to generate this information. This just seems wrong for me.

I could have an "adapter object", that has the required information (a class that would have a properties Student, Course and Payment). But I would required one adapter object for each similar case, this may get very bad for big projects.

I still don't like them. Would you have ideas? How would you change the architecture to avoid this kind of problems?

@Rory:
I read the CQRS and I don't think this suits my needs. As taken from a link references in your link

Before describing the details of CQRS we need to understand the two main driving forces behind it: collaboration and staleness

That means: many different actors using the same object (collaboration) and once data has been shown to a user, that same data may have been changed by another actor – it is stale (staleness).

My problem is that I want to show to the user information from different BO, so I would need to receive them from the service layer. How can my service layer assemble and deliver this information?

Edit to @AndrewM:
Yes, you understood it correctly, the original idea was to have the view layer to build the BOs, but you have a very nice point about the creation of the BO inside the business layers.
Assuming I follow your advice and move the creation logic inside the business layer, my business layer interface would contain the DTOs, for instance

```<code>public void foo(MyDTO object)
</code>```

But as far as I understand, the DTO is tightly coupled to each view, so it would not be reusable by a second view. In order to use it, the second view would need to build a specific DTO from a specific view or I would have to duplicate the code in the business layer. Is this correct or am I missing something?

答: You may want to look at the Command Query Responsibility Segregation pattern. Essentially, you introduce new models to match how the system is used. You might have e.g. an enrolment reporting model to handle your query, while using Student, Course etc. models for your basic CRUD operations.</p>


答:
To answer, you have to ask yourself how you expect to use the results of these commits in the future.  The most common reasons are:

To see what release a bug was introduced.

To see why a certain line of code is present.

To merge into another branch.

To be able to check out a previous version for troubleshooting an issue a customer or tester is seeing in that version.

To be able to include or exclude certain parts from a release.

The first two reasons can be served just as well with one big check-in, assuming you can create a check-in message that applies equally well to each line of changed code.  If you're the only programmer, then smaller commits aren't going to make your merge any easier.  If you don't plan on doing a release or testing with only part of your unsubmitted changes, then the last two reasons don't apply.

There are other reasons for making small commits, but they are for while you are in the middle of the changes, and that time is past.  Those reasons are making it easier to back out a mistake or an experimental change, and making it easier to keep synced up with colleagues without huge scary merges.

From my understanding of your situation as you described it, it seems there's little to no benefit to splitting your commit at this point.


答:
Try to break it into smaller commits that likely won't compile, as files have multiple fixes, changes, additional method names, etc.

When I've found myself in a similar situation I used the following technique:

Add only the code that is relevant to a particular feature: git add --patch

Stash all other changes: git stash save --keep-index

Run tests/try compiling

Commit changes if everything is okay, if not go to 1

I'm not familiar with SVN, so I don't know if this is applicable to your specific situation, but the basis should be the same - isolate small parts of code and test them individually.


答:
The most important reason to make frequent, small, and meaningful commits is to aid understanding of the history of the code. In particular, it's very difficult to understand how code has changed if it's difficult to generate understandable diffs.

Option 1 obfuscates the history of changes you've made, but otherwise it won't cause any problems.

Option 2 obfuscates the history of changes you've made, possibly somewhat less than option 1, but it could cause other problems for yourself or others if they assume or otherwise conclude that the commits are distinct, e.g. can be merged into other branches independently. Unless there's a strong practical reason why this is preferred over option 1, this is less ideal than it.

Option 3 is best, all else being equal, but if, as you've described elsewhere, doing so would require "extreme" amounts of time or would incur other significant costs, you'll have to weigh those costs against the expected benefits of creating cleaner commits.

Based on the info you've provided, I'd opt for option 1. Maybe you should setup reminders prompting you to commit your changes?

Prototyping and Rewriting

Another consideration to keep in mind, especially in light of your note about being the sole programmer, and my suspicion that you're working on a relatively new codebase, is that it's probably good to develop different habits with respect to committing changes for when you're prototyping new code versus maintaining or extending existing code. There probably isn't a terribly sharp division between the two, but I think it's still a useful distinction.

When you're prototyping new code, commit whenever you want to save your changes, almost certainly in a branch, but perhaps in a separate project. Or maybe even just work outside version control altogether. You can instead focus on gathering evidence about the feasibility of various hypotheses or designs you're considering. I often write small prototypes using different tools, e.g. LINQPad instead of Visual Studio for C# code.

When you've validated a particular hypothesis or design, rewrite it in your main project, ideally in a branch, and make the small, meaningful commits that will best aid the understanding of others (including future you) as to the nature of the changes you're making.


问:
What is the point of a Gantt Chart, and will it help me?
My (non-technical) colleague has threatened me with a Gantt chart for a new project that we are currently planning.  What is this likely to provide for us, and will it be a helpful tool?</p>

答:
If your project is a software development project then a gantt chart won't be very helpful and will mostly be a waste of time. They aren't designed for the fluid nature of software development, ie.

Tasks aren't usually order dependent. They can be done in any order.

The order of the tasks can alter the time required to complete the task.

Tasks can spawn other tasks, eg bugs

The upshot is you will spend more time updating the plan than doing the work.

Just manage your requirements and everything else will take care of itself.

YMMV

ContentLicense: CC BY-SA 2.5


答:
As others have said, this is a case where you must practice, practice, practice.

Write a bunch of small programs that solve one problem only

Sometimes, the hardest part is actually coming up with something worth programming.  If you can, try to work in a topic that you think you're struggling with - like classes, inheritance, etc.  Some ideas off the top of my head:

Generate 1000 random numbers and insert them into a collection(queue, list, etc).  Sort the collection without using any provided methods that sort the collection for you.

List 10 people you know.  First sort their names based on first names and display them.  Then, sort their names based on their last names and display them.  Then, try sorting them based on the pattern "last, first"(ie so Smith, Andrew would be before Smith, Jessica).

Find all prime numbers between 1 and 100.

(Inheritance) Make a Polygon class, and give it the function GetArea.  Now, make the classes Triangle and Rectangle inherit from Polygon, and make sure they implement GetArea.  Keep doing this for higher order polygons(pentagon, hexagon, etc).

Try picking things from the code golf stack exchange*

*The purpose of code golf is to do the provided task by using the least amount of characters, bytes or some other metric stated in the question.  If you read some of the answers, you quickly appreciate the clever ways people solve these problems.  Do not focus on solving the problem in the fewest bytes!  The people who post to code golf are very experienced programmers.  But, some of the questions offer easy tasks in and of themselves.

Some fun code golf examples:

Powers of 4.  Don't worry about solving with a regex(it is quite difficult, as you can see by the answers).  But, instead solve the question "Given a string s, is its length divisible by a power of 4?"  You can do offshoots as well: Is a string's length divisible by 4? Is it divisible by 6?  Is it prime(this is difficult for long strings, so try it if you get gutsy!)?

Substrings. Given a string s, output all possible substrings.

Word counting.  This one may be tricky depending on how far you are in your programming studies.  There are a few things that make it very easy(like associative collections), but if you don't know those things it can be difficult.

If the title sounds cryptic to you, just ignore the question.  Like I said, code golf is for experienced programmers.  Just focus on the simple problems, and try to come up with a simple answer.

Basic structure of solving a problem:

A lot of these give you a good idea of what a function should look like.  Given X, do Y, and the result should be Z:

```<code>void foo()
{
    // Set up X here

    // Do Y here

    // Display Z here
}
</code>```

For the purposes of learning the basics and becoming familiarized with a language, the above template is sufficient.  A more object-oriented template would be:

```<code>Z foo(input X)
{
    Z result;
    // Do Y to X
    return result;
}
</code>```

If it helps, write it down on paper as well.  Talk yourself through the process of how you, as a human being, would solve this problem.  Example: Given the numbers i, j, and k, display them in descending order.  As a person, it's easy to solve.  The hard part is translating your ideas into line-by-line instructions so a computer can solve it.

Try to come up with your own ideas as well.  It can be tough, but even the simplest of programs might teach you something you didn't know.  The whole point is to drill yourself with the basics, until they become second nature.

Body:
As others have said, this is a case where you must practice, practice, practice.

Write a bunch of small programs that solve one problem only

Sometimes, the hardest part is actually coming up with something worth programming.  If you can, try to work in a topic that you think you're struggling with - like classes, inheritance, etc.  Some ideas off the top of my head:

Generate 1000 random numbers and insert them into a collection(queue, list, etc).  Sort the collection without using any provided methods that sort the collection for you.

List 10 people you know.  First sort their names based on first names and display them.  Then, sort their names based on their last names and display them.  Then, try sorting them based on the pattern "last, first"(ie so Smith, Andrew would be before Smith, Jessica).

Find all prime numbers between 1 and 100.

(Inheritance) Make a Polygon class, and give it the function GetArea.  Now, make the classes Triangle and Rectangle inherit from Polygon, and make sure they implement GetArea.  Keep doing this for higher order polygons(pentagon, hexagon, etc).

Try picking things from the code golf stack exchange*

*The purpose of code golf is to do the provided task by using the least amount of characters, bytes or some other metric stated in the question.  If you read some of the answers, you quickly appreciate the clever ways people solve these problems.  Do not focus on solving the problem in the fewest bytes!  The people who post to code golf are very experienced programmers.  But, some of the questions offer easy tasks in and of themselves.

Some fun code golf examples:

Powers of 4.  Don't worry about solving with a regex(it is quite difficult, as you can see by the answers).  But, instead solve the question "Given a string s, is its length divisible by a power of 4?"  You can do offshoots as well: Is a string's length divisible by 4? Is it divisible by 6?  Is it prime(this is difficult for long strings, so try it if you get gutsy!)?

Substrings. Given a string s, output all possible substrings.

Word counting.  This one may be tricky depending on how far you are in your programming studies.  There are a few things that make it very easy(like associative collections), but if you don't know those things it can be difficult.

If the title sounds cryptic to you, just ignore the question.  Like I said, code golf is for experienced programmers.  Just focus on the simple problems, and try to come up with a simple answer.

Basic structure of solving a problem:

A lot of these give you a good idea of what a function should look like.  Given X, do Y, and the result should be Z:

void foo()
{
    // Set up X here

    // Do Y here

    // Display Z here
}

For the purposes of learning the basics and becoming familiarized with a language, the above template is sufficient.  A more object-oriented template would be:

Z foo(input X)
{
    Z result;
    // Do Y to X
    return result;
}

If it helps, write it down on paper as well.  Talk yourself through the process of how you, as a human being, would solve this problem.  Example: Given the numbers i, j, and k, display them in descending order.  As a person, it's easy to solve.  The hard part is translating your ideas into line-by-line instructions so a computer can solve it.

Try to come up with your own ideas as well.  It can be tough, but even the simplest of programs might teach you something you didn't know.  The whole point is to drill yourself with the basics, until they become second nature.


问:
Is there a design pattern for updating lists?
I want to modify one list (actually info stored in a database).  A person doesn't have access to update every part of the list, but can update and delete parts they do have access to and add whatever they want to the list.

Here's my pseudocode:

```<code>ModifiedList
OriginalList
OriginalListWithUserRights

for each Thing in ModifiedList do
  if Thing in OriginalList then
    //Leave Along - nothing to change
  else
    OriginalList.add(Thing)

for each Thing in OriginalList do
  if (Thing in ModifiedList) then
    //LeaveAlone - nothing to change (same as above)
  else
    for each RightsThing in OriginalListWithUserRights do
       if RightsThing not in OriginalList then
         //Leave Alone - don't remove things you don't have rights to
       else
         OriginalList.Remove(RightsThing)

OriginalList.ReIndex() //because there will be some gaps
</code>```

So, I guess this would work, but I think it's not right because it's just an obvious solution.  I don't need to start with three lists as my inputs to this function.  I could look up particular pieces of information while I'm iterating through my modified list.  It just seems to structured and not object oriented enough for 2014.

One problem I have is that I'm going to be adding everything to the end of the list, seems like I should be adding things relative to where they were in the passed in list, but in a way that doesn't mess up the order of things that are not in my OriginalListWithUserRights.

答:
You could extend/wrap your Thing class in a ModifiedThing that includes a HowModified enum with values Create, Remove, Update, and None, and then you can do something like:

```<code>foreach ModifiedThing in ModifiedList
    thing = ModifiedThing.Thing
    switch ModifiedThing.HowModified
        case Create:
            if UserHasRightsToCreate
                OriginalList.InsertAt(ModifiedThing.index, thing)
        case Delete:
            if UserHasRightsToDelete(thing)
                OriginalList.Remove(thing)
        case Update:
            if UserHasRightsToUpdate(thing)
                OriginalList[thing.Key] = thing
        case None:
            //leave it alone
</code>```

Body:
You could extend/wrap your Thing class in a ModifiedThing that includes a HowModified enum with values Create, Remove, Update, and None, and then you can do something like:

foreach ModifiedThing in ModifiedList
    thing = ModifiedThing.Thing
    switch ModifiedThing.HowModified
        case Create:
            if UserHasRightsToCreate
                OriginalList.InsertAt(ModifiedThing.index, thing)
        case Delete:
            if UserHasRightsToDelete(thing)
                OriginalList.Remove(thing)
        case Update:
            if UserHasRightsToUpdate(thing)
                OriginalList[thing.Key] = thing
        case None:
            //leave it alone


问:
Is there really anything to gain with complex design?
I've been working for a consulting firm for some time, with clients of various sizes, and I've seen web applications ranging in complexity from really simple:

MVC

Service Layer

EF

DB

To really complex:

MVC

UoW

DI / IoC

Repository

Service

UI Tests

Unit Tests

Integration Tests

But on both ends of the spectrum, the quality requirements are about the same.  In simple projects, new devs / consultants can hop on, make changes, and contribute immediately, without having to wade through 6 layers of abstraction to understand what's going on, or risking misunderstanding some complex abstraction and costing down the line.

In all cases, there was never a need to actually make code swappable or reusable - and the tests were never actually maintained past the first iteration because requirements changed, it was too time-consuming, deadlines, business pressure, etc etc.

So if - in the end -

testing and interfaces aren't used

rapid development (read: cost-savings) is a priority

the project's requirements will be changing a lot while in development

...would it be wrong to recommend a super-simple architecture, even to solve a complex problem, for an enterprise client?  Is it complexity that defines enterprise solutions, or is it the reliability, # concurrent users, ease-of-maintenance, or all of the above?

I know this is a very vague question, and any answer wouldn't apply to all cases, but I'm interested in hearing from devs / consultants that have been in the business for a while and that have worked with these varying degrees of complexity, to hear if the cool-but-expensive abstractions are worth the overall cost, at least while the project is in development.

答:
A lot of what this question asks is incredibly subjective, I think it's important to bring up some data on the compounding costs of architectural complexity. There is a really  interesting case study coming from MIT Sloan which measures

decrease in developer productivity

increased turnover

and increased defect density that results from more complexity.

Basically, I would say there's some happy medium which every codebase should strive to strike between (A) simplicity so that developer productivity is high and (B) foresight so that functionality isn't compromised when new features are being added.

The case study was on this one company with a monolithic codebase that had a high-complexity core (think like utilities and high abstraction stuff) and lower-complexity periphery (think newer features with few dependencies). Between the periphery and core, developer productivity decreased by 50% (crazy stuff) and defects increased 2.6x.


问:
How to slow down your computer (for testing purposes)?
As most people agree, encouraging developers to make  fast code by giving them slow machines is not a good idea. But there's a point in that question. My dev machine is fast, and so I  occasionally write code that's disturbingly inefficient, but that only becomes apparent when running it on other people's machines.

What are some good ways to temporarily slow down a turbocharged dev machine? The notion of "speed" includes several factors, for example:

CPU clock frequency.

Amount of CPU cores.

Amount of memory and processor cache.

Speed of various buses.

Disk I/O.

GPU.

etc.

答: Install Virtual PC, create a hardware profile, create a virtual machine and start playing :)</p>


答:
How about option 4: Back up your repo's current state in a temporary place, revert your repo to its original state, make a list of all the changes you did (you can still look at the temporary backup), then manually reimplement (and compile and test!) them as separate commits.

This should be easier, because you've already written the code, it's just a bit of figuring out which parts to copy and paste from your temporary backup.

When you have re-implemented every change cleanly, and thus ensured that commits are self-contained, small, and compile, you can delete the temporary backup, and everything will be almost exactly as (except for the time/date of commits) it would have been if you did it right from the start.


问:
Programs that claim they are not "multi-core" friendly
You see this phrase or similar kicked around from time to time, generally referring to a program that claims they were not designed to take full advantage of multi-core processors. This is common especially with video game programming. (of course a lot of programs have no concurrency and do not need it, such as basic scripts, etc).

How can this be? A lot of programs (especially games) inherently use concurrency, and since the OS is in charge of task scheduling on the CPU, then are these programs not inherently taking advantage of the multiple cores available? What would it mean in this context to "take advantage of multiple cores"? Are these developers actually forbidding OS task scheduling and forcing affinity or their own scheduling? (Sounds like a major stability issue).

I'm a Java programmer, so maybe I have not had to deal with this due to abstractions or whatnot.

答:
A lot of programs (especially games) inherently use concurrency,

No, actually it's the reverse.  Most apps are written in a single threaded mindset, and the developer(s) never made the necessary changes to support concurrency.

In C, C++, and C# you need to explicitly tell the application to start new threads and / or processes.

I think you're focusing too much on the scheduling of the threads and not enough on the data handling within the potential threads.  Sharing data across threads and / or processes requires some form of synchronization.  If you change an application to use multiple threads but fail to have that synchronization in place then you're likely going to see a lot of hard to track down bugs in the code.

For the multi-threaded applications I have worked on, I have generally never worried about dispatch and only about data synchronization.  The only times I had to worry about dispatch was when I was chasing race conditions due to incorrect data synchronization.

Generally, when an application says it can't use multiple cores then it means they don't have the synchronization in place to protect the data manipulation.


答:
This is not so much about multiple cores as it is about multiple threads. The OS may schedule a thread to run on whatever core it likes, and this scheduling is transparent for the program being scheduled. However, many programs are not written using multiple threads, so they can only run on one core at once.

Why would I write a single-threaded program? They are easier to write and easier to debug: one things happens after another (instead of multiple things happening at once and possible getting in each others ways). Or your program may not be targeting multi-core machines (as was the case with old games). In some cases, a multi-threaded program could even run slower than a single-threaded version if the overhead from context-switches and communication between threads outweighs the speed gained by parallel execution (some parts of the program may not be parallelizable).

Title: Programs that claim they are not "multi-core" friendly

Body:
You see this phrase or similar kicked around from time to time, generally referring to a program that claims they were not designed to take full advantage of multi-core processors. This is common especially with video game programming. (of course a lot of programs have no concurrency and do not need it, such as basic scripts, etc).

How can this be? A lot of programs (especially games) inherently use concurrency, and since the OS is in charge of task scheduling on the CPU, then are these programs not inherently taking advantage of the multiple cores available? What would it mean in this context to "take advantage of multiple cores"? Are these developers actually forbidding OS task scheduling and forcing affinity or their own scheduling? (Sounds like a major stability issue).

I'm a Java programmer, so maybe I have not had to deal with this due to abstractions or whatnot.


问:
How do memory-clean apps work?
In terms of operating system architecture, what does a memory-clean software to get rid of all data that fill the virtual memory? I assume that it simply saves all RAM data into a file, but how does it exactly do this? What happens if you delete a file while a process that has resources on that file is executing?

Hope this is not a too-broad question.

答: They don't work. Basically they're snake oil whose only function is to extract money from the gullible.

Title: How do memory-clean apps work?


答:
Good concurrency requires a lot more than throwing a few threads in an application and hoping for the best.  There's a range in how concurrent a program can be going from embarrassingly parallel to pure sequential.  Any given program can use Amdahl's law to express how scalable a problem or algorithm is.  A couple qualifications for a embarrassingly parallel application would be:

No shared state, every function only depends on the parameters passed in

No access to physical devices (graphic cards, hard drives, etc)

There are other qualifications, but with just these two we can understand why games in particular are not as easy as you might think to take advantage of multiple cores.  For one, the model of the world that will be rendered has to be shared as different functions calculate physics, movement, apply artificial intelligence etc.  Second, each frame of this game model has to be rendered on screen with a graphics card.

To be fair, many game makers use game engines that are produced by third parties.  It took a while, but these third party game engines are now much more parallel than they used to be.

There are bigger architectural challenges in dealing with effective concurrency

Concurrency can take many forms, from running tasks in the background to a full architectural support for concurrency.  Some languages give you very powerful concurrency features such as ERLANG, but it requires you to think very differently about how you construct your application.

Not every program really needs the complexity of full multicore support.  One such example is tax software, or any form driven application.  When most of your time is spent waiting on the user to do something, the complexity of multithreaded applications are just not that useful.

Some applications lend themselves to a more embarrassingly parallel solution, such as web applications.  In this case, the platform starts out embarrassingly parallel and it's up to you not have to impose thread contention.

The bottom line:

Not all applications are really hurt by not taking advantage of multiple threads (and thus, cores).  For the ones that are hurt by that, sometimes the computations are not friendly to parallel processing or the overhead to coordinate it would make the application more fragile.  Unfortunately, parallel processing is still not as easy as it should be to do well.


答:
Run your tests in a virtual machine with limited memory and only one core.

The old machines people still may have now are mostly Pentium 4 era things. That's not that unrealistic - I'm using one myself right now. Single core performance on many current PCs normally isn't that much better, and can be worse. RAM performance is more important than CPU performance for many things anyway, and by limiting a little more harshly than for an old 1GB P4, you compensate for that a bit.

Failing that, if you're willing to spend a bit, buy a netbook. Run the tests on that.

Title: How to slow down your computer (for testing purposes)?

Body:
As most people agree, encouraging developers to make  fast code by giving them slow machines is not a good idea. But there's a point in that question. My dev machine is fast, and so I  occasionally write code that's disturbingly inefficient, but that only becomes apparent when running it on other people's machines.

What are some good ways to temporarily slow down a turbocharged dev machine? The notion of "speed" includes several factors, for example:

CPU clock frequency.

Amount of CPU cores.

Amount of memory and processor cache.

Speed of various buses.

Disk I/O.

GPU.

etc.