问:
Which things instantly ring alarm bells when looking at code?
I attended a software craftsmanship event a couple of weeks ago and one of the comments made was "I'm sure we all recognize bad code when we see it" and everyone nodded sagely without further discussion.

This sort of thing always worries me as there's that truism that everyone thinks they're an above average driver. Although I think I can recognize bad code I'd love to learn more about what other people consider to be code smells as it's rarely discussed in detail on people's blogs and only in a handful of books. In particular I think it'd be interesting to hear about anything that's a code smell in one language but not another.

I'll start off with an easy one:

Code in source control that has a high proportion of commented out
  code - why is it there? was it meant
  to be deleted? is it a half finished
  piece of work? maybe it shouldn't have
  been commented out and was only done
  when someone was testing something
  out? Personally I find this sort of
  thing really annoying even if it's just the odd line here and there, but when you see large blocks interspersed with the rest of the code it's totally unacceptable. It's
  also usually an indication that the rest of
  the code is likely to be of dubious
  quality as well.

答:
Code smell: not following best practices

This sort of thing always worries me as there's that truism that everyone thinks they're an above average driver.

Here's a news flash for ya: 50% of the world's population is below average intelligence. Ok, so some people would have exactly average intelligence, but let's not get picky. Also, one of the side affects of stupidity is you can't recognize your own stupidity! Things don't look so good if you combine these statements.

Which things instantly ring alarm bells when looking at code?

Many good things have been mentioned, and in general it seems that not following best practices is a code smell.

Best practices are usually not invented randomly, and are often there for a reason. Many times it can be subjective, but in my experience they are mostly justified. Following best practices should not be a problem, and if you're wondering why they are as they are, research it rather than ignoring and/or complaining about it - maybe it's justified, maybe it's not.

One example of a best practice might be using curlies with every if-block, even if it only contains one line:

if (something) {
    // whatever
}
```

You might not think it's necessary, but I recently read that it is a major source of bugs. Always using brackets have also been discussed on Stack Overflow, and checking that if-statements have brackets is also a rule in PMD, a static code analyzer for Java.

Remember: "Because it's best practice" is never an acceptable answer to the question "why are you doing this?" If you can't articulate why something is a best practice, then it's not a best practice, it's a superstition.

Body:
Code smell: not following best practices

This sort of thing always worries me as there's that truism that everyone thinks they're an above average driver.

Here's a news flash for ya: 50% of the world's population is below average intelligence. Ok, so some people would have exactly average intelligence, but let's not get picky. Also, one of the side affects of stupidity is you can't recognize your own stupidity! Things don't look so good if you combine these statements.

Which things instantly ring alarm bells when looking at code?

Many good things have been mentioned, and in general it seems that not following best practices is a code smell.

Best practices are usually not invented randomly, and are often there for a reason. Many times it can be subjective, but in my experience they are mostly justified. Following best practices should not be a problem, and if you're wondering why they are as they are, research it rather than ignoring and/or complaining about it - maybe it's justified, maybe it's not.

One example of a best practice might be using curlies with every if-block, even if it only contains one line:

if (something) {
    // whatever
}

You might not think it's necessary, but I recently read that it is a major source of bugs. Always using brackets have also been discussed on Stack Overflow, and checking that if-statements have brackets is also a rule in PMD, a static code analyzer for Java.

Remember: "Because it's best practice" is never an acceptable answer to the question "why are you doing this?" If you can't articulate why something is a best practice, then it's not a best practice, it's a superstition.


问:
Showing real time data using WCF call (silverlight)
Currently I have a WCF method which brings back all the data from the db and binds it to a grid, but I would like to call this method regularly to get the updated data back each time, to show the user real time data, what is the best way to go about this?

Thanks in advance.

答:
Hmmm,

I do not know what your application function is, but could you try something like this?

What puts the data in your db constantly? Why not just give that to your grid ( might need a bit of formatting and data hiding of course / or store data at application level up to certain limit )
That way you are absolute real time.

Now, to update db why not make a db update when a grid add 10 rows or something from that application level storage or your data grid.

This makes you have less db calls , increasing latency.
Also makes you real time.

Thoughts?

ContentLicense: CC BY-SA 3.0


问:
How to convince teammates to use TDD
I am the only person on my team that use TDD. How do I make them to use it?

I am annoyed that when I pull, someone's code will break my tests and I am the one who has to fix them.

Will using github, fork and pull request solve this problem, so that they need to pass the test before the pull is accepted?

I am not the project manager and I can't seems to convince her to use it.

答:
As said in a lot of other "how should I convince X to use Y method/technology", my answer is always the same: by example.

Use it and have better (mesurable) results. Then make sure the others notice.

Title: How to convince teammates to use TDD


问:
When is Java a good choice for web development?
When is Java a good choice for web development?

Please do not say "When you have a development team that knows only Java."

答:
Every time yet another Java team pisses me off, I blow off steam by looking up questions like this one. Let me reiterate. I am a client side dev and have been for close to 5 years now. I've worked on sites ranging from one-off mostly-content microsites, to sites as massive as Sears, to more sophisticated app-type sites where really deep UI expertise is needed. I have dealt with Rails, PHP, .net web forms (ew), .net MVC (much better) and a bouquet arrangement of Java solutions for web development accompanied by devs and teams that have all been complete disasters to deal with. I also write a bit of Python and am starting to dig Django.

My experience with Java teams has been universally awful. The tools are always a PITA. The devs never want to believe they did anything wrong and getting them to reinvestigate their own turf once you've ruled out a problem on your end is like pulling teeth. The first casualty of dealing with Java teams in my experience is development time converted to e-mail time writing multiple lengthy explanations of why the problem is definitely on their end. HTML is generally not their problem unless you actually want some control over it. Then everything is likely to go to hell on their end because you actually want to move some upper level divs around.

There are things about the language I dislike but I think the real problem is the culture and the fact that acceptance is so widespread, you have a ton of mediocrity in the middle. The culture I suspect springs from the way Java is marketed. Write once, deploy everywhere. Translation: "You only need to learn one thing!" People who find that appealing basically want to wield Java like one gigantic hammer for every nail with a minimum of actually honing of their craft in regards to web development.

So if you have devs who know Java and other languages but still actually prefer Java, I would say, yes, go ahead if it seems like the right solution. But if you have Java devs who know Java and everything else is just barely meeting the criteria to actually make it a bullet point on their resume, have them build a simple app with a variety of semi-complex pages on the HTML end and try this simple test. Break some HTML. Try to get them to figure out what's wrong. If the immediate problem they start to solve is diverting blame from themselves, keep them the !@#$ away from web development. Web dev is multidisciplinary and requires active interest in the field to be successful. It is not a place for people who only want to have to maintain knowledge of one language and are more horrified by problems than interested in solving them.

I'm not asserting that Java itself is the root of incompetence and I've heard Spring is good. I'm sure there's competent Java teams out there. I just haven't run into one yet and I don't think it's a coincidence. I think Sun has a lot to do with it. I also think running web teams like or under IT departments has a lot to do with it.


问:
how a pure functional programming language manage without assignment statements?
When reading the famous SICP, I found the authors seem rather reluctant to introduce the assignment statement to Scheme in Chapter 3. I read the text and kind of understand why they feel so.

As Scheme is the first functional programming language I ever know something about, I am kind of surprised that there are some functional programming languages (not Scheme of course) can do without assignments.

Let use the example the book offers,the bank account example. If there is no assignment statement, how can this be done?How to change the balance variable? I ask so because I know there are some so-called pure functional languages out there and according to the Turing complete theory, this must can be done too.

I learned C, Java, Python and use assignments a lot in every program I wrote. So it's really an eye-opening experience. I really hope someone can briefly explain how assignments are avoided in those functional programming languages and what profound impact (if any) it has on these languages.

The example mentioned above is here:

```<code>(define (make-withdraw balance)
    (lambda (amount)
        (if (>= balance amount)
            (begin (set! balance (- balance amount))
                balance)
            "Insufficient funds")))
