答:
It is important that you provide a design because some preliminary work needs to go into creating a project.  I like ammoQ's answer as he puts it best.

I would just like to add however that in an ideal world we will have all the time to become experts in an unknown framework or library before we commit to designing a software around something that isn't yet 100% understood.  We do not live in a perfect world however.

Every design document should have an Assumptions section that details every remaining unknown that we still have about aspects of the design.  If for example the documentation for the library claims to have functionality A, but you were not able to figure that out yet in your prototype, then claim it as an Assumption and design accounting for it being true.

You may from time to time find that not all of your assumptions were correct, or that perhaps you missed a few.  At this point you will need to revise your design and cite the failed assumption as a reason, as well as revise estimates going forward.


问:
Interface naming: prefix 'Can-' vs suffix '-Able'
It's common to use '-able' as a suffix for interfaces e.g.

Serializable
Printable
Enumerable
Drinkable
Shootable
Rotatable

I was thinking that 'Can-' might better because it may be more descriptive. Yes, it is more wordy and it adds noise to the interface name. In particular, passive verbs can be used.

E.g. 1 does Shootable mean that the object is able to shoot (a gun might implement this), or does it means that it can be shot at (a target board might implement this). With the 'Can-' prefix, the former would be "CanShoot" and the latter would be "CanBeShotAt" or "CanShootAt".

E.g. 2 A document 'CanBePrinted' and a printer 'CanPrint'

Or, should we stick with '-Able' and let the documentation provide the context?

Any opinions.

答:
I think that both grammar-wise and convention-wise Xable is better for names of interfaces, whereas IsX, CanX, DoesX are better for names of properties.

From MSDN:

"Do name Boolean properties with an affirmative phrase (CanSeek instead of CantSeek). Optionally, you can also prefix Boolean properties with Is, Can, or Has, but only where it adds value." http://msdn.microsoft.com/en-us/library/ms229012.aspx

ContentLicense: CC BY-SA 3.0


问:
Should an application be designed without prototyping first?
I've just begun using a popular, well-documented graphics engine, and was given a month to create some small programs and get familiar with it.

The library is huge, and there are sections I haven't explored.

Due to a time-crunch, my tech-lead has asked me to start designing my software (sequence and class diagrams) even for the parts I haven't explored, just by looking at the documentation and figuring out the capabilities of those classes.

It's my understanding that designing software requires good knowledge of how something works. Does it make sense to create a design with only a vague understanding of how a class works, just by looking at the class's documentation? Shouldn't I be prototyping it with a small program, tweaking it here and there and understand how it behaves and THEN do the design for it?

答:
The answer really depends...

If you want to design a highly maintainable software, in which you can yank out the graphics engine and put in a new one, then you can do a high-level design without getting into too much detail on how to use the graphics engine.

If you want to base your design on that of the graphics engine (high coupling), then you need to know its specifics up front.


问:
Should I intentionally break the build when a bug is found in production?
It seems reasonable to me that if a serious bug is found in production by end-users, a failing unit test should be added to cover that bug, thus intentionally breaking the build until the bug is fixed. My rationale for this is that the build should have been failing all along, but wasn't due to inadequate automated test coverage.

Several of my colleagues have disagreed saying that a failing unit test shouldn't be checked in. I agree with this viewpoint in terms of normal TDD practices, but I think that production bugs should be handled differently - after all why would you want to allow a build to succeed with known defects?

Does anyone else have proven strategies for handling this scenario? I understand intentionally breaking the build could be disruptive to other team members, but that entirely depends on how you're using branches.

答:
One problem with adding a know-to-fail test to the build is that your team may get in the habit of ignoring failing tests because they expect the build to fail. It depends on your build system, but if a failing test doesn't always mean "something has just broken" then it's easy to pay less attention to failing tests.

You don't want to help your team get into that mindset.

So I agree with sleske that you should add the test, but mark it as 'ignored' for the purpose of the automatic build, until the bug is fixed.


问:
Platform design Issues
Suppose I design a platform over a platform (say Java or Win32 or .NET), which consists of various layers like Database, User Interface, Cloud etc.

Now every team would be working to make their product, say database best and less focused on their relationship with other teams, hence resulting in various issues when doing an integration of it.

Now, these are my questions in order to achieve a stable and bug-free platform:

How could one ensure that while integrating all the layers, there is less overhead involved and also is there any other way to automate this process ?

Also, if one particular team is using the API calls provided by other team and if the other team is still not ready with the API calls, there comes a DEADLOCK . How to step over such situations ?

Say, I want to monitor and get feedback from various teams regarding their progress. Is there any automation available for such activities ?

答:
How could one ensure that while integrating all the layers, there is less overhead involved

Performance measurements and profiling.

and also is there any other way to automate this process ?

No.  Good design is really hard work.

if one particular team is using the API calls provided by other team and if the other team is still not ready with the API calls, there comes a DEADLOCK . How to step over such situations ?

Sadly.  You can't.  The team that is producing the API calls needs to break the API suite into pieces and deliver the important piece first.

The team that is consuming the API calls needs to break their work into pieces based on importance.  They need to focus on the important pieces first.  They need to communicate their priorities to the API producers.

Say, I want to monitor and get feedback from various teams regarding their progress. Is there any automation available for such activities ?

Do Not Automate this.

Actually talk to the actual people every single day.

Have a daily Scrum meeting within each team.  This is 15 minutes that will dramatically improve the project.

Have a daily Scrum-of-scrums among the team leaders.  This is 15 minutes that will dramatically improve the project.

Title: Platform design Issues


问:
How can I convince a team member to use a web framework?
The question is this and the detail follows: is there anything I can say/bring up, as a programmer, to bring him to my side?

I'd love to hear valid arguments for both sides on this one, but mostly suggestions for how to talk him around.

My situation is this: I'm working on a team project on my degree course, building a mid-sized website as a prototype for the university. All are considered equals in the group and there is no one appointed leader so the answer to this problem can't be "pull rank".

All are equals, however there is a huge gap in knowledge between members. The team member in question and I are both capable developers, though he holds no industry experience. The other three members are less capable, and two have opted out of development entirely. All three have declined to comment on the situation due to lack of knowledge.

As as a group, we are coming to decide on what technologies to use in the implementation of the website; specifically, whether to use a PHP framework (Code Igniter) or not.

I am arguing in favour, citing:

Not reinventing the wheel

Well written and tested code base to work from

Getting going (the deadline is closer than we'd like)

Speed of development

Sound and maintainable design patterns and good practices

He is arguing in favour of working in the way he's used to:

Writing bespoke, one-time functions in to a "library" file as when he needs them

Functions for data access and rendering that data the page, getting/setting to and from session and get/post data etc

Having 1 file per page (resulting in no separation of concerns amongst control, presentation and data)

His reasons against using are framework are mostly based on him not being able to see the point: he can do all those things already. The framework doesn't change that, it just makes it harder because he has to learn the framework; he doesn't want to use code he hasn't personally written.

He has also said that it "doesn't matter the quality of the code base, since the project is only a prototype and will never be maintained". For me, that is no excuse to write unmaintainable code.

I can see why he makes those arguments, but I hold issue with his "lack of concern over maintainability" and his "disregard for good design", or even separation of concerns. However, I suspect he has never studied design patterns, so I don't know how effective demonstrating why his method could prove unmaintainable would be.

I want to get going on this project, but I don't want to do it without regard for everything I've learnt over the years. As I said before, there is no possibility of pulling rank here, nor are other team members willing to pitch in. Should I just back down and do things his way? Is he too stubborn and inexperienced to know better? Or am I being the stubborn one here?

TL;DR
Inexperienced team member is being stubborn, how can I win him over?

答:
One argument in your favor is reusability of knowledge. All team members who learn a well known and widely used framework (such as CodeIgniter) will be able to reuse their knowledge on the next project. Whereas knowledge of a haphazard, proprietary "library" is not reusable. This can resonate well with the other team members, as they probably prefer gaining some useful, reusable knowledge on this project.

Another argument might be a concrete measurement of development / maintenance costs. I imagine that a developer well versed in CodeIgniter can develop faster than your colleague writing all those proprietary functions himself. This could be demonstrated by having both you and him build an identical web page - you with CodeIgniter, he on his own way - and measure times to completion. Then make a set of modifications / extensions to the pages, again measuring time to completion. Of course, the specification should be prepared by someone independent from both of you, to fight on neutral ground.

Another - as you mentioned - is code quality. Once the web pages are ready, run the same set of acceptance tests on each, and compare bug density.

Of course, when you are under time pressure, there may be no possibility to stop and do such measurements. So you probably want a fast resolution to this dilemma. Try convincing the other team members (e.g. by having them read the upcoming answers to your post here :-), to mount some group pressure on him. In the end, if he really can't be convinced, you may want to cut the project into two parts, one for him and - ideally - one for the rest of the team, using CodeIgniter. Focus on doing your own part to the best of your abilities and let him do whatever he wants. The results will probably speak for themselves.


问:
Search algorithm with co-ordinate (x,y) hints?
I am about to start writing a UI view where many small text items are laid-out over the view and when the user hovers over a text item a dynamically-generated image is displayed (like a tooltip), relevant to the context of that text item.  When the user clicks the text item, another view will change with a larger version of that image.

I will obviously need to hold the items in a collection along with the rect hit-area that surrounds the text, and I am wondering if anyone can suggest an storage format and search algorithm I can use to find the text item as quickly as possible using the position of the mouse as a hint to localise the search, rather than do hit-tests for every item in the collection?

答:
An alternative technique that you may want to consider (depends on your needs) is to use an off-screen bitmap to store a reference to text items.  The basic approach is to draw the bounding rectangle to the off screen bitmap with a unique color for each item.  The look up is constant time, just index into the bitmap with the (x,y) coordinate of interest (e.g., mouse location).

The disadvantage to this technique is the memory requirements.  The bitmap needs to be as large as the display area on the screen.


答:
You're not going to be able to talk him into it.  It's called the Dunning-Kruger effect.  He's too ignorant to know what he doesn't know, and too afraid to lose what he terms as an advantage.

When you are unable to reach a consensus, you must instead reach a compromise.  Maybe you can split up the work so his need to learn the framework is minimal.  Maybe you have some sort of "design-off" where you each do it your way for a couple weeks and then the team votes on which one is best.  Maybe you can involve your sponsoring professor or whoever the customer is in resolving the tie.

Title: How can I convince a team member to use a web framework?

Body:
The question is this and the detail follows: is there anything I can say/bring up, as a programmer, to bring him to my side?

I'd love to hear valid arguments for both sides on this one, but mostly suggestions for how to talk him around.

My situation is this: I'm working on a team project on my degree course, building a mid-sized website as a prototype for the university. All are considered equals in the group and there is no one appointed leader so the answer to this problem can't be "pull rank".

All are equals, however there is a huge gap in knowledge between members. The team member in question and I are both capable developers, though he holds no industry experience. The other three members are less capable, and two have opted out of development entirely. All three have declined to comment on the situation due to lack of knowledge.

As as a group, we are coming to decide on what technologies to use in the implementation of the website; specifically, whether to use a PHP framework (Code Igniter) or not.

I am arguing in favour, citing:

Not reinventing the wheel

Well written and tested code base to work from

Getting going (the deadline is closer than we'd like)

Speed of development

Sound and maintainable design patterns and good practices

He is arguing in favour of working in the way he's used to:

Writing bespoke, one-time functions in to a "library" file as when he needs them

Functions for data access and rendering that data the page, getting/setting to and from session and get/post data etc

Having 1 file per page (resulting in no separation of concerns amongst control, presentation and data)

His reasons against using are framework are mostly based on him not being able to see the point: he can do all those things already. The framework doesn't change that, it just makes it harder because he has to learn the framework; he doesn't want to use code he hasn't personally written.

He has also said that it "doesn't matter the quality of the code base, since the project is only a prototype and will never be maintained". For me, that is no excuse to write unmaintainable code.

I can see why he makes those arguments, but I hold issue with his "lack of concern over maintainability" and his "disregard for good design", or even separation of concerns. However, I suspect he has never studied design patterns, so I don't know how effective demonstrating why his method could prove unmaintainable would be.

I want to get going on this project, but I don't want to do it without regard for everything I've learnt over the years. As I said before, there is no possibility of pulling rank here, nor are other team members willing to pitch in. Should I just back down and do things his way? Is he too stubborn and inexperienced to know better? Or am I being the stubborn one here?

TL;DR
Inexperienced team member is being stubborn, how can I win him over?


答:
I feel college is like a sandbox. Most of the stuff you do there are not used in deployment. So it gives you a lot more freedom to experiment and get out of your comfort zone. Explore new stuff because failing will not have too much of an impact. Also in your situation, your team members have the extra advantage of having someone with prior knowledge helping them out.

As for the other experienced team member, he needn't have come to college if he didn't want to learn anything new. This is a good opportunity to learn something new and add it to his toolbox.

And for the inexperienced team members, their chances of being employed/better employed will increase with a framework like CodeIgniter on their resume (actually the knowledge to justify that on their resume).


答:
I feel you need to engage the other 3 team mates. You both need to present your arguments to them and explain things to them so that they understand. At the end of the day, they will have to work with this code base as well. And if all are equals, then they should have some say over what they wish to work with.

I think a good approach would be for each of you to outline the benefits of your respective solutions, and show the other team members why you feel it's the best way to go. Then let them decide. There are 3 of them so it'll be the tie breaker.

One thing that you'll want to point out is that if this is your Sr. project, and the other team members have no other experience, this project needs to reflect the work they can do to potential employers. If you do it right it can be a good talking point in an interview. I know I ask new grads to outline their senior project, and how it was designed and developed.

If they go with the other guy's approach, you'll have to suck it up. But don't give up hope. Come up with a good design so that the chaos he's writing won't impact everything. If you have time, do some code clean up and refactor some of his stuff and show him that he doesn't have to reinvent the wheel each time.


问:
Is querying KeyValue Pairs efficient compared to two-property objects?
I'm working on a webservice and I'm returning JSON. However, I'm returning a List<KeyValuePair<string, int>>, since that's all I'm really ever going to be dealing with (property => value)

Now sometimes I myself will be calling these functions to aggregate the results, so I end up with something like

```<code>List<KeyValuePair<string, int>> myList = resultList.where(o => o.Key =="StringKEY");
</code>```

and sometimes

```<code>List<KeyValuePair<string, int>> myList = resultList.sum(o => o.Key =="StringKEY");
</code>```

My question is, would it be more efficient to do the following (custom class vs dictionary):

```<code>List<MyObject> myObj = resultObjList.where(o => o.Property1 == "stringProperty")
</code>```

and so on.

Is there any benefit to using custom objects? I will not ever need to be adding properties, and in this case I can say there will never be a need for additional properties.

答:
I think you'll be hard pressed to find any real-world performance difference given this is a web service -- the fastest HTTP request will still be orders of magnitude slower than any sort of micro-optimization you can get here.

Code-wise, unless I am actually dealing with an arbitrary list of keys, I'd run with a good old fashioned POCO. Intellisense and compile-type checking are cool.


问:
Should one bind data with Eval on aspx or override ItemDataBound in code-behind?
For data bound controls (Repeater, ListView, GridView, etc.), what's the preferred way of binding data?

I've seen it where people use Eval() directly on the aspx/ascx inside the data bound control to pull the data field, but to me, it just seems so...inelegant. It seems particularly inelegant when the data needs to be manipulated so you wind up with shim methods like <%# FormatMyData(DataBinder.Eval(Container.DataItem, "DataField")) %> inside your control.

Personally, I prefer to put in Literal controls (or other appropriate controls) and attach to the OnItemDataBound event for the control and populate all the data to their appropriate fields in the code-behind.

Are there any advantages of doing one over the other? I prefer the latter, because to me it makes sense to compartmentalize the data binding logic and the presentation layer. But maybe that's just me.

答:
I think building in codebehind has some significant disadvantages in workflow -- mainly that changing output formatting for a web app requires a recompile.

Personally, when I was doing ASP.NET webforms, I would cast the Container.DataItem to the appropriate object and then bind directly to that object. Also opens the door to smarter formatting and such as you can access members of said object.

Performance-wise, I don't think it is probably a wash in real-world conditions. There typically is enough data transfer on a remote network that any micro optimization one might make in rendering the list will never make a difference.


问:
How to correct a junior, but encourage him to think for himself?
I am the lead of a small team where everyone has less than a year of software development experience. I wouldn't by any means call myself a software guru, but I have learned a few things in the few years that I've been writing software.

When we do code reviews I do a fair bit of teaching and correcting mistakes. I will say things like "This is overly complex and convoluted, and here's why," or "What do you think about moving this method into a separate class?" I am extra careful to communicate that if they have questions or dissenting opinions,  that's ok and we need to discuss. Every time I correct someone, I ask "What do you think?" or something similar.

However they rarely if ever disagree or ask why. And lately I've been noticing more blatant signs that they are blindly agreeing with my statements and not forming opinions of their own.

I need a team who can learn to do things right autonomously, not just follow instructions. How does one correct a junior developer, but still encourage him to think for himself?

Edit:
Here's an example of one of these obvious signs that they're not forming their own opinions:

Me: I like your idea of creating an extension method, but I don't like how you passed a large complex lambda as a parameter. The lambda forces others to know too much about the method's implementation.

Junior (after misunderstanding me): Yes, I totally agree. We should not use extension methods here because they force other developers to know too much about the implementation.

There was a misunderstanding, and that has been dealt with. But there was not even an OUNCE of logic in his statement! He thought he was regurgitating my logic back to me, thinking it would make sense when really he had no clue why he was saying it.

答:
When I have had to deal with this, I have said (honestly) things like:

You know, that's a really creative solution which I would never have thought of. How does it scale?/Do you think there might be an approach which is conceptually simpler, to make development faster or maintenance easier?/Unfortunately, I don't think it really fits in with the rest of the project's architecture./What will the configuration look like?

This has usually been enough to point people in a new direction.


答:
Short Answer:

Engage them (put the puzzle in their mind), empower them (trust their answers).

It is the question that drives us! - Matrix.

Generally, in my observations, that juniors have their own world - their own limited view of how they think and in some part their own enthusiasm/favorites/opinions about things.

There is nothing wrong about telling them head-on that you are wrong - but best is that you make them think. Why? Are there any other ways? Are there better ways to do the same thing?  One of the anecdotes I always use is - "Give me three solutions (to this problem)!"

By the time they think about these solutions, they begin to realize many issues. It takes them some investment of time - but over time they tend to visualize the limitations and shortcomings of their thinking. They begin to see that more as "I didn't think of it!" which is much better than going home with the feeling that "I was wrong!" or even worse "I was told/proven wrong even when I had valid viewpoints".

In general, very young kids will tend to be more adept related to technical issues (such as which design pattern works better!) over process issues, but over time when you coach them, it works.

However they rarely if ever disagree or ask why. And lately I've been
  noticing more blatant signs that they are blindly agreeing with my
  statements and not forming opinions of their own.

This generally is an outcome that you do take their suggestions but later overrule them and they are equally unconvinced about your views; just because you are senior they are avoiding a fight!

The best thing I learnt from one of my past bosses: He will ask team members to debate first (they feel fairly equal here), and hopefully after all the arguments being exhausted, he would enter the room with only one question - "What were the points of disagreement?" - The point is, people always like to participate in debates and discussion, but if their (valid) points are not taken up to action next time they feel it's not worth it to participate in discussion.

Not only in software, but everywhere ultimately only the most empowered teammates will dare to reply let alone question the system.

Title: How to correct a junior, but encourage him to think for himself?

Body:
I am the lead of a small team where everyone has less than a year of software development experience. I wouldn't by any means call myself a software guru, but I have learned a few things in the few years that I've been writing software.

When we do code reviews I do a fair bit of teaching and correcting mistakes. I will say things like "This is overly complex and convoluted, and here's why," or "What do you think about moving this method into a separate class?" I am extra careful to communicate that if they have questions or dissenting opinions,  that's ok and we need to discuss. Every time I correct someone, I ask "What do you think?" or something similar.

However they rarely if ever disagree or ask why. And lately I've been noticing more blatant signs that they are blindly agreeing with my statements and not forming opinions of their own.

I need a team who can learn to do things right autonomously, not just follow instructions. How does one correct a junior developer, but still encourage him to think for himself?

Edit:
Here's an example of one of these obvious signs that they're not forming their own opinions:

Me: I like your idea of creating an extension method, but I don't like how you passed a large complex lambda as a parameter. The lambda forces others to know too much about the method's implementation.

Junior (after misunderstanding me): Yes, I totally agree. We should not use extension methods here because they force other developers to know too much about the implementation.

There was a misunderstanding, and that has been dealt with. But there was not even an OUNCE of logic in his statement! He thought he was regurgitating my logic back to me, thinking it would make sense when really he had no clue why he was saying it.


问:
What should every programmer know about programming?
Please, stay on technical issues, avoid behavior, cultural, career or political issues.

答:
It stands in a few letters, really:

RTFM (and for the kewl kidz today: JFGI)

DRY

KISS

H2G2

Ok, I'm over-simplifying, but basically if you are pretty autodidact, never stop to learn, and are a bit of a perfectionist, you should have the basis to become a good programmer.

Anything beyond that would be more specific to particular roles and technologies.

ContentLicense: CC BY-SA 2.5


答:
I wouldn't worry too much about the fact that they blindly follow you, this is what they should be doing as juniors.  The thing is that they are likely not going to understand the true reasons for the items you address in code reviews until they are gone and working somewhere else that has terrible software developers, terrible management, and terrible code.

By that time they will have learned good practices out of habit and will have to live through the coding and design mistakes that others make and they are FORCED to make that they now have to work on poorly designed and implemented software.

This will be an eventual inevitability at some point in their careers.  You are doing them a great service by getting them used to good coding standards and practices.  Unfortunately most of us had to learn the hard way.


答:
When I first started working in a programming job, I did the exact same thing you described: when told about something I could be doing, I would always agree.  It was mainly because I didn't have enough experience to say otherwise.

What gave me the ability to actually discuss methodologies and ideas was learning from experience as well as reading about different approaches and new technologies.  In order for your team to think for themselves, they need to actually know about what problems can arise from things like "overly complex and convoluted" code, and the only real way they will find out is through experience.

A good way to facilitate individual thinking is by having them look into programming websites like Stack Overflow or Programmers SE.  I know that these helped me learn about the different techniques that were out there and allowed me to have discussions with senior members of the team, instead of blindly agreeing with them.

The point is that without experience, suggestions from senior members will always sound right to them.


答:
Based on the example given I would say following up your comments with questions would probably be the best way to go. If you ask a question along with your comments it doesn't leave them to simply agree or disagree they at least have to think about how they may implement something.

e.g. "I like your idea of creating an extension method, but I don't like how you passed a large complex lambda as a parameter. The lambda forces others to know too much about the method's implementation. Can you think of a better way to implement this extension method that doesn't expose as much information?"

This allows them to see the faults in what they are developing while at the same time giving them the opportunity to solve the problem they introduced into the application.


答:
Responsiblity is one thing that can help them.

I've led a team or two in the past and one of the things that made juniors shine was the burden of personal responsibility.
When one realizes that his actions may implicate on him at one point, he/she usually commits a wee-bit-more of himself in what he does.
No to mention that when they feel their work, the good results are much more satisfying.


答:
The interaction from your post demonstrates a key principle to teaching almost anything: ask them to explain what they think you said, and listen carefully to the response: it will tell you precisely what needs to be corrected.

I have shamelessly stolen copied this trick from my math tutor some 25 years ago, and it has not failed me since. I used it in class during my brief stint as a teaching assistant, at work when talking about software design, and with my eight year old when talking about her school assignments.

Of course you cannot always be blunt about asking them to repeat what you just said, so you need to adjust your strategy. For example, here is how I would re-phrase your follow-up statement from the OP as a "probing" question:

I like your idea of creating an extension method, but I don't like how you passed a large complex lambda as a parameter. Do you see how this complex lambda forces others to know too much certain things about the method's implementation?

This question is impossible to answer correctly without understanding the issue that you are trying to highlight. I found that ending my explanations with a question that requires analysis of what I just said speeds up the learning process, and gives me feedback that I need to make corrections.


问:
How can I motivate myself to start learning more?
I've been interested in programming for a while now, and have been slowly, slowly, slowly working on things over the years. However, I don't feel like I've learned much.

I've only really stuck with familiar languages (Java, C# and I've tried a little bit of PHP). The problem is that in those languages, I've only brushed upon the surface of them and have restricted myself to doing fairly simple things.

For example, as a Java project, I've downloaded the source code for some game and changed a few things to my liking, but nothing terribly difficult. In C#, I've made a few WinForm and console projects to do some repetitious or routine tasks for me, which is nice, but again nothing too complicated.

I've just barely begun to grasp the concept of classes, multithreading and some basic but essential tools that are required in modern object-oriented programming. ("Why can't I just shove everything into one monster-sized class?" "Why can't I just run everything in one thread?" are questions I used to wonder about)

I've never made a large project by myself. Ultimately, my kind of "dream" hobby project is that I would like to create a game using DirectX technology. I say that because I've used XNA but it requires the user to install a framework to get it running, and I also feel that if I use the framework, that a lot of the back-end work is being obscured from me. (DirectX or OpenGL seem to be about as close to the machine as I can get without going overboard in complexity. DirectX is also installed on most [if not all] Windows machines that plan on running games.)

But I haven't even begun to even think about starting that. The amount of things I need to know to undertake a task is absolutely overwhelming. I wouldn't know where to begin. Likewise, I also feel inadequate because I've restricted myself to [what I see as] easy languages. I feel like I should start learning some scripting language or learn this or learn that, which is quite daunting.

--

tl;dr: I've been slowly teaching myself to program for a while now, but have been restricting my knowledge to limited languages and only scratching the surface of what I can do. I want to learn more and possibly start a decent-sized project (I can only make so many text-based RPGs and calculators), but the massive amount of knowledge I'll need is very intimidating.

One of my concerns is that I know so little about programming languages in general. Is it better to learn several languages or to be able to delve deep into one single language?

How can I motivate myself to learn more?

Am I thinking about this the wrong way?

答: To really get motivated and to be able to learn from other peoples code you could start looking at some open source. With limited knowledge it would probably take you a while before you felt like you could contribute but it would give you real-world problems to solve and there would be real people out there using it which is fun.</p>


答:
If you want your juniors to think for themselves, don't correct them: get them to correct themselves.

Instead of telling them what you think is wrong about their solution, ask them pertinent questions about it. In your example, you could ask them about what someone using the extension method would need to know to create the lambda. Keep asking questions like this until they suggest that it's a problem. That way, you know they have understood why their solution could be a problem and furthermore are more likely to learn from it - if you simply tell them that their solution is wrong, that's an external judgement, and easily ignored. If they come to the realisation on their own (with a little prompting), they will realise how well-grounded it is and be much more likely to learn from their mistake.

In addition, this gives your juniors a chance to defend their design - perhaps they have thought of the problem and have a good justification that addresses your concern, meaning there's no need for you to do any correcting. That reduces any perception (however unintentional) that you're ruling by executive fiat.


问:
Designing web-based plugin systems correctly so they don't waste as many resources?
Many CMS systems which rely on third parties for much of their code often build "plugin" or "hooks" systems to make it easy for developers to modify the codebase's actions without editing the core files.

This usually means an Observer or Event design pattern.

However, when you look at systems like wordpress you see that on every page they load some kind of bootstrap file from each of the plugin's folders to see if that plugin will need to run that request. Its this poor design that causes systems like wordpress to spend many extra MB's of memory loading and parsing unneeded items each page.

Are there alternative ways to do this? I'm looking for ideas in building my own.

For example, Is there a way to load all this once and then cache the results so that your system knows how to lazy-load plugins? In other words, the system loads a configuration file that specifies all the events that plugin wishes to tie into and then saves it for future requests?

If that also performs poorly, then perhaps there is a special file-structure that could be used to make educated guesses about when certain plugins are unneeded to fullfil the request.

Any ideas?

If anyone wants an example of the "plugin" concept you can find one here.

答:
Xeoncross,

I really like this question so I will take some time to answer it. The first thing to know about wordpress and CMS systems like it is that they are not built for speed. They are built to be easy to use easy to configure. People that normally use a wordpress site want to be able to easily edit there site and throw new things into it togeather or dont even know how to program. So things like scanning all the plugins asking them if they need to do something with this page or not is a resource risk can be taken to give very easy to use functions to the CMS

If you are trying to build a CMS and find an easy way to get both of best worlds I have not found a way around the issue with out a little bit more work Here is an idea I have had That maybe able to help you a little bit. For each of the new plugins that are added to the site when they are installed or activated in the admin panel they should write to a file stating when they need to do something and what they need to do. When they are deleted they scan for there entries and delete them. The admin system should also have a method of checking to see if a plugin is missing and delete lines no longer associated with the system. THis way you will be able to get ease of use for simple click installs but will give you more speed because insteed of scanning and asking each plugin if they need to do something at this point in time they would have built a list that you can search for and use as your guide.


答:
Since you have multiple junior developers do code reviews as group not 1 one 1.

Open by ask the group "How else could the problem be solved?", and allow the other junior developers to suggest their implementations first.  Only add your implementation after the other team members have spoken and if none have suggested something similar to what your idea is.

Then have a roundtable discussion about the relative advantages and disadvantages of different implementations with the intent to guide the junior devs to picking the best implementation without being told what it is.

As a confidence builder for the junior devs you could start with some cases where they picked what you think was the best option and make your alternative a strawman that has an semi-obvious flaw and direct the discussion toward why the original implementation is best.


问:
How to use Blend sample data as real data?
I am trying to do some design in Blend 4. The sample data function of Blend is nice to have during design time, but it could be much more better to see the design in browser.

Can anyone help me to use sample data created by Blend as real data (see same data in browser) also ?

Thanks in advance.

答:
Hopefully your application is using MVVM pattern so that it can manufacture Blend data.  I believe this is the recommended approach.  If you are unfamiliar with it, definately take some time to get familiar with it.

I've inlcuded some code snippets below, but don't fret about the code too much, just follow the pattern.

To blend your data:

Set up MMVM in your project and in the View Model constructor, check to see if you are in Blend.  Pass in an agent that will handle getting the data for you.

```<code>public MainPageViewModel(IUserAgent userAgent)
        {
            //Design Mode Check, use WCF when not in design mode
            if (!base.InDesignerTool)
            {
                if (userAgent != null)
                {
                    UserAgent = userAgent;
                }
            }
            else // In Cider (CS 2010 designer) or Expression Blend, don't call WCF, so use the UserAgentDesigner instead
            {
                UserAgent = new UserAgentDesigner();
            }

            //Wire up the commands to the view model.
            this.WireUpCommands();
        }
</code>```

We have an interface to populate the view, called IUserAgent, and two implementations, one for a service call and then one for the design time (fake data):

```<code>namespace SilverlightApplicationChannelWCF.ServiceAgent
{
    /// <summary>
    /// The User Agent Interface
    ///
    /// We use an interface so the the get data method is loosely coupled with the view model.
    ///
    /// We could get the data from a WCF service, or manufacture data if in a design environment like
    /// Expression Blend.
    /// </summary>
    public interface IUserAgent
    {
        /// <summary>
        /// Gets users
        /// </summary>
        /// <param name="callback">The call back when the call completes.</param>
        void GetUsers(System.EventHandler<DataTransferObjectEventArgs> callback);

        /// <summary>
        /// Saves users
        /// </summary>
        /// <param name="users">The users to save.</param>
        /// <param name="callback">The call back when the method completes.</param>
        void SaveUsers(DataTransferObject dto, System.EventHandler<DataTransferObjectEventArgs> callback);
    }
}
</code>```

Then we have two implementation classes, one that gets data from the service:

```<code>public class UserAgent : IUserAgent
</code>```

And another that manufacturers data for the designer:

```<code> public class UserAgentDesigner : IUserAgent
</code>```

Each implementation returns back the same type of DTOs, for designer the data is manufactured:

```<code>        /// <summary>
        /// Gets users.
        /// </summary>
        /// <param name="callback"></param>
        public void GetUsers(System.EventHandler<DataTransferObjectEventArgs> callback)
        {
            //Wire up the call back
            this.AgentGetUsersCompleted += callback;

            DataTransferObject dto = new DataTransferObject();
            //Return the users
            List<BaseDTO> users = new List<BaseDTO>();

            users.Add(new UserDTO() { FirstName = "Jon", LastName = "Raynor (Design Data)", IsDirty = false });
            users.Add(new UserDTO() { FirstName = "Sunil", LastName = "Munikar(Design Data)", IsDirty = false });
            users.Add(new UserDTO() { FirstName = "Aaron", LastName = "McIver(Design Data)", IsDirty = false });

            //Assign users to DTO
            dto.DataTransferObjects = users;

            //Setup and assign event args
            DataTransferObjectEventArgs e = new DataTransferObjectEventArgs();
            e.Dto = dto;

            //Raise an event for the callback
            if (!ReferenceEquals(null, AgentGetUsersCompleted))
            {
                AgentGetUsersCompleted(this, e);
            }
        }
</code>```

Now, you can hand off your applicate to Blend and it will populate with data without using a WCF service call so that UI can be designed and rendered with data.

Body:
Hopefully your application is using MVVM pattern so that it can manufacture Blend data.  I believe this is the recommended approach.  If you are unfamiliar with it, definately take some time to get familiar with it.

I've inlcuded some code snippets below, but don't fret about the code too much, just follow the pattern.

To blend your data:

Set up MMVM in your project and in the View Model constructor, check to see if you are in Blend.  Pass in an agent that will handle getting the data for you.

public MainPageViewModel(IUserAgent userAgent)
        {
            //Design Mode Check, use WCF when not in design mode
            if (!base.InDesignerTool)
            {
                if (userAgent != null)
                {
                    UserAgent = userAgent;
                }
            }
            else // In Cider (CS 2010 designer) or Expression Blend, don't call WCF, so use the UserAgentDesigner instead
            {
                UserAgent = new UserAgentDesigner();
            }

            //Wire up the commands to the view model.
            this.WireUpCommands();
        }

We have an interface to populate the view, called IUserAgent, and two implementations, one for a service call and then one for the design time (fake data):

namespace SilverlightApplicationChannelWCF.ServiceAgent
{
    /// <summary>
    /// The User Agent Interface
    ///
    /// We use an interface so the the get data method is loosely coupled with the view model.
    ///
    /// We could get the data from a WCF service, or manufacture data if in a design environment like
    /// Expression Blend.
    /// </summary>
    public interface IUserAgent
    {
        /// <summary>
        /// Gets users
        /// </summary>
        /// <param name="callback">The call back when the call completes.</param>
        void GetUsers(System.EventHandler<DataTransferObjectEventArgs> callback);

        /// <summary>
        /// Saves users
        /// </summary>
        /// <param name="users">The users to save.</param>
        /// <param name="callback">The call back when the method completes.</param>
        void SaveUsers(DataTransferObject dto, System.EventHandler<DataTransferObjectEventArgs> callback);
    }
}

Then we have two implementation classes, one that gets data from the service:

public class UserAgent : IUserAgent

And another that manufacturers data for the designer:

 public class UserAgentDesigner : IUserAgent

Each implementation returns back the same type of DTOs, for designer the data is manufactured:

        /// <summary>
        /// Gets users.
        /// </summary>
        /// <param name="callback"></param>
        public void GetUsers(System.EventHandler<DataTransferObjectEventArgs> callback)
        {
            //Wire up the call back
            this.AgentGetUsersCompleted += callback;

            DataTransferObject dto = new DataTransferObject();
            //Return the users
            List<BaseDTO> users = new List<BaseDTO>();

            users.Add(new UserDTO() { FirstName = "Jon", LastName = "Raynor (Design Data)", IsDirty = false });
            users.Add(new UserDTO() { FirstName = "Sunil", LastName = "Munikar(Design Data)", IsDirty = false });
            users.Add(new UserDTO() { FirstName = "Aaron", LastName = "McIver(Design Data)", IsDirty = false });

            //Assign users to DTO
            dto.DataTransferObjects = users;

            //Setup and assign event args
            DataTransferObjectEventArgs e = new DataTransferObjectEventArgs();
            e.Dto = dto;

            //Raise an event for the callback
            if (!ReferenceEquals(null, AgentGetUsersCompleted))
            {
                AgentGetUsersCompleted(this, e);
            }
        }

Now, you can hand off your applicate to Blend and it will populate with data without using a WCF service call so that UI can be designed and rendered with data.


答:
Writing a test that you know will fail until the bug is fixed is a good idea, it's the basis of TDD.

Breaking the build is a bad idea. Why? Because it means that nothing can move on until it is fixed. It essentially blocks all other aspects of development.

Example 1

What if your application is vary large, with many components? What if those components are worked on by other teams with their own release cycle? Tough! They have to wait for your bug fix!

Example 2

What if the first bug is hard to fix and you find another bug with a higher priority? Do you also break the build for the second bug? Now you can't build until both are fixed. You have created an artificial dependency.

There is no logical reason why failing a test should stop a build. This is a decision that the dev team needs to make (perhaps with management discussion) weighing up the pros and cons of releasing a build with known bugs. This is very common in software development, pretty much all major software is released with at least some known issues.

Title: Should I intentionally break the build when a bug is found in production?

Body:
It seems reasonable to me that if a serious bug is found in production by end-users, a failing unit test should be added to cover that bug, thus intentionally breaking the build until the bug is fixed. My rationale for this is that the build should have been failing all along, but wasn't due to inadequate automated test coverage.

Several of my colleagues have disagreed saying that a failing unit test shouldn't be checked in. I agree with this viewpoint in terms of normal TDD practices, but I think that production bugs should be handled differently - after all why would you want to allow a build to succeed with known defects?

Does anyone else have proven strategies for handling this scenario? I understand intentionally breaking the build could be disruptive to other team members, but that entirely depends on how you're using branches.


问:
Is it possible to learn maths via programming, or you should learn maths for programming?
I am not the best in maths, not very horrid either, but lower than the average, I've always been thinking to improve my maths, but schools and books didn't do the job because I get bored too fast. The only thing I don't get bored with is coding and gaming, so I thought what if coding a program that solves mathematical problems will help me understand maths better, most of these problems are limits (calculus), functions, Differential calculus, and some other subjects (I already said am not that good) similar to the previous noted.

My question is: Am I able to achieve a better knowledge in maths if I do some specific program coding, and if possible, is physics possible that way too? Or am I wrong and Maths should be learned before programming to help improve my coding?

P.S : C++ is the preferred language.

答: Obviously you should learn maths through programming.  If you attempt to simulate physical objects you will need to learn all sorts of physics and maths, and you will enjoy it.</p>


答:
Have a look at matlab. Its a language designed for doing mathematical functions in code.

a numerical computing environment and fourth-generation programming language... MATLAB allows matrix manipulations, plotting of functions and data, implementation of algorithms, creation of user interfaces, and interfacing with programs written in other languages...

Although MATLAB is intended primarily for numerical computing, an optional toolbox uses the MuPAD symbolic engine, allowing access to symbolic computing capabilities. An additional package, Simulink, adds graphical multi-domain simulation and Model-Based Design for dynamic and embedded systems...

Title: Is it possible to learn maths via programming, or you should learn maths for programming?

Body:
I am not the best in maths, not very horrid either, but lower than the average, I've always been thinking to improve my maths, but schools and books didn't do the job because I get bored too fast. The only thing I don't get bored with is coding and gaming, so I thought what if coding a program that solves mathematical problems will help me understand maths better, most of these problems are limits (calculus), functions, Differential calculus, and some other subjects (I already said am not that good) similar to the previous noted.

My question is: Am I able to achieve a better knowledge in maths if I do some specific program coding, and if possible, is physics possible that way too? Or am I wrong and Maths should be learned before programming to help improve my coding?

P.S : C++ is the preferred language.


问:
What should I do to scale out a high-traffic website?
What best practices should be undertaken for a website that needs to "scale out" to handle capacity?  This is especially relevant now that people are considering the cloud, but may be missing out on the fundamentals.

I'm interested in hearing about anything you consider a best practice from development-level tasks, to infrastructure, to management.

答:
Share Nothing architecture.

With that in mind, and contrary to what you might think, don't jump to a scale-out solution right away.  The off-system overhead vs. an in-system call should not be under-weighed.  For instance, it takes a LOT longer to make an DB connection across any network interface than it does to make a local call.  Budget how much time in management, power, and tuning effort is needed in scale-out vs. the extra $ for a true large system.

Regardless, I there is still great value in "share nothing" architectures and you can layer and scale-out your systems when the time comes.


问:
How to solve a fundamental cloud data storage dispute?
I'm working for a company that has recently hired me to create a new version of their existing software, which is now over 12 years old. The new software is a complete re-write of the old and they want it to be much more "online" than the previous version. I'm one of two programmers, the other having been with the company for 20+ years and is now close to retirement.

The problem I'm facing is that with almost every idea I suggest that doesn't fall in line with what he thinks, it just gets shot-down, ignored and forgotten. So far I've let a lot slide; nothing too critical, and things that could be changed later on if needed.

However, we're now on the subject of how to store the data that needs to be accessible to all the customers; he wants to use SQL Azure and store as much data as possible in xaml-string blobs, then use DevForce IdeaBlade to generate all the back end code. I'm not convinced, I think that if we're using a SQL storage solution we should be using relational database tables, which are normalized, etc. OR we shouldn't be using SQL at all, and perhaps use another method that allows storage of C# objects directly?

What do you guys think?

EDIT: Ok, so to give people a bit more information, the program could be considered a sort of Photoshop-like application, but aimed at a specific market. Users have access to a library of template "backgrounds" which they can then add text, images, etc. on too. When they browse the library of templates, they will be able to filter them by type, color, etc.

答:
I think you will remain unsatisfied at your job until you leave, or the other developer does. ;)