</code>```

This changed the balance by set!. To me it looks a lot like a class method to change the class member balance.

As I said, I am not familiar with functional programming languages, so if I said something wrong about them, feel free to point out.

答:
Assignment is bad operation because it divides the state-space to two parts, before-assignment, and after-assignment. This causes difficulties tracking how the variables are being changed during program execution. The following things in functional languages are replacing assignments:

Function parameters linked directly to return values

choosing different objects to be returned instead of modifying existing objects.

creating new lazy-evaluated values

listing all possible objects, not just the ones that need to be in memory

no side effects


问:
I just started a job with Scrum and something seems to be missing. I am new to Scrum
The code is a complete mess of a combination of classic ASP/ASP.NET. The scrum consist of us patching up the big mess or making additions to it. We are all too busy doing that to start a rewrite so I am wondering..

Where is the part in Scrum where the developers can have the power to say that enough is enough and demand that they are given time to start the big rewrite? We seem in an endless loop of just patching old code with 'Stories'.

So things are being run by the non-technical people who seem to have no desire to push for a rewrite because they don't understand how bad the codebase has gotten..

So who is in charge of making this big rewrite change happen? The developers? The Scrum Master?

The current strategy is just to find time and do it ourselves without the higher-ups involved since they are mostly to blame for the current mess we are in.. <- insert rant about non-technical people telling technical people what to do here ->.

答:
As you describe this, I have to say I don't see anything that has anything to do with SCRUM, or your product development team being a problem currently.

This is Normal

What you describe is the normal entropy of a code base. In your case, the team probably started off farther off from ideal, but still every code base eventually becomes a Big Ball of Mud.

In a completely perfect greenfield scenario, all you can possibly do is start farther from absolute entropy and move towards it slower.

I agree with others, the code base mess is because of developers. I am sure it predates the adoption of SCRUM by many years.

This isn't a technical or developer decision to re-write, it is a business decision.

You aren't privy to why the product owners don't want a re-write. You as a developer think it is needed, but is there really any business case for it?

If there is a true business case, not just a hand waving; "the code is a legacy mess I want to start greenfield because that is what I want", then management would entertain the expense of a re-write, given a consideration of a return on that investment.

You haven't given one solid business case for a re-write, just a rant about your opinion on how everyone else caused this mess and you don't want to deal with it.

Proof - Profit drives business decisions to toss out working software, not some OCD need for a clean code base

If you can really show proof, not just theory but hard proof that spending X dollars on a greenfield re-write will be guaranteed to MAKE X * N dollars for the business in Y time frame ( where N is high and Y is short ), you might get some traction from management. This is a highly unlikely case that you can present and prove.

Otherwise you just need to deal with it, this is reality. Contrary to your adamant assertions that there is absolutely no way forward without this grand immaculate re-write, I would bet money that 5+ years from now code base you are complaining about will still be working and running somewhere providing someone functionality and value long after you have left the company.


问:
How to separate sensitive data in database(MySql)
I need to design a database that will contains information about personal disease of users.

What can be the approach in order to implement the columns of the DB's tables: encrypt the information, separate data within two differents DB, one for sensitive data and another for not sensitive data, or both or another approach?

答:
You could encrypt the data with a key stored in your web application so that the data is written/read from db in its encrypted form. However anyone with access to the code would have access to the key and with the key the unencrypted data. This solves the requirement

the dba should not be able to view the information about disease of
  the user of the database.

As far as using to separate databases I don't think that is needed. You are storing the data encrypted and using database permissions by user, table (if that's even needed) will be more than enough. I think the extra DB adds a layer of complexity without much else. Unless its at a different location, then it might have a SMALL improvement from a single database system.


问:
Testing loses its effectiveness if all programmers don't use them
Let's assume you are convinced that the extra time spent unit testing has merit and improves production. Does that still hold up when everyone working on the same code doesn't use them? This question makes me wonder if fixing tests that everyone doesn't use is a waste of time. If you correct a test so the new code will pass, you're assuming the new code is correct. The person updating the test better have a firm understanding of the reasoning behind the code change and decide if the test or the new code needs to be fixed. This much inconsistency in a team when it comes to testing is probably an indication of other problems as well.

There is a certain amount of risk involved that someone else on the team will alter code that is covered by testing. Is this the point where testing becomes counter-productive?

答:
One's tests must be trusted to be effective. A man with two watches does not know what time it is. That is: bad, inaccurate, unmaintained tests ruins the good stuff. Further, benign neglect is a death spiral, ultimately to the point that the test suite as a whole will be discredited and abandoned.

A test may be bad because it is not current or it lies. It does not matter which, the damage to trust is the same.

When it comes to tests, maintained accuracy and quality over quantity is key.


答:
Unit testing goes hand-in-hand with continuous integration.  When someone changes code and checks it into your source control, your CI tool (e.g., Jenkins) should be rebuilding your project with the new code and running EVERY unit test.  If any test fails, the build fails and the CI should inform everyone of the fact by email.

When people get sick of getting the email, they may realize that if they just run the tests BEFORE they check in code, then life will be easier and everyone will be happy.

Title: Testing loses its effectiveness if all programmers don't use them

Body:
Let's assume you are convinced that the extra time spent unit testing has merit and improves production. Does that still hold up when everyone working on the same code doesn't use them? This question makes me wonder if fixing tests that everyone doesn't use is a waste of time. If you correct a test so the new code will pass, you're assuming the new code is correct. The person updating the test better have a firm understanding of the reasoning behind the code change and decide if the test or the new code needs to be fixed. This much inconsistency in a team when it comes to testing is probably an indication of other problems as well.

There is a certain amount of risk involved that someone else on the team will alter code that is covered by testing. Is this the point where testing becomes counter-productive?


答:
```<code>{ Let it Leak, people have good enough computers to cope these days }
</code>```

Whats worse is that's from a commercial library!

ContentLicense: CC BY-SA 2.5

Title: Which things instantly ring alarm bells when looking at code?

Body:
I attended a software craftsmanship event a couple of weeks ago and one of the comments made was "I'm sure we all recognize bad code when we see it" and everyone nodded sagely without further discussion.

This sort of thing always worries me as there's that truism that everyone thinks they're an above average driver. Although I think I can recognize bad code I'd love to learn more about what other people consider to be code smells as it's rarely discussed in detail on people's blogs and only in a handful of books. In particular I think it'd be interesting to hear about anything that's a code smell in one language but not another.

I'll start off with an easy one:

Code in source control that has a high proportion of commented out
  code - why is it there? was it meant
  to be deleted? is it a half finished
  piece of work? maybe it shouldn't have
  been commented out and was only done
  when someone was testing something
  out? Personally I find this sort of
  thing really annoying even if it's just the odd line here and there, but when you see large blocks interspersed with the rest of the code it's totally unacceptable. It's
  also usually an indication that the rest of
  the code is likely to be of dubious
  quality as well.

Body:
{ Let it Leak, people have good enough computers to cope these days }

Whats worse is that's from a commercial library!


答: Unit testing is an all or nothing decision for a team. By that I mean everyone has to be on board with unit testing for it to work. If there is no team wide buy in for unit testing you are just creating more code to maintain that is potentially broken and out of sync, wasting everyones time and effort. </p>


答:
The person updating the test better have a firm understanding of the reasoning behind the code change and decide if the test or the new code needs to be fixed. This much inconsistency in a team when it comes to testing is probably an indication of other problems as well.

I think it's the other way around. When test is good, its failure should guide one in deciding whether (and why, and, ideally, how) to modify the code or test.

In that sense, responsibility starts not with the person updating the test but with person creating test.

The one who creates test would better have a firm understanding of the reasoning behind the code. If this is not the case then test is of pretty little value and one would better stop worrying about changing it - or even removing it if it indeed stands in a way of development.

If test produces nothing but incomprehensible crywolfs at reasonable code changes, this is an issue in test - this is what needs to be fixed.

There is a certain amount of risk involved that someone else on the team will alter code that is covered by testing. Is this the point where testing becomes counter-productive?

Less productive - maybe. Counter productive - hardly.

Time lag between code changes and test execution may feel unnatural for someone used to mature forms of unit testing and it indeed may incur some effectiveness losses but in other forms of testing (functional, integration, QA) it is quite a common thing and it is not considered a reason to drop testing.

To deal with test execution lagged that way, one probably has to get out of the box of "classical" unit testing approaches and look at the way how our colleagues testers do their stuff.

Now, imagine someone some time ago has changed code and some time later you run test and it fails. Think of how tester would handle that...

Study test failure.

If test helps you to find bug in code, great - open the ticket in issue tracker to get this fixed.

Note, later you can use these tickets to justify benefits of running tests in the build time - that is, if tests are indeed that helpful.

If test does not help, modify it to match the code changes (are you afraid of that? if yes, that indeed can become counter-productive).

If you feel there is an issue in test... guess what? open the ticket in issue tracker to get this fixed.

Note, later you can use this data to explain why regression bugs slip through and justify the need to invest efforts in testing.

Here is where you may experience some loss in productivity - because you act as a tester with the tool that is intended to be used by developer. This is not good, but not really the end of the world don't you think.


问:
Better word for Optional Requirements?
What's a better word for an optional requirement in software engineering? The phrase is contradictory. I've used "Non-Core Requirements" in previous projects.</p>

答:
I am surprised that all the responses are concerned with tracking requirements in project development. Despite being a developer I have never worried overmuch about this terminology in that context.
When i first read the question I assumed it related to user product specification, not product development.
For example, an encyclopaedia might list a color printer as an optional requirement. Its required if you want the full benefit of the app but optional if you want to view the screen.
But what if you had for example a monochrome printer?
How to make clear whether your app works with the obvuous restriction that some photos might not look so good? Or wont print at all?as another example, how should i check a printer review to check whether ink is a requirement or an optional requirement requirement in a multi-function printer? In other words can i still scan? Some hints on terminology and what to search for would be welcome both as a product developer/seller and as a consumer.</p>

Title: Better word for Optional Requirements?


答:
I'm not sure why this is so hard for people. His business case is right here:

```<code>We seem in an endless loop of just patching old code with 'Stories'.
</code>```

Developer time is money. Lots of money. I left a company that planned on revamping their UI over a year ago and hoped that adopting scrum would help them stop spinning their wheels. What happened? Same ol' same ol'. They continued to bolt new features on and "technical debt" had no business case even though half the code we wrote became meaningless with every iteration due to the underlying codebase being a complete outdated mess. Not one thing has changed on their front end since I left, and I was brought on for the very purpose of completely revamping it. In the two months I was there I didn't actually touch a lick of CSS or JavaScript. I was just messing with HTML and some ancient Java templating system from the late 1990s.

My answer? Do what you can, but if the other developers have already given up and are working late to meet sprint goals rather than assert more practical deadlines and insisting that tech debt is in fact a blocking issue, assume the worst and start looking for a new job now. Your developers are either unable or not allowed to communicate their concerns or business is too !@#$ing shortsighted to understand how much money they're pissing away.

Ignoring these problems ALWAYS costs more in the long run. And not a little bit more, but a LOT more. Not only is it a sucking chest wound where development time is concerned, but it's also inevitably going to reduce your talent levels as developers who know better and have other options will avoid your company like the plague. My current boss is a developer AND the owner of the company. There's stuff we won't rewrite in favor of focusing on other priorities, but when something truly needs a refactor due to being a consistent timesink, it gets a proper refactor. And the results are obvious. Modifying and adding new stuff becomes easier and faster by multiple factors. What once may have taken hours can take minutes with proper architecture. Business doesn't like to hear it, but it's worth putting things on hold for that.

Scrum is a failure in environments where developers don't hold a lot of sway, IMO, because it's too easy for the business types to want to ignore maintenance and updates in favor of bullet points they can put on their "successful initiatives" lists when evaluation time comes around. They will always favor their hides and potential for promotion in favor of the long-term, even when it consistently bites them in the ass to ignore these issues too.

Scrum is also a profit-motivated industry and then some. Companies pay a lot of money for scrum training. People looking to adopt should cast a wary eye towards who is being marketed to and how realistic it's really going to be within their given culture.

Regardless, if you actually give a damn about development, a crappy codebase, management with wax in its ears and developers without spines is a recipe for misery and an environment that will do very little to enhance your skillset in any useful regard. Don't hesitate to start putting steps in motion to GTFO before you've actually discovered whether your efforts to fix the problem are actually paying off.

Title: I just started a job with Scrum and something seems to be missing. I am new to Scrum

Body:
The code is a complete mess of a combination of classic ASP/ASP.NET. The scrum consist of us patching up the big mess or making additions to it. We are all too busy doing that to start a rewrite so I am wondering..

Where is the part in Scrum where the developers can have the power to say that enough is enough and demand that they are given time to start the big rewrite? We seem in an endless loop of just patching old code with 'Stories'.

So things are being run by the non-technical people who seem to have no desire to push for a rewrite because they don't understand how bad the codebase has gotten..

So who is in charge of making this big rewrite change happen? The developers? The Scrum Master?

The current strategy is just to find time and do it ourselves without the higher-ups involved since they are mostly to blame for the current mess we are in.. <- insert rant about non-technical people telling technical people what to do here ->.

Body:
I'm not sure why this is so hard for people. His business case is right here:

We seem in an endless loop of just patching old code with 'Stories'.

Developer time is money. Lots of money. I left a company that planned on revamping their UI over a year ago and hoped that adopting scrum would help them stop spinning their wheels. What happened? Same ol' same ol'. They continued to bolt new features on and "technical debt" had no business case even though half the code we wrote became meaningless with every iteration due to the underlying codebase being a complete outdated mess. Not one thing has changed on their front end since I left, and I was brought on for the very purpose of completely revamping it. In the two months I was there I didn't actually touch a lick of CSS or JavaScript. I was just messing with HTML and some ancient Java templating system from the late 1990s.

My answer? Do what you can, but if the other developers have already given up and are working late to meet sprint goals rather than assert more practical deadlines and insisting that tech debt is in fact a blocking issue, assume the worst and start looking for a new job now. Your developers are either unable or not allowed to communicate their concerns or business is too !@#$ing shortsighted to understand how much money they're pissing away.

Ignoring these problems ALWAYS costs more in the long run. And not a little bit more, but a LOT more. Not only is it a sucking chest wound where development time is concerned, but it's also inevitably going to reduce your talent levels as developers who know better and have other options will avoid your company like the plague. My current boss is a developer AND the owner of the company. There's stuff we won't rewrite in favor of focusing on other priorities, but when something truly needs a refactor due to being a consistent timesink, it gets a proper refactor. And the results are obvious. Modifying and adding new stuff becomes easier and faster by multiple factors. What once may have taken hours can take minutes with proper architecture. Business doesn't like to hear it, but it's worth putting things on hold for that.

Scrum is a failure in environments where developers don't hold a lot of sway, IMO, because it's too easy for the business types to want to ignore maintenance and updates in favor of bullet points they can put on their "successful initiatives" lists when evaluation time comes around. They will always favor their hides and potential for promotion in favor of the long-term, even when it consistently bites them in the ass to ignore these issues too.

Scrum is also a profit-motivated industry and then some. Companies pay a lot of money for scrum training. People looking to adopt should cast a wary eye towards who is being marketed to and how realistic it's really going to be within their given culture.

Regardless, if you actually give a damn about development, a crappy codebase, management with wax in its ears and developers without spines is a recipe for misery and an environment that will do very little to enhance your skillset in any useful regard. Don't hesitate to start putting steps in motion to GTFO before you've actually discovered whether your efforts to fix the problem are actually paying off.


答:
You asked:

Where is the part in Scrum where the developers can have the power to say that enough is enough and demand that they are given time to start the big rewrite? We seem in an endless loop of just patching old code with 'Stories'. So things are being run by the non-technical people who seem to have no desire to push for a rewrite because they don't understand how bad the code base has gotten..

As someone who is both a manager and a developer, the simplest answer to your question is there is no part in Scrum, or any other methodology, or in any business scenario, where the developer have the power to say enough is enough and demand a re-write. Many people here have made good, valid, arguments to explain why re-writes are frequently bad ideas, and to explain how change can and should be brought about in an incremental, agile fashion. And I agree with them all.

But the bottom line is even simpler. You don't get to make that decision, EVER. You are the employee, and the only decision you really get to make is "will I continue to work for these asshats or find a new job that fears my mad skillz." Your new job won't allow you to make that decision either, but at least you will feel like you are in control of your fate as you hop from job to job.


问:
How to share problem solving knowledge in a multiteam group?
I've been working in multiteam groups for as long as I've been a web developer, and in my experience, a team can be a lonely soldier or several people; generally a company will have multiple teams working on different projects and once the project is out in the wild, any team can perform maintenance on it.

This is a simple example since I'm not talking only about project related knowledge, but "craft related" knowledge, but it should give you an idea of how I'm used to working:

Since we work on modularised teams, sometimes I feel like the teams are too tightly focused in their projects. I've seen cases where after an hour of discussion, the question was asked aloud and someone on a totally unrelated project suggested a much simpler solution.

The problem is difficult to solve because people tend not to be available all the time, and sometimes the person with the knowledge can't afford the time to go through a problem with the asker, but could do it themselves easily.

I've thought about software based solutions, something along the lines of SE, but I'd like to know other programmers opinions on the subject.

EDIT

I don't know if this is a problem that a wiki can solve, because I feel that wikis don't encourage the user to actually ask questions, but rather to write articles, and sometimes we don't know the knowledge we need before needing it.

答:
A wiki can definitely be helpful, but it takes time to write articles that will be useful to others. In my experience, there are two ways that content gets added:

Someone with knowledge about a particular module or feature writes some content that they think would be useful to others.

It's often difficult for the higher-level developer or engineer to find time in their schedule to dedicate to writing documentation, and since many don't enjoy writing documentation, they may put it off until they forget about it.

Someone who has required help or had to do some serious research to solve a problem documents how they solved it.

This type of article can be very useful, in part because the user of a module might (even if they read some existing documentation) have identified some gotchas for their particular use case. They can also work very well as a sort of guide to future users, even if the use case isn't exactly the same.

I feel that an employer should encourage - and build in time to write - both types of articles, because by doing so you end up relying less on the knowledge of certain individuals.


问:
Automated architecture validation
I am aware of the fact that TFS 2010 ultimate edition can create and validate architecture diagrams.  For example, I can create a new modeling project > add Layer Diagram > Add Layer called View > Add BL Layer > Add DL layer.

Then I can validate this architecture as part of the build process when someone tries to check code into TFS.  In other words, if the View references the DL then the compilation process will fail and the checkin will not be allowed.

For those without an MSDN ultimate license, can FxCop or some 3rd party utility be used to validate architecture in an automated fashion?  I prefer a TFS install-able plugin, but a local VS plugin will do.

答:
For the work with TFS I don't know any other solution than the ultimate edition. The main fact is, controlling the architecture is part of the work of a sw architect, and a architect of a .net project should have the ultimate version :-)

The main problem is that you need to ensure, that the system know's which layer is which one and who can communicate with which layer. THere is one other tool (i've never used it) NDepend but its not for free too.

Title: Automated architecture validation


答:
This is not a problem with unit testing specifically. It is a general problem that programming techniques will not work for a team if some team members do no support it.

Seperation of layers will fall apart if one team member decides to put some business logic in the presentation layer.

My security scheme for a database centric application would fail if any team member wrote front facing stored procedures which did not call my procedure which validates the session and checks permissions.

If a team member violates naming conventions, you cannot rely on names to be how you expect.

If your team wants to use unit testing, and a team member is ruining it, that member is a bad fit for your team.


答: I feel your pain, but am not sure what it has to do with Scrum. The decision whether to re-write code does not depend on the development process.</p>


答: I would call them "optional features", not optional requirements. Requirements sound like something that you have to have, while features sound like an add-on to the original product.

Title: Better word for Optional Requirements?

Body: What's a better word for an optional requirement in software engineering? The phrase is contradictory. I've used "Non-Core Requirements" in previous projects.</p>


问:
How do you unit test private methods?
I am working on a java project. I am new to  unit testing. What is the best way to unit test private methods in java classes?</p>

答:
First of all, as other authors suggested: think twice if you do really need to test private method. And if so, ...

In .NET you can convert it into "Internal" method, and make package "InternalVisible" to your unit test project.

In Java you can write tests itself in the class to be tested and your test methods should be able to call private methods as well. I don't really have big Java experience, so that's probably not the best practice.

Thanks.

Title: How do you unit test private methods?


问:
What services exist for finding someone specific to then run your own peer to peer software with?
If you give people peer to peer software (such as a web sockets application if the peer to peer part gets implemented, but could be anything) the first step for some kinds of applications is to find a specific person and try to connect with them.  If neither of you has a URI (and knows what it is) you need a third party to handle finding each other and verifying your identities.  After that the third party isn't needed because you go peer to peer.

I could of course write that third party software and put it up on a website, but then I would have to write that third party software and put it up on a website (or a server that isn't a website if that's how I want to do it).

Does anyone offer this service?  Ideally as a website and of course ideally free.

答:
Check out GWebCache, which is an open-source spec for this sort of thing.

http://www.gnucleus.com/gwebcache/

And here's an open source implementation:

http://code.google.com/p/cachechu/


问:
Biggest mistake you've ever made
Similar to the question I read on Server Fault, what is the biggest mistake you've ever made in an IT related position. Some examples from friends:

I needed to do some work on a production site so I decided to copy over the live database to the beta site. Pretty standard, but when I went to the beta site it was still pulling out-of-date info. OOPS! I had copied the beta database over to the live site! Thank god for backups.

And for me, I created a form for an event that was to be held during a specific time range. Participants would fill out the form for a chance to win, and we would send the event organizers a CSV from the database. I went into the database, and found ONLY 1 ENTRY, MINE. Upon investigating, it appears as though I forgot an auto increment key, and because of the server setup there was no way to recover the lost data.

I am aware this question is similar to ones on Stack Overflow but the ones I found seemed to receive generic answers instead of actual stories :)

What is the biggest coding error/mistake ever…

答: Using == instead of equals for string comparison in Java

Title: Biggest mistake you've ever made


问:
Any enlightenment for understanding Object Oriented Programming?
I studied computer science near the end of 1980s, and wasn't taught OOP that formally.

With Pascal or C, when I understand the top-down design of functions, and the idea of black box, then everything just seem to make sense, as if there is a "oh I get it!" -- some kind of totally getting it and enlightenment feeling.

But with OOP, all I know was the mechanics: the class, instance, method, inheritance, polymorphism, encapsulation.  It was like, I knew all the "this is how it is", but never had the feeling of "I totally get it", the enlightened feeling.

Would somebody be able to describe it, or point to a chapter in some book or paper which talks about OOP so that the reader can feel: "I totally get it!" on OOP?

答:
OOP is basically the same principle. Except now the black box can also contain data (member variables) and can be chosen at run-time through inheritance.

Of course, those things are very important. But conceptually, they're quite simple.


问:
how to do database updates in each release
Our application uses database (mostly Oracle), and database is at the core. Each customer has its own database, with its own copy of application. Now with each new release of our product, we also need to update the database schema. These changes are adding new tables, removing columns, manipulating data etc. How do the people handle this? Are there any standard processes for this? </p>

<p>EDIT:- The main issue is the databases are huge with many tables and more of huge amount of data. We provide the scripts and some utilities to manipulate the data. How to handle the failures and false negatives? More of looking for this kind articles.
http://thedailywtf.com/Articles/Database-Changes-Done-Right.aspx </p>

答:
It depends on your data, but in general you want to ensure that all the data makes it through the upgrade intact.

You will probably want to prepare some DDL scripts that create/modify structures, maybe even one script per structure. You will also probably need some DML scripts that update/backup/transform data during this process. Again, how much of this you will need to do will depend on the nature of the upgrade.

For testing purposes, it might be a good idea to try and get some (or all, if possible) of the client's data before the scheduled upgrade and test it out on their data to see if there's any data in their systems that could break the upgrade process.

Finally, you will want to take a full back up of the client's database right before begining their upgrade, so you can restore if things get weird.

Some other points that might be good to think about:

If tables/columns are being removed, be sure to remove them in the correct order to avoid integrity constraint violations.

Are there any constraints or triggers that should be disabled/removed for all or part of the upgrade? Are there any constraints or triggers you could create just for the upgrade that might make it easier?

If you are updating data for columns that have been indexed, you might want to include re-indexing/stats gathering as a part of the upgrade process.


答: I recommend you look into myBatis migrations.  You can use this to wrap your modification (and rollback) scripts into a simple commmand than can be run as part of an installation/upgrade.</p>

Title: how to do database updates in each release

Body:
Our application uses database (mostly Oracle), and database is at the core. Each customer has its own database, with its own copy of application. Now with each new release of our product, we also need to update the database schema. These changes are adding new tables, removing columns, manipulating data etc. How do the people handle this? Are there any standard processes for this? </p>

<p>EDIT:- The main issue is the databases are huge with many tables and more of huge amount of data. We provide the scripts and some utilities to manipulate the data. How to handle the failures and false negatives? More of looking for this kind articles.
http://thedailywtf.com/Articles/Database-Changes-Done-Right.aspx </p>


问:
How do I handle a Controller that's not controlling a specific Model?
I've got a nice MVC set up going but my website requires some views that don't map directly to a model. Specifically I've got some generic Reports users need to run, and now I'm creating a utility for comparing some system configurations.

Right now the logic is crammed into a Reports Controller and I'm starting a Comparison Controller but this feels like a big abuse of the system. Both controllers use an assortment of different Models to pull data from, and they're only related based on what the user is doing. Reports are run from the Reports Controller and their views are all grouped together in the file system/URL structure.

Is this an acceptable use of the Controller paradigm? I can't think of a better way to structure my Controllers, and making a Controller for each model I'm using to make reports/ect doesn't seem like a good idea; I'd end up with one Controller/Model/View per report or comparison, vastly complicating the apparent structure of my site.

答:
Favor thin controllers; push as much of the data analysis as you can into a Business Logic Layer that coordinates data transfer between the controllers and the model, and use the controllers merely to coordinate the display of the data.

The model is not necessarily a database. In MVC, the Model is both the data and the business logic needed to manipulate the data in the application.


答:
NDepend really is a great option. it can do a lot and analyze your code during the build. You would need to write your own CQL querys to check for valid dependencies and you need to pay for it. If you do a lot of code reviews or need to investigate legacy software NDepend brings a lot of value.

Another solution could be to write your own custom build task ( There might already be one somewhere, but I could not find it ) Here is a simple start https://stackoverflow.com/questions/5622141/msbuild-reference-resolution  together with this great series you should be able to get it to work.

Hope this helps.

update (11-6-2012) NDepend 4.0 was released including default rules for architecture and layering check out the new default rules here : http://www.ndepend.com/DefaultRules/webframe.html

update (10-2-2013) I tried using nDepend for validation and wrote a post about it "Using NDepend as an alternative to the Layered Diagram"

Title: Automated architecture validation

Body:
I am aware of the fact that TFS 2010 ultimate edition can create and validate architecture diagrams.  For example, I can create a new modeling project > add Layer Diagram > Add Layer called View > Add BL Layer > Add DL layer.

Then I can validate this architecture as part of the build process when someone tries to check code into TFS.  In other words, if the View references the DL then the compilation process will fail and the checkin will not be allowed.

For those without an MSDN ultimate license, can FxCop or some 3rd party utility be used to validate architecture in an automated fashion?  I prefer a TFS install-able plugin, but a local VS plugin will do.


问:
Rails and Mongoid best way to implement sharing system
I have to model User and Board in rails using mongoid as ODM.

Each board is referenced to an user through a foreign key user_id and now I want to add the ability to share a board with other users.

Following CRUD I'd create a new Model called something like Share and it's releated Controller with the ability to create/edit/delete a Share but I have some doubts:

First, where to save informations about Shares? I think I may create a field in the Board's collection called shared_with including an array of user ids. in a MySQL I'd created a new table with the ids of who share, the resource shared and the user the resources is shared with but I don't think that's necessary using MongoDB.

Every user a Board is shared with should be able to edit the Board (but not to delete it) so the Board should have two relations one with the owner and another with the users the board is shared with, right?

For permission (the owner should be able to delete a board but the users it is shared with shouldn't) what to use? I'm using Devise for authentication but I think something like CanCan would fit better. but how to implement it?

What do you think about this way? Do you find any problems or have better solutions?

答:
I think you might find better answers on stackoverflow. I'm not an expert in RAILS or mongodb, but I'll try.

Creating a field in the Board's collection would probably work OK.

You might want to make a single relation collection, and have a type added to the relation. That way you could have multiple owners if you wanted, and you could add more types later, like a 'read only' or a blocked.

Check the type and render views based on whether or not they are shared to and whether or not they are an owner. I don't think you need a permissions framework for this, but that doesn't mean it's a bad idea to put one in.

Hope that helps!


问:
Is dynamic HTML layout good from an SEO perspective?
Just wondering whether dynamically built HTML layout is fine from SEO perspectives? So let's assume e-commerce engine and its most popular page - products catalog. So 90% of the page is built using AJAX and MVVM library knockoutjs which builds HTML on the fly on the client side. So how search bots would parse such content? Is it fine indexed and would be such effective as server-side built HTML pages from the SEO perspectives?</p>

答:
Here are some resources for you to peruse.  In short:

If you have dynamic generation schemes embedded in your javascript (javascript menus for example), provide a static sitemap to the embedded content.

Google can crawl Ajax links, if you take certain steps.

https://developers.google.com/webmasters/ajax-crawling/docs/getting-started

http://www.webbizideas.com/images/SEO-Friendly-Design-Guidelines.pdf


答:
Top-down, structured programming tends to focus on actions -- verbs you'd use in describing the program. The data used/produced by those actions tends to be treated as secondary at best.

OOP focuses much more on the "things" in the program -- nouns you'd use in describing the program. This thing (object) over here talks to that thing (another object) over there. Data is placed on a much more even footing with the actions. More importantly, rather than segregating all the data into one set and all the code into another, it encourages thinking in terms of putting specific data together with the code that works on that data.

Rather than segregating between data and code, segregation is based more on functionality -- all the code and data related to one thing become an object. The code and data related to  something else become another object.

Title: Any enlightenment for understanding Object Oriented Programming?

Body:
I studied computer science near the end of 1980s, and wasn't taught OOP that formally.

With Pascal or C, when I understand the top-down design of functions, and the idea of black box, then everything just seem to make sense, as if there is a "oh I get it!" -- some kind of totally getting it and enlightenment feeling.

But with OOP, all I know was the mechanics: the class, instance, method, inheritance, polymorphism, encapsulation.  It was like, I knew all the "this is how it is", but never had the feeling of "I totally get it", the enlightened feeling.

Would somebody be able to describe it, or point to a chapter in some book or paper which talks about OOP so that the reader can feel: "I totally get it!" on OOP?


问:
What are some useful things you can do with Mvc Modelbinders?
It occurs to me that the ModelBinder mechanism in ASP MVC

```<code>public interface IModelBinder {
  object BindModel(System.Web.Mvc.ControllerContext controllerContext, System.Web.Mvc.ModelBindingContext bindingContext);
}
</code>```

Is insanely powerful.  What are some cool uses of this mechanism that you've done/seen?

I guess since the concept is similar in other frameworks there's no reason to limit it to Asp Mvc

答:
Consider a custom type called TimeInterval that is stored as a double, but is displayed as hh.mm.ss.ffffff where ffffff is fractional seconds.  With custom binding, it is possible to show the binder how to properly parse and display these numbers, without having to write custom code in the controller.

```<code>// This class implements a custom data type for data binding.
public class TimeInterval
{
    double _value;