More seriously, there isn't enough information to know if the other developer is shooting down your ideas because he doesn't like change, or if he is shooting them down because he has good, solid reasons that he isn't communicating well.

I would take the approach of assuming the later, and ask him if you can go over the details of his decision until you understand them.  Most people are happy if you take the position of explicitly saying that you accept their decision, and want to understand why to reduce friction in future.

That will help you work out if you should move on, or if you should start listening more to what he has to say.

To the specific question, I think it entirely depends on the timeframe, needs of the company, and needs of the product.  Generally, something like IdeaBlade that solves a whole pile of problems means a whole lot of code you don't have to write, so that isn't a bad plan.

To the underlying store, using an SQL database to store NoSQL style data is not terrible if it is the primary storage engine, and your problem maps well to storage form.

Azure offers pretty much nothing that isn't SQL, other than a hard disk, so you would have to write a whole pile of code to use any other base storage engine.

Using normalized SQL has the obvious advantages, though, and I would certainly wonder if the NoSQL store was actually more efficient.  See "talk to him and understand why" earlier for the answer to "is it better" though.


答: The SICP book has a very nice section on math.  But I would suggest that you try to take linear algebra, discrete mathematics, and The Calculus at a minimum, if you learn only from writing programs your education is likely to be very deep, but not very broad.</p>


答: You will only learn math or physics from programming if you actually use the programming to solve math and physics problems, although functional languages like Haskell have concepts in them that are very "mathy". I would suggest going to a web site like Kahn Academy or Project Euler. Solve the problems on there using code, and you'll improve both your coding skills and math skills at the same time.</p>


答:
I think they go hand in hand. A solid grounding in mathematical techniques will open up options in programming you wouldn't have otherwise, meanwhile programming can open up interesting avenues of mathematical study.

I've recently started using wxMaxima, a nice graphical front-end to the excellent open source Maxima Computer Algebra System (aka a CAS, like the commercial Maple or Mathematica systems).

It won't teach you anything about maths on it's own, but it will certainly make playing around with maths more interesting and fun, that in itself could encourage you to learn more.


问:
Can I use the concept of 'tags' (derived from StackExchange sites) in a personal project?
I have a small personal project that I expect will be viewed by, at most, about 5 people. 'Tags', as used on this site and StackOverflow, would be helpful. Can I explicitly use something called a Tag in my personal project where the purpose/function is essentially the same?</p>

答:
The Stack Exchange network has not invented tagging and has not patented their use.

Tag to your heart's content.


答:
Usually when people aren't saying what you want, it means you need to work on your listening.  Listening means hearing the reasons for their design before passing judgment.  It means not just telling them it's okay to dissent, but proving it by honestly considering what they have to say, and not just correcting them.  Look for the good things about their solution, and modify your solution to incorporate those things.