    // Constructor
    public TimeInterval(string value)
    {
        // Extension method parses hh.mm.ss.ffffff string value to double.
        _value = value.ToSeconds();
    }
    // Constructor
    public TimeInterval(double value)
    {
        _value = value;
    }
    public string GetText()
    {
        // Extension method formats double value as hh.mm.ss.ffffff time string.
        return _value.ToTimeString();
    }
    public double? GetValue()
    {
        return _value;
    }
}

// This class implements custom binding for the TimeInterval custom type.
// It is registered in Global.asax
public class TimeIntervalBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        string value = GetAttemptedValue(bindingContext);

        if (value == "")
            return null;

        return new TimeInterval(value);
    }

    private static string GetAttemptedValue(ModelBindingContext context)
    {
        ValueProviderResult value = context.ValueProvider[context.ModelName];
        return value.AttemptedValue ?? string.Empty;
    }
}

// in Global.asax:
protected void Application_Start()
{
    RegisterRoutes(RouteTable.Routes);
    ModelBinders.Binders.Add(typeof(TimeInterval), new TimeIntervalBinder());
}
</code>```

Now binding happens automatically for the new custom type.

Body:
Consider a custom type called TimeInterval that is stored as a double, but is displayed as hh.mm.ss.ffffff where ffffff is fractional seconds.  With custom binding, it is possible to show the binder how to properly parse and display these numbers, without having to write custom code in the controller.

// This class implements a custom data type for data binding.
public class TimeInterval
{
    double _value;

    // Constructor
    public TimeInterval(string value)
    {
        // Extension method parses hh.mm.ss.ffffff string value to double.
        _value = value.ToSeconds();
    }
    // Constructor
    public TimeInterval(double value)
    {
        _value = value;
    }
    public string GetText()
    {
        // Extension method formats double value as hh.mm.ss.ffffff time string.
        return _value.ToTimeString();
    }
    public double? GetValue()
    {
        return _value;
    }
}

// This class implements custom binding for the TimeInterval custom type.
// It is registered in Global.asax
public class TimeIntervalBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        string value = GetAttemptedValue(bindingContext);

        if (value == "")
            return null;

        return new TimeInterval(value);
    }

    private static string GetAttemptedValue(ModelBindingContext context)
    {
        ValueProviderResult value = context.ValueProvider[context.ModelName];
        return value.AttemptedValue ?? string.Empty;
    }
}

// in Global.asax:
protected void Application_Start()
{
    RegisterRoutes(RouteTable.Routes);
    ModelBinders.Binders.Add(typeof(TimeInterval), new TimeIntervalBinder());
}

Now binding happens automatically for the new custom type.


答: I've used model binders to localize content based on session state information. By the time the controller knows anything, the content has already been set according to the user's preferred locale.</p>

Title: What are some useful things you can do with Mvc Modelbinders?

Body:
It occurs to me that the ModelBinder mechanism in ASP MVC

```<code>public interface IModelBinder {
  object BindModel(System.Web.Mvc.ControllerContext controllerContext, System.Web.Mvc.ModelBindingContext bindingContext);
}
</code>```

Is insanely powerful.  What are some cool uses of this mechanism that you've done/seen?

I guess since the concept is similar in other frameworks there's no reason to limit it to Asp Mvc


答:
For this type of application you need to think about who should be allowed to access the data.  With medical information I think it sould be restricted to the user who entered it and anyone they gave permission to view it.

In order to prevent the DBA from viewing the data you will have to encrypt it using a code that the DBA does not have access to.

You also need to encrypt the information in a way that the application programmer can't access it either.  There's no point in encrypting the information from the DBA if a programmer can log in as any user.

You also don't want to encrypt all the data with the same code.  The software might have a bug that shows one user the information of another.  So it would probably be best to encrypt each users data using a code specific to that user.

It is important to note that you need to encrypt more than just the medical information; as an end user I wouldn't want your DBA even knowing I have a medical condition, let alone what it is.  So you'll need to also encrypt any personally identifying information about the user.  This includes such things as:

name

date of birth

email address

sex

address

Title: How to separate sensitive data in database(MySql)

Body:
I need to design a database that will contains information about personal disease of users.

What can be the approach in order to implement the columns of the DB's tables: encrypt the information, separate data within two differents DB, one for sensitive data and another for not sensitive data, or both or another approach?


答: the safest bet is to have the content you want spidered as HTML (not brought through ajax). Even if Google does something, that doesn't mean other spiders do.  If uncertain, you can use Google webmaster tools to see how Google sees your page ( https://www.google.com/webmasters/tools/home ) under diagnostics/fetch as googlebot</p>

Title: Is dynamic HTML layout good from an SEO perspective?

Body: Just wondering whether dynamically built HTML layout is fine from SEO perspectives? So let's assume e-commerce engine and its most popular page - products catalog. So 90% of the page is built using AJAX and MVVM library knockoutjs which builds HTML on the fly on the client side. So how search bots would parse such content? Is it fine indexed and would be such effective as server-side built HTML pages from the SEO perspectives?</p>


答:
Do you already understand the principle of Object Based programming?    Many people may tell you that they are one and the same thing, but really Object Oriented programming is an extension of the former.

In the world of procedural programming, things are pretty much broken down between data structures and behaviour (functions/procedures);  your functions/procedures stand alone, and perform operations on your data.

e.g. a classic linked list header might look like

```<code>struct node { /* */ };