You also need to lead by example.  I don't mean by writing uber-awesome code, I mean by asking them for their opinion on your own designs.  Don't wait for code reviews after the fact, but work together all along the way.  Say things like, "My interface seems too complex, but I'm not sure the best way to simplify it."  And give them time to answer without biasing them to your own ideas first.


答:
This is my take...

Programming Will Help Test Your KNOWLEDGE

When I was in high school and middle school, I would program my calculators to do the monotonous math for me. Some people claimed it was cheating, but I always argued that I wouldn't be able to write the programs if I didn't truly understand the math.

For instance, let's say you wanted to create a small program to compute the C value, given A and B, within the Pythagorean theorem. How do we do it? Well, we know that:

```<code>A^2 + B^2 = C^2
</code>```

So to solve for C, we have:

```<code>C = SQRT(A^2 + B^2)
</code>```

Therefore, the program might be something like (assuming proper headers, this is a bare bones example):

```<code>cout << "Enter value for A: "
cin << valA;
cout << "Enter value for B: "
cin << valB;

float valC = sqrt(pow(valA, 2) + pow(valB, 2))
cout << "C = " << valC << "\n";
</code>```

HOWEVER...

Where and How Do You Acquire Said Knowledge?

In the previous example, we needed to know how to solve for C within the equation A^2 + B^2 = C^2. If we didn't know to square root both sides to find C, how could we solve the problem?

IMO, it boils down to: programming will not TEACH you math absolutely, but it WILL IMPROVE the skills you acquire.

Body:
This is my take...

Programming Will Help Test Your KNOWLEDGE

When I was in high school and middle school, I would program my calculators to do the monotonous math for me. Some people claimed it was cheating, but I always argued that I wouldn't be able to write the programs if I didn't truly understand the math.

For instance, let's say you wanted to create a small program to compute the C value, given A and B, within the Pythagorean theorem. How do we do it? Well, we know that:

A^2 + B^2 = C^2

So to solve for C, we have:

C = SQRT(A^2 + B^2)

Therefore, the program might be something like (assuming proper headers, this is a bare bones example):

cout << "Enter value for A: "
cin << valA;
cout << "Enter value for B: "
cin << valB;

float valC = sqrt(pow(valA, 2) + pow(valB, 2))
cout << "C = " << valC << "\n";

HOWEVER...

Where and How Do You Acquire Said Knowledge?

In the previous example, we needed to know how to solve for C within the equation A^2 + B^2 = C^2. If we didn't know to square root both sides to find C, how could we solve the problem?

IMO, it boils down to: programming will not TEACH you math absolutely, but it WILL IMPROVE the skills you acquire.


答:
Unless you are talking many thousands of items, try it first without any special algorithms.  A simple hit test for a rectangle is very cheap, processor wise.  I seriously doubt you'd see any percievable improvment over more efficient schemes.

Basically, while great in theory, this is a place where there's no need to prematurely optimize.

Also, make sure you cycle backwards (top to bottom), so as to hit the top item if two are overlapped.

Title: Search algorithm with co-ordinate (x,y) hints?

Body:
I am about to start writing a UI view where many small text items are laid-out over the view and when the user hovers over a text item a dynamically-generated image is displayed (like a tooltip), relevant to the context of that text item.  When the user clicks the text item, another view will change with a larger version of that image.

I will obviously need to hold the items in a collection along with the rect hit-area that surrounds the text, and I am wondering if anyone can suggest an storage format and search algorithm I can use to find the text item as quickly as possible using the position of the mouse as a hint to localise the search, rather than do hit-tests for every item in the collection?


问:
Are there any downsides or problems with Haskell?
I'm looking at diving into Haskell for my next (relatively trivial) personal project. The reasons that I'm tackling Haskell are:

Get my head into a purely functional language

Speed. While I'm sure this can be argued, profiling that I've seen nails Haskell close to C++ (and seems to be quite a bit faster than Erlang).

Speed. The Warp web server seems to be crazy fast in comparison to virtually everything else.

So, given this, what I'm looking for are the downsides or problems that come along with Haskell. The web has a tremendous amount of information about why Haskell is a Good Thing, but I haven't found many topics about its ugly side (apart from gripes about its syntax which I don't care about at all).

An example of what I'm looking for could be like Python's GIL. Something that didn't rear its head until I really started looking at using concurrency in a CPython environment.

答:
The down side to Haskell is that its different. It's a bigger step away from languages that are more commonly taught or talked about, so there will be a larger learning curve. It's also less popular of a language which may limit availability of help if you get stuck. These really aren't major downsides though.

The one thing that is a potential downside is that it's a functional language, so it is less useful for certain problem domains, but this is true for object oriented languages as well. Generally languages don't have true negatives beyond learning curves, at least for the relatively popular languages. As long as a language is Turing complete it is theoretically capable of anything.


答:
As mentioned by sebastiangeiger, spatial indexes help. I've found quad trees to be simple to implement. Another alternative that may even be simpler is to just divide your space into a grid, and insert each rectangle into the series of spaces that it intersects with (this is actually similar to what each node of a quad tree does, given that each node is a 2x2 grid).

Ultimately, find the simplest approach that meets your performance requirement.


答: Do a decision analysis. Talk to your boss and the other programmer and, as a group, determine what are the most important criteria your solution must have (performance, extensibility, faster development, etc.). Have your boss rate each item on how important it is to the project (1-5, 5 being the most important). These are the weighting factors. Then for your idea assign a numerical score (1-5, 5 being the best) to each criteria the solution must meet. Have the other developer do the same for his idea. These are the scores. Then, do the math. Multiply each score by the weighting factor the boss assigned and sum up all the scores for each idea. Then you know which idea has the best chance of meeting the criteria that the project needs to meet to succeed. You may quibble over the specific numbers a line item might have for a specific solution, but it would then open a dialog and once you agree on a anumber or if you realize you have forgotten a critical criteria, then you can easily make the changes and see if the same solution still prevails. It also will teach you how to think about what is important for a solution to have and will get you takling about specific factors and more objective assessments than just "I hate your idea". IT will get you talking about the real reasons why it may or may not work. You may find that when you judge the real factors and the real weights on those factors that neither solution is strong in all the areas it needs to be and you can start looking for something better.</p>

Title: How to solve a fundamental cloud data storage dispute?

Body:
I'm working for a company that has recently hired me to create a new version of their existing software, which is now over 12 years old. The new software is a complete re-write of the old and they want it to be much more "online" than the previous version. I'm one of two programmers, the other having been with the company for 20+ years and is now close to retirement.

The problem I'm facing is that with almost every idea I suggest that doesn't fall in line with what he thinks, it just gets shot-down, ignored and forgotten. So far I've let a lot slide; nothing too critical, and things that could be changed later on if needed.

However, we're now on the subject of how to store the data that needs to be accessible to all the customers; he wants to use SQL Azure and store as much data as possible in xaml-string blobs, then use DevForce IdeaBlade to generate all the back end code. I'm not convinced, I think that if we're using a SQL storage solution we should be using relational database tables, which are normalized, etc. OR we shouldn't be using SQL at all, and perhaps use another method that allows storage of C# objects directly?

What do you guys think?

EDIT: Ok, so to give people a bit more information, the program could be considered a sort of Photoshop-like application, but aimed at a specific market. Users have access to a library of template "backgrounds" which they can then add text, images, etc. on too. When they browse the library of templates, they will be able to filter them by type, color, etc.


问:
Why didn't the C++ Standard adopt expression templates?
It's my understanding that expression templates as a technique were discovered significantly prior to the original C++ Standard in 1998. Why weren't they used to improve the performance of several standard classes like std::string and streams?

答: My best guess is that no compiler would have been able to compile expression templates back in 1998.</p>

OwnerDisplayName: DeadMG

OwnerDisplayName: FredOverflow


答:
Expression templates were first published by Todd Veldhuizen in June 1995, in an article in the C++ Report magazine. By that time, the standard committee was already heavily involved with adding the STL to the C++ standard, a task which all by itself delayed the standard by one or two years. (The STL was presented to the committee in 1993, and officially proposed in 1994. It took another four years to finish the standard.)

Given that the C++ standardization committee is a bunch of volunteers, some of them not even backed by companies paying their expenses, I don't think anyone had any resources to use on adding yet another idea to the C++ standard.

Also, 1995 is just the year Veldhuizen's article was published. For the technique to become known and recognized, it would have taken another few years. (The idea of the STL dates back to the 70s, an Ada implementation was done in the late 80s, work at a C++ implementation must have started around 1990, and it took another three years for the idea to find its way to the C++ standardization committee.)

There were, however, just three years from Todd's article until the final vote on the standard. That was way too little time to incorporate an idea that was still brand-new and basically untested.

Add to that the fact that Expression Templates, being a kind of template meta-programming, stress compilers way more than the comparatively "simple" STL does. And from what I remember, even in 1998, when the standard was published, we didn't have a compiler that could even compile all of the STL.

Given that one of the standardization committee's main goals was to standardize established practice (not that they stuck to this rigorously), Expression Templates should never have been on the agenda back then.

Title: Why didn't the C++ Standard adopt expression templates?

Body: It's my understanding that expression templates as a technique were discovered significantly prior to the original C++ Standard in 1998. Why weren't they used to improve the performance of several standard classes like std::string and streams?

OwnerDisplayName: sbi


答:
Evaluation.

A programmer ought to know how the statements they write are evaluated. a(line.of(code) is aSequenceOf(evaluations)) and if you don't understand what that line looks like after each step of its evaluation, you are going to be extremely restricted as a programmer in your ability to take advantage of language features.

I'm not just talking about the basic

```<code>if (bool == false):
    return true
else:
    return false
</code>```

which of course can just be replaced by return !bool.

I'm also referring to the ability to understand your language to the point where you can come up with something like this:

```<code>string[] thingsToOutput;
for(int i = 0; i <= thingsToOutput.Length; print(thingsToOutput[i++]));
</code>```

When I first saw a statement like that it blew my mind a little bit; it hadn't occurred to me I could leverage the for loop in such a way. The person who wrote that statement more fully understood the possibilities available to them - they saw more open doors than I, which gave them more freedom and power in their ability to design code.

Now, whether it's good code is an issue - whether any of those doors should be opened - that's up to debate. It remains that with great power comes great responsibility.

Title: What should every programmer know about programming?

Body: Please, stay on technical issues, avoid behavior, cultural, career or political issues.

Body:
Evaluation.

A programmer ought to know how the statements they write are evaluated. a(line.of(code) is aSequenceOf(evaluations)) and if you don't understand what that line looks like after each step of its evaluation, you are going to be extremely restricted as a programmer in your ability to take advantage of language features.

I'm not just talking about the basic

if (bool == false):
    return true
else:
    return false

which of course can just be replaced by return !bool.

I'm also referring to the ability to understand your language to the point where you can come up with something like this:

string[] thingsToOutput;
for(int i = 0; i <= thingsToOutput.Length; print(thingsToOutput[i++]));

When I first saw a statement like that it blew my mind a little bit; it hadn't occurred to me I could leverage the for loop in such a way. The person who wrote that statement more fully understood the possibilities available to them - they saw more open doors than I, which gave them more freedom and power in their ability to design code.

Now, whether it's good code is an issue - whether any of those doors should be opened - that's up to debate. It remains that with great power comes great responsibility.


答:
The simple answer is: you obviously didn't lobby for it. Nor did I because I had (and have) my own agenda which doesn't include expression templates. Also, the interface in particular for strings is already trying to serve way too many masters, resulting in a class which is used for everything and good for mothing.

The standard library has already std::valarray and family which is intended to support an expression template style of implementation. As far as I can tell it doesn't quite cut it, though. One problem which caused this is that the people who lobbied to get its half-baked version included into the standard stopped working in it the moment it included. There were attempts to rescue it (e.g. David Vandevoorde, Matt Austern, and I worked on it for a day or so at the Stockholm meeting) but in the end nobody was interested enough.

OwnerDisplayName: Dietmar Kühl


答:
I am not a Haskell expert: I have learnt the basics but unfortunately I haven't
had the chance to do some serious project in Haskell (I would like though, because I like this language a lot).

However, from what I know and from a discussion with somebody who's been working
in a field quite close to functional programming, Haskell might not be the best
solution when you want to implement graphs algorithms, where you need e.g.
to walk through the graph and perform many local changes on the graph structure.

Since a graph does not have a recursive structure in general, my feeling is
that the best approach is to build one copy of the graph using structures
and pointers between them (as you can do e.g. in C++) and manipulate that
copy by changing pointers, creating or destroying nodes, and so on.

I wonder how such data structures and operations can be handled properly
in Haskell, since to my knowledge in Haskell it is not possible to use the above representation / approach. Some problems with graph algorithms in Haskell are briefly discussed in this article

EDIT

I recently spoke with an expert of functional programming and he confirmed that implementing certain graph algorithm efficiently can be quite tricky in Haskell: moving around pointers like you do in C or C++ can be much faster.

Title: Are there any downsides or problems with Haskell?

Body:
I'm looking at diving into Haskell for my next (relatively trivial) personal project. The reasons that I'm tackling Haskell are:

Get my head into a purely functional language

Speed. While I'm sure this can be argued, profiling that I've seen nails Haskell close to C++ (and seems to be quite a bit faster than Erlang).

Speed. The Warp web server seems to be crazy fast in comparison to virtually everything else.

So, given this, what I'm looking for are the downsides or problems that come along with Haskell. The web has a tremendous amount of information about why Haskell is a Good Thing, but I haven't found many topics about its ugly side (apart from gripes about its syntax which I don't care about at all).

An example of what I'm looking for could be like Python's GIL. Something that didn't rear its head until I really started looking at using concurrency in a CPython environment.


问:
What are the most common options for data storage in desktop applications?
When I was working as a website designer/engineer I primarily used databases for storage of much of my dynamic data.  It was very easy and convenient to use this method and seemed like a standard practice from my research on the matter.  I'm now working on shifting away from websites and into desktop applications.  What are the best practices for data storage for desktop applications?  I ask because I have noticed that most programs I use on a personal level don't appear to use a database for data storage unless its embedded in the program.

I'm not thinking of an application like a word processor where it makes sense to have data stored in individual files as defined by the user.  Rather I'm thinking of something more along the lines of a calendar application which would need to store dates and event info and such where accessing that information would be much easier if stored in a database... at least as far as my experience would indicate.

答:
Data can be stored in many formats. The relational database approach is one of them of course. However, some vendors may want to stay away for ODBC settings and OLEDB problems as well as connectivity issues with regular relational databases. Some vendors opt to use their own 'databases' systems (some of those are based on Indexed Sequential Access Method ISAM Wiki-ISAM).

Some applications use direct-files and some may opt to use sequential (csv or otherwise)/binary files. Since most personal applications have small number of data rows, it is easy to read the entire data in memory and use arrays, LINQ, DotNet ADO, and many like methods to access the data in memory.

The best practice depends on many factors such as your programming language, need to protect the schema, need to protect the data, logging, transaction rollback, etc. For example, using a relational database on the client would expose your schema which is something you may not want to do. On the other hand, if you use a sequential file, you may not be able to use a reporting tool directly.

I would prefer a relational database if you could live with the drawbacks such as exposing data and exposing schema to end user.


问:
How can I defend Ruby on Rails against customers' not technical opinion?
My customer, a translations business owner, just told me that he has been reading about Ruby on Rails and told me that "there are more PHP guys around there" and "it seems the community prefers it".
What would you, as software engineer and freelancer, say to the customer to achieve these goals:

Sell

Make him see that the technology is my expert decision and Rails
is as good or better than PHP (+ whatever framework) for this
particular project.

UPDATE:
Thank you all for the suggestions! Tomorrow I've got another meeting with him, let's see how it goes, I will update again :)

UPDATE 2:
Finally I told him to read this thread and the result has been fantastic: He gave me the project and we are going to start right now. Thank you all for the help, you have free beer in my charge if we see someday :)