void add_to_list( node* head, data d );
void remove_from_list( node* head, data d );
data* find_in_list( node* head, data d );
void sort_list( node* head );
</code>```

There's a straightforward pattern between each of those functions - their first argument always references the linked list structure in some way;   The calling-convention will always look something like

```<code>node* head = create_node( 1 );
add_to_list( head, 2 );
add_to_list( head, 3 );
remove_from_list( head, 2 );
data* d = find_in_list( head, 1 );
sort_list( head );
</code>```

In the world of object-based programming, the relationship between the data structure and the behaviour which operates on the data is acknowledged, then tightly bound together in the form of data structures which have both data and behaviour (a.k.a classes).    The difference between object-based programming and procedural programming is extremely simple - it is nothing more than a different way to organise your code into logical units.

```<code>class linked_list
{
    void add( data d );
    void remove( data d );
    data* find( data d );
    void sort();
}
</code>```

Compare that to the procedural solution - the main differences are

1) the functions exist inside a data structure

2) The functions no longer reference to the data structure in their arguments - because a reference to a data structure Object is implied by the way the function is used and the object is called, using the new calling convention...

```<code>linked_list my_list;
my_list.add( 2 );
my_list.add( 3 );
my_list.remove( 2 );
data* d = my_list.find( 1 );
my_list.sort();
</code>```

Hardly revolutionary from a pure code point of view; but looking more closely at it, the code is now a little bit more organised.  Not only this, there's no longer a concept of a 'head' floating around the main bit of code where the list is actually used!.    The head is an implementation detail of the linked list.
In the procedural solution, the head is wide open for all to see, and there's nothing stopping a rogue bit of code from breaking the list.
Furthermore, programming languages which support classes tend to also help you isolate the memory management - with any luck, any heap-management is entirely self-contained within the depths of the class instead of in standalone functions.

Furthermore, the real benefit of approaching programming in this way is the benefit for the person designing it;   You can "think bigger" than simply juggling characters, integers, arrays, structures, pointers, handles, etc;

Stepping away from the linked list example, think of GUI code - instead of worrying about API calls, resource lifetimes, callbacks, handles, etc, you can design code which says "First I'll create a Dialogue Box, then I'll add a button, then I'll link this button to a function/event".

Given the ability to create classes which represent real-world entities, you can write the code in a manner which fits far more closely to your problem domain; selectively ignoring all of the nitty-gritty-details, and working at a high level where concerns about precisely how a Window/Form/Button/Tickbox/etc functions is a problem to be solved elsewhere.   There are a bunch of software-design principles associated with this kind of thing, but the main ones are Encapsulation and Separation of Concerns.

--

Note - this far I've only mentioned Object-Based programming; Object-Oriented programming takes it one step further, Although in my personal opinion, "Object Orientated Programming" (OOP) is perhaps the most widely-used and poorly-name software development concept ever uttered.   (Others feel free to disagree, that's just my take on it)

The real power and purpose of Object Oriented Programming has nothing (IMHO) to do with Objects and is not specifically about Programming.  To my mind, "OOP" is about Designing to an interface  (Maybe Interface Oriented Design would be a better name?)

The thing which separates "OOP" from Object-based programming is called Inheritance - it is the ability to specify a general-purpose class which is reused by other specialised classes.

going back to the linked list example - look at the functions

```<code>    void add( data d );
    void remove( data d );
    data* find( data d );
    void sort();