BTW: I learned the lesson: be as transparent as possible, because if you believe in yourself and your work, there is no question compromising enough to beat you.

regards

答: I'd explain that it's basically a "Coke" vs. "Pepsi" choice.  Both are widely accepted, both have people that will fight and die for each, and they're both perfectly adequate.  Point out the reasons you prefer RoR.</p>

OwnerDisplayName: okeen


答:
For starters, you can direct you client here for a look at the ecosystem that exists around Rails. You can also point to the successful startups like LivingSocial, Shopify, 37signals, etc. that built their businesses with Ruby and Rails.

You can mention that massive enterprises like AT&T, SAP, and Symantec are using Rails, too (they were all heavily recruiting at RailsConf last year).

You can point out that a translations business has a lot to gain by using a language/framework that makes Unicode support and i18n relatively painless.

Ultimately, I think you need to sell the idea that being able to use Rails is a premium feature he gets by hiring you: "Of course all those other guys are using PHP. But you have the opportunity to have a modern stack powering your application."

At the end of the day, it also needs to be clear that what he's ultimately buying is your skill and expertise; if he was that knowledgeable on server-side web technologies, he wouldn't need you. Language and framework are implementation decisions, not requirements.

P.S. Don't mention Twitter. We're still trying to undo the bad PR Rails took from that.

Title: How can I defend Ruby on Rails against customers' not technical opinion?

Body:
My customer, a translations business owner, just told me that he has been reading about Ruby on Rails and told me that "there are more PHP guys around there" and "it seems the community prefers it".
What would you, as software engineer and freelancer, say to the customer to achieve these goals:

Sell

Make him see that the technology is my expert decision and Rails
is as good or better than PHP (+ whatever framework) for this
particular project.

UPDATE:
Thank you all for the suggestions! Tomorrow I've got another meeting with him, let's see how it goes, I will update again :)

UPDATE 2:
Finally I told him to read this thread and the result has been fantastic: He gave me the project and we are going to start right now. Thank you all for the help, you have free beer in my charge if we see someday :)

BTW: I learned the lesson: be as transparent as possible, because if you believe in yourself and your work, there is no question compromising enough to beat you.

regards


答:
First off: Eval is pretty bad. As @NiranjanKala's answer mentions it uses Reflection to get the value of the relevant property/field, and using Reflection to get values from object members is very slow (see this article for more details).

As for the other two syntaxes, it really depends. I used to be a proponent of the event binding syntax, as it reduces clutter in the ASPX file, and keeps the databinding logic and the markup separate. Plus, it's easy to debug and you can make use of other features such as sub-repeaters that share templates with the parent repeater for hierarchical data, or the ability to turn other Controls inside the repeater on and off based on accessible data. I think it really fits with the "stateful web" approach that WebForms goes for.

However, more recently I've been doing a lot of MVC and you can really apply a similar approach to the repeaters; bind a pre-formatted object, and you no longer need to worry about your "shim" methods being in the ASPX:

```<code>protected class MyUiBoundClass
{
   public string DataField {get;set;}
}

public IEnumerable<MyUiBoundClass> PrepareForBind(IEnumerable<MyEntity> entities)
{
    return entities.Select(x =>
                new MyUiBoundClass {
                    DataField = FormatMyData(entity.DataField)
                });
}

public void LoadAndBindData()
{
    /// Load some data from somewhere.
    IEnumerable<MyEntity> myData = this.SomeService.LoadMyData();
    IEnumerable<MyUiBoundClass> myFormattedData = PrepareToBind(myData);

    this.MyRepeater.DataSource = myFormattedData;
    this.MyRepeater.DataBind();
}
</code>```

If you use this ViewModel-style pattern you separate the data formatting from the markup, and still get to use the faster and more concise <%# %> syntax. Plus, you've pretty much solved the "harder to debug" issue that normally comes with the <%# %> syntax, as you would find all the debug-worthy code in the PrepareToBind method.

Title: Should one bind data with Eval on aspx or override ItemDataBound in code-behind?

Body:
For data bound controls (Repeater, ListView, GridView, etc.), what's the preferred way of binding data?

I've seen it where people use Eval() directly on the aspx/ascx inside the data bound control to pull the data field, but to me, it just seems so...inelegant. It seems particularly inelegant when the data needs to be manipulated so you wind up with shim methods like <%# FormatMyData(DataBinder.Eval(Container.DataItem, "DataField")) %> inside your control.

Personally, I prefer to put in Literal controls (or other appropriate controls) and attach to the OnItemDataBound event for the control and populate all the data to their appropriate fields in the code-behind.

Are there any advantages of doing one over the other? I prefer the latter, because to me it makes sense to compartmentalize the data binding logic and the presentation layer. But maybe that's just me.

Body:
First off: Eval is pretty bad. As @NiranjanKala's answer mentions it uses Reflection to get the value of the relevant property/field, and using Reflection to get values from object members is very slow (see this article for more details).

As for the other two syntaxes, it really depends. I used to be a proponent of the event binding syntax, as it reduces clutter in the ASPX file, and keeps the databinding logic and the markup separate. Plus, it's easy to debug and you can make use of other features such as sub-repeaters that share templates with the parent repeater for hierarchical data, or the ability to turn other Controls inside the repeater on and off based on accessible data. I think it really fits with the "stateful web" approach that WebForms goes for.

However, more recently I've been doing a lot of MVC and you can really apply a similar approach to the repeaters; bind a pre-formatted object, and you no longer need to worry about your "shim" methods being in the ASPX:

protected class MyUiBoundClass
{
   public string DataField {get;set;}
}

public IEnumerable<MyUiBoundClass> PrepareForBind(IEnumerable<MyEntity> entities)
{
    return entities.Select(x =>
                new MyUiBoundClass {
                    DataField = FormatMyData(entity.DataField)
                });
}