</code>```

They belong to a linked list, but in fact, they should also be applicable to an array, a binary tree, a hashmap...

Suppose you have 4 different classes for each kind of data structure - you want to write a find-and-replace function which stands on its own and simply looks like

```<code>data* item = structure.find( something );
if ( item != NULL )
{
    *data = replacement;
    return true;
}
else
{
    return false;
}
</code>```

I guess it could be a standalone function, what does the signature for the function look like though?  That logic applies to any structure which has a find(data) member, but if all you've got are a bunch of different data types, then you might end up doing something like

```<code>bool replace(void* structure, int structure_type, data something, data replacement)
{
    if( structure_type == eLINKEDLIST ) // etc.
    else if( structure_type == eARRAY ) // etc.
    else if( structure_type == eBINARYTREE ) // etc.
</code>```

Yuck, yuck, and more yuck!   the code suffers from else-if-heimers disease (Where's the hashmap? Oops!) and looks like a dumping ground for special-case stuff.   Furthermore, there might be a bunch of other identical chunks of code lying around im similar functions.

Inheritance to the rescue maybe?  Well, a void* is unpleasant - it would be nice to be able to simply pass in a reference to a data type which simply provides access to the find function of any kind of data structure.  Who cares whether its a linked list, an array, a hashmap.  Most importantly, any code which uses too much if-else-if-else-if is usually a careless mistake waiting to happen

```<code>class interface_structure
{
    virtual void add( data d );
    virtual void remove( data d );
    virtual data* find( data d );
    virtual void sort();
}
</code>```

Then all which is left to do is define each of the other structures

```<code>class linked_list : public interface_structure;
class hashmap : public interface_structure;
class array : public interface_structure;
class binary_tree : public interface_structure;
</code>```

Now there's an obvious way to write the replace function.  No need to figure out what the kind of structure is - replace() simply couldn't care, because it has been designed by way of selective ignorance:

```<code>bool replace( interface_structure* structure, data something, data replacement )
{
    data* item = structure.find( something );
    if ( item != NULL )
    {
        *data = replacement;
        return true;
    }
    else
    {
        return false;
    }
}
</code>```

In fact, the replace function could possibly also be part of the interface structure (Which would turn the interface structure into an Abstract Base Class - that's a design choice which a programmer would be faced with.    Standalone functions are not necessarily a bad thing).

As I hinted before, I don't believe the power here is necessarily in the programming - it's all in the design.  "Object Oriented Programming" is a complete paradigm shift which requires that you re-learn how to approach problem solving all over again.   You need to make the mental shift which ignores implementation detail and examines a program's behaviour at the higher level.

Designing OO code is all about identifying themes and commonalities across different "kinds of" entities;  making the shift isn't something which happens straight away or naturally, but I believe you need to learn to "think" OO before you can program it. (But of course the programming practice is generally where the learning happens)

(There's a lot more to "Object based" and "Object Oriented" design/programming than this.. design patterns, S.O.L.I.D principles, and a whole bunch of other things. )

Body:
Do you already understand the principle of Object Based programming?    Many people may tell you that they are one and the same thing, but really Object Oriented programming is an extension of the former.

In the world of procedural programming, things are pretty much broken down between data structures and behaviour (functions/procedures);  your functions/procedures stand alone, and perform operations on your data.

e.g. a classic linked list header might look like

struct node { /* */ };

void add_to_list( node* head, data d );
void remove_from_list( node* head, data d );
data* find_in_list( node* head, data d );
void sort_list( node* head );

There's a straightforward pattern between each of those functions - their first argument always references the linked list structure in some way;   The calling-convention will always look something like

node* head = create_node( 1 );
add_to_list( head, 2 );
add_to_list( head, 3 );
remove_from_list( head, 2 );
data* d = find_in_list( head, 1 );
sort_list( head );

In the world of object-based programming, the relationship between the data structure and the behaviour which operates on the data is acknowledged, then tightly bound together in the form of data structures which have both data and behaviour (a.k.a classes).    The difference between object-based programming and procedural programming is extremely simple - it is nothing more than a different way to organise your code into logical units.

class linked_list
{
    void add( data d );
    void remove( data d );
    data* find( data d );
    void sort();
}

Compare that to the procedural solution - the main differences are

1) the functions exist inside a data structure

2) The functions no longer reference to the data structure in their arguments - because a reference to a data structure Object is implied by the way the function is used and the object is called, using the new calling convention...

linked_list my_list;
my_list.add( 2 );
my_list.add( 3 );
my_list.remove( 2 );
data* d = my_list.find( 1 );
my_list.sort();

Hardly revolutionary from a pure code point of view; but looking more closely at it, the code is now a little bit more organised.  Not only this, there's no longer a concept of a 'head' floating around the main bit of code where the list is actually used!.    The head is an implementation detail of the linked list.
In the procedural solution, the head is wide open for all to see, and there's nothing stopping a rogue bit of code from breaking the list.
Furthermore, programming languages which support classes tend to also help you isolate the memory management - with any luck, any heap-management is entirely self-contained within the depths of the class instead of in standalone functions.

Furthermore, the real benefit of approaching programming in this way is the benefit for the person designing it;   You can "think bigger" than simply juggling characters, integers, arrays, structures, pointers, handles, etc;

Stepping away from the linked list example, think of GUI code - instead of worrying about API calls, resource lifetimes, callbacks, handles, etc, you can design code which says "First I'll create a Dialogue Box, then I'll add a button, then I'll link this button to a function/event".

Given the ability to create classes which represent real-world entities, you can write the code in a manner which fits far more closely to your problem domain; selectively ignoring all of the nitty-gritty-details, and working at a high level where concerns about precisely how a Window/Form/Button/Tickbox/etc functions is a problem to be solved elsewhere.   There are a bunch of software-design principles associated with this kind of thing, but the main ones are Encapsulation and Separation of Concerns.

--

Note - this far I've only mentioned Object-Based programming; Object-Oriented programming takes it one step further, Although in my personal opinion, "Object Orientated Programming" (OOP) is perhaps the most widely-used and poorly-name software development concept ever uttered.   (Others feel free to disagree, that's just my take on it)

The real power and purpose of Object Oriented Programming has nothing (IMHO) to do with Objects and is not specifically about Programming.  To my mind, "OOP" is about Designing to an interface  (Maybe Interface Oriented Design would be a better name?)

The thing which separates "OOP" from Object-based programming is called Inheritance - it is the ability to specify a general-purpose class which is reused by other specialised classes.

going back to the linked list example - look at the functions

    void add( data d );
    void remove( data d );
    data* find( data d );
    void sort();

They belong to a linked list, but in fact, they should also be applicable to an array, a binary tree, a hashmap...

Suppose you have 4 different classes for each kind of data structure - you want to write a find-and-replace function which stands on its own and simply looks like

data* item = structure.find( something );
if ( item != NULL )
{
    *data = replacement;
    return true;
}
else
{
    return false;
}

I guess it could be a standalone function, what does the signature for the function look like though?  That logic applies to any structure which has a find(data) member, but if all you've got are a bunch of different data types, then you might end up doing something like

bool replace(void* structure, int structure_type, data something, data replacement)
{
    if( structure_type == eLINKEDLIST ) // etc.
    else if( structure_type == eARRAY ) // etc.
    else if( structure_type == eBINARYTREE ) // etc.

Yuck, yuck, and more yuck!   the code suffers from else-if-heimers disease (Where's the hashmap? Oops!) and looks like a dumping ground for special-case stuff.   Furthermore, there might be a bunch of other identical chunks of code lying around im similar functions.

Inheritance to the rescue maybe?  Well, a void* is unpleasant - it would be nice to be able to simply pass in a reference to a data type which simply provides access to the find function of any kind of data structure.  Who cares whether its a linked list, an array, a hashmap.  Most importantly, any code which uses too much if-else-if-else-if is usually a careless mistake waiting to happen

class interface_structure
{
    virtual void add( data d );
    virtual void remove( data d );
    virtual data* find( data d );
    virtual void sort();
}

Then all which is left to do is define each of the other structures

class linked_list : public interface_structure;
class hashmap : public interface_structure;
class array : public interface_structure;
class binary_tree : public interface_structure;

Now there's an obvious way to write the replace function.  No need to figure out what the kind of structure is - replace() simply couldn't care, because it has been designed by way of selective ignorance:

bool replace( interface_structure* structure, data something, data replacement )
{
    data* item = structure.find( something );
    if ( item != NULL )
    {
        *data = replacement;
        return true;
    }
    else
    {
        return false;
    }
}

In fact, the replace function could possibly also be part of the interface structure (Which would turn the interface structure into an Abstract Base Class - that's a design choice which a programmer would be faced with.    Standalone functions are not necessarily a bad thing).

As I hinted before, I don't believe the power here is necessarily in the programming - it's all in the design.  "Object Oriented Programming" is a complete paradigm shift which requires that you re-learn how to approach problem solving all over again.   You need to make the mental shift which ignores implementation detail and examines a program's behaviour at the higher level.

Designing OO code is all about identifying themes and commonalities across different "kinds of" entities;  making the shift isn't something which happens straight away or naturally, but I believe you need to learn to "think" OO before you can program it. (But of course the programming practice is generally where the learning happens)

(There's a lot more to "Object based" and "Object Oriented" design/programming than this.. design patterns, S.O.L.I.D principles, and a whole bunch of other things. )


问:
How do we provide valid time estimates during Sprint Planning without doing "too much" design?
My team is getting up to speed with Scrum, but most of us are more familiar with non-agile or  "pseudo-"agile methodologies. The part that is the biggest hurdle for us is running an efficient Sprint Planning meeting where we break our backlog items into tasks, and estimate hours. (I'm using the terminology from the VS2010 Scrum Template; apologies if I use the wrong word somewhere.)

When we try to figure out how long a task is going to take, we often fall into the trap of designing the feature at the code level -- table layout, interfaces, etc -- in order to figure out how long that's going to take.

I'm pretty sure this is not the appropriate place to be doing that kind of design. We  should be scheduling tasks for these design meetings during the sprint. However, we are having trouble figuring out how else to come up with meaningful estimates for the tasks.

Are there any practical habits/techniques/etc. for making a judgement call about how long a feature is going to take, without knowing how you plan to implement it? If our time estimates are going to change significantly once the design has been completed, how can we properly budget our Sprint backlog ahead of time?

EDIT:

Just to clarify, since some of the comments/answers are very valid but I think addressing the wrong question.

We know that what we're doing is not right, and that we should be building time into the sprint for this design. Conceptually all of the developers understand that. We also also bringing in a team member with Scrum experience to keep us on track if we start going off into the weeds.

The problem is that, without going through this design process, we are finding it difficult to provide concrete time estimates for anything. We are constantly saying things like "well if we design it this way it might take 8 hours but if we end up having to do this other way instead that will take about 32 but it might not be as bad once we start trying to write it...".

I also assume that this process will get better once we have some historical velocity to work from, but many of the technologies and architectural patterns we are using are new to us. But if potentially-wildly-wrong estimates are just a natural part of adapting this process then we will just need to recondition ourselves to accept that :)

答:
There are two things you can do here.

First have some sort of scrum master who's role is to monitor the discussion and say "Hey, you're designing again" when you are. It's harder than it seems, rotate people into it day by day and initially have everyone be the scrum master so anyone can pipe up.

Second, if you are designing during the sprint planning you need to be able to differentiate between not knowing enough to make a call on a task's duration, or whether you are just designing because it's more fun.

Again, the scrum master should kick in here and tell you to put the item back on hold until you know enough to schedule it, or get you to stop designing and answer the original question (How long will it take).

So if you are doing sprint planning, it makes sense to have a business sponsor there to go over the backlog with you and prioritise stuff they want to see done first. If you do that you will find it is harder to design during the session because they will get restless and eventually won't want to come.


问:
Is it just me or is this a baffling tech interview question?

Background

I was just asked in a tech interview to write an algorithm to traverse an "object" (notice the quotes) where A is equal to B and B is equal to C and A is equal to C.

That's it.  That is all the information I was given.

I asked the interviewer what the goal was but apparently there wasn't one, just "traverse" the "object".

I don't know about anyone else, but this seems like a silly question to me.  I asked again, "am I searching for a value?".  Nope.  Just "traverse" it.

Why would I ever want to endlessly loop through this "object"??  To melt my processor maybe??

The answer according to the interviewer was that I should have written a recursive function.

OK, so why not simply ask me to write a recursive function?  And who would write a recursive function that never ends?

My question:

Is this a valid question to the rest of you and, if so, can you provide a hint as to what I might be missing?  Perhaps I am thinking too hard about solving real world problems.  I have been successfully coding for a long time but this tech interview process makes me feel like I don't know anything.

答:
This is just a wild guess, but assuming the interviewer is talking about pointer references (and it's a trick question), the answer is: there's nothing to traverse, because all of the references point to the same object.

A recursive function?  That's for traversing a tree.  I see nothing in the original question that would imply that he's talking about a tree.


答:
Schedule a recurring "grooming" meeting where you have these design discussions.  The team I'm on has them once per sprint, on the day before planning.  The goal there is to have the design far enough nailed down that the team can agree on the time estimates for the overall story.  You could consider doing task breakdowns in this meeting, so that planning becomes purely an exercise in deciding how much to pick up.  In other words you should be doing the design in the sprints BEFORE you start doing the actual work.

Consider using planning poker, i.e. points/units of "effort" rather than man-days to estimate tasks.  Also try to break down the stories as much as you can.  The longer/more complex a story is, the less likely your estimate is going to be accurate.

In planning, the scrum master should keep the planning on track by calling a halt to any discussions that get too far into "solving."  At that point the team members are required to quickly come to an agreement on the estimate, usually giving an upper-bounds/worst case number.  It's much easier to pick up more work if the tasks end up being easier than you plan, than it is to deal with schedules slipping due to tasks taking longer than planned and stories rolling over into multiple sprints.

Talk about how the estimates panned out in the retrospective at the end of the sprint.  Particularly if there were any that were remarkably far off. Did the team learn anything from how the story went versus how they expected it to go? The scrum master should keep the focus on actionable changes that can be made to your design/estimation process.

Title: How do we provide valid time estimates during Sprint Planning without doing "too much" design?

Body:
My team is getting up to speed with Scrum, but most of us are more familiar with non-agile or  "pseudo-"agile methodologies. The part that is the biggest hurdle for us is running an efficient Sprint Planning meeting where we break our backlog items into tasks, and estimate hours. (I'm using the terminology from the VS2010 Scrum Template; apologies if I use the wrong word somewhere.)

When we try to figure out how long a task is going to take, we often fall into the trap of designing the feature at the code level -- table layout, interfaces, etc -- in order to figure out how long that's going to take.

I'm pretty sure this is not the appropriate place to be doing that kind of design. We  should be scheduling tasks for these design meetings during the sprint. However, we are having trouble figuring out how else to come up with meaningful estimates for the tasks.

Are there any practical habits/techniques/etc. for making a judgement call about how long a feature is going to take, without knowing how you plan to implement it? If our time estimates are going to change significantly once the design has been completed, how can we properly budget our Sprint backlog ahead of time?

EDIT:

Just to clarify, since some of the comments/answers are very valid but I think addressing the wrong question.

We know that what we're doing is not right, and that we should be building time into the sprint for this design. Conceptually all of the developers understand that. We also also bringing in a team member with Scrum experience to keep us on track if we start going off into the weeds.

The problem is that, without going through this design process, we are finding it difficult to provide concrete time estimates for anything. We are constantly saying things like "well if we design it this way it might take 8 hours but if we end up having to do this other way instead that will take about 32 but it might not be as bad once we start trying to write it...".

I also assume that this process will get better once we have some historical velocity to work from, but many of the technologies and architectural patterns we are using are new to us. But if potentially-wildly-wrong estimates are just a natural part of adapting this process then we will just need to recondition ourselves to accept that :)


答:
While I cannot speak for this specific interviewer, I've seen similar questions in a front-end developer position interview, so the language I'll use in this example will be JavaScript.

Given:

```<code>var A = {
    key1: 'value1',
    key2: 2,
    key3: {
        innerkey1: 'value3'
    }
}
</code>```

A typical wrong response may "traverse" the first level only and print/compare:

```<code>'value1'
2
[Object object]
</code>```

So while coding a recursive example that would traverse all levels, I would mention things like:

Circular reference handling

How to handle arrays (should they be recursively traversed too?)

Should functions be evaluated and their return value processed?

For JavaScript: should the prototype match and should inherited properties also be compared?

So the "solution" that I'm guessing the interviewer was going for was to get a conversation started on a seemingly-simple question that has many advanced topics - recursiveness, pointers/references, expectations, etc.

Title: Is it just me or is this a baffling tech interview question?

Body:
Background

I was just asked in a tech interview to write an algorithm to traverse an "object" (notice the quotes) where A is equal to B and B is equal to C and A is equal to C.

That's it.  That is all the information I was given.

I asked the interviewer what the goal was but apparently there wasn't one, just "traverse" the "object".

I don't know about anyone else, but this seems like a silly question to me.  I asked again, "am I searching for a value?".  Nope.  Just "traverse" it.

Why would I ever want to endlessly loop through this "object"??  To melt my processor maybe??

The answer according to the interviewer was that I should have written a recursive function.

OK, so why not simply ask me to write a recursive function?  And who would write a recursive function that never ends?

My question:

Is this a valid question to the rest of you and, if so, can you provide a hint as to what I might be missing?  Perhaps I am thinking too hard about solving real world problems.  I have been successfully coding for a long time but this tech interview process makes me feel like I don't know anything.

Body:
While I cannot speak for this specific interviewer, I've seen similar questions in a front-end developer position interview, so the language I'll use in this example will be JavaScript.

Given:

var A = {
    key1: 'value1',
    key2: 2,
    key3: {
        innerkey1: 'value3'
    }
}

A typical wrong response may "traverse" the first level only and print/compare:

'value1'
2
[Object object]

So while coding a recursive example that would traverse all levels, I would mention things like:

Circular reference handling

How to handle arrays (should they be recursively traversed too?)

Should functions be evaluated and their return value processed?

For JavaScript: should the prototype match and should inherited properties also be compared?

So the "solution" that I'm guessing the interviewer was going for was to get a conversation started on a seemingly-simple question that has many advanced topics - recursiveness, pointers/references, expectations, etc.


答: They may want to try to figure out how you deal with strange problems. But in this case, it has nothing to do with a "tech interview". It looks more like a psychological interview.</p>


答: Part of the challenge here is to get more detail by asking specific questions to get out that there is a tree structure and what are the components involved in doing a traversal.  There may have been the assumption that there aren't many other data structures that one traverses besides trees but that is a bit of a leap to my mind.</p>


答:
It's a baffling, invalid interview question.  The interviewer couldn't clearly articulate what it was that he/she was looking for and expected you to read his/her mind instead of responding meaningfully to your appropriate attempts to clarify the statement of the problem.  Consider yourself lucky you didn't get the job.

The meaning of the verb "traverse" operating on a generic "object" is ambiguous, in my opinion.  Start substituting a variety of different nouns for the word object and it quickly becomes obvious that traversal of an object is only meaningful for a small subset of the universe of things that are objects.

It makes sense to "traverse" the nodes of a "binary tree".  It doesn't make sense to "traverse" a "clown".  Yet, an object can just as easily represent a "clown" as it can represent a "binary tree".


答:
First, recognize that accurate estimates are impossible under those circumstances.  Don't stress out if you get it wrong.  However, you still need a rough idea in order to plan, and really the only way to account for complete uncertainty is to add more story points to your estimate.  If you don't know if it's a 5 or a 13, use the 13.

It's also helpful to break stories down as small as possible.  We often have a research/design story with the sole purpose of doing enough work to have a better idea of how to do the feature, then the feature story itself goes into a subsequent sprint.  Think about why this works.  Even if you have no idea how hard something will be, you usually know fairly accurately from past experience how long it will take to find out.


问:
How to implement smart card authentication with a .NET Fat client?
I know very little about smart card authentication in general so please point out or correct me if anything below doesn't make sense.

Lets say i have:

A Certificate Authority "X"-s smart card (non-exportable private key)

Drivers for that smart card written in C

A smart card reader

CA-s authentication OCSP web service

A requirement to  implement user authentication in a .NET fat client application via a smart card, that was given out by the CA "X".

I tried searching info on the web but no prevail. What would the steps be ? My first thought was:

Set up a web service, that would allow saving of (for example) scores of a ping pong game for each user.
Each time someone tries to submit a score via the client application, he can only do so by inserting the smart card into the reader.

Then the public key is read from the smart card by native c calls through .NET and sent to my custom web service, which in return uses the CA-s authentication OCSP web service to prove the validity of the public key/public certificate (?). If the public key is okay and valid, encrypt a random sequence of bytes with the public key and send it to the client application.
If the client application sends back the correctly decrypted random sequence of bytes along with the score of the ping pong game, then the score is saved in the database for the given user.

My question is, is this the correct way to do it ? What else should i know about smart card authentication ?

答:
Instead of trusting the operating system if you want to do authentication yourself, yes you are in right track.

AFAIK using smart cards in os level requires the domain authentication. If not your all of your users uses domain you have to authenticate yourself. (ex: internet user)

More practical way is;

[client] get the hash of score point (sha1, sha2 etc)

[client] encrypt the hash (it's actually called signature)

[client] send the signature + user's public certificate to web service

[server] Validate the user's certificate (ocsp)

[server] get hash of score (again)

[server] decrypt sent hash

[server] compare the calculated hash with sent hash (verifying the signature)

this way is more less chatty and less data transferred.

you may calculate the hash with by .net API or you can use the smart card it self but smart carts usually slow, i recommend the use .net API if security is not too tight.


答:
I think the issue is that you are trying to estimate time.  Don't.

Estimate complexity.  Look at a requirement, (hopefully a user story) and rate how complicated the team thinks it will be to figure out how to build it and test it, relative to how complicated other requirements or user stories are.  Sometimes you'll be wrong, but often you'll get a good idea of how hard something is going to be.  You'll also find that items that are the around same complexity tend to take the same amount of effort to complete.

So, complexity rankings become the "story points" associated with the user stories in your product backlog.  After you work through a few sprints, you'll get an idea of how many story points you can get through in a sprint, and that is your velocity.  At that point, you'll have a much better idea of how long each item will take.

I highly recommend Mike Cohn's User Stories Applied.


答:
I can see three possibilities here.

She was completely incompetent. Not much more to say on that one.

She was deliberately making it ambiguous, to see how well you'd do at asking questions to figure out what you were supposed to do, and what she was really after.

For whatever reason, she'd decided she didn't want you hired, so she asked a question that was unanswerable as given. When she was asked about your skills, she'd skip over that part and say something like: "I asked him about how to traverse a three-node graph, and he was completely stumped -- didn't have even a clue of how to start. Obviously he's grossly incompetent! We shouldn't even consider hiring him."


问:
Reinforcing Syntax Elements
I am currently learning Javascript, and there is one element of the syntax that I can just not seem to nail down. That element is adding semicolons at the end of each line. I have learned Python and Ruby, and written a ton of both, so the lack of semicolons is stuck in my mind! Is there a way to drill that (or even any syntax, to make this more useful to future readers) into my brain?</p>

答:
No tricks for this I'm afraid. As @Raynos pointed out, semicolons are optional. But if you want to learn the habit in case you might learn other languages that require them, just code slowly and remember it for each line. As you get used to the idea, you'll be able to code faster and it'll become a habit over time.

You'll only get it in the same way you got the habit of not placing any: by "writing a ton of the language".

Title: Reinforcing Syntax Elements


问:
What do you use to organize your team knowledge?
Last year, me and three good old friends of mine founded a small web/mobile development team. Things are going pretty well. We're learning a lot, and new people are joining the group.
Keeping knowledge always updated and in-sync is vital for us. Long emails threads are simply not the way to go for us: too dispersing and confusing, and hard to retrieve after a while.

How your team manages and organizes common knowledge? How do you collect and share useful resources (articles, links, libraries, etc) inside your team?

Update: Thanks for the feedback. More than using a wiki to share team common procedures or informations, I'd like to share external links, articles, code libraries, and be able to comment them easily within my team.

I was particularly interested in knowing if you're aware of any way/webservice to share a reading list with a team. I mean, something like Readitlater/Instapaper, but for teams, maybe with some stats available, like "# of coworkers who read it".

答:
This may be a long shot, but where I work, we share links, interesting Q&A questions, blogs, videos and other non company related content on our Facebook group.

It may not be an option in every company, but it's working greatly with our team.

OwnerDisplayName: Stefano Verna


问:
Testing loses its effectiveness if all programmers don't use them
Let's assume you are convinced that the extra time spent unit testing has merit and improves production. Does that still hold up when everyone working on the same code doesn't use them? This question makes me wonder if fixing tests that everyone doesn't use is a waste of time. If you correct a test so the new code will pass, you're assuming the new code is correct. The person updating the test better have a firm understanding of the reasoning behind the code change and decide if the test or the new code needs to be fixed. This much inconsistency in a team when it comes to testing is probably an indication of other problems as well.

There is a certain amount of risk involved that someone else on the team will alter code that is covered by testing. Is this the point where testing becomes counter-productive?

答:
EDIT:
My views have completely changed since I first was introduced to the concept of code coverage. I don't like this metric anymore, and below advice goes against my believes now. One should use code coverage metric to learn about the code that might need additional attention. Never should the target of X% coverage be set as it will often make developers write unit tests for a wrong reason (get the coverage up instead of properly testing the code) and waste time that could be spent on something more improtant.

Thanks to someone who down voted this post, I wouldn't have found it otherwise.

[Original answer] You could use code coverage as a way to require developers to work on the tests.
Tests must be run before check-in and if new code results in regression of code coverage it is simple to observe. Code coverage reports also have nice reports on per-module/ per-class basis - so you will be able to see clearly whose code is not covered and where you need to spend more time to get a better coverage.

Set up a goal for you team, say 60% code coverage and try to maintain it whether through automated scripts or via regular reviews of the statistics.