public void LoadAndBindData()
{
    /// Load some data from somewhere.
    IEnumerable<MyEntity> myData = this.SomeService.LoadMyData();
    IEnumerable<MyUiBoundClass> myFormattedData = PrepareToBind(myData);

    this.MyRepeater.DataSource = myFormattedData;
    this.MyRepeater.DataBind();
}

If you use this ViewModel-style pattern you separate the data formatting from the markup, and still get to use the faster and more concise <%# %> syntax. Plus, you've pretty much solved the "harder to debug" issue that normally comes with the <%# %> syntax, as you would find all the debug-worthy code in the PrepareToBind method.


答:
He's talking about people, you're talking about a language and framework. He is not going to hear any reasons that are purely technical, so you should focus on what people are doing with the language. You can talk about people-power under Rails, how it's easier for one person to do more than a PHP person, faster (if this is what you believe). You can ask whether the prevalence of Honda drivers means it's a better car than a Rolls Royce, which is rarely seen. You can talk about what the community is actually comprised of, whether there are too many cooks in the module soup (gems vs. modules, etc.), whether everybody has NIH syndrome, and so on.

Regardless, it needs to be in terms of people because he wants to know that he can replace you. Help him to know this, because he (probably) won't want to switch away anyway. Your "expert decision" has absolutely no bearing when he gives much less care to what a given person knows. He just wants there to be "more people" who know the same thing.

At the end of the day, there's no shame in calling his bluff. "Fine, go with PHP. Good luck!"


答:
Point out that the PHP crowd has more members because its the lowest barrier to entry and has been around longer. Make sure to point out that smaller communities have higher percentages of programmers worth hiring, PHP may have 10,000 good programers compared to 5,000 rails programmers, but the PHP programmers are hidden in a block of 100,000 compared to 20,000 for rails programers. (These numbers are made up, but it gets the point across.) Then you need to explain that the community really doesn't have a preference between PHP and Rails.

You can't use technical reasons on a non technical person, you can't explain why the iPhone is inferior to other smartphones to someone who only knows about what phones look like. You need reasons they understand.


问:
Never use Strings in Java?
I stumbled upon a blog entry discouraging the use of Strings in Java for making your code lack semantics, suggesting that you should use thin wrapper classes instead. This is the before and after examples the said entry provides to illustrate the matter:

```<code>public void bookTicket(
  String name,
  String firstName,
  String film,
  int count,
  String cinema);

public void bookTicket(
  Name name,
  FirstName firstName,
  Film film,
  Count count,
  Cinema cinema);
</code>```

In my experience reading programming blogs I've come to the conclusion that 90% is nonsense, but I'm left wondering whether this is a valid point. Somehow it doesn't feel right to me, but I couldn't exactly pinpoint what is amiss with the style of programming.

答:
That's just crazy:)

Use common sense

Don't over-engineer!

Keep it small simple!

You Arent Gonna Need It (YagNi)

Title: Never use Strings in Java?


答:
Encapsulation is there to protect your program against change. Is the representation of a Name going to change? If not, then you're wasting your time and YAGNI applies.

Edit: I've read the blog post and he has a fundamentally good idea. The problem is that he's scaled it way too far. Something like String orderId is really bad, because presumably "!"£$%^&*())ADAFVF is not a valid orderId. This means that String represents a lot more possible values than there are valid orderIds. However, for something like a name, then you can't possibly predict what might or might not be a valid name, and any String is a valid name.

In the first instance, you are (correctly) reducing the possible inputs to only valid ones. In the second instance, you have achieved no narrowing of possible valid inputs.

Edit again: Consider the case of invalid input. If you write "Gareth Gobulcoque" as your name, it's going to look silly, it's not going to be the end of the world. If you put in an invalid OrderID, chances are that it's simply not going to function.

Title: Never use Strings in Java?

Body:
I stumbled upon a blog entry discouraging the use of Strings in Java for making your code lack semantics, suggesting that you should use thin wrapper classes instead. This is the before and after examples the said entry provides to illustrate the matter:

```<code>public void bookTicket(
  String name,
  String firstName,
  String film,
  int count,
  String cinema);

public void bookTicket(
  Name name,
  FirstName firstName,
  Film film,
  Count count,
  Cinema cinema);
</code>```

In my experience reading programming blogs I've come to the conclusion that 90% is nonsense, but I'm left wondering whether this is a valid point. Somehow it doesn't feel right to me, but I couldn't exactly pinpoint what is amiss with the style of programming.


答:
Translate your beliefs into quantifiable economic terms (if possible/valid). The fact that his business is translation specific suggests that RoR (or any language with native multilingual support) is technically superior to PHP - but this has to be offset against the costs of developers and server provisioning associated with those respective platforms. Their business is likely to last longer than your relationship, they will want reassurance that they are laying the right foundations.

IME, admitting the cons (as well as the pros) of your strategy is more convincing than any amount of evangelism - it suggests that you are more interested in solving their problem than using your favourite hammer.


答: To me doing this is the same as using regions in C#. Generally if you feel this is needed to make your code readable then you have bigger problems you should be spending your time on.</p>

Title: Never use Strings in Java?


答:
Most of Haskell's downsides (as well as most of Haskell's upside) come from its two defining characteristics: It's lazy and purely functional.

Being lazy makes it harder to reason about performance. Especially for people not used to laziness, but even for experienced Haskellers it can be hard to see how laziness will affect performance in certain cases.

Laziness also means that it's harder to create accurate benchmarks without using libraries like Criterion.

Being purely functional means that whenever you need to use mutable data structures (in cases where it's not possible to achieve the desired performance without them - though thanks to GHC's optimizer that doesn't happen as often as you might think), you'll be stuck in the IO (or ST) monad, which makes the code more cumbersome.

Since you mentioned speed as one of your goals, I should point out that there are often huge differences in performance between hand-optimized Haskell code and Haskell code that was written without giving much thought to performance (more so than in other languages). And hand-optimized Haskell code is often quite ugly (though I suppose that is also true in most other languages).


答:
A few downsides I can think of:

Due to the language's nature and its firm roots in the academic world, the community is very math-minded; if you're a pragmatic person, this can be overwhelming at times, and if you don't speak the jargon, you'll have a harder time than with many other languages.

While there is an incredible wealth of libraries, documentation is often terse.

Gentle entry-level tutorials are few and hard to find, so the initial learning curve is pretty steep.

A few language features are unnecessarily clumsy; a prominent example is how record syntax does not introduce a naming scope, so there is no way to have the same record field name in two different types within the same module namespace.

Haskell defaults to lazy evaluation, and while this is often a great thing, it can bite you in nasty ways sometimes. Using lazy evaluation naively in non-trivial situations can lead to unnecessary performance bottlenecks, and understanding what's going on under the hood isn't exactly straightforward.

Lazy evaluation (especially combined with purity and an aggressively optimizing compiler) also means you can't easily reason about execution order; in fact, you don't even know whether a certain piece of code actually gets evaluated in a given situation. Consequently, debugging Haskell code requires a different mindset, if only because stepping through your code is less useful and less meaningful.

Because of Haskell's purity, you can't use side effects to do things like I/O; you have to use a monad and 'abuse' lazy evaluation to achieve interactivity, and you have to drag the monadic context around anywhere you might want to do I/O. (This is actually a good feature in many ways, but it makes pragmatic coding impossible at times.)


问:
How to structure unit tests for a GUI app using C# and NUnit
I've been asked to do a small side-project to supply a simple application to one of our customers. Normally I would be working on back-end code where I have all of my testing needs figured out, and I've not yet had the dubious pleasure of writing tests for the GUI, so it's a little unclear to me how I should set up the testing code and tools for an EXE.

My first instinct was to simply include the tests with the application code, however that would require supplying a number of test-specific dependencies, which I have been instructed to specifically not ship to the customer. I am also unable to squeeze out any cash for a purpose built test tool, so I need to use the tools I have at hand (StoryQ, RhinoMocks, and NUnit), which really should be more than enough to test the behavior of a simple GUI app. So as far as I can see, this leaves me with trying to strike a good balance between keeping the design really simple, or purposefully over-engineering for the sake of the tests. It seems I'm either building the app with the business logic in a separate library and testing against the library as I usually would, or finding some other mechanism to allow me to the executable without breaking out additional modules that the application design doesn't really need.

Edit:

Please note that this question is about how to structure the relationship between NUnit and my executable - as opposed to a DLL - and not about how to separate presentation and business logic.

/Edit

So my question is:

Is there a specific/recommended method for configuring a simple GUI application with unit tests to allow me to adequately check state and behavior, using the tools I have at hand, and without resorting to over-engineering?

Have I missed something fundamental about the way NUnit should be invoked/configured when testing an EXE (as opposed to a DLL)?

Can you provide or point me in the direction of examples of how achieve all of this?

I realize that there may be more than one way to do this so I'm looking for specific implementation guidelines based on your experience.

答:
Take a look at my answer on this question:  How do I set up MVP for a Winforms solution?

I've actually written a sample application that shows how I layer, and how I test, my GUI.

reading your edit: use a test runner that integrates with your development environment.  I use ReSharper.


答:
If you're interested in working in AI, data processing, physics simulation or graphics then you need maths. Conversely, if you're not, then I reckon you don't.
It's a case of use it or lose it, why learn French if you don't want to live in France? There are plenty of problem domains that just require conditional logic.

Having said that, there's a natural incline in programming towards mathematics , and it's going to do you nothing but good to gain some understanding of it